I'm using python to try and talk to my Arduino with pyserial. The code should wait for an input from COM5, (the arduino), and then sends a 1 and waits for the response.

import serial

connected = False

ser = serial.serial("COM5", 9600)

while not connected:
    serin = ser.read()
    connected = True

ser.write("1")

while ser.read() == '1':
    ser.read()

ser.close()

All I get if this error message.

Traceback (most recent call last):
  File "C:\Users\Patrick\Documents\Python\serial.py", line 2, in <module>
    import serial
  File "C:\Users\Patrick\Documents\Python\serial.py", line 10, in <module>
    ser = serial.serial("COM5", 9600)
TypeError: 'module' object is not callable

Python is case sensitive, so try:

ser = serial.Serial("COM5", 9600)

'module' object has no attribute 'Serial'

This happens if you try that.

PySerial finds the port by he offset so the first port would be offset 0, since it is at the beginning. Port #5 would offset the first 4 ports from the beginning so would be

ser = serial.Serial(4, 9600)

Take a look at the intro docs Click Here
and try python -m serial.tools.list_ports

I would also suggest that you sleep for one or two tenths of a second in the while loop so you don't a lot of computer resources unnecessarily.

Strange, pyserial has a class Serial()
Did you accidentally save your code file as serial.py?

The Python interpreter searches for module "serial" first in the working directory, then in its builtin modules in directory Lib, then in its packages.

When it finds a file serial.py in the working directory it will import your code file instead of the module. So please do not name any of your code files the same as a module file you want to import.

Just one of the nasty surprises Python has waiting for you!

Thanks, that was the problem I named my file serial. But now that it works I'm being told that:

'int' object is not iterable

What is the cause of this?

I should say the this relates to line 11. Which created an error that said it must be an integer so I changed it to:

ser.write(1)

Without the quotation marks.

Add

if ser.isOpen():    
    print "open"
    ## read and write code goes here
else:
    print "closed"

to first make sure the port is open.

Are you using Python3 and trying to write bytes instead of strings? Try

output = "1"
print type(output)
ser.write(output)

Also, this

while not connected:
    serin = ser.read()
    connected = True

only happens once so it is the same as just

serin = ser.read()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.