Python Forum

Full Version: Python3 to Arduino
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi. My first post on here.
 I am trying to send - receive Python3 <> Arduino.
I had this working with Python2.7 now would like to convert to Pyhon3.
python2.7 code that worked.
    ser.write('<')
    ser.write(RorD)
    ser.write('>')
python3 code
    ser.write(bytes(b'<'))
    ser.write(b'RorD')
    ser.write(bytes(b'>'))
I think the Arduino is now receiving b'<'
RorB is a int.

Arduino snip

char startMarker = '<';
char endMarker = '>';

How can I send just '<'
Thanks for any help.
Hope I used the python tag right.
(Oct-24-2016, 05:39 PM)metulburr Wrote: [ -> ]Are you sending it over the net?
http://pythoncentral.io/encoding-and-dec...ython-3-x/

Thanks for the link, that could help a lot.
The Arduino will be plugged in to an EEEPC (USB) to control a rotatory table on my lathe.
From what I gather from the pySerial docs (I presume that's what your using), in Python 3, you have to convert to 'bytes' type.

So this is the correct format

ser.write(b'RorD')
Are you receiving an error? If so, is it coming from Python or the Arduino?
There is problem if you do this b'RorD' is now not a int.
Convert to Python 3.x Unicode string it will just be string 'RorD'
>>> s = b'RorD'
>>> type(s)
<class 'bytes'>
>>> s = s.decode('utf-8')
>>> type(s)
<class 'str'>
>>> s
'RorD'
When sending data to Arduino, they have to be converted to bytes. This can be done by prefixing the string with b:

So can look at RorD as integer.
>>> RorD = 100
>>> n = (RorD).to_bytes(2, byteorder='big')
>>> n
b'\x00d'
>>> # Back to int in Python 3
>>> int.from_bytes(n, byteorder='big')
100
for < is okay to use b'<'.
Back to string in Python 3 use decode(utf-8).
>>> s = b'<'
>>> s
b'<'
>>> type(s)
<class 'bytes'>
>>> s = s.decode('utf-8')
>>> s
'<'
>>> type(s)
<class 'str'>
Thanks snippsat, metulburr and sparkz_alot.
You have been a great help. I can now see how to send from Python3.
Many thanks.