Cover image
    Activity

    Code a micro:bit as a Light Switch

    Toggle as an on and off light switch.

    Coding
    Get Started
    8-14+
    40:00
    micro:bit Coding Cards

    Code

    Light Switch

    00:10

    Use a toggle variable to store the state of the RGB LED A. 1 means on, and 0 means off.

    When the Button A is pressed, use an if statement to check the value of the variable and then, depending on the value, turn the LED on or off, and toggle the value stored inside the variable.

    let toggle = 0
    input.onButtonPressed(Button.A, function () {
        if (toggle == 0) {
            sb.setRgbLedColorRGB(sb.rgbLed(SBRgbLed.RgbLedA), 100, 0, 0)
            toggle = 1
        } else {
            sb.setRgbLedColorRGB(sb.rgbLed(SBRgbLed.RgbLedA), 0, 0, 0)
            toggle = 0
        }
    })

    If using micro:bit for the first time, follow this setup.