A material on the basics of interaction between Arduino boards and the Python programming language.
Introduction
Almost all projects that you have to work on need to be able to communicate with the Arduino and, fortunately, it can communicate via a serial port.
What’s more interesting is that almost any programming language can be used for serial communication, but Python seems to be the simplest and most accessible at the moment. Its popularity and clarity attracts more and more new followers.
In the beginning, you may have some difficulties with how Arduino and Python interact, but hopefully this material will explain the basics to anyone looking to start using the serial functions that Arduino provides.
I also assume that since you are reading this post, you have some knowledge about how Arduino works, how to upload sketches, and the like. If not, you can take my Arduino for Beginners course. But anyway, I will explain below the Arduino and Python code which is quite simple. The program itself is not as difficult to understand as understanding how serial communication works.
Below we will analyze how to make an Arduino LED blink using a computer. I hope this knowledge will allow you to further extend the Python code and Arduino code for your own projects.
Installing Python and Libraries
Obviously, we need Python on our computer if we want to do something. If you do not have Python installed, then you need to go to the python official website and download: python.org (link). You will most likely download a file with the extension .exe… Run the file and go through all the necessary installation steps. It’s very simple.
Once we have Python installed, you need a new additional library called PySerial… This library will provide all the functions and methods that we need to communicate with our Arduino.
PySerial link
Also you can look at GitHub:
- library: https://github.com/pyserial/pyserial
- documentation: https://pyserial.readthedocs.org/en/latest/
For installation, we use the built-in package manager pip:
pip install pyserial
Another option for an earlier version – after you download Python, open Terminal and type:
tar xfvz /Users/*Account*/Downloads/pyserial-2.6.tar.gz cd pyserial-2.6 sudo python setup.py install
To make sure everything is installed correctly, open Idle and type: Import Serial… If there are no mistakes, then everything is fine.
You can check the available ports this way:
ls /dev/tty.*
Follow the links above to find documentation on working with the library in Windows, macOS, Linux. If you are using Eclipse, the Eclipse Python add-on may come in handy if you want to program in the Eclipse environment. Now that everything is installed, we can start writing our Python program.
Python code
We can now start programming. Also below we will analyze the program code in more detail.
import serial connected = False ser = serial.Serial("COM11", 9600) while not connected: serin = ser.read() connected = True ser.write("1") while ser.read() == '1': ser.read() ser.close()
To actually use the methods PySerial, we need to import the serial library before we try to use it, which is what we do in the first line of the program.
Next, I declare a variable that will act as a flag when the Arduino’s serial connection is opened. We won’t try to send anything to the Arduino until the board sends something to us.
Then we initialize the sequential variable serwhich will communicate with the Arduino. Two parameters are sent when the serial variable is initialized.
First, you must specify the port on which we will communicate (in my case, this is COM11, but in your case it may be different). To find out which port your Arduino is using, connect it to your computer and open the device manager. The Arduino IDE will also tell you which port it is using.
The second parameter sent is the baud rate. The baud rate is the rate at which the serial controller will send and receive data. The important thing is that the baud rate should match the baud rate you use in your Arduino sketch. I chose 9600 because this is an average speed and in our example there is no urgent need for high speed.
Next, we use a write function that sends the number 1 to the Arduino to make the LED flash. The board will blink twice.
Next, we wait for the Arduino to tell us that it blinked twice. The while loop will run until it receives a message. When we receive a message from the Arduino, we can close the serial port and complete the program. So that’s all we need for a Python program, just 10 lines of code.
Important! You should always remember to close the serial port when you are done using ser.close ()…
There is another example of Python code. Look at it yourself and try to figure it out:
from time import sleep import serial ser = serial.Serial('/dev/tty.usbmodem1d11', 9600) counter = 32 while True: counter +=1 ser.write(str(chr(counter))) print ser.readline() sleep(.1) if counter == 255: counter = 32
For the second example of Python code below, I will provide the corresponding code for the Arduino program.
In the second example, you also need to keep two main points in mind. You need to determine which serial port your Arduino is connected to. Whatever it is, it must be quoted on line 3 of the Python program.
You can also change the baud rate in line 3 of the Python program and line 2 of the Arduino program, if they do not change.
After running the program, it will output most of the ASCII characters, first sending them to the Arduino, which in turn will send them back to the computer, which will then output Python.
Arduino sketch
Arduino sketch for the first example with LED below:
void setup(){ Serial.begin(9600); pinMode(13, OUTPUT); Serial.write('1'); } void loop(){ if(Serial.available() > 0){ digitalWrite(13, HIGH); delay(500); digitalWrite(13, LOW); delay(500); digitalWrite(13, HIGH); delay(500); digitalWrite(13, LOW); Serial.write('0'); } }
I initially assume you have the Arduino software installed and running. Since we just want to blink the LED, we can just use the LED of the Arduino board or connect the LED to pin 13 and ground.
AT void setup () we run the serial monitor at 9600 baud. The baud rate doesn’t matter, just make sure it matches the baud rate in your Python program.
Then we create the output pin that the LED is connected to. Finally, we write to the serial port so that the Python program knows that we are ready.
AT void loop () we have one big conditional expression if… The bottom line is waiting for the moment when the python program will send something over the serial port. When the Arduino receives something, the LED will blink twice.
After two blinks, the Arduino sends a message that the board has stopped blinking. The Python program will see this and then stop.
For the second option, our Arduino sketch will look like this:
void setup() { Serial.begin(9600); Serial.println("Ready"); } void loop() { char inByte=" "; if(Serial.available()){ char inByte = Serial.read(); Serial.println(inByte); } delay(100);
Upload the sketch to your board and run the Python program. If done correctly, you should see the LED from the first example blinking. Next, for experiment, you can try adding another LED and making them alternate. That’s all. Good projects to you.