I am trying to get data from Python to Arduino. In the serial monitor(Arduino Tools->serial monitor), i am receiving the data. When the data is sent from python, i am getting the message, "Error in getting the data"
I am using Arduino Mega.
I am using Arduino Mega.
Code:
void setup() {
Serial.begin(9600); // Initialize serial communication at 9600 baud rate
}
void loop() {
if (Serial.available()) {
String message = Serial.readStringUntil('\n'); // Read message until newline
Serial.println("Received message: " + message); // Send a response back to Python
} else {
Serial.println("Error in getting the data");
}
}
Code:
import serial
SERIAL_PORT = "COM20" # Replace with your Arduino's serial port
BAUD_RATE = 9600
with serial.Serial(SERIAL_PORT, BAUD_RATE, timeout=1) as ser:
message = "Hello from Python!"
ser.write(message.encode() + b'\n') # Send message with newline
while True:
response = ser.readline().decode().strip()
if response:
print("Received from Arduino:", response)
break # Exit loop after receiving response
print("Message sent and received successfully!")
