en fr

Serial commincation made easy with Python

Posted on 2014-01-11 in Arduino - RPi - Robotique Last modified on: 2016-08-28

With Python, it is easy to communicate with USB from your computer to your Arduino card. I'll illustrate this with a small example: the card will send some text to the computer and then we are going to send a number, X, to the Arduino whose LED will blink X times.

Upload the code below to your Arduino card:

#define LED_PIN 13
void setup()
{
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop()
{
    Serial.println("Hi");
    Serial.println("I am your Arduino card");

    while(Serial.available()) {
         int lu = Serial.read();
        flash(lu);
    }
    delay(1000);
}

void flash(int n)
{
  for (int i = 0; i < n; i++)
  {
    digitalWrite(ledPin, HIGH);
    delay(1000);
    digitalWrite(ledPin, LOW);
    delay(1000);
  }
}

To read the data from the Arduino:

# Module to read/write on a serial port
from serial import *
# Sereial port: ACM0
# Speed: 9600
# Read timeout: 1 sec
# Write timeout: 1 sec
with Serial(port="/dev/ttyACM0", baudrate=9600, timeout=1, writeTimeout=1) as port_serie:
    if port_serie.isOpen():
        while True:
            ligne = port_serie.read_line()
            print ligne

To send data to the Arduino, in Python 2:

nombre = raw_input("Entrez un nombre : ")
port_serie.write([nombre])

Note: it is possible to send one or more numbers in a row trough the serial port since the function serial.write() takes a list of ints.

In Python 3:

nombre = input("Entrez un nombre : ")
port_serie.write(nombre.encode('ascii'))

The difference between Python 2 and Python 3 comes from the fact that in Python 3, network and serial transfer must be done with bytes. Likewise, the data you receive are of type bytes in Python 3 but of type str in Python 2.