Home Code Controlling the Arduino built in LED with Python and PySerial

Controlling the Arduino built in LED with Python and PySerial

by shedboy71

In this article we will control the built in LED on an Arduino using Python. Python will be running on the desktop PC and we will be sending simple commands via the serial port to the Arduino.

You can hook up an external LED if you want but that would involve some extra components and you can see this working just fine with the built in LED

There are 2 parts to this example, the arduino code and the python code. Lets start with the Arduino code and test it out.


There is an easy to use example that you can find by navigating to the PhysicalPixel sketch which can be found in the Arduino IDE under File –> Examples –> 04.Communication –> PhysicalPixel

Here is the code with a lot of the comments and commented out processing code.

Looking at it you can see that we are opening a serial connection and reading in data, the key is whether the serial input is H or L.

Looking at the code below you can see that H will turn on the LED and L will turn the LED off

const int ledPin = 13; // the pin that the LED is attached to
int incomingByte;      // a variable to read incoming serial data into
void setup() {
  // initialize serial communication:
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
void loop() {
  // see if there's incoming serial data:
  if (Serial.available() > 0) {
    // read the oldest byte in the serial buffer:
    incomingByte = Serial.read();
    // if it's a capital H (ASCII 72), turn on the LED:
    if (incomingByte == 'H') {
      digitalWrite(ledPin, HIGH);
    // if it's an L (ASCII 76) turn off the LED:
    if (incomingByte == 'L') {
      digitalWrite(ledPin, LOW);

Now we can test this out before we start the python part by using the Serial Monitor which is built in the Arduino IDE

serial monitor pyserial

serial monitor pyserial

Remember and set the baud rate, type in either H or L (watch the case, it makes a difference) and check whether the LED on the board or connected externally goes on and off. If it does lets move on to the next step


I’ll assume you have installed Python, if not visit https://www.python.org/downloads/ and pick the version and OS you want and install it. I have various versions and the installation has always worked on Windows anyway.

Next you need to install PySerial, you can get this from https://pypi.org/project/pyserial/ 

The easiest way is to open a command line and type pip install pyserial

All going well this should download and install the correct files for you.

There are now 2 options you can use the python REPL like this

REPL example

>>> import serial
>>> import time
>>> ser = serial.Serial('COM5', 9600)
>>> time.sleep(2)                    
>>> ser.write(b'H')
# LED turns on
>>> ser.write(b'L')
# LED turns off
>>> ser.close()
>>> exit()

It is important to realize that you have to set the correct serial port and it cannot be already open otherwise you will see an error message on the screen. All going well when you send the ser.write(b’H’) and ser.write(b’L’) command syou see the LED going on and off.

Now I personally  prefer to write python scripts so lets see an example of this

Python script

In this example we will import the pyserial module, open a serial connection to COM5 with a baud rate of 9600 to match our Arduino settings. You may have to change the COM port.

We then have 3 options

on which sends a H – which in turn matches the arduino sketch earlier switching the LED on
off which sends a L – which in turn matches the arduino sketch earlier switching the LED off

You can use any text editor or python IDE for this – I personally use either Notepad++ or Thonny

import serial
import time
# Define the serial port and baud rate.
ser = serial.Serial('COM5', 9600)
def led_on_off():
    user_input = input("\n Type on / off / quit : ")
    if user_input =="on":
        print("LED is on...")
    elif user_input =="off":
        print("LED is off...")
    elif user_input =="quit" or user_input == "q":
        print("Program Exiting")
        print("Invalid input. Type on / off / quit.")
time.sleep(2) # wait for the serial connection to initialize

Save this with a .py extension and run it via the command line with python nameoffile.py.

Lets see a run of this below

And that’s it a simple example on how to switch an LED on and off that is connected to your Arduino using Python on the PC end.




You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More