Arduino and Python are two powerful tools that, when combined, open up a world of possibilities for electronics projects. Arduino is a microcontroller platform that lets you control hardware components, while Python is a versatile programming language used for automating and interacting with the world of IoT (Internet of Things). In this guide, you'll learn how to integrate Python with Arduino, allowing you to control your Arduino projects with Python.
Python is known for its simplicity and ease of use, making it a great companion for Arduino programming. By integrating Python with Arduino, you can:
To get started with Arduino and Python, you’ll need the following:
Before you can control Arduino with Python, you need to upload a sketch (program) that allows it to communicate over serial (USB). Here's how to set up the Arduino:
Here’s an example sketch that will blink an LED based on commands received from Python:
void setup() {
Serial.begin(9600); // Initialize serial communication at 9600 bps
pinMode(13, OUTPUT); // Set pin 13 (built-in LED) as an output
}
void loop() {
if (Serial.available() > 0) {
char command = Serial.read(); // Read the incoming data
if (command == '1') {
digitalWrite(13, HIGH); // Turn the LED on
} else if (command == '0') {
digitalWrite(13, LOW); // Turn the LED off
}
}
}
Next, install Python and the pySerial
library, which allows Python to communicate with the Arduino over serial ports.
Install pySerial: Open your terminal or command prompt and install the pySerial library using pip:
pip install pyserial
Now that your Arduino is set up and you've installed pySerial, you can write a Python script to control the Arduino. This script will send commands to the Arduino to turn the LED on or off.
Here’s an example Python script:
import serial
import time
# Establish a connection to the Arduino
arduino = serial.Serial(port='COM3', baudrate=9600, timeout=.1)
def send_command(command):
arduino.write(bytes(command, 'utf-8'))
time.sleep(0.05)
while True:
user_input = input("Enter 1 to turn on the LED, 0 to turn it off: ").strip()
if user_input in ['1', '0']:
send_command(user_input)
else:
print("Invalid input. Please enter 1 or 0.")
In the code:
COM3
(you may need to change this to match your system’s port).Run the Python script: In your terminal or command prompt, navigate to the folder where your Python script is saved and run:
python your_script_name.py
If everything is set up correctly, the Arduino should receive the command and control the LED accordingly!
With the basics in place, you can now expand your Arduino and Python integration by:
matplotlib
or Plotly
.