wokwi / rp2040js

A Raspberry Pi Pico Emulator in JavaScript
MIT License
384 stars 40 forks source link

How to calculate duty cycle of gpio-pin output value? #100

Closed BFjacky closed 2 years ago

BFjacky commented 2 years ago

I execute code on rp2040js like that:

from machine import Pin, PWM;
from time import sleep_ms;
pin = Pin(1);
pwm = PWM(pin);
pwm.freq(1000);
pwm.duty_u16(6554);
sleep_ms(100);
pwm.deinit();

As I expected, the duty cycle of pwm should be 10%. But i don't konw how to verify the result that i expect. I try to addListener on gpio-pin, then i receive a lot of output value of gpio-pin.Does there exist someway of calculating the real duty cycle of gpio-pin's output value?

urish commented 2 years ago

Does there exist someway of calculating the real duty cycle of gpio-pin's output value?

In general, look at the simulation time whenever the pin goes high/low, and then derive duty cycle from that.

e.g. if the pin has been low for 10 ms, then high for 20 ms, then low for 10 ms, then high for 20 ms, the duty cycle would be the sum of the high times (20 + 20 = 40) divided by the total time (10+20+10+20=60), or 2/3 (66.66%).

You can see an example of doing it with code here: calculating LED brightness by measuring the duty cycle of PWM signal