Search code examples
avr

AVR / Atmega128rfa1: Reading registers gives different results


So, I'm working with the Atmega128rfa1 board and I'm getting strange results.

My code uses the MAC symbol counter. It uses manual beacon timestamping. In my code the following happens, with PORT_RADIOTIMER_WIDTH being a macro for uint32_t:

....
*((PORT_RADIOTIMER_WIDTH *)(&SCOCR2LL)) = 0;
SCOCR2LL = 0;   //set compare registers

*((PORT_RADIOTIMER_WIDTH *)(&SCBTSRLL)) = 0;
SCBTSRLL = 0;   //set compare registers

SCCNTHH = SCCNTHL = SCCNTLH = 0;
SCCNTLL = 0;    // reset timer value

radiotimer_setPeriod(period);   //set period


SCCR0 |= (1 << SCMBTS); // "reset" radiotimer

After this, I immediately try to get the relative time since the timestamp with the following code:

    PORT_RADIOTIMER_WIDTH count_time = (uint8_t) SCCNTLL;
count_time |= (uint8_t)SCCNTLH << 8;
count_time |= (uint8_t)SCCNTHL << 16;
count_time |= (uint8_t)SCCNTHH << 24;

PORT_RADIOTIMER_WIDTH beacon_time2;
beacon_time2 = (uint8_t) SCBTSRLL;
beacon_time2 |= (uint8_t)SCBTSRLH << 8;
beacon_time2 |= (uint8_t)SCBTSRHL << 16;
beacon_time2 |= (uint8_t)SCBTSRHH << 24;
PORT_RADIOTIMER_WIDTH beacon_time = (uint16_t)beacon_time2;
PORT_RADIOTIMER_WIDTH captured_time = count_time - beacon_time;
print_debug("radiotimer_getCapturedTime count_time %lu or %u\n", count_time);
print_debug("radiotimer_getCapturedTime beacon_time %lu  or %u\n", beacon_time);
print_debug("radiotimer_getCapturedTime captured_time %lu  or %u\n",captured_time);

What is printed is:

radiotimer_getCapturedTime count_time 859 or 859
radiotimer_getCapturedTime beacon_time 7090  or 859
radiotimer_getCapturedTime captured_time 4294961065  or 859

Contrary to expectations, the beacon time isn't roughly the same as the count_time, only when comparing as an unsigned int, not as an unsigned long int. What is happening? I'm completely flabbergasted by this.


Solution

  • The print_debug() statements look suspicious. The format calls for two variables, but you only supply one. The 859 printed in each call may be from a variable you are not expecting.

    Otherwise, the arithmetic in the ul version is correct. 859 - 7090 does equal 4294961065 in 32-bit unsigned arithmetic.

    Try something like:

    print_debug("radiotimer_getCapturedTime count_time %lu or %u\n", count_time, count_time);
    print_debug("radiotimer_getCapturedTime beacon_time %lu  or %u\n", beacon_time, beacon_time);
    print_debug("radiotimer_getCapturedTime captured_time %lu  or %u\n",captured_time, captured_time);
    

    and see if the results are still always the same in the 16 bit cases.