Cover image
    Activity

    Code a micro:bit to Toggle Positions

    Use button press to shift between servo positions.

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

    Code

    Press Button to Toggle Positions

    00:10

    Use a toggle variable to store the state of the Servo A position. 1 means one position, and 0 means another.

    When the Button A is pressed, use an if statement to check the value of the variable and then, depending on the value, set the position of the servo to 20 or 80, and toggle the value stored inside the variable.

    let toggle = 0
    input.onButtonPressed(Button.A, function () {
        if (toggle == 0) {
            sb.setServoPosition(sb.servo(SBServo.ServoA), 20)
            toggle = 1
        } else {
            sb.setServoPosition(sb.servo(SBServo.ServoA), 80)
            toggle = 0
        }
    })

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