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

How to trigger writehooks at a specific microsecond efficiently? #42

Closed tawjaw closed 4 years ago

tawjaw commented 4 years ago

Hi Uri, I am simulating the ultrasonic sensor. I need to trigger an event at a specific microsecond. For the ultrasonic sensor, I need to trigger the pin LOW after a specific microsecond duration.

In my Arduino class, I have events that are triggered with periods. see here

The events are being handled inside the this.runner.execute function call. (I don't know if it is the best way to trigger such events)

I lowered the workUnitCycles in execute.ts to have the execute callback be triggered at microseconds, but that made the speed extremely slow.

You can find the source code here And you can check the working environment here

Right now the ultrasonic sensor is triggered to return constant distance (200cm). Because the call back of the writehook is not accurate to microseconds, the pin is not triggered low on time. Which is resulting in inaccurate pulseIn return value.

urish commented 4 years ago

Hi Tawfiq, I think the best method would just be to add some check to the CPU main loop.

This can be achieved by adding some member to the AVRRunner class that will specify a callback and a clock cycle when to call it. The important thing is to keep the actual check inside the execute() function as simple as possible, otherwise it will considerably slow down the execution.

In the future, we may add some built-it support for this in the simulator, as this would speed up things like the timers that are being checked on every clock cycle, or relevant for issues such as #16.

But for now I think that modifying AVRRunner.execute() would be the best way to go.

tawjaw commented 4 years ago

Thanks Uri! that works! Still not very efficient especially when triggering an event at every microsecond. But it is much better than before. I look forward to future built-in support for this.

But finally I have a working ultrasonic sensor simulation with 2 servos here

Cheers!

urish commented 4 years ago

Awesome! Thanks for the update, I love seeing your progress!