How to connect Arduino and Python

Example, how to send a message from Arduino to a Python-program

Arduino code:

void setup() {
	Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}

void loop() {
	Serial.println("Hello, it'a Ardunio!"); //send message
	delay(5000);
}

In Python we use pyserial library

In the examples in this library, the following is used to open the port:

ser = serial.Serial('/dev/ttyUSB0')

but I had no success with such type to the port open. To find in Linux, that name is used as serial-port name need run command:

$ ls /dev/serial/by-id/

the output will be something like:

usb-1a86_USB2.0-Serial-if00-port0 

Python-code will look so:

import serial
arduino = serial.Serial('/dev/serial/by-id/usb-1a86_USB2.0-Serial-if00-port0', 9600, timeout=.1)

while True:
    data = arduino.readline()[:-3] #the last bit gets rid of the new-line chars
    if data:
        print (data)

Load the firmware on Arduino and run our python script. We can see the following in the terminal:

Now send a message from Python to Arduino

Arduino code:

void setup() {
    Serial.begin(9600);
}

void loop() {
	if(Serial.available() > 0) {
		char data = Serial.read();
		char str[2];
		str[0] = data;
		str[1] = '\0';
		Serial.print(str);
	}
}

Python-code:

import serial, time
arduino = serial.Serial('/dev/serial/by-id/usb-1a86_USB2.0-Serial-if00-port0', 9600, timeout=.1)
time.sleep(1) #give to the connection a second

while True:
    arduino.write(str.encode('Hello from Python!' + '\n'))
    time.sleep(10)

Now open Serial Monitor in Arduino IDE and there we can see:

There is 1 comment below.

Post your comment


  • March 31, 2021, 5:52 a.m. - HP_riya  
    I'm not able to send a message from Python to Arduino. Nothing is displayed in my arduino serial monitor.
    Reply
  • Search
    Popular Posts
    Subscribe
    {{post}}