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
