Pyserial and Arduino Input Capture

Hello everyone. I have strange problem.I try to create app to perioid meansurment incoming signal with arduino mega in input capture mode ( timer 4). When i try send data from arduino, pyserial give me sometimes trash data. And this data is in the same level by few seconds and go back to normal. I think i have wrong configration of pyserial. Enyone had this problem ? Here is my code from arduino, pyserial configuration and reading data.

#include <Arduino.h>
#define icpPin 49
volatile long Overflow;
bool shouldISpam = false;
// bool ledstate = false;
volatile uint16_t Nprev = 0;
volatile uint16_t Tdiff = 0;
volatile uint16_t Nnext = 0;
volatile uint16_t ovf = 65535;

void setup()
{
  Serial.begin(115200);
  pinMode(icpPin, INPUT);

  noInterrupts ();  

  TCCR4A = 0;
  TCCR4B = 0;
  TCNT4 = 0;
  TIMSK4 = 0;

  TIFR4 |= _BV(ICF4) |  _BV(TOV4); 
  TCCR4B |= _BV(CS40) | _BV(ICES4)| _BV(ICNC4);	   
  TIMSK4 |= _BV(ICIE4) | _BV(TOIE4); 

  interrupts ();
}



ISR(TIMER4_OVF_vect){
	Overflow++;
}

ISR(TIMER4_CAPT_vect)
{
    if (bitRead(TCCR4B,ICES4))
    {
        Nnext = ICR4;
        if(Nnext>Nprev){
          Tdiff=ICR4-Nprev;
          Nprev = ICR4;
        }else{
          Tdiff = ICR4-Nprev+65535;
          Nprev = ICR4;
        }
      }

}
  
void loop()
{
   if(shouldISpam) {
    noInterrupts();
    uint16_t ticks = Tdiff;
    interrupts();

    if (ticks)
    {
      
      Serial.write((byte*)&ticks,sizeof(ticks));

      noInterrupts();
      Tdiff = 0;
      interrupts();
    }
    }
    

     if (Serial.available()) {
       char c = Serial.read();
        if (c == 's') {
         shouldISpam = !shouldISpam;
        } else if (c == 'k') {
         shouldISpam = false;
        }
     }
}`

Pyserial configuration and methood to read data:

def connect(self, device, baudrate):
        try:
            self.connection = sr.Serial()
            self.baudrate = int(baudrate)
            for port in self.ports:
                if device in port.description:
                    self.COM = port[0]
            self.connection.port = f'{self.COM}'
            self.connection.baudrate = self.baudrate
            self.connection.timeout = None
            # self.connection.rtscts = True
            self.connection.xonxoff = True
            self.connection.stopbits = STOPBITS_TWO
            # self.connection.parity = PARITY_MARK
            self.connection.bytesize = EIGHTBITS
            print(self.connection.isOpen())
            self.connection.open()
def readValue(self):
        self.value = self.connection.read(2)
        unpacked_data = struct.unpack(">H", self.value)[0]
        return unpacked_data  

Sounds like an unreliable USB serial connection that's sometimes dropping an odd number of bytes, de-synchronizing the 16 bit packets.

Can you verify PySerial is working with some other known good USB serial device?

Why are you using 's' and 'k'? XON is cntl-Q and XOFF is cntl-S

Thanks you for response. I using "s" and "k" for asynchronous sending. When i running program in python sometimes i get data with missing part,so i usethis because this is something like start point from sending.
Im testing Pyserial with Arduino Uno and Arduino Mega and i still had the same bugs ( even with XON and XOFF and in another PC). Right now i thinking about checksum but i have almost no knowledge about that.

Try this short Python script just to see if it prints the values you expect.

import serial

ser = serial.Serial("COM7",9600)

while True:

		read_a_byte=bytes()
		read_a_byte=ser.read(2)
		i = int.from_bytes(read_a_byte, byteorder='little')
		print(i)

Adjust baud and port to match the ones you have

Thanks you for response. I try your code but still sometimes i get wrong data.I test arduino Mega with prototype generator from Arduino Uno.
Here is output from vs code terminal:
obraz
Input signal to arduino Mega from arduino Uno:

#include <Arduino.h>
#include <TimerOne.h>
void setup()
{
pinMode(9,OUTPUT);

Timer1.initialize(100);  // Frequency, 100us = 10khz
Timer1.pwm(9,512);       // 50% DC on pin 9
}

void loop()
{
}

if i calculate 1/(1600* (1/16*10^6)) i get 10kHz of signal -- 16*10^6 is the frequency of arduino Mega crystal. When i get 16390 and do again the same operation i get ~980Hz, and this is wrong value.