reading TCNT

hello guys is it possible to read a TCNT timer counter precisly? i want to do an IF condition in certain part of TCNT counter. if i do simple

if(TCNT5>OCR5B-5 && TCNT5<OCR5B+5){U=HIGH;}
else{U=LOW;}

it missing match of the condition sometimes.

robot_chobot:
hello guys is it possible to read a TCNT timer counter precisly? i want to do an IF condition in certain part of TCNT counter. if i do simple

if(TCNT5>OCR5B-5 && TCNT5<OCR5B+5){U=HIGH;}

else{U=LOW;}


it missing match of the condition sometimes.

Read the counters value before comparing it:

auto counterValue = TCNT5;
auto compareValue = OCR5B;
if (counterValue > compareValue - 5 && counterValue < compareValue + 5) {
  U = HIGH;
}
else {
  U = LOW;
}

How fast is Timer5 running? If it is counting at 16 MHz then you are looking for an interval of less than a microsecond. I don’t think your loop is running fact enough to reliably catch that interval.

clocking frequency is 16mhz. and timer 5 has prescaler lowest in fast pwm mode.i can see on ossciloscope that mostly it cathes the match but sometimes not. so if there is a some way…
to LightuC: i tried but it misses catch too.

here is piece of code that reads TCNT.the main purpose of this reading is to do a deadtime between pwm signals on 2 outputs. DT is varying by potentiometer from 20 to 5.

if(TCNT5>=OCR5B-DT && TCNT5<=OCR5B+DT ){OCR1A=OCR1B=0;}
else if(  TCNT5>=OCR5C-DT && TCNT5<=OCR5C+DT ){OCR1A=OCR1B=0;}
  else{
if(PINH & (1<<PH4) || PINH & (1<<PH5))  {OCR1A=pwm;OCR1B=0;} 
  else{OCR1B=pwm;OCR1A=0;}}