Shopping Cart

⚡️ We’re Helping 1 Million People Build Their First Robots

🇺🇸 Proudly Women-Owned Small Business
Arduino Python Communication

Communication Between Arduino & Python

We sometimes use affiliate links in our content. This won't cost you anything, but it helps us to offset the costs of paying our writing team. You can support us directly on BuyMeACoffee. Thank you!

Recently I started learning Python, and I was amazed by the simplicity and capabilities. So, I thought let’s connect it to Arduino, and see what I can do with it.

Communication between Arduino and Python isn’t a new concept, There are many modules available for Python that help in the process. In this tutorial, I’m going to use ‘pyserial‘ package for communication. For this, you will need a basic understanding of Python and Arduino. I’m using ‘Python 2.7‘ here.

Once you learn how to communicate between these two environments you can use it for multiple projects. Python is a great tool for image processing, object detection, and color recognition which can be used in various robotics projects.

So let’s get started…

What You Need

Check The Video Tutorial

Setup Process

Arduino Python Communication

  1. Download and install Python 2.7.x compatible with your OS. If you use Linux, Python is probably already installed. I use Windows 10, so I installed Python for Windows.
  2. Once it is properly installed, set environmental variables so it can be accessed from CMD.
  3. Now to communicate between Arduino and Python, we need to install a Python module called “pyserial“. To install modules we use the command “pip install“.
  4. Open up a CMD terminal, and type pip install pyserial this will install the module required for Serial communication.

With these steps done, we are ready to start programming.

First Download the Arduino and Python example codes, below.

Writing the Arduino Sketch to Communicate to Python

Arduino Python Communication

Open up the Arduino Sketch, LED.ino.

Now select the board & correct COM port and upload the code.

After the sketch is uploaded Goto >> Tools >> Serial Monitor, Enter ‘1’ to turn the LED on and ‘0’ to turn it off.  We used the built-in LED (pin 13) in the code, but you can connect an external LED to pin 13, 220-ohm resistor, and GND.

Arduino Python Communication

Writing Python Script

Next, let’s write the python code. But first, note the COM port to which the Arduino is connected. Mine is “COM3”. You can find it out from Tools >> Port or through Device Manager. We will need it in the next step.

Open the example Python script first in Python IDLE. Goto >> Files >> Open.

Now in the script, you have to make a small change. The COM port to which the Arduino is connected needs to be added in the script.  In the example code, replace ‘COM’ with your COM port.

Tip: If you’re on a Mac, open up the Arduino IDE, Goto Tools >> Port, and copy the port address into your python code.

Testing the Build

After writing and editing the script in IDLE, save it as LED.py (Hit Ctrl  + S to save).

Arduino Python Communication

Now before running the program, close the Arduino IDE. We need the COM port to be available for serial communication, so both programs can’t be running simultaneously.

Finally, you can RUN the code. Go ahead and hit F5 to run the script.

You will see a screen asking for input. Just enter ‘1’ or ‘0’ to turn the LED on/off. If the LED does not respond for the first time just close the IDLE and unplug Arduino and plug it again and retry.

Arduino Python Communication

If you can control the LED, you have successfully established communication between Arduino and Python.

How to Control Arduino with Python 3.7 and 3.9

For Python 3.7, you need to make a few minor adjustments to the code. A special thanks to Paulo, for his improvement to this project and for providing us the sample code for Python 3.7. Give it a try, and let us know how it goes!

Tip: If you get an error: ModuleNotFoundError: No module named ‘serial’, then you’ll need to install the pyserial module for the version of Python that you want to use. This code works on Python 3.9 as well. To install pyserial on python 3.9, you can use the command python3.9 -m pip install pyserial.

import serial
import time

arduino = serial.Serial(port = 'COM3', timeout=0)
time.sleep(2)

while True:

    print ("Enter '1' to turn 'on' the LED and '0' to turn LED 'off'")

    var = str(input())
    print ("You Entered :", var)

    if(var == '1'):
        arduino.write(str.encode('1'))
        print("LED turned on")
        time.sleep(1)

    if(var == '0'):
        arduino.write(str.encode('0'))
        print("LED turned off")

Other Arduino and Python Projects to Try

Now, you’re ready to try out our other Arduino and Python Projects.

I hope you enjoyed this tutorial. Let me know what you think in the comments, below!

How to Interface Python with Arduino

Support Content Like This

You May Also Like

Have a question? Need Help?

Thanks for dropping by! Comments are no longer moderated daily.
Before posting your comment, please consider buying a coffee.
If you'd like to work with Liz, you can schedule a call here.

8 comments

  1. Paulo Yun Cha

    Hi! Nice project! btw, Python 3.7 requires some updates regarding to the code above

    import serial
    import time

    arduino = serial.Serial(port = **, timeout=0)
    time.sleep(2)

    while True:

    print (“Enter ‘1’ to turn ‘on’ the LED and ‘0’ to turn LED ‘off'”)

    var = str(input())
    print (“You Entered :”, var)

    if(var == ‘1’):
    arduino.write(str.encode(‘1’))
    print(“LED turned on”)
    time.sleep(1)

    if(var == ‘0’):
    arduino.write(str.encode(‘0’))
    print(“LED turned off”)

  2. You can communicate between Python and an Arduino a lot easier (and in a more robust fashion) if you use libraries. On the Python side, you can use pySerialTransfer (pip installable). On the Arduino side, you can use SerialTransfer.h (installable through the Arduino IDE).

    ​pySerialTransfer: https://github.com/PowerBroker2/pySerialTransfer
    ​SerialTransfer.h: https://github.com/PowerBroker2/SerialTransfer

    The libraries allow your software on both sides to automatically packetize and parse serial/USB data.

    1. Liz Miller

      PB, thanks for sharing!

  3. Ahmed Nasser

    Thank you very much, that helped a lot. everything was so easy.

  4. Hi there I keep on getting an error that says

    AttributeError: module ‘serial’ has no attribute ‘Serial’

    on the following line of the code

    arduino = serial.Serial(‘/dev/cu.usbmodem14101’, 9600)

    why might that be?

    1. Liz Miller

      Alex, glad you dropped by.

      Try adjusting your import line from import serial to from serial import Serial

      Make sure you have the serial module properly installed. You can use the command pip install pyserial

      Let me know how it goes!

  5. Nice easy start into python, even this 73 year old hobbyist newbee could read and understand what the progam did, well done. Thank you

    1. Liz Miller

      Hey Bobkat! Great to see you’re building projects! Stop back anytime 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Learn Robotics Botly Favicon

Become a Learn Robotics Insider

 

Be the first to know when we launch new robotics content. Plus gain FREE robotics tips to your inbox.

Awesome! Check your inbox for a surprise!

Remote Robotics Courses for High School, Middle School, or Pre-College Training

Join the Powered by Learn Robotics Program

Teach robotics anywhere with our turnkey robotics program!

Download our free program brochure!

Success! Check your email for the download!