Python Serial Writes to Arduino is different from Arduino's Serial Monitor's Serial Writes
<p>I have a Python script that writes a string <code>test</code> to the Arduino serial port. If the arduino receives the <code>test</code> string, it should reply with a string <code>ok</code> and LED 13 should like up..</p>

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

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

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

<p><strong>Arduino Sketch</strong></p>

<pre><code>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);
}
</code></pre>

<p><strong>Python Script</strong></p>

<pre><code>port = 'COM5'
ser = serial.Serial(
    port=port,
    baudrate=9600,
    timeout=5
)

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

response = serial.readline()
print response
</code></pre>

<pre><code>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
</code></pre>

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

python arduino serial-port pyserial