wokwi / avr8js

Arduino (8-bit AVR) simulator, written in JavaScript and runs in the browser / Node.js
https://blog.wokwi.com/avr8js-simulate-arduino-in-javascript/
MIT License
481 stars 78 forks source link

Timers keeps counting even when stopped #41

Closed urish closed 4 years ago

urish commented 4 years ago

Use the following code to reproduce:

int main() {
  TCCR2B = 1 << CS20;
  byte value = TCNT2;
  Serial.begin(115200);
  Serial.println(value);
}

On a physical ATmega328p this code prints 1, as the counter only starts counting after we set the prescaler in the first line of main(). In the simulation, however, the same code prints 22, as the timer is counting even before the prescaler is set.

urish commented 4 years ago

Issue reproduced by the following assembly code:

  NOP
  NOP
  NOP
  NOP
  LDI r16, 0x1    ; TCCR2B = 1 << CS20;
  STS 0xb1, r16   ; Should start counting after this line
  NOP
  LDS r17, 0xb2   ; ; TCNT should equal 2 at this point

  LDI r16, 0xff
  OUT 0xa, r16
  OUT 0xb, r17

loop:
  RJMP loop

When running this code, we get 9 in the simulator, but 2 on an Uno board.

Reproduction sandbox: https://avr8js-asm-issue-41.stackblitz.io