I apologize for basically hijacking this thread, but I am finding that this code DOES NOT work after rollover occurs:
if ((counter - start_time) >= interval)
I resisted what you guys were saying at first because the example code I have provided demonstrates this fact. Once the variable "counter" rolls over, the check always fails. Now that I have tested some more, I understand what Mark and others are saying about the maximum value that can be used if the operation is cast to signed. I agree, in the case of a char it limits you to 127.
What I still don't understand is why in this code, the "recommended check" fails after roll over. UNLESS you specifically cast it to unsigned.
unsigned char counter = 0;
unsigned char start_time = 0;
#define interval 147
void setup() {
Serial.begin(9600);
for (int x=0; x<1000; x++) { // run through uchar a few times
counter++; // simulate millis() or micros()
Serial.print(counter); Serial.print(","); Serial.println(start_time);
if ((counter - start_time) >= interval) { // check for rollover // WITHOUT A CAST TO (unsigned char) this will NOT WORK
Serial.println("Trigger Event!");
start_time=counter;
}
}
}
void loop() {
}
Change line 10 to:
if ((unsigned char)(counter - start_time) >= interval) {
and the check works after rollover. Why is the explicit cast to unsigned char necessary?