📅 Duration: 1.5 hours
🎯 Objective:
By the end of the session, students will be able to:
- Understand how Python communicates with Arduino via serial communication
- Read sensor data (temperature, ultrasonic sensor, etc.) from Arduino using Python
- Control actuators (LED, buzzer) using Python commands
- Understand baud rate, parsing serial data, and structuring data exchange
- Complete a simple project using the concepts learned
Step 1: Understanding Serial Communication (15 min)
What is Serial Communication?
Serial communication allows two devices (e.g., a computer and Arduino) to exchange data through a wired connection.
Key Terms:
- Baud Rate: Speed of data transfer (e.g., 9600 baud = 9600 bits per second)
- Serial Monitor: Used in Arduino IDE to see messages from Arduino
- Serial.println(): Sends text data from Arduino to the computer
- Serial.read(): Reads data from the computer to Arduino
void setup() {
Serial.begin(9600); // Set baud rate
}
void loop() {
Serial.println("Hello from Arduino!"); // Send message every second
delay(1000);
}
Step 2: Setting Up Python Serial Communication (15 min)
Installing pyserial
In Mac/Linux, install pyserial using:
pip install pyserial
Finding the Correct Serial Port
🔹 On Mac/Linux, run:
ls /dev/tty.*
Look for something like /dev/ttyUSB0 or /dev/ttyACM0 (Linux) or /dev/tty.usbmodemXYZ (Mac).
Python Code to Read Data from Arduino
import serial
ser = serial.Serial('/dev/ttyUSB0', 9600) # Change port as needed
while True:
data = ser.readline().decode('utf-8').strip()
print("Received:", data)
👉 Demo: Run Python script to receive "Hello from Arduino!"
Step 3: Sending Commands from Python to Arduino (15 min)
Arduino Code for LED Control
void setup() {
Serial.begin(9600);
pinMode(13, OUTPUT); // LED on Pin 13
}
void loop() {
if (Serial.available() > 0) {
String command = Serial.readStringUntil('\n');
command.trim();
if (command == "ON") {
digitalWrite(13, HIGH);
Serial.println("LED is ON");
} else if (command == "OFF") {
digitalWrite(13, LOW);
Serial.println("LED is OFF");
}
}
}
Python Code to Send Commands
import serial
import time
# Initialize serial connection
ser = serial.Serial(
port='/dev/ttyUSB0', # Change this to match your port
baudrate=9600,
timeout=1
)
# Wait for connection to establish
time.sleep(2)
try:
# Turn LED ON
ser.write(b'ON\n')
print("Sent: ON command")
time.sleep(2)
# Turn LED OFF
ser.write(b'OFF\n')
print("Sent: OFF command")
except KeyboardInterrupt:
print("\nProgram terminated by user")
finally:
ser.close()
print("Serial connection closed")
Step 4: Parsing Sensor Data (Temperature & Ultrasonic) (20 min)
🔹 Arduino Code for Temperature Sensor
int sensorPin = A0;
void setup() {
Serial.begin(9600);
}
void loop() {
int sensorValue = analogRead(sensorPin);
float temperature = (sensorValue * 5.0 / 1023.0) * 100;
Serial.print("Temperature:");
Serial.println(temperature);
delay(1000);
}
🔹 Python Code to Parse Temperature Data
import serial
ser = serial.Serial('/dev/ttyUSB0', 9600)
while True:
data = ser.readline().decode('utf-8').strip()
if data.startswith("Temperature:"):
temp_value = data.split(":")[1]
print("Temperature:", temp_value)
👉 Demo: Display real-time temperature values in Python.
Step 5: Reading Ultrasonic Sensor Data (15 min)
Arduino Code for Ultrasonic Sensor
int trigPin = 9;
int echoPin = 10;
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration / 2) / 29.1;
Serial.print("Distance: ");
Serial.println(distance);
delay(1000);
}
Python Code to Read Ultrasonic Sensor Data
import serial
ser = serial.Serial('/dev/ttyUSB0', 9600)
while True:
data = ser.readline().decode('utf-8').strip()
if data.startswith("Distance:"):
distance_value = data.split(":")[1]
print("Distance:", distance_value)
Step 6: Controlling a Buzzer with Python (10 min)
🔹 Arduino Code for Buzzer
#define BUZZER 7
void setup() {
pinMode(BUZZER, OUTPUT);
Serial.begin(9600);
}
void loop() {
if (Serial.available() > 0) {
String command = Serial.readStringUntil('\n');
command.trim();
if (command == "BUZZER_ON") {
digitalWrite(BUZZER, HIGH);
Serial.println("Buzzer ON");
} else if (command == "BUZZER_OFF") {
digitalWrite(BUZZER, LOW);
Serial.println("Buzzer OFF");
}
}
}
🔹 Python Code to Control Buzzer
import serial
import time
ser = serial.Serial('/dev/ttyUSB0', 9600)
time.sleep(2)
ser.write(b'BUZZER_ON\n')
time.sleep(2)
ser.write(b'BUZZER_OFF\n')
👉 Demo: Run script and verify buzzer turns on/off.
Today's Submission
Students must combine all the elements into a single Arduino-Python program where:
- The Arduino continuously sends temperature and humidity data (use DHT11 sensor library).
- The Python program:
- Reads and displays the sensor data in real-time.
- Saves the data to a CSV file with the following format:
- Columns:
timestamp, temperature, humidity
- File name format:
sensor_data_YYYY_MM_DD.csv
- Update frequency: Every 5 seconds
- Columns:
- Turns the LED ON when temperature > 30°C and OFF otherwise.
- Activates the buzzer if the temperature is more than 30°C and OFF otherwise.
Submission Requirements (E-Learning):
- Arduino code with DHT11 sensor implementation.
- Python code with CSV logging functionality.