Mathematics Microbit
Normal
50 mins
120 points
What you need:
  • Computer/laptop
  • Microbit
  • USB Cable

Microbit Egg & Spoon Race

1 - Create a new Microbit project

Go to the makecode.microbit.org website and create a new project.

2 - Create a sprite variable called 'Egg'

Create the Egg sprite in the middle of the screen on start.

let Egg = game.createSprite(2, 2)

3 - Create a variable called 'XAcceleration'

Now we'll create a variable for the acceleration of the egg in the x-direction. We're going to use the Microbit's accelerometer and store it's x-value in our variable.

let XAcceleration = 0
basic.forever(function () {
    XAcceleration = input.acceleration(Dimension.X)
})

4 - Make the egg move left & right

We can use the XAcceleration variable to make the Egg move either left or right.

We'll need to check if the value of XAcceleration is above a certain threshold to make the egg move initially. We'll also need to check if the value is positive or negative (a positive value will make the Egg go right and a negative value will make it go left).

let Egg = game.createSprite(2, 2)
basic.forever(function () {
    XAcceleration = input.acceleration(Dimension.X)
    if (XAcceleration < -150) {
        Egg.change(LedSpriteProperty.X, -1)
    } else if (XAcceleration > 150) {
        Egg.change(LedSpriteProperty.X, 1)
    }
basic.pause(700)
})

Note that 150 is just an arbitrary value. You can change this value to make the Egg more or less reactive to movement.

Also, put in a pause block at the end of the code above if the egg is moving too fast!


5 - Make the egg move up & down

Use what you learned in previous steps to make the Egg move up and down!

see the code

You will need to create a variable called YAcceleration to store the acceleration for the Y axis (up and down), and then make the sprite move up or down based on that.

let Egg = game.createSprite(2, 2)
basic.forever(function () {
    XAcceleration = input.acceleration(Dimension.X)
    YAcceleration = input.acceleration(Dimension.Y)
    if (XAcceleration < -150) {
        Egg.change(LedSpriteProperty.X, -1)
    } else if (XAcceleration > 150) {
        Egg.change(LedSpriteProperty.X, 1)
    }
    if (YAcceleration < -150) {
        Egg.change(LedSpriteProperty.Y, -1)
    } else if (YAcceleration > 150) {
        Egg.change(LedSpriteProperty.Y, 1)
    }
    basic.pause(700)
})

Join our club 😃

To view the remaining 3 steps and access hundreds of other coding projects please login or create an account.

Copyright Notice
This lesson is copyright of Coding Ireland. Unauthorised use, copying or distribution is not allowed.
🍪 Our website uses cookies to make your browsing experience better. By using our website you agree to our use of cookies. Learn more