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

SBI / CBI work differently from hardware #103

Closed urish closed 3 years ago

urish commented 3 years ago

SBI / CBI sometimes produce incorrect result when used with special I/O registers, such as the PIN registers.

The following Arduino program demonstrates the issue:

void setup() {
  DDRD = bit(3) | bit(6);
  PIND |= bit(3) | bit(6);
}

void loop() {
  delay(1000);
  PIND |= bit(6);
}

When running in simulation, the second line of loop() will drive pin 3 LOW in addition to toggling pin 6. This is in contrast with the physical hardware, where pin 3 (the red LED) in unaffected:

https://user-images.githubusercontent.com/892318/132061911-7b258248-aa2b-4297-900f-ee23c0e8f8c9.mp4

By looking at the assembly listing, you can see that PIND |= bit(6) compiles to:

sbi 0x09, 6 ; 9
rcwilcox commented 3 years ago

Just to exonerate the PIN Register simulation, I verified that writing PINx without using SBI works fine in Sim.

e.g.

ldi r18,0b00000100 ; Set B2
out PIND,r18 ; Toggle PD2

urish commented 3 years ago

And now, a video version of how I fixed this bug: https://youtu.be/r_ZIiDi8nCU