How to read from serial port?

Grant Edwards grant.b.edwards at gmail.com
Tue Apr 26 14:29:53 EDT 2016


On 2016年04月26日, David Aldrich <David.Aldrich at EMEA.NEC.COM> wrote:
> #!/usr/bin/python3
> import serial
>> ser=serial.Serial('COM1',115200)
> while True:
> out = ser.read()
> print('Receiving...'+out)
>> When I run it and send data for it to read I get:

> Traceback (most recent call last):
> File "serial_read.py", line 9, in <module>
> print('Receiving...'+out)
> TypeError: Can't convert 'bytes' object to str implicitly

Try this:
 print('Receiving...',out)
If you want to convert the bytes you read from the serial port into a
string, you need to decode they bytes (and you have to specify what
encoding to use):
 print('Receiving...' + out.decode('ascii'))
If you google 'Python 3 bytes strings' you should find a bunch of info:
https://docs.python.org/3.5/library/stdtypes.html
http://www.diveintopython3.net/strings.html
http://pythoncentral.io/encoding-and-decoding-strings-in-python-3-x/
https://www.safaribooksonline.com/library/view/fluent-python/9781491946237/ch04.html
-- 
Grant Edwards grant.b.edwards Yow! I haven't been married
 at in over six years, but we
 gmail.com had sexual counseling every
 day from Oral Roberts!!


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /