Arduino has always been a powerful and an easy to use learning/developing platform when it comes to open source hardware development. In today’s modern world, every hardware is powered by a high-level general purpose programming language to make it more effective and user friendly. One such language is Python. Python is an interpreted, object-oriented, high-level programming language with dynamic semantics with high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development.

Combining the power of Arduino and Python will open doors to lots of possibilities since python has an increased productivity with its ability to interact with other platforms like openCV, Matlab etc.. So in this tutorial we will learn how we can install python on our computer and how to use it with Arduino for toggling the on-board LED of Arduino.

So, Let’s get started....

Materials Required:

Arduino Uno (or any Arduino Boards)

Computer with Internet connection

Installing Python on your Computer:

Obviously the first step in this tutorial would be installing Python on our computer. The steps mentioned below are applicable only for windows users running either 32-bit or 64-bit OS. The installation procedure for MAC and Linux is different.

Click on 32-bit Python-2.7.9 and this will install the 32-bit Python IDLE on your Computer. Do not download the 64-bit version or updated versions since they do not provide support for our Arduino Libraries. Even if your Computer is operating on 64-bit you can use 32-bit Python itself.

Open the downloaded exe file and follow through the instruction. Do not change the directory in which the python is getting installed. It will be C:\Python27 by default and leave it as such.

While the installation takes place you might get a warning from your anti-virus (if any) in that case click on allow.

That is it!, python is successfully installed on our computer. You can verify it by searching for “Python IDLE” in Windows search box and opening it.

When opened you should get the following screen. This window is called the Python Shell and we will refer to it as “Python shell” from now.

This screen is called the Python Shell. You can directly code in here and get the output on the same screen or create a new file and write the program there and verify the program here. We will later get into the details of creating a python program, for now let us check if python is working.

To do so, simply type “print (1+1)” and press enter. You should see the result getting printed as shown below.

Getting PySerial in Python:

The next step is to install pyserial. PySerial is a Python API module which is used to read and write serial data to Arduino or any other Microcontroller.

Click on Pyserial Windows to download PySerial. The resulting download will be a exe file which can be directly installed. Do not change any setting while installing. Leave it to the default directory and default settings.

Now, let us check if PySerial is installed properly. To do this, open Python Shell again and type in

import serial. If the library was successfully installed then you should not get any error messages as shown in the picture below. If you get any errors post them on the comment section and we will try resolving it.

This tutorial assumes that you are familiar with Arduino and have experience in uploading projects to Arduino. So let us directly jump into our Python program. If you are a beginner with Arduino check our Arduino Projects and start from LED Blinking with Arduino.

Our First Arduino Python Program:

As said earlier we will be controlling the in-built Arduino board LED using Python script. Let us start with the Arduino code.

Program for Arduino:

The complete program for this Arduino python tutorial is given at the end of this page. Read further to know how it works.

Inside the setup function we initialize the serial communication at 9600 baud rate and declare that we will be using the built in led as output and turn it low during program start. We have also sent a welcome message to python via serial print as shown below:

Inside the loop function, we read whatever the data that is coming in serially and assigning the value to the variable “data”. Now based on the value of this variable (“data”) we toggle the built in led as shown below.

The complete python program for this tutorial is given at the end of this page. Read further to know how to write and use the same.

Open your Python Shell (Python IDLE) and click File->New

This will open a new text file where you can type in your program.

Before we type anything lets save the file, by Ctrl+S. Type in any name and click on save. This will automatically save you file in “.py” extension.

Now, type in the program or paste the python code given at the end of this page. The explanation for the same is given below and finally run the program.

In our program the first step would be to import the serial and time library. The serial library as said earlier will be used to read and write serial data and the time library will be used to create delays in our program. These two libraries can be imported in our program using the following two lines:

The next step would be to initialize a serial object using our serial library. In this program we have named our serial object as “ArduinoSerial”. In this line we have to mention the name of the COM port to which our Arduino is connected and at what baud rate it is operating as shown below.

ArduinoSerial = serial.Serial('com18',9600)

Note: It is very important to mention the correct COM port name. It can found by using the Device manager on your computer.

As soon the serial object is initialized we should hold the program for two seconds for the Serial communication to be established. This can be done by using the below line:

time.sleep(2)

Now we can read or write anything from/to our Arduino Board.

The following line will read anything coming from Arduino and will print it on the shell window

print ArduinoSerial.readline()

You can also assign the value to a variable and use it for computations.

The following line will write the value of the parameter to Arduino Board.

ArduinoSerial.write('1')

This line will write ‘1’ to the Arduino. You can send anything from decimals to strings using the same line.

Now, getting back to our program, inside the infinite while loop, we have the following lines

The line var=raw_input will get any value that is typed in the Shell script and assign that value to the variable var.

Later, if the value is 1 it will print ‘1’ serially to Arduino and if 0 it will print ‘0’ serially to Arduino. The code in our Arduino Program (discussed above) we will toggle the LED based on the received value.

Once the complete program is done your script should look something like this below

Now click on Run -> Run Module or press F5 this might ask you to save the program and then will launch it.

Controlling LED with Python and Arduino:

The working of this project is pretty straight forward. Upload the program to your Arduino and verify it is connected to the same COM port as mentioned in the python program. Then Launch the Python program as mentioned above.

This will launch a python shell script as shown below. The window on the left is the shell window showing the output and the window on the right is the script showing the program.

As you can see the string “Hi!, I am Arduino” entered in the Arduino program is received by the Python and displayed on its shell window.

When the shell window asks to enter values, we can enter either 0 or 1. If we send 1 the LED on the Arduino Board will turn ON and if we send 0 the LED on our Arduino Board will turn OFF. Showing a successfully connection between our Arduino Program and Python.

There are two program given below, one to be uploaded and run from Arduino and second is to be run from Python Shell in Windows.

Hope you understood the project and were able to get it working. If not, post your problem in the comment below and I will be happy to help you out. In our next project we will learn what else can be done cool with Python and Arduino by exploring deep into other python modules like Vpython, gamepython etc. Until then stay tuned....

You just don't have the module installed in your Python library........To install it open up your command prompt and type "pip install pyserial" in the python directory of your computer. Hope that solves your problem.

Superb what a perfect and clear explanation. I have a doubt that , the output shown in python shell is what output of the controller. For example we say if we interface LCD with arduino, the output of the python shell will be displayed in LCD?? or the output of arduino serial monitor will be displayed??.

Whenever I try to run module, it keeps showing "Invalid Syntax" and highlighted ArduinoSerial of print ArduinoSerial.readline()... For Arduino it is working fine and able to read 1 & 0. Any idea on how I can solve this issue?

hello sir,
I encountered a problem. When I opened the python shell to execute the program, I typed it in the python shell.
'1' or '0', "Error opening serial port 'COM5'. (Port busy)" appears in rduino. I use anaconda enviroment.
I hope you can help me, thank you very much.

Whenever I try to run module, it keeps showing "Invalid Syntax" and highlighted ArduinoSerial of print ArduinoSerial.readline()... For Arduino it is working fine and able to read 1 & 0.
So I tried to execute single line in shell. Then I found that there is no Attribute named Serial in module serial. And I get this error.

When trying to run the python code this is what I get:
Traceback (most recent call last):
File "C:/Python27/FirstProject.py", line 9, in <module>
ArduinoSerial = serial.Serial('com6',9600) #Create Serial port object called arduinoSerialData
File "C:\Python27\lib\site-packages\serial\serialwin32.py", line 38, in __init__
SerialBase.__init__(self, *args, **kwargs)
File "C:\Python27\lib\site-packages\serial\serialutil.py", line 282, in __init__
self.open()
File "C:\Python27\lib\site-packages\serial\serialwin32.py", line 66, in open
raise SerialException("could not open port %r: %r" % (self.portstr, ctypes.WinError()))
SerialException: could not open port 'com6': WindowsError(5, 'Access is denied.')

hi
I am doing Arduino based project, in my project m using the python programming(laptop) to communicate with the Arduino Ethernet shield to control the fan and bulb by using the relay. I want to use the wifi to send and receive the signal from pc to Arduino and Arduino to pc. could you help me and tell me how can I do this.
what kind of thing I have to use for the bidirectional communication between the pc and the Arduino through the internet.

Hey I had a question regarding the support for python's 64-bit version or updated versions with the arduino libraries. As i have to install pynput which is used by the latest updated version of python for my project. Can you please help me with the same?

arduino = serial.Serial('com4',9600) #Create Serial port object called arduinoSerialData
time.sleep(2) #wait for 2 secounds for the communication to get established
print (arduino.readline()) #read the serial data and print it as line
print ("Enter 1 to get LED ON & 0 to get OFF")