Hi Everyone!

I have this project wherein a user enters a frequency and a light bulb blinks with the corresponding frequency. (i.e. If the user enters a 0.5 Hz, the light bulb will blink on for 1 second and off for 1 second. (This will repeat forever)

Here’s how the code works
The agent takes the value from the URL and sends it to the device.
The device receives the value and calls a function.
This function calculates how long the light bulb should be on/off for and then calls the function blinkOn()
blinkOn() turns the light on and waits the calculated time before calling blinkOff()
blinkOff() turns the light off and waits the calculated time before calling blinkOn() (<-- Both use the imp.wakeup() method)
This process repeats forever.

Now, for smaller frequencies like 1 or 2 Hz, this code works fine. However, I am testing with frequencies much larger (60 to 100 Hz)

The problem is that there is a significant delay in time when these frequencies are inputted. Using an analog scope to test it, I found that the actual frequency of electrical impulses being sent to the bulb does NOT match the requested amount. (There’s a consistent 40 millisecond delay)

Further research has shown me that the imp.wakeup() method which I am using has limitations. For the numbers I need, the imp.wakeup() is probably not the most effective tool. (i.e. It looks like it takes too long to process my code which is causing the delay)

Does anyone know of a faster way to code a timer method that can handle these small numbers?

Sorry if this seems kind of confusing. Really what I’m looking for is an alternative to the imp.wakeup() method. :slight_smile:

Any help is much appreciated.


If you’re trying to just drive an output high and low at a specific rate, you can just use a PWM - you have to reconfigure it to change the frequency, but it’s timed down to the tens-of-nanoseconds level in hardware.

See, period, dutyCycle)

To have a 100Hz signal at 50% duty cycle (ie on for exactly half the time) you’d use:

hardware.pin1.configure(PWM_OUT, 1.0/100, 0.5);

Thanks so much! This is exactly what I was looking for!