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
461 stars 73 forks source link

Help required with analogWrite #114

Closed hacktronics closed 2 years ago

hacktronics commented 2 years ago

How to implement analogWrite simulation, I believe the example https://stackblitz.com/edit/avr8js-pwm?file=index.ts uses the cpu clock, but the analogWrite can be anywhere in the conditional nested statements, and the cpu cycle trick won't work. How to implement the same. I mean how to find out the analogwrite value of a PIN and then change the brightness of a LED.

urish commented 2 years ago

analogWrite() starts a timer, which uses the CPU clock under the hood. So the avr8js-pwm example should work regardless of where you call analogWrite()

You can probably look at the timer registers and try to figure out the analogWrite value from them (e.g. OCR0A/OCR0B), but that method might break if the user uses a different method of generating the PWM signal.

You can take a look at the source code for analogWrite to figure out which registers it writes, depending on the pin.