bavcol
bavcol

Reputation: 11

Serial connection between arduino and pyserial slows down after reopening

I need your help with an issue I stumbled upon, when using a serial connection between an arduino and pyserial:

When I am using the serial connection for the first time, it is significantly faster, than when i am using the serial connection again.

Here's a bare minimum example:

Arduino-code:

void setup() {
  Serial.begin(9600);
  Serial.println("Arduino ready"); // Print when Arduino ready
}

void loop() {
  // send data only when you receive data:
  if(Serial.available() > 0) {
      Serial.read();
      Serial.println(' ');
  }
  delay(1); // delay in between reads for stability
}

Python-code:

import serial
import time

ser = serial.Serial('COM5',9600,timeout=1)
print(ser.readline()) # Wait until Arduino is ready

for i in range(1,10):
    tic = time.time() # Start timer

    ser.write(b' ')
    ser.readline()

    toc = time.time() # Log time
    print("Serial write / read took %7.4f ms" % ((toc-tic)*1000))

ser.close()

Running the python code for the first time:

b'Arduino ready\r\n'
Serial write / read took  5.9998 ms
Serial write / read took  6.0000 ms
Serial write / read took  7.0000 ms
Serial write / read took  5.9998 ms
Serial write / read took  6.0003 ms
Serial write / read took  5.9998 ms
Serial write / read took  6.0000 ms
Serial write / read took  7.0002 ms
Serial write / read took  5.9998 ms

Running the python code again:

b'Arduino ready\r\n'
Serial write / read took 27.9999 ms
Serial write / read took 29.0003 ms
Serial write / read took 27.9999 ms
Serial write / read took 28.0001 ms
Serial write / read took 27.9999 ms
Serial write / read took 29.0000 ms
Serial write / read took 27.9999 ms
Serial write / read took 28.0001 ms
Serial write / read took 27.9999 ms

Actions that recover the speed of the serial connection:

Resetting the arduino via reset button doesn't recover the serial connection.

Any ideas how to achive the connection speed of the first connection when reopening the connection?

I am using python 3.6 and pyserial 3.4. Do you need any further information?

Thanks in advance!

Upvotes: 0

Views: 150

Answers (1)

bavcol
bavcol

Reputation: 11

The problem no longer occurs when I increase the serial baud rate from 9600 to 28800.

I also found out, that the problem only occurs with my Arudino Uno clone. The serial connection speed does not decrease at baud 9600 when I'm using the original Arudino Uno.

Upvotes: 1

Related Questions