Program to read data sent by Python code over serial port using Arduino Board

In this code, python code sends a command "LED_ON" over the serial port which will be ready by the Arduino board and glows a LED for some time and then turns OFF.

Below is the python code to generate "LED_ON" command:

import serial
import time

ser = serial.Serial('COM7', 9600)  # Change COM port as needed
time.sleep(2)  # Wait for Arduino to reset

ser.write(b'LED_ON\n')  # Send command
response = ser.readline().decode().strip()
print("Response from Arduino:", response)

ser.close()

Below is the Arduino code to read data over serial port and glow a LED:

#define PIN 13

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

void loop() {
    if (Serial.available()) {
        String command = Serial.readStringUntil('\n');
        if (command == "LED_ON") {
            Serial.println("LED turned on");
            digitalWrite(PIN,HIGH);
            delay(10000);
            digitalWrite(PIN,LOW);
        }
    }
}

Post a Comment

Previous Post Next Post

Facebook