the Arduino only blinks the LED when it receives a command from the Python script.
Arduino Code
This code will wait for a command from the Python script to blink the LED:
C++:
void setup() {
// Initialize the built-in LED pin as an output
pinMode(LED_BUILTIN, OUTPUT);
// Start serial communication at 9600 baud
Serial.begin(9600);
}
void loop() {
// Check if data is available to read
if (Serial.available() > 0) {
// Read the incoming byte
char data = Serial.read();
// Blink the LED if the received data is '1'
if (data == '1') {
digitalWrite(LED_BUILTIN, HIGH);
delay(1000); // LED on for 1 second
digitalWrite(LED_BUILTIN, LOW);
delay(1000); // LED off for 1 second
}
}
}
Python Code
This Python script will send a command to the Arduino to blink the LED:- Install pyserial (if not already installed):
pip install pyserial
- Python script:
-
Python:
import serial import time # Set up the serial connection with a timeout of 0.1 seconds arduino = serial.Serial('COM3', 9600, timeout=0.1) time.sleep(2) # Wait for the connection to establish try: while True: # Send the command to blink the LED arduino.write(b'1') print("Command sent to blink LED") time.sleep(2) # Wait for 2 seconds before sending the next command except KeyboardInterrupt: print("Exiting the loop and closing the connection.") finally: arduino.close() print("Serial connection closed.")
Explanation
- Arduino Code: The Arduino code waits for a serial input. When it receives ‘1’, it blinks the LED on and off for one second each.
- Python Code: The Python script sends the ‘1’ command to the Arduino every 2 seconds, which triggers the LED to blink.
Last edited: