The following page provides an example of fading an LED in and out.
Background
To modify the brightness of an LED, we utilise Pulse-Width-Modulation (PWM) – modifying the duty cycle of a square wave to control its average supply power.
Example
As usual, first the required functions from the API are imported.
import("reset_all_io_type_cfg")
import("set_io_type_cfg")
import("set_pwm")
import("set_gpio")
import("msleep_f")
Next (again, as usual) set the I/O to the desired type:
PWM_PIN = 1 LOOP_COUNT = 10 reset_all_io_type_cfg() set_io_type_cfg(PWM_PIN, PWM) set_io_type_cfg(PIN2, GPIO_OUT) set_io_type_cfg(PIN3, GPIO_OUT)
A helper function, which returns true if the number argument passed to it is even (false otherwise), is added to simplify some of the script:
function is_even(x)
return ((x & 1) == 0)
end
Set other LEDs (present depending upon target hardware) to GND in order to not obscure the fading LED.
-- Set other LEDs to GND set_gpio(PIN2, LOW) set_gpio(PIN3, LOW)
The core LED fade algorithm is as follows:
for i=1,LOOP_COUNT do
for j=5,PWM_MAX do
if is_even(i) then
set_pwm(PWM_PIN, j)
msleep_f(100/j)
else
set_pwm(PWM_PIN, (PWM_MAX-j))
msleep_f(100/((PWM_MAX+5)-j))
end
end
end
On many of the Beta release hardware boards, PIN1 is also tied to LED4. If running on a Beta release board, you will notice LED4 fade in and out (so don’t require external hardware to achieve this).
Finally, lets discard all of the variables, functions etc, that are now unused (to re-acquire the memory they utilise). Also, for good measure, force a garbage collection.
PWM_PIN = nil LOOP_COUNT = nil reset_all_io_type_cfg = nil set_io_type_cfg = nil set_pwm = nil msleep_f = nil collectgarbage()
That’s it!