N
N
Nikita Chukov2018-06-12 17:11:41
Python
Nikita Chukov, 2018-06-12 17:11:41

Communication between arduino and pyserial. What's wrong?

Please help me figure out why the following python code only works if the delay (time.sleep(1)) is greater than 1 second?

import time
import serial

ser = serial.Serial(port='/dev/ttyUSB0',baudrate=115200)
ser.write(b'1')
while 1:
    ser.write(b'test\n')
    time.sleep(1)
    while ser.inWaiting() > 0:
        line = ser.readline()
        if line:
            print(line.decode().strip())

Sketch code for Arduino UNO:
void setup() {
  Serial.begin(115200);
}

void loop() {

String incomingData;

if (Serial.available() > 0) {  //если есть доступные данные

       incomingData = Serial.readString();
       Serial.println("123456789");
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nikita Chukov, 2018-06-14
@chukov

After a lot of experimentation, we managed to achieve acceptable performance, 100 messages went for 0:00:00.601094:

#include <Arduino.h>

void setup() {
  Serial.begin(115200);
  Serial.println("Booting");
}

void loop() {


  while(Serial.available()){
    Serial.write(Serial.read());
  }
  delay(10);


}

python test code:
import time
import serial
import datetime

ser = serial.Serial(port='/dev/ttyUSB0', baudrate=115200)
received = []

ser.write(b'begin\n')
time.sleep(5)

start = datetime.datetime.now()
for i in range(1, 100):
    ser.write(b'test%i\r\n' % i)
    time.sleep(0.005)
    while ser.inWaiting() > 0:
        line = ser.readline()
        if line:
            received.append(line.decode().strip())

print(datetime.datetime.now() - start)
print(received)

ser.write(b'begin\n')
time.sleep(5)
This piece is needed so that the arduin (esp32 too) has time to reboot, because. dtr is related to software reset.
Read more here

A
Alexander, 2018-06-12
@NeiroNx

This is normal for serial ports. While the data is being sent, while the arduina will send the answer.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question