Cover image
    Activity

    Code a micro:bit to Tilt and Move

    Control a servo's position based on tilting the micro:bit.

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

    Code

    Tilt to Move

    00:10

    Continuously store the value of the x axis of the accelerator in the variable movement. Since the accelerator gives readings in the range -1023 to 1023, use a map to convert it to the range 0 to 100 and store it in the position variable. Set the Servo A to the value of the position variable.

    let movement = 0
    let hue = 0
    basic.forever(function () {
        movement = input.acceleration(Dimension.X)
        hue = Math.map(movement, -1023, 1023, 0, 100)
        sb.setRgbLedColorHSB(sb.rgbLed(SBRgbLed.RgbLedA), hue, 100, 100)
    })

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