How to Program Arduino with Python: Complete Guide and Examples

  • The PySerial library allows seamless communication between Arduino and Python over the serial port.
  • It is possible to send commands and receive data between Arduino boards and Python scripts easily.
  • Integration with image processing using OpenCV expands the capabilities of Arduino.
  • Electronic tasks can be automated by combining Python, Arduino sensors and actuators.

python arduino

Did you know you can control an Arduino board using just Python? Although Arduino's native language is based on C++, there is a fairly accessible way to program and communicate your Arduino projects using Python, thanks to specialized libraries like PySerial. This combination of both worlds is not only interesting but also very powerful, especially for those looking to integrate electronics with data processing, computer vision, or even artificial intelligence. If you'd like to delve deeper into this topic, you can check out our practical Guide.

In this article we explain what you need, how to connect Arduino to Python, and show you several practical examples. that you can follow step by step to start controlling your board using Python scripts. All explained clearly and with a structure designed for both beginners and those with some background in programming and electronics.

Can Arduino be programmed directly with Python?

Yes, although with nuances. Arduino is natively programmed using its own development environment (Arduino IDE), which uses a C++-based language. However, thanks to the use of libraries like PySerial and other alternatives like Snek or MicroPython (although with hardware limitations), it is possible to establish communication between Python and Arduino to control the board or interact with its peripherals. For more information about MicroPython, you can read our article on What's new in MicroPython.

The most common way to send data to Arduino is to use Python. through the serial port, and the board interprets them to perform physical actions (such as turning on LEDs or reading sensors). We can also do the opposite: have Arduino send data to Python, and Python can display, process, or store it.

Tools needed to get started

Before we get our hands dirty with cables and code, you'll need to have a few basic items ready:

  • An Arduino board: Any model will do, although the most common are the Arduino UNO or the Nano.
  • USB Cable to connect your Arduino to your computer.
  • Python installed on your computer. You can get it from the official Python website.
  • Installing PySerial, the library that enables serial communication between Arduino and Python. You can install it by running:
pip install pyserial

PySerial is the key piece which allows us to send commands from Python and receive responses from Arduino as if we were chatting with an electronic robot.

Step 1: Connect Arduino to Python via serial port

One of the most common forms of interaction is to send data from a Python script to the Arduino to turn an LED on or off.Let's see how to do it step by step.

1. Upload a basic program to Arduino

This code is loaded from the Arduino IDE and will be responsible for controlling the LED integrated on pin 13, depending on the data received via serial port:

void setup() {
  Serial.begin(9600);
  pinMode(13, OUTPUT);
}

void loop() {
  if (Serial.available() > 0) {
    char data = Serial.read();
    if (data == '1') {
      digitalWrite(13, HIGH);
    } else if (data == '0') {
      digitalWrite(13, LOW);
    }
  }
}

This sketch interprets the data received by the serial portIf it receives a '1', it turns on the LED; if it receives a '0', it turns it off. For more Arduino project examples, visit our article on How to create a chess set with Arduino.

2. Send commands from Python

Once the code is loaded onto the board, we create a Python script that is responsible for sending the commands:

import serial
import time

# Inicializa la conexión
arduino = serial.Serial('COM3', 9600)
time.sleep(2)

# Enciende el LED
arduino.write(b'1')
print("LED encendido")
time.sleep(2)

# Apaga el LED
arduino.write(b'0')
print("LED apagado")

# Cierra la conexión
arduino.close()

Please note that you must replace 'COM3' with the corresponding port on your operating system. On Windows, this is usually COM3 or COM4; on Linux, something like /dev/ttyUSB0.

Reading data from sensors connected to Arduino

In addition to sending instructions, we can use Python to read data sent by Arduino, for example from a temperature sensor. For a guide on how to use different sensors, we recommend This article about the DPS310 sensor.

1. Arduino code to read a sensor

The following routine reads an analog value (such as the output of an LM35 sensor) and sends it through the serial port:

int sensorPin = A0;

void setup() {
  Serial.begin(9600);
}

void loop() {
  int sensorValue = analogRead(sensorPin);
  Serial.println(sensorValue);
  delay(1000);
}

2. Python script to read the values

From Python we can read this data and display it on the screen:

import serial
import time

arduino = serial.Serial('COM3', 9600)
time.sleep(2)

while True:
  sensor_data = arduino.readline().decode('utf-8').strip()
  print(f"Valor del sensor: {sensor_data}")
  time.sleep(1)

This simple loop allows us to display the measured values ​​directly on our terminal.

Sending data from Python to Arduino with practical examples

Let's look at another example where we send a number from 1 to 9 from Python, and Arduino blinks the LED that number of times:

Sketch in Arduino

const int pinLED = 13;

void setup() {
  Serial.begin(9600);
  pinMode(pinLED, OUTPUT);
}

void loop() {
  if (Serial.available() > 0) {
    char option = Serial.read();
    if (option >= '1' && option <= '9') {
      option -= '0';
      for (int i = 0; i < option; i++) {
        digitalWrite(pinLED, HIGH);
        delay(100);
        digitalWrite(pinLED, LOW);
        delay(200);
      }
    }
  }
}

Python script to send the value

import serial
import time

arduino = serial.Serial("COM4", 9600)
time.sleep(2)

arduino.write(b'5')  # Parpadea 5 veces
arduino.close()

This type of interaction is ideal for creating user interfaces in Python., and that they intuitively control physical devices. In this context, you can also explore more about How to use electronic displays with Arduino.

Advanced example: detection with computer vision

A more advanced project that demonstrates the power of combining Arduino with Python is to use Computer vision with OpenCV and MediaPipe to detect whether a person is wearing a mask, and control LEDs on Arduino based on the detection.

Arduino: controlling two LEDs

int led1 = 50;
int led2 = 51;
int option;

void setup() {
  Serial.begin(9600);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
}

void loop() {
  if (Serial.available() > 0){
    option = Serial.read();
    if(option == 'P'){
      digitalWrite(led1, HIGH);
      digitalWrite(led2, LOW);
    }
    if(option == 'N'){
      digitalWrite(led1, LOW);
      digitalWrite(led2, HIGH);
    }
  }
}

Python with OpenCV and MediaPipe

In the Python code, the camera image is analyzed, detecting faces, and depending on whether they are wearing a mask or not, the corresponding value is sent:

# fragmento clave
if LABELS] == "Con_mascarilla":
    ser.write(b'P')
else:
    ser.write(b'N')

This example demonstrates how powerful the combination of Python and Arduino is., as it allows the physical world to be linked with sophisticated algorithms such as facial recognition or object detection.

Programming Arduino with Python is entirely possible, accessible, and even fun. From lighting an LED to implementing complex systems with sensors and computer vision, the possibilities are endless. Python acts as a powerful interface that allows you to take your Arduino projects to the next level. If you're looking for a practical way to apply your programming knowledge or give your Arduino boards a second life, this combination is definitely the way to go.


Be the first to comment

Leave a Comment

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

*

*

  1. Responsible for the data: Miguel Ángel Gatón
  2. Purpose of the data: Control SPAM, comment management.
  3. Legitimation: Your consent
  4. Communication of the data: The data will not be communicated to third parties except by legal obligation.
  5. Data storage: Database hosted by Occentus Networks (EU)
  6. Rights: At any time you can limit, recover and delete your information.