Language: EN

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

Controlling Arduino with Python and the PySerial library

Python is one of the programming languages that has experienced considerable growth in recent times. Its ease of use allows for the rapid creation of 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), whether by cable, Bluetooth, or the Internet.

Of course, the world of Arduino is no exception, and it is very easy to connect Arduino with Python, using the serial port and the PySerial library.

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

Communication via the serial port can be done both wired and wirelessly via Bluetooth, as we saw in the entry Connect Arduino via Bluetooth with HC-05 or HC-06 modules.

For this entry, we will use the Arduino port. If you are not yet familiar with the serial port, you can read the entry Arduino Communication with Serial Port.

Install Python and PySerial

The first thing we need is to have Python installed on our device. If you are new to Python, you can check the entry Our first program in Python where we saw how to install Python on Windows and Linux, along with some basic examples to introduce its use.

Once we have Python installed, to communicate with Arduino we need the PySerial library, which allows us to easily use the serial port. 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 in a console.

python -m pip install PySerial

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

Code Examples

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

Receive Information from Arduino

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

To do this, we start by uploading the following sketch to Arduino, which simply continuously sends the text “Hello World” once per second.

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

void loop() {
Serial.println("Hola mundo");
delay(1000);
}

We leave the sketch running on Arduino, and we will create the script in Python. 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 PySerial 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 to which Arduino is connected.

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

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

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

The reason is that from the moment we create the Serial object until it is actually available for use, a certain amount of time is needed to open the serial port. Therefore, we need to introduce a wait using the “Sleep” function, which belongs to the “time” library.

Send Information to Arduino

In this second example, we will send data to Arduino from Python. To do this, we are going to use the following sketch that we saw in the entry Arduino Communication with Serial Port.

This sketch receives a number from 1 to 9 and makes the built-in LED, connected to PIN13, blink the number of times received. We upload the sketch to 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, the writing is very similar to the reading. First, we import the PySerial library and create a new Serial object, indicating the values of the serial port we are using.

This time, we write the value using the “write” function (in this 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 this example b’9’).

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

Again, we had to import the time library to be able to use the Sleep function and provide a delay between the start of the serial port connection and the data sending.

With this, we now 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 from this entry is available for download on Github. github-full