Learn how to set up your Arduino with Python and PySerial to create serial communications for a variety of projects. 

In this post, you are going to learn about how to set up serial communications between an Arduino UNO and Python IDE. Using Python, we will create buttons to send commands to the UNO to turn an LED ON or OFF. In return, the UNO will respond with a confirmation message that the LED is ON or OFF.

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse.

How to Install Python

First, you need to install Python 2 since Python 3 doesn’t have support for all the Arduino libraries yet. I have tested this example on Python 2.7.15 and it works great.

Visit and download Python 2.7.15 from Python's official page.

Open the downloaded file and go through the installation steps and install it into the default directory.    

How to Install PySerial

Next, we have to install the PySerial module. PySerial is a module for Python and is used to send and receive data from an Arduino. The downloaded file is an exe file. Run the file and it will install.

The Arduino Code

Before uploading the code, make sure that you have selected a COM port in the option. This selected COM port will be used in the development, particularly working with the python code. 

Also, we will have to take note of the baud rate used in the development. After uploading the code, avoid using the serial monitor since this serial monitor will start to use the selected COM port for the development with Python.

        int incomingData;

void setup() {
  Serial.begin(9600);
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite (LED_BUILTIN, LOW);
  Serial.write("Press the button to control LED (Message from Arduino");
}

void loop() {
  while (Serial.available()) {
    incomingData = Serial.read();
    if (incomingData == '1') {
      digitalWrite (LED_BUILTIN, HIGH);
      Serial.write("LED Turned ON");
    }
    if (incomingData == '0') {
      digitalWrite (LED_BUILTIN, LOW);
      Serial.write("LED Turned OFF");
    }
  }
}
    

Python Code

In Python, we are going to make a simple GUI application in which we will create two buttons to send the data to the Arduino.

Create two buttons in Python to send data to the Arduino.

It is important to enter the correct Com port in the below code, so make sure to double-check your code!

Reginald Watson
I love challenging myself by creating new projects using different microcontrollers to see what I can come up with.

Maker Pro Logo
Continue to site
Quote of the day

-