Using Python with Arduino

Loading

Arduino is a microcontroller-based platform widely used for embedded systems and IoT projects. Python can be used to communicate with an Arduino for data collection, automation, and control.

Why Use Python with Arduino?
Data Logging – Store sensor data in databases or files.
Automation – Control devices from a computer.
Visualization – Graph sensor readings in real time.
Machine Learning – Process and analyze data from Arduino sensors.


1. Setting Up the Environment

To connect Python with Arduino, we use PySerial, which allows serial communication.

Install PySerial

pip install pyserial

Check Your Arduino COM Port

  • On Windows: Open Device Manager → Ports (COM & LPT) → Find the Arduino COM port.
  • On Mac/Linux: Run: ls /dev/tty* Look for something like /dev/ttyUSB0 or /dev/ttyACM0.

2. Writing the Arduino Code

Load this code onto your Arduino using the Arduino IDE.

void setup() {
Serial.begin(9600); // Set baud rate to 9600
}

void loop() {
int sensorValue = analogRead(A0); // Read from sensor (e.g., temperature)
Serial.println(sensorValue); // Send data to Python
delay(1000); // Wait for 1 second
}

This sends sensor readings from Arduino to Python.


3. Reading Data from Arduino with Python

Create a Python script to read sensor data.

import serial

# Replace with your Arduino port (e.g., 'COM3' for Windows or '/dev/ttyUSB0' for Linux/Mac)
arduino_port = "COM3"
baud_rate = 9600

# Open serial connection
ser = serial.Serial(arduino_port, baud_rate, timeout=1)

while True:
data = ser.readline().decode().strip() # Read data
if data:
print(f"Sensor Value: {data}") # Print to console

This reads and displays sensor data from Arduino in real time.


4. Controlling Arduino from Python

Python can send commands to control Arduino’s LEDs, motors, relays, etc.

Modify Arduino Code to Receive Commands

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

void loop() {
if (Serial.available() > 0) {
char command = Serial.read();
if (command == '1') {
digitalWrite(13, HIGH); // Turn LED ON
} else if (command == '0') {
digitalWrite(13, LOW); // Turn LED OFF
}
}
}

Python Script to Control LED

import serial
import time

ser = serial.Serial("COM3", 9600)
time.sleep(2) # Wait for Arduino to initialize

while True:
command = input("Enter 1 to turn ON LED, 0 to turn OFF: ")
ser.write(command.encode()) # Send command

This lets you control an LED on Arduino using Python.


5. Visualizing Data with Matplotlib

You can visualize sensor data in real time using Matplotlib.

Install Matplotlib

pip install matplotlib

Python Script to Plot Data

import serial
import matplotlib.pyplot as plt

ser = serial.Serial("COM3", 9600)
data = []

plt.ion() # Enable real-time plotting
fig, ax = plt.subplots()

while True:
value = ser.readline().decode().strip()
if value:
data.append(int(value))
ax.clear()
ax.plot(data, label="Sensor Value")
ax.legend()
plt.pause(0.1)

This creates a real-time plot of sensor values.


6. Storing Data in a CSV File

Save sensor data for further analysis.

Python Script to Save Data

import serial
import csv

ser = serial.Serial("COM3", 9600)
csv_file = open("sensor_data.csv", "w", newline="")
csv_writer = csv.writer(csv_file)
csv_writer.writerow(["Timestamp", "Sensor Value"])

while True:
value = ser.readline().decode().strip()
if value:
csv_writer.writerow([time.time(), value])
print(f"Saved: {value}")

This logs sensor data to a CSV file for analysis.


7. Using Python for IoT and Cloud Integration

You can send Arduino sensor data to IoT dashboards or cloud platforms like Firebase, AWS, or Google Sheets.

Example: Sending Data to Firebase

pip install firebase-admin
import serial
import firebase_admin
from firebase_admin import credentials, db

# Firebase Setup
cred = credentials.Certificate("firebase_config.json")
firebase_admin.initialize_app(cred, {"databaseURL": "https://your-database.firebaseio.com/"})
ref = db.reference("sensor_data")

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

while True:
value = ser.readline().decode().strip()
if value:
ref.push({"temperature": value})
print(f"Sent to Firebase: {value}")

This uploads Arduino data to Firebase in real time.

Leave a Reply

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