mopsiok
mopsiok

Reputation: 565

Python, serial - changing baudrate, strange behaviour

I am having troubles with changing baudrate while the port is running. All the communication is run at 100k baud, but I also need to send some data at 10k baud. I've read I should use setBaudrate method, so I tried this:

ser = serial.Serial(2, baudrate=BAUD, timeout=TIMEOUT)

def reset(string):
    if string:
        ser.flushInput() #erase input and output buffers
        ser.flushOutput()
        ser.setBaudrate(RESET_BAUD) #change baudrate to 10k
        ser.write(string)
        ser.setBaudrate(BAUD) #go back to 100k

The problem is, it doesn't work right. I don't know what is wrong here, but the string just isn't received properly. But here is interesting part - if I remove the last line (going back to 100k) and run this function from the shell, everything is fine. Then I can just run the last command directly in shell, not inside function.

My question is what exactly happens here and how to avoid it? All I need is a function to send a string with different baudrate and then return to the original baudrate...

Upvotes: 1

Views: 3361

Answers (2)

Rafael Lerm
Rafael Lerm

Reputation: 1400

My guess is that the baud rate is being changed before the data is actually sent. A good bet is to force the data to be sent before trying to change the baud rate.

According to the docs, this is done by calling Serial.flush() (not flushInput() or flushOutput(), as these just discard the buffer contents).

Upvotes: 2

Steve Barnes
Steve Barnes

Reputation: 28370

You need to wait long enough for the string to be sent before resetting the BAUD rate - otherwise it changes while some of it is still in the serial port (hardware) buffer.

Add time.sleep(0.01*len(string)) before the last line.

BTW try not to use reserved words like string as variable names as it can cause problems.

Upvotes: 2

Related Questions