1

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

1 Answer 1

2
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)

Sign up to request clarification or add additional context in comments.

3 Comments

Works!! Spent over an hour trying encoding of string and stuff lol
I have had lottttts of experience with python + serial + ardiuno ;P
Awesome! A related question: In an infinite loop in Python, it takes about a second for Arduino to reply with ok after sending test. Is there a way to speed this up?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.