serial Communication Arduino and python

KPH's picture
KPH

Offline

Joined: Oct 29, 2018

Replies: 0
serial Communication Arduino and python
October 29, 2018 - 9:28am

How to Serially write in python 3 ?

can we continuously read and write from python and arduino    ?

Jayant's picture

Offline

Joined: May 19, 2015

Replies: 187
Use pySerial with prefix 'b'
October 30, 2018 - 11:41am

Communicating between Arduino and Python 2 and Python 3 is almost similar. 

The concept is to establish a serial communication between Arduino and Python. Arduino being a Microcontroller Development Board has a USART for Serial communication so you can directly use Serial.write() function to write from Arduino to Python.

Whereas for python to understand or send/receive Serial data we need use an external library called "PySerial". You can follow the below tutorial to learn how to use pySerial to communicate between Arduino and Python

https://circuitdigest.com/microcontroller-projects/arduino-python-tutorial

 

The tutorial uses Python 2.0, the only major change between python 2.0 and Python 3.0 is that in python 3.0 the strings are Unicode in nature so you have to change them to byte format before to send them to Arduino. This can be done by then prefixing 'b' before the data. For example to send the number 5 from Python to Arduino use the following code 

>>> import serial # if you have not already done so
>>> ser = serial.Serial('/dev/tty.usbserial', 9600)
>>> ser.write(b'5')

Hope this helps