ISR doesn't increment over 255 !?

Hello all,

If you please, I am having the following problem:

The variable “u32RevolutionsCount” which is incremented in “PIN2ISR()” never reaches a value that is larger than (255) despite that it is a (u32) variable.

When it reaches (255), it is reset automatically to (0) again !!

I really don’t know what is going on !!

Please help.

Best Regards.

Arduino_Code.ino (2.58 KB)

Variables used in ISRs and other functions need to be volatile.

Variables that are more than one byte in length need to be read with interrupts disabled. An interrupt can happen in the middle of a read, resulting in bogus data being used by the function doing the read.

    au8RevCount[0] = (unsigned char)((u32RevolutionsCount >> 24) & 0xFF);
    au8RevCount[1] = (unsigned char)((u32RevolutionsCount >> 16) & 0xFF);
    au8RevCount[2] = (unsigned char)((u32RevolutionsCount >> 8) & 0xFF);
    au8RevCount[3] = (unsigned char)(u32RevolutionsCount & 0xFF);
    Serial.write(au8RevCount, 4);

As opposed to

Serial.write(u32RevolutionsCount, 4);

? Why?

1- Even if I add the critical section as you can see in the updated code. the result is the same !!

2- “Serial.write()” first argument is unfortunately an address of (UCHAR) or (UCHAR array), therefore I need theses lines of code.

Arduino_Code.ino (2.67 KB)

2- "Serial.write()" first argument is unfortunately an address of (UCHAR) or (UCHAR array), therefore I need theses lines of code.

Or a cast.

  • Anyway, the problem is not here :slight_smile: because I tried to comment the increment in the ISR and I just initialized the variable with a known number like 12458751 and it is reported very well through serial.

  • The problem relies in the increment in the ISR !

  • The problem relies in the increment in the ISR !

Sure. Did you make the variable volatile? Are you reading the value with interrupts disabled?

Can you simply print the value to the Serial Monitor application, instead of write()ing it to whatever you are sending it to now?

You must declare the variable volatile.

You must access it from loop() using noInterrupts()/interrupts() to prevent it being
garbled. Then everything will work.