Arduino With Python How to Get Started – Real Py…
Arduino With Python How to Get Started – Real Py…
Python Tricks
Email…
Browse Topics
Mark as Completed Tweet Share Email
Guided Learning Paths
Basics Intermediate
You’ll cover the basics of Arduino with Python and learn how to:
Recommended Video Course
With the growing popularity of the Maker Movement and the concept of the
Internet of Things, Arduino has become one of the main platforms for electronic
prototyping and the development of MVPs.
Arduino uses its own programming language, which is similar to C++ . However,
it’s possible to use Arduino with Python or another high-level programming
language. In fact, platforms like Arduino work well with Python, especially for
applications that require integration with sensors and other physical devices.
All in all, Arduino and Python can facilitate an e"ective learning environment that
encourages developers to get into electronics design. If you already know the
basics of Python, then you’ll be able to get started with Arduino by using Python
to control it.
The Arduino platform includes both hardware and so!ware products. In this
tutorial, you’ll use Arduino hardware and Python so!ware to learn about basic
circuits, as well as digital and analog inputs and outputs.
Remove ads
Arduino Hardware
To run the examples, you’ll need to assemble the circuits by hooking up
electronic components. You can generally find these items at electronic
component stores or in good Arduino starter kits. You’ll need:
Components 5 and 6 are resistors. Most resistors are identified by colored stripes
according to a color code. In general, the first three colors represent the value of
a resistor, while the fourth color represents its tolerance. For a 470 Ohm resistor,
the first three colors are yellow, violet, and brown. For a 10 KOhm resistor, the
first three colors are brown, black, and orange.
Arduino So!ware
In addition to these hardware components, you’ll need to install some so!ware.
The platform includes the Arduino IDE, an Integrated Development Environment
for programming Arduino devices, among other online tools.
Arduino was designed to allow you to program the boards with little di"iculty. In
general, you’ll follow these steps:
To install the Arduino IDE on your computer, download the appropriate version
for your operating system from the Arduino website. Check the documentation
for installation instructions:
If you’re using Windows, then use the Windows installer to ensure you
download the necessary drivers for using Arduino on Windows. Check the
Arduino documentation for more details.
If you’re using Linux, then you may have to add your user to some groups
in order to use the serial port to program Arduino. This process is described
in the Arduino install guide for Linux.
If you’re using macOS, then you can install Arduino IDE by following the
Arduino install guide for OS X.
Note: You’ll be using the Arduino IDE in this tutorial, but Arduino also
provides a web editor that will let you program Arduino boards using the
browser.
Now that you’ve installed the Arduino IDE and gathered all the necessary
components, you’re ready to get started with Arduino! Next, you’ll upload a
“Hello, World!” program to your board.
The Blink example code will be loaded into a new IDE window. But before you can
upload the sketch to the board, you’ll need to configure the IDE by selecting your
board and its connected port.
To configure the board, access the Tools menu and then Board. For Arduino Uno,
you should select Arduino/Genuino Uno:
A!er you select the board, you have to set the appropriate port. Access the Tools
menu again, and this time select Port:
The names of the ports may be di"erent, depending on your operating system. In
Windows, the ports will be named COM4, COM5, or something similar. In macOS or
Linux, you may see something like /dev/ttyACM0 or /dev/ttyUSB0. If you have
any problems setting the port, then take a look at the Arduino Troubleshooting
Page.
A!er you’ve configured the board and port, you’re all set to upload the sketch to
your Arduino. To do that, you just have to press the Upload button in the IDE
toolbar:
When you press Upload, the IDE compiles the sketch and uploads it to your board.
If you want to check for errors, then you can press Verify before Upload, which will
only compile your sketch.
The USB cable provides a serial connection to both upload the program and
power the Arduino board. During the upload, you’ll see LEDs flashing on the
board. A!er a few seconds, the uploaded program will run, and you’ll see an LED
light blink once every second:
A!er the upload is finished, the USB cable will continue to power the Arduino
board. The program is stored in flash memory on the Arduino microcontroller.
You can also use a battery or other external power supply to run the application
without a USB cable.
Remove ads
Although these connections are commonly called pins, you can see that they’re
not exactly physical pins. Rather, the pins are holes in a socket to which you can
connect jumper wires. In the figure above, you can see di"erent groups of pins:
Orange rectangle: These are 13 digital pins that you can use as inputs or
outputs. They’re only meant to work with digital signals, which have 2
di"erent levels:
1. Level 0: represented by the voltage 0V
2. Level 1: represented by the voltage 5V
Green rectangle: These are 6 analog pins that you can use as analog
inputs. They’re meant to work with an arbitrary voltage between 0V and 5V.
Blue rectangle: These are 5 power pins. They’re mainly used for powering
external components.
To get started using external components, you’ll connect an external LED to run
the Blink example sketch. The built-in LED is connected to digital pin #13. So,
let’s connect an external LED to that pin and check if it blinks. (A standard LED is
one of the components you saw listed earlier.)
Before you connect anything to the Arduino board, it’s good practice to
disconnect it from the computer. With the USB cable unplugged, you’ll be able to
connect the LED to your board:
Note that the figure shows the board with the digital pins now facing you.
Using a Breadboard
Electronic circuit projects usually involve testing several ideas, with you adding
new components and making adjustments as you go. However, it can be tricky to
connect components directly, especially if the circuit is large.
You can see which holes are interconnected by looking at the colored lines. You’ll
use the holes on the sides of the breadboard to power the circuit:
Then, you can easily connect components to the power source or the ground by
simply using the other holes on the red and blue lines. The holes in the middle of
the breadboard are connected as indicated by the colors. You’ll use these to make
connections between the components of the circuit. These two internal sections
are separated by a small depression, over which you can connect integrated
circuits (ICs).
You can use a breadboard to assemble the circuit used in the Blink example
sketch:
For this circuit, it’s important to note that the LED must be connected according
to its polarity or it won’t work. The positive terminal of the LED is called the
anode and is generally the longer one. The negative terminal is called the
cathode and is shorter. If you’re using a recovered component, then you can also
identify the terminals by looking for a flat side on the LED itself. This will indicate
the position of the negative terminal.
When you connect an LED to an Arduino pin, you’ll always need a resistor to limit
its current and avoid burning out the LED prematurely. Here, you use a 470 Ohm
resistor to do this. You can follow the connections and check that the circuit is the
same:
A!er you finish the connection, plug the Arduino back into the PC and re-run the
Blink sketch:
As both LEDs are connected to digital pin 13, they blink together when the sketch
is running.
Remove ads
However, there are some approaches you can take to use Arduino with Python or
other languages. One idea is to run the main program on a PC and use the serial
connection to communicate with Arduino through the USB cable. The sketch
would be responsible for reading the inputs, sending the information to the PC,
and getting updates from the PC to update the Arduino outputs.
To control Arduino from the PC, you’d have to design a protocol for the
communication between the PC and Arduino. For example, you could consider a
protocol with messages like the following:
VALUE OF PIN 13 IS HIGH: used to tell the PC about the status of digital
input pins
SET PIN 11 LOW: used to tell Arduino to set the states of the output pins
With the protocol defined, you could write an Arduino sketch to send messages to
the PC and update the states of the pins according to the protocol. On the PC, you
could write a program to control the Arduino through a serial connection, based
on the protocol you’ve designed. For this, you can use whatever language and
libraries you prefer, such as Python and the PySerial library.
Fortunately, there are standard protocols to do all this! Firmata is one of them.
This protocol establishes a serial communication format that allows you to read
digital and analog inputs, as well as send information to digital and analog
outputs.
The Arduino IDE includes ready-made sketches that will drive Arduino through
Python with the Firmata protocol. On the PC side, there are implementations of
the protocol in several languages, including Python. To get started with Firmata,
let’s use it to implement a “Hello, World!” program.
The sketch will be loaded into a new IDE window. To upload it to the Arduino, you
can follow the same steps you did before:
A!er the upload is finished, you won’t notice any activity on the Arduino. To
control it, you still need a program that can communicate with the board through
the serial connection. To work with the Firmata protocol in Python, you’ll need
the pyFirmata package, which you can install with pip:
Shell
A!er the installation finishes, you can run an equivalent Blink application using
Python and Firmata:
Python
1 import pyfirmata
2 import time
3
4 board = pyfirmata.Arduino('/dev/ttyACM0')
5
6 while True:
7 board.digital[13].write(1)
8 time.sleep(1)
9 board.digital[13].write(0)
10 time.sleep(1)
Here’s how this program works. You import pyfirmata and use it to establish a
serial connection with the Arduino board, which is represented by the board
object in line 4. You also configure the port in this line by passing an argument to
pyfirmata.Arduino(). You can use the Arduino IDE to find the port.
board.digital is a list whose elements represent the digital pins of the Arduino.
These elements have the methods read() and write(), which will read and write
the state of the pins. Like most embedded device programs, this program mainly
consists of an infinite loop:
In line 7, digital pin 13 is turned on, which turns the LED on for one second.
In line 9, this pin is turned o", which turns the LED o" for one second.
Now that you know the basics of how to control an Arduino with Python, let’s go
through some applications to interact with its inputs and outputs.
Remove ads
0 Low 0V
1 High 5V
To control the LED, you’ll use a push button to send digital input values to the
Arduino. The button should send 0V to the board when it’s released and 5V to the
board when it’s pressed. The figure below shows how to connect the button to
the Arduino board:
You may notice that the LED is connected to the Arduino on digital pin 13, just like
before. Digital pin 10 is used as a digital input. To connect the push button, you
have to use the 10 KOhm resistor, which acts as a pull down in this circuit. A pull
down resistor ensures that the digital input gets 0V when the button is released.
When you release the button, you open the connection between the two wires on
the button. Since there’s no current flowing through the resistor, pin 10 just
connects to the ground (GND). The digital input gets 0V, which represents the 0
(or low) state. When you press the button, you apply 5V to both the resistor and
the digital input. A current flows through the resistor and the digital input gets 5V,
which represents the 1 (or high) state.
Now that you’ve assembled the circuit, you have to run a program on the PC to
control it using Firmata. This program will turn on the LED, based on the state of
the push button:
Python
1 import pyfirmata
2 import time
3
4 board = pyfirmata.Arduino('/dev/ttyACM0')
5
6 it = pyfirmata.util.Iterator(board)
7 it.start()
8
9 board.digital[10].mode = pyfirmata.INPUT
10
11 while True:
12 sw = board.digital[10].read()
13 if sw is True:
14 board.digital[13].write(1)
15 else:
16 board.digital[13].write(0)
17 time.sleep(0.1)
pyfirmata also o"ers a more compact syntax to work with input and output pins.
This may be a good option for when you’re working with several pins. You can
rewrite the previous program to have more compact syntax:
Python
1 import pyfirmata
2 import time
3
4 board = pyfirmata.Arduino('/dev/ttyACM0')
5
6 it = pyfirmata.util.Iterator(board)
7 it.start()
8
9 digital_input = board.get_pin('d:10:i')
10 led = board.get_pin('d:13:o')
11
12 while True:
13 sw = digital_input.read()
14 if sw is True:
15 led.write(1)
16 else:
17 led.write(0)
18 time.sleep(0.1)
Since digital_input is a digital input using pin 10, you pass the argument
'd:10:i'. The LED state is set to a digital output using pin 13, so the led
argument is 'd:13:o'.
Digital inputs are widely used in electronics projects. Several sensors provide
digital signals, like presence or door sensors, that can be used as inputs to your
circuits. However, there are some cases where you’ll need to measure analog
values, such as distance or physical quantities. In the next section, you’ll see how
to read analog inputs using Arduino with Python.
Remove ads
The voltage range for an analog input is encoded to numbers ranging from 0 to
1023. When 0V is applied, the Arduino encodes it to the number 0. When 5V is
applied, the encoded number is 1023. All intermediate voltage values are
proportionally encoded.
A potentiometer is a variable resistor that you can use to set the voltage applied
to an Arduino analog input. You’ll connect it to an analog input to control the
frequency of a blinking LED:
In this circuit, the LED is set up just as before. The end terminals of the
potentiometer are connected to ground (GND) and 5V pins. This way, the central
terminal (the cursor) can have any voltage in the 0V to 5V range depending on its
position, which is connected to the Arduino on analog pin A0.
Before you control the LED, you can use the circuit to check the di"erent values
the Arduino reads, based on the position of the potentiometer. To do this, run the
following program on your PC:
Python
1 import pyfirmata
2 import time
3
4 board = pyfirmata.Arduino('/dev/ttyACM0')
5 it = pyfirmata.util.Iterator(board)
6 it.start()
7
8 analog_input = board.get_pin('a:0:i')
9
10 while True:
11 analog_value = analog_input.read()
12 print(analog_value)
13 time.sleep(0.1)
In line 8, you set up analog_input as the analog A0 input pin with the argument
'a:0:i'. Inside the infinite while loop, you read this value, store it in
analog_value, and display the output to the console with print(). When you
move the potentiometer while the program runs, you should output similar to
this:
Shell
0.0
0.0293
0.1056
0.1838
0.2717
0.3705
0.4428
0.5064
0.5797
0.6315
0.6764
0.7243
0.7859
0.8446
0.9042
0.9677
1.0
1.0
The printed values change, ranging from 0 when the position of the
potentiometer is on one end to 1 when it’s on the other end. Note that these are
float values, which may require conversion depending on the application.
To change the frequency of the blinking LED, you can use the analog_value to
control how long the LED will be kept on or o":
Python
1 import pyfirmata
2 import time
3
4 board = pyfirmata.Arduino('/dev/ttyACM0')
5 it = pyfirmata.util.Iterator(board)
6 it.start()
7
8 analog_input = board.get_pin('a:0:i')
9 led = board.get_pin('d:13:o')
10
11 while True:
12 analog_value = analog_input.read()
13 if analog_value is not None:
14 delay = analog_value + 0.01
15 led.write(1)
16 time.sleep(delay)
17 led.write(0)
18 time.sleep(delay)
19 else:
20 time.sleep(0.1)
Here, you calculate delay as analog_value + 0.01 to avoid having delay equal
to zero. Otherwise, it’s common to get an analog_value of None during the first
few iterations. To avoid getting an error when running the program, you use a
conditional in line 13 to test whether analog_value is None. Then you control the
period of the blinking LED.
Try running the program and changing the position of the potentiometer. You’ll
notice the frequency of the blinking LED changes:
By now, you’ve seen how to use digital inputs, digital outputs, and analog inputs
on your circuits. In the next section, you’ll see how to use analog outputs.
Remove ads
Not all Arduino digital pins can be used as PWM outputs. The ones that can be are
identified by a tilde (~):
When a PWM signal is applied to an LED, its brightness varies according to the
duty cycle of the PWM signal. You’re going to use the following circuit:
This circuit is identical to the one used in the previous section to test the analog
input, except for one di"erence. Since it’s not possible to use PWM with pin 13,
the digital output pin used for the LED is pin 11.
With the circuit assembled, you can control the LED using PWM with the following
program:
Python
1 import pyfirmata
2 import time
3
4 board = pyfirmata.Arduino('/dev/ttyACM0')
5
6 it = pyfirmata.util.Iterator(board)
7 it.start()
8
9 analog_input = board.get_pin('a:0:i')
10 led = board.get_pin('d:11:p')
11
12 while True:
13 analog_value = analog_input.read()
14 if analog_value is not None:
15 led.write(analog_value)
16 time.sleep(0.1)
There are a few di"erences from the programs you’ve used previously:
1. In line 10, you set led to PWM mode by passing the argument 'd:11:p'.
2. In line 15, you call led.write() with analog_value as an argument. This is
a value between 0 and 1, read from the analog input.
Here you can see the LED behavior when the potentiometer is moved:
To show the changes in the duty cycle, an oscilloscope is plugged into pin 11.
When the potentiometer is in its zero position, you can see the LED is turned o",
as pin 11 has 0V on its output. As you turn the potentiometer, the LED gets
brighter as the PWM duty cycle increases. When you turn the potentiometer all
the way, the duty cycle reaches 100%. The LED is turned on continuously at
maximum brightness.
With this example, you’ve covered the basics of using an Arduino and its digital
and analog inputs and outputs. In the next section, you’ll see an application for
using Arduino with Python to drive events on the PC.
In this section, you’ll use a push button connected to your Arduino to mimic a
digital sensor and trigger a notification on your machine. For a more practical
application, you can think of the push button as a door sensor that will trigger an
alarm notification, for example.
To display the notification on the PC, you’re going to use Tkinter, the standard
Python GUI toolkit. This will show a message box when you press the button. For
an in-depth intro to Tkinter, check out Python GUI Programming With Tkinter.
You’ll need to assemble the same circuit that you used in the digital input
example:
A!er you assemble the circuit, use the following program to trigger the
notifications:
Python
1 import pyfirmata
2 import time
3 import tkinter
4 from tkinter import messagebox
5
6 root = tkinter.Tk()
7 root.withdraw()
8
9 board = pyfirmata.Arduino('/dev/ttyACM0')
10
11 it = pyfirmata.util.Iterator(board)
12 it.start()
13
14 digital_input = board.get_pin('d:10:i')
15 led = board.get_pin('d:13:o')
16
17 while True:
18 sw = digital_input.read()
19 if sw is True:
20 led.write(1)
21 messagebox.showinfo("Notification", "Button was pressed")
22 root.update()
23 led.write(0)
24 time.sleep(0.1)
This program is similar to the one used in the digital input example, with a few
changes:
2. The loop pauses until the user presses OK. This way, the LED remains
on as long as the message is on the screen.
3. A!er the user presses OK, root.update() clears the message box from
the screen and the LED is turned o".
To extend the notification example, you could even use the push button to send
an email when pressed:
Python
1 import pyfirmata
2 import time
3 import smtplib
4 import ssl
5
6 def send_email():
7 port = 465 # For SSL
8 smtp_server = "smtp.gmail.com"
9 sender_email = "<your email address>"
10 receiver_email = "<destination email address>"
11 password = "<password>"
12 message = """Subject: Arduino Notification\n The switch was turned on."""
13
14 context = ssl.create_default_context()
15 with smtplib.SMTP_SSL(smtp_server, port, context=context) as server
16 print("Sending email")
17 server.login(sender_email, password)
18 server.sendmail(sender_email, receiver_email, message)
19
20 board = pyfirmata.Arduino('/dev/ttyACM0')
21
22 it = pyfirmata.util.Iterator(board)
23 it.start()
24
25 digital_input = board.get_pin('d:10:i')
26
27 while True:
28 sw = digital_input.read()
29 if sw is True:
30 send_email()
31 time.sleep(0.1)
You can learn more about send_email() in Sending Emails With Python. Here,
you configure the function with email server credentials, which will be used to
send the email.
Note: If you use a Gmail account to send the emails, then you need to
enable the Allow less secure apps option. For more information on how to
do this, check out Sending Emails With Python.
With these example applications, you’ve seen how to use Firmata to interact with
more complex Python applications. Firmata lets you use any sensor attached to
the Arduino to obtain data for your application. Then you can process the data
and make decisions within the main application. You can even use Firmata to
send data to Arduino outputs, controlling switches or PWM devices.
A temperature monitor to alert you when the temperature gets too high or
low
An analog light sensor that can sense when a light bulb is burned out
A water sensor that can automatically turn on the sprinklers when the
ground is too dry
Remove ads
Conclusion
Microcontroller platforms are on the rise, thanks to the growing popularity of the
Maker Movement and the Internet of Things. Platforms like Arduino are receiving
a lot of attention in particular, as they allow developers just like you to use their
skills and dive into electronic projects.
You also saw how Firmata may be a very interesting alternative for projects that
demand a PC and depend on sensor data. Plus, it’s an easy way to get started
with Arduino if you already know Python!
Further Reading
Now that you know the basics of controlling Arduino with Python, you can start
working on more complex applications. There are several tutorials that can help
you develop integrated projects. Here are a few ideas:
REST APIs: These are widely used to integrate di"erent applications. You
could use REST with Arduino to build APIs that get information from sensors
and send commands to actuators. To learn about REST APIs, check out
Python REST APIs With Flask, Connexion, and SQLAlchemy.
Threading: The infinite while loop that you used in this tutorial is a very
common feature of Arduino applications. However, using a thread to run the
main loop will allow you to execute other tasks concurrently. To learn how
to use threads, check out An Intro to Threading in Python.
Face Detection: It’s common for IoT apps to integrate machine learning and
computer vision algorithms. With these, you could build an alarm that
triggers a notification when it detects faces on a camera, for example. To
learn more about facial recognition systems, check out Traditional Face
Detection With Python.
Lastly, there are other ways of using Python in microcontrollers besides Firmata
and Arduino:
pySerial: Arduino Uno cannot run Python directly, but you could design
your own Arduino sketch and use pySerial to establish a serial connection.
Then you can control Arduino with Python using your own protocol.
Mark as Completed
Watch Now This tutorial has a related video course created by the Real
Python team. Watch it together with the written tutorial to deepen your
understanding: Arduino With Python: How to Get Started
Python Tricks
Email Address
Jon Joanna
What’s your #1 takeaway or favorite thing you learned? How are you going
to put your newfound skills to use? Leave a comment below and let us
know.
Commenting Tips: The most useful comments are those written with
the goal of learning from or helping out other students. Get tips for
asking good questions and get answers to common questions in our
support portal.
Keep Learning
Remove ads