Serial Communication between Teensy 4.0 and PC via PySerial

tranhao3097

New member
Hi,

I'm currently a student working on a project with sensitive timing (us). What I'm trying to do is to send trigger signal to the Teensy 4.0 board via serial port using the Python PySerial library. I tried with simple scripts for Python and Teensyduino. The problem I'm having is that the Teensy reported back the package number is lower than the number of package PySerial are sending. I've tried multiple testing and debugging but couldn't find where it went wrong. Any suggestions or helps would greatly be appreciated. Thank you!
Python
Code:
import serial
import time
teensy = serial.Serial(port='COM8', baudrate=1000000, timeout=.01)
count = 0

def write_read(x):
    teensy.write(bytes(x, 'utf-8'))
start_time = time.time()
while(1):
    write_read("a")
    count = count+1
    if(teensy.in_waiting >0):
        break
print("--- %s seconds ---" % ((time.time() - start_time)*1000),"count: ",count)
while(1):
    data = teensy.readline()
    print(data)
    time.sleep(1)
Teensyduino:
Code:
unsigned int count;
uint32_t startTime;

void setup() {
  Serial.begin(1000000);
  Serial.setTimeout(0.00001);
  while (!Serial) ;
  count = 0;
  startTime = millis();
}

void loop() {
  if(Serial.available() >0){
    if(Serial.readString() == "a"){
      count = count+1;
    }
  }
  if (millis() - startTime > 1000) {
    while(1){
     Serial.print(count);
     delay(2000);
    }
  }
}
 
Back
Top