Using Python with Arduino- Controlling an LED

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.

controlling onboard led of arduino using python

So, Let’s get started....

 

Materials Required:

  1. Arduino Uno (or any Arduino Boards)
  2. 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.

  1. 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.
  2. 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.
  3. 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.

python-idle-in-windows

 

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.

python shell in windows

 

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.

running testing python in windows

 

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.

importing python serial library for communication with arduino

 

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:

void setup() {
  Serial.begin(9600); //initialize serial COM at 9600 baudrate
  pinMode(LED_BUILTIN, OUTPUT); //make the LED pin (13) as output
  digitalWrite (LED_BUILTIN, LOW);
  Serial.println("Hi!, I am Arduino");
}

 

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.

void loop() {
while (Serial.available()){
  data = Serial.read();
}

if (data == '1')
digitalWrite (LED_BUILTIN, HIGH);

else if (data == '0')
digitalWrite (LED_BUILTIN, LOW);
}

 

Program for Python:

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.

  1. Open your Python Shell (Python IDLE) and click File->New
  2. This will open a new text file where you can type in your program.
  3. 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.
  4. 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:

import serial #Serial imported for Serial communication
import time #Required to use delay functions

 

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

var = raw_input() #get input from user
    print "you entered", var #print the input for confirmation
   
    if (var == '1'): #if the value is 1
        ArduinoSerial.write('1') #send 1
        print ("LED turned ON")
        time.sleep(1)

    if (var == '0'): #if the value is 0
        ArduinoSerial.write('0') #send 0
        print ("LED turned OFF")
        time.sleep(1)

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

python program for controlling LED with arduino

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.

python program output for controlling LED with arduino

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....

 

Code: 

Program for Arduino:

/*
 * Code to blink an LED using Python
 * Code by: Aswint Raj, Dated: 8-9-2017
 * Webiste: www.circuitdigest.com
 */

int data;

void setup() { 
  Serial.begin(9600); //initialize serial COM at 9600 baudrate
  pinMode(LED_BUILTIN, OUTPUT); //make the LED pin (13) as output
  digitalWrite (LED_BUILTIN, LOW);
  
  Serial.println("Hi!, I am Arduino");
}
 
void loop() {
while (Serial.available()){
  data = Serial.read();
}

if (data == '1')
digitalWrite (LED_BUILTIN, HIGH);

else if (data == '0')
digitalWrite (LED_BUILTIN, LOW);

}

 

Python Program for Windows:

#Program to Control LED of Arduino from Python
#Code by: Aswinth Raj, Dated: 8-9-2017
#Website: www.circuitdigest.com

import serial #Serial imported for Serial communication
import time #Required to use delay functions
 
ArduinoSerial = serial.Serial('com18',9600) #Create Serial port object called arduinoSerialData
time.sleep(2) #wait for 2 secounds for the communication to get established

print ArduinoSerial.readline() #read the serial data and print it as line
print ("Enter 1 to turn ON LED and 0 to turn OFF LED")

 
while 1: #Do this forever

    var = raw_input() #get input from user
    print "you entered", var #print the intput for confirmation
    
    if (var == '1'): #if the value is 1
        ArduinoSerial.write('1') #send 1
        print ("LED turned ON")
        time.sleep(1)
    
    if (var == '0'): #if the value is 0
        ArduinoSerial.write('0') #send 0
        print ("LED turned OFF")
        time.sleep(1)

Video: 

Comments (7)

  • Mohsen Marzouk's picture
    Mohsen Marzouk

    Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
    Type "copyright", "credits" or "license()" for more information.
    >>> print (1+1)
    2
    >>> import serial

    Traceback (most recent call last):
    File "<pyshell#1>", line 1, in <module>
    import serial
    ImportError: No module named serial
    >>>

    Sep 20, 2017
  • B.Aswinth Raj's picture
    B.Aswinth Raj

    You get this error because you should missed adding the serial librarey to your Python code.

    This line "import serial" should have been deleted by mistake in your code. 

     

    Sep 21, 2017
  • Shin Thant Aung's picture
    Shin Thant Aung

    Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
    Type "copyright", "credits" or "license()" for more information.
    >>> ================================ RESTART ================================
    >>>

    Traceback (most recent call last):
    File "C:\Python27\arduino_py\my_1st_project.py", line 4, in <module>
    ArduinoSerial = serial.Serial('com18',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 'com18': WindowsError(2, 'The system cannot find the file specified.')
    >>>

    When I run the Python, I get this error.

    Sep 21, 2017
  • Raheel's picture
    Raheel

    not working properly
    >>> import serial

    Traceback (most recent call last):
    File "<pyshell#1>", line 1, in <module>
    import serial
    ImportError: No module named serial
    >>>

    Oct 01, 2017
  • Shin Thant Aung's picture
    Shin Thant Aung

    I've fixed my problem already. I'm sorry for my carelessness. My problem is putting wrong com port.

    Oct 16, 2017

Leave a comment