Python Code:
import serial
import time
# Open the serial port (adjust the port and baudrate as needed)
ser = serial.Serial('COM3', 9600, timeout=1)
def send_command(command):
data = {"command": command}
ser.write(str(data).encode('utf-8'))
time.sleep(1) # Give Arduino some time to process the data
# Example: Turn on the LED
send_command("ON")
# Close the serial port
ser.close()
Arduino Code:
#include <ArduinoJson.h>
const int ledPin = 12;
const char *command;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}
void loop() {
if (Serial.available() > 0) {
StaticJsonDocument<200> doc;
DeserializationError error = deserializeJson(doc, Serial);
if (error) {
Serial.print(F("Error: "));
Serial.println(error.c_str());
return;
}
command = doc["command"];
}
if (strcmp(command, "ON") == 0) {
digitalWrite(ledPin, HIGH);
} else if (strcmp(command, "OFF") == 0) {
digitalWrite(ledPin, LOW);
}
}
For some reason it seems that the above code is not working properly. My intention is to have the LED consistently turned on when the 'ON' message is sent. Additionally, I expect the Arduino's Serial Monitor to continuously display the 'ON' message after it has been sent.
You can modify the python code like this and see if it works.