dddienst
Posts: 2
Joined: Fri Apr 26, 2013 5:02 pm

Python3 Serial issue on rpi

Fri Apr 26, 2013 5:14 pm

I am trying to use the serial port via the gpio connector through a RS232 buffer chip. I have disabled the terminal connections to this port. My problem is that it works under python2 but not under python3 and I developed all my other code using python3.

Here is my test code:

Code: Select all

#!/usr/bin/env python
#
print ("Starting program")
import serial
#import MAX3100 as COM
import time
# import string
#
count = 1
myin = ""
test=serial.Serial("/dev/ttyAMA0",9600,timeout=5)
test.close()
test.open()
teststring = "ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz\r\n"
#
try:
    while True:
                print (count, teststring)
                test.write(teststring)
                print ("Waiting 5 second")
                #time.sleep(10)
                myin = test.readline()
                print("recieved :"+myin)
                count = count + 1
#
except KeyboardInterrupt:
    pass # do cleanup here
#
test.close()
And this is the error I get under python3:
pi@raspberrypi ~/te1860-4 $ sudo py serialtest.py
Starting program
1 ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz

Traceback (most recent call last):
File "serialtest.py", line 19, in <module>
test.write(teststring)
File "/usr/local/lib/python3.2/dist-packages/serial/serialposix.py", line 475, in write
n = os.write(self.fd, d)
TypeError: 'str' does not support the buffer interface
So what is wrong and how do I fix it? I tried installing pyserial-2.6 but this did not help. I removed python3 and reinstalled it but got the same error. Again, this same code works under python2.

stevech
Posts: 144
Joined: Sun Jul 15, 2012 11:53 pm

Re: Python3 Serial issue on rpi

Sat Apr 27, 2013 5:32 pm

IMO, Python 3 is too leading edge. Better to use 2.x

Sleep Mode zZ
Posts: 319
Joined: Sun Aug 19, 2012 5:56 am
Location: Finland

Re: Python3 Serial issue on rpi

Sat Apr 27, 2013 6:12 pm

I'm guessing that the problem has to do with python's changes in string handling. From Dive into python 3: "Python 2 had “strings” and “Unicode strings.” Python 3 has “bytes” and “strings.”

In python3, "the buffer interface" expects bytes, not strings.

http://getpython3.com/diveintopython3/strings.html

gordon77
Posts: 4992
Joined: Sun Aug 05, 2012 3:12 pm

Re: Python3 Serial issue on rpi

Sat Apr 27, 2013 9:45 pm

I use python 2.7 and when l write to the serial port l use

ser.write(bytes(Vcorrt.encode('ascii')))

Where vcorrt = ":Mgn1000" for example

Daveawalker
Posts: 20
Joined: Fri Apr 26, 2013 3:26 pm

Re: Python3 Serial issue on rpi

Mon Jul 01, 2013 10:00 am

works on Python3 as well! Thanks

Return to “Python”