Cover image
    Activity

    Code a micro:bit to Gradually Change Position

    Every time a button is pressed on the micro:bit, the servo's position incrementally increases by 4 until it reaches a value of 100.

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

    Code

    Gradually Change Position

    00:10

    Create a variable position to store a value, and then continuously set the Servo A position to its value. Every time the Button A is pressed, increment the variable by 4 units, and constrain it so that its value doesn't go over 100.

    input.onButtonPressed(Button.A, function () {
        position = Math.constrain(position + 4, 0, 100)
    })
    let position = 0
    position = 0
    basic.forever(function () {
        sb.setServoPosition(sb.servo(SBServo.ServoA), position)
    })

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