LEDs
In this section, we will walk through the blink
example in Rust. It will blink in order each LED
of the board every second in an infinite loop (going back to the first LED after the last LED).
The number of LEDs available on the board is advertised by the led::count()
function. We want to
make sure there is at least one LED available:
// Make sure there is at least one LED.
let num_leds = led::count();
assert!(num_leds > 0, "Board has no LEDs.");
We start the infinite loop cycling through all LEDs in order:
// Cycle indefinitely through all LEDs in order.
for led_index in (0 .. num_leds).cycle() {
Within the infinite loop (notice the indentation), we first turn on the current LED using the
led::set()
function:
// Turn on the current LED.
led::set(led_index, led::On);
We now wait for half a second because we want to blink each LED for one second which means half a second on and half a second off:
// Wait before turning it off.
timer::sleep(Duration::from_millis(500));
Finally, we repeat the same process but turning the LED off before looping to the next LED:
// Turn it off and wait before turning on the next LED.
led::set(led_index, led::Off);
timer::sleep(Duration::from_millis(500));
The final code looks like this:
#![no_std] wasefire::applet!(); use core::time::Duration; fn main() { // Make sure there is at least one LED. let num_leds = led::count(); assert!(num_leds > 0, "Board has no LEDs."); // Cycle indefinitely through all LEDs in order. for led_index in (0 .. num_leds).cycle() { // Turn on the current LED. led::set(led_index, led::On); // Wait before turning it off. timer::sleep(Duration::from_millis(500)); // Turn it off and wait before turning on the next LED. led::set(led_index, led::Off); timer::sleep(Duration::from_millis(500)); } }
Testing
The host
runner currently has 1 LED and, either prints its state to stdout
(the default) or
blinks the LED in the Web UI (with --interface=web
). Eventually, the number of LEDs will be
configurable.
To build and install the applet on a connected platform:
wasefire rust-applet-install
The output in a host platform without Web UI (i.e. wasefire host
) should look like this:
Applet running.
Led is on
Led is off
Led is on
Led is off
Led is on
Led is off
Led is on
Led is off
Led is on
Led is off
Led is on
Led is off
Led is on
Led is off
Led is on
The applet was killed.
Where the applet was uninstalled (and thus killed) with wasefire applet-uninstall
.