Language: EN

controlar-arduino-con-python-y-la-libreria-pyserial

Controlling Arduino with Python and the PySerial library

Python is one of the most popular programming languages in recent times. Its ease of use allows for quickly creating small programs and scripts with very short development times.

This simplicity has made Python carve out a niche in the Internet of Things (IoT), where it stands out for its ease of communication with different devices (computers, tablets, smartphones), both by cable, Bluetooth, or the Internet.

Of course, the world of Arduino is no exception and connecting Arduino with Python is very simple, using the serial port and the PySerial library.

In this post, we will see how to connect Arduino with Python and the PySerial library, to use it in our electronics, robotics, and IoT projects.

Serial port communication can be done both by cable and wirelessly via Bluetooth, as we saw in the post Connect Arduino by Bluetooth with HC-05 or HC-06 modules.

For this post, we will use the Arduino port. If you are not familiar with the serial port, you can read the post Arduino communication with the serial port.

Install Python and PySerial

The first thing we need is to have Python installed on our device. If you haven’t started with Python yet, you can refer to the post Our first program in Python, where we saw how to install Python on Windows and Linux, and some basic examples to introduce its use.

Once we have Python installed to be able to communicate with Arduino, we need the PySerial library, which allows us to use the serial port easily. The PySerial library is available at this link https://github.com/pyserial/pyserial

We download and run the installer to add the PySerial library to our Python installation.

We can also install the PySerial library directly from Python by typing the following command from a console.

python -m pip install PySerial

With either of the two methods, we will have the PySerial library installed and ready to be used in our projects.

Code examples

Next, we will see a couple of simple examples to start testing and using the PySerial library with Arduino.

Receive information from Arduino

In this first example, we are going to read information sent by Arduino and captured and displayed on the screen by Python.

For this, we start by loading the following sketch into Arduino, which simply continuously sends the text “Hello World” once per second.

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

void loop() {
Serial.println("Hello world");
delay(1000);
}

We leave the sketch running on Arduino, and then we create a new empty text file, which we save with the name “read.py”. Inside it, we copy the following code.

import serial, time
arduino = serial.Serial('COM4', 9600)
time.sleep(2)
rawString = arduino.readline()
print(rawString)
arduino.close()

What we do is import the Serial library (PySerial) and instantiate a Serial object, which we have called “arduino”. In the constructor of the Serial object, we pass the parameters of the serial port we are using.

Remember to replace the serial port in the code, in the example “COM4”, with the serial port where you have Arduino connected.

Next, we use the “readline()” command of the Serial object to read a line sent by Arduino. We show the line on the screen using the “Print()” command.

Finally, we close the serial port using the “close()” command.

As we can see, using the serial port with PySerial is really simple. The only thing that may seem strange is why we had to import the “time” library.

The reason is that from when we create the Serial object until it is actually available to be used, a certain amount of time is needed to open the serial port. Therefore, we have to introduce a delay using the “Sleep” function, which belongs to the “time” library.

Send information to Arduino

In this second example, we are going to send data to Arduino from Python. For this, we are going to use the following sketch that we saw in the post Arduino communication with the serial port.

This sketch receives a number from 1 to 9 and blinks the built-in LED, connected to PIN13, the number of times received. We load the sketch on Arduino, and just like before, we leave it running.

const int pinLED = 13;

void setup() 
{
  Serial.begin(9600);
  pinMode(pinLED, OUTPUT);
}

void loop()
{
  if (Serial.available()>0) 
  {
    char option = Serial.read();
    if (option >= '1' && option <= '9')
    {
      option -= '0';
      for (int i = 0;i<option;i++) 
      {
        digitalWrite(pinLED, HIGH);
        delay(100);
        digitalWrite(pinLED, LOW);
        delay(200);
      }
    }
  }
}

In the Python part, we will need a new script that we will call, for example, “write.py”. Inside it, we paste the following code.

import serial, time
arduino = serial.Serial("COM4", 9600)
time.sleep(2)
arduino.write(b'9')
arduino.close()

As we can see, writing is very similar to reading. First, we import the PySerial library and create a new object of type Serial, indicating the values of the serial port we are using.

This time, we write the value using the “write” function (in the example, 9). The “Write” function sends bytes, so it is necessary to convert the value to bytes by preceding a b to the sent value (in the example b’9’).

Finally, we close the serial port with the “close()” function.

Once again, we had to import the time library in order to use the Sleep function and give some time between the start of the serial port connection and the data transmission.

With this, we already have the basic functions to send and receive information to Arduino from Python, using the PySerial library to control the serial port. It is easy to integrate these functions into our programs.

Download the code

All the code in this post is available for download on Github. github-full