DEV Community

Cover image for Programming Arduino with Python
Sheriff S
Sheriff S

Posted on

Programming Arduino with Python

Arduino is an open-source hardware and software platform that is popularly used for building electronic projects. While the Arduino IDE (Integrated Development Environment) is the go-to tool for programming an Arduino board, Python can also be used as an alternative. In this documentation, we will explore how to program an Arduino board using Python.

Prerequisites:

  • An Arduino board
  • Arduino IDE installed on your computer
  • PySerial library installed on your computer

Step 1: Install PySerial Library
PySerial is a Python library that enables communication between a Python script and a serial port, which is the interface used to communicate with an Arduino board. To install PySerial, open your terminal or command prompt and type the following command:

pip install pyserial

Enter fullscreen mode Exit fullscreen mode

Step 2: Connect the Arduino Board
Connect the Arduino board to your computer using a USB cable. Make sure that the board is properly powered and the LED light is on.

Step 3: Upload Arduino Sketch
Before we can start communicating with the Arduino board using Python, we need to upload a sketch to the board that will listen for incoming serial data. Open the Arduino IDE and create a new sketch. Copy and paste the following code into the sketch:

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

void loop() {
  if (Serial.available() > 0) {
    char data = Serial.read();
    Serial.write(data);
  }
}
Enter fullscreen mode Exit fullscreen mode

This code listens for incoming data on the serial port and echoes it back to the computer. Compile and upload the sketch to the Arduino board.

Step 4: Write Python Code
Now that the Arduino board is set up to receive serial data, we can write a Python script to send data to the board. Open your text editor and create a new Python script. Import the PySerial library and create a serial object that corresponds to the serial port that the Arduino board is connected to:

import serial

ser = serial.Serial('COM3', 9600)

Enter fullscreen mode Exit fullscreen mode

Replace 'COM3' with the name of the serial port that your Arduino board is connected to.

Next, we can send data to the board using the serial object:

ser.write(b'Hello, Arduino!')

Enter fullscreen mode Exit fullscreen mode

This code sends the string "Hello, Arduino!" to the Arduino board.

Step 5: Run Python Script
Save the Python script and run it in the terminal or command prompt. You should see the message "Hello, Arduino!" echoed back to the terminal.

Congratulations! You have successfully programmed an Arduino board using Python.

Note: This is just a basic example to get you started. You can explore more advanced features of PySerial to send and receive data to and from the Arduino board.

Oldest comments (0)