Science Oxford Logo

Adding an Alarm

Setting your alarm time

You need to use variables to set the time your alarm should go off.

Before your while True loop, add two new lines:

alarm_hour = '11'
alarm_minute = '30'

This tells the micro:bit that you want the alarm to go off at half past 11 - change the numbers in the quote marks to pick your alarm time.

While you are testing your code, keep changing this to be in 1 minute's time!


Comparing the times

You need to ask the micro:bit to compare the current time, to your alarm's time, so it knows whether to go off or not.

A good place to do this is in your else statement - so the micro:bit will check every time it loops.

To compare things in Python, you use a double equals sign, like this:

time['hours'] == alarm_hour

This line asks if the two things are the same (is the current hour the same as the alarm's hour?).

To use this in your code, you can use another if statement:

time = get_time()
if time['hours'] == alarm_hour:
    audio.play(Sound.TWINKLE)

This only compares the hour, not the minutes!

So it needs expanding with an and:

time = get_time()
if time['hours'] == alarm_hour and time['minutes'] == alarm_minute:
    audio.play(Sound.TWINKLE)

If this code is inside your else block, which runs every loop unless you press a button, the alarm will go off once your chosen time is reached.

A full version of this code is below for you to add to your program, modify, and test.


display.show(Image.DUCK)
sleep(1000)

alarm_hour = '11'
alarm_minute = '30'

while True:
    if button_a.is_pressed():
        time = get_time()
        display.scroll(time['year'])

    else:
        time = get_time()
        if time['hours'] == alarm_hour and time['minutes'] == alarm_minute:
            audio.play(Sound.TWINKLE)

        display.clear()
        sleep(100)

Download the example here.