Nyxynyx Nyxynyx - 2 months ago 15
Python Question

Python Serial Writes to Arduino is different from Arduino's Serial Monitor's Serial Writes

I have a Python script that writes a string

test
to the Arduino serial port. If the arduino receives the
test
string, it should reply with a string
ok
and LED 13 should like up..

Problem: When the Arduino Serial Monitor is used to write
test
to serial port, Arduino replies with
ok
as expected and the LED #13 lights up.

However when the Python script writes
test
to the same serial port, nothing happens. Arduino does not reply to serial port and the LED #13 does not light up.

Any ideas how Python script can be fixed to get the
ok
response from Arduino and LED 13 to light up?

Arduino Sketch

int ledPin = 13;


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


void loop() {

while(Serial.available() == 0) { }

if(Serial.readString() == "test\r\n") {
Serial.print("ok\r\n");
digitalWrite(ledPin, HIGH);
}

readString = ""; // Clear recieved buffer
delay(100);
}


Python Script

port = 'COM5'
ser = serial.Serial(
port=port,
baudrate=9600,
timeout=5
)

serial.write("test\r\n")

response = serial.readline()
print response

Answer
port = 'COM5'
ser = serial.Serial(
    port=port,
    baudrate=9600,
    timeout=5
)

# you need to sleep after opening the port for a few seconds
time.sleep(5) # arduino takes a few seconds to be ready ...

#also you should write to your instance
ser.write("test\r\n")
# and give arduino time to respond
time.sleep(0.5)
response = self.serial.readline()
print response

if you dont want to wait a fixed number of seconds you probably need to wait for ser.cts (clear to send)