Ravi Mevada
Ravi Mevada

Reputation: 63

Serial Communication: python

I am using Python Anaconda 2.7. I would like to toggle the port using serial communication, But I am getting error: AttributeError: 'module' object has no attribute 'Serial'

My sample program is:

import serial 
import time 
#remember to adjust “COM3”
port = serial.Serial("COM3", 19200, timeout=0.5) 
#turn on port 2, sleep 2 seconds, turn off port 2 
port.write(b"\nF2\r") 
time.sleep(2.0) 
port.write(b"\nF2\r")             
#turn on port 2 and 7, sleep 2 seconds, turn off port 2 and 7 
port.write(b"\nF2\r\nF7\r") 
time.sleep(2) 
port.write(b"\nF2\r\nF7\r")             
#close the port 
port.close()

I have tried many solutions:

  1. changing file name from 'serial.py' to 'any_other_name.py' and vise versa
  2. deleting related .pyc file
  3. Installing 'pip install pyserial'
  4. Doing From serial import serial

When I run the same program from psychopy, it is working really fine. I don't know How to solve it. If some one can give me suggestions that It would be great help for me. Thanking you in advance.

Ravi

Upvotes: 0

Views: 1053

Answers (1)

Cédric Julien
Cédric Julien

Reputation: 80761

Your code seems good, so the problem you encounter is probably due to a bad import.

You really should avoid to name your python script like "standard" modules (serial.py, string.py...), because by doing this, you expose yourself to accidentally import those files instead of the correct one (probably what happened to you).

If you need to be sure of what you're importing, try this :

import serial
print serial.__file__  # this will tell you the position of the file you've imported and help you to be sure of what you're using.

# in case you're not importing a module, only a class... try this : 
help(serial) # even without any help, it will give you at the end the path where this object is defined :)

Upvotes: 1

Related Questions