Solutions to Challenges¶
Area of Triangle¶
Below is the solution this activity
from microbit import *
# welcome message
display.show(Image.TRIANGLE)
sleep(1000)
# define function for area of triangle
def area_triangle(base,height):
return 0.5 * base * height
# define function for entering number
def input_num():
i = 0
while True:
if button_a.was_pressed():
i = i+1
display.show(i)
sleep(700)
elif button_b.was_pressed():
display.show(Image.YES)
sleep(700)
return i
# get user input for base and height
display.scroll("base?")
b = input_num()
display.scroll("height?")
h = input_num()
# display area of traingle
display.scroll(area_triangle(b,h))
Binary to Decimal¶
Below is the solution this activity
from microbit import *
import math
value = 0
# enter your own decimal value
binary = list("11100011")
for j in range(len(binary)):
digit = binary.pop()
if digit == '1':
value = value + pow(2,j)
display.scroll('value is ' + str(value))
Bedside Light¶
Below is the solution this activity
from microbit import *
while True:
light = pin0.read_analog()
# use this to print the reading to REPL
# try to turn on and off the light and compare the values
print(light)
# i use 50 as threshold, might be different from your value
if light > 50:
# turns on the light
pin1.write_digital(1)
else:
# turns off the light
pin1.write_digital(0)
sleep(300)
Coin Flipper¶
Below is the solution this activity
from microbit import *
import random
while True:
# checks if micro:bit has been shaken
if accelerometer.was_gesture('shake'):
# generate random number from 0 to 1
if random.randint(0,1):
sleep(500)
display.show(Image.TORTOISE)
sleep(500)
display.show(Image.SKULL)
else:
sleep(500)
display.show(Image.SQUARE_SMALL)
sleep(500)
display.show(Image.SQUARE)
Consonant or Vowel¶
Below is the solution this activity
from microbit import *
import random
#define consonants and vowels
consonants = ['B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Y', 'Z']
vowels = ['A', 'E', 'I', 'O', 'U']
# initialize correct count
correct_answers = 0
# display welcome message and sleep for 1 second
display.show(Image.HEART)
sleep(1000)
while True:
# generate a number 0 to 2, where 0 will be vowel and 1 and 2 will be consonant
selected = random.randint(0, 2)
if selected:
display.show(random.choice(consonants))
else:
display.show(random.choice(vowels))
# 1 second timer
sleep(1000)
# if button a was pressed when consonant was displayed
if button_a.was_pressed() and selected:
correct_answers = correct_answers + 1
# display a check
display.show(Image.YES)
sleep(200)
# display current correct count
display.scroll(correct_answers)
sleep(300)
# of button b was pressed when vowel was displayed
elif button_b.was_pressed() and not selected:
correct_answers = correct_answers + 1
# display a check
display.show(Image.YES)
sleep(200)
# display current correct count
display.scroll(correct_answers)
sleep(300)
else:
# display an X
display.show(Image.NO)
sleep(500)
Earthquake Detector¶
Below is the solution this activity
from microbit import *
while True:
# detects seismic activity. Starting position is face up
seismic = accelerometer.get_x() + accelerometer.get_y()
# if connected to the usb and mu editor, you can plot the values using the plotter function
# on the mu editor
print(tuple([seismic]))
# if it detects earthquake it will make a sound
if abs(seismic) > 700:
audio.play(Sound.SOARING) # if using an external buzzer use pin0.write_digital(1) if connected to pin0
display.show(Image.ANGRY)
else:
audio.stop() # if using an external buzzer use pin0.write_digital(0) if connected to pin0
sleep(100)
Personal Safety Alarm¶
from microbit import *
display.show(Image.YES) set_volume(255) while True:
- if button_b.is_pressed() or button_b.was_pressed():
- display.show(Image.YES) audio.stop() cont = 0
- if button_a.is_pressed() or button_a.was_pressed():
- display.show(Image.SKULL) audio.play(Sound.SOARING)
sleep(100)
FireFlies¶
Below is the solution this activity
# A micro:bit Firefly.
# By Nicholas H.Tollervey. Released to the public domain.
import radio
import random
from microbit import display, Image, button_a, sleep
# Create the "flash" animation frames. Can you work out how it's done?
flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]
# The radio won't work unless it's switched on.
radio.on()
# Event loop.
while True:
# Button A sends a "flash" message.
if button_a.was_pressed():
radio.send('flash') # a-ha
# Read any incoming messages.
incoming = radio.receive()
if incoming == 'flash':
# If there's an incoming "flash" message display
# the firefly flash animation after a random short
# pause.
sleep(random.randint(50, 350))
display.show(flash, delay=100, wait=False)
# Randomly re-broadcast the flash message after a
# slight delay.
if random.randint(0, 9) == 0:
sleep(500)
radio.send('flash') # a-ha
Light Detector¶
Below is the solution this activity
import microbit as m
SUN_IMAGE = m.Image(
"90909\n"
"09990\n"
"99999\n"
"09990\n"
"90909")
MOON_IMAGE = m.Image(
"99900\n"
"09990\n"
"00990\n"
"09990\n"
"99900")
while True:
light = m.pin0.read_analog()
if light > 512:
m.display.show(SUN_IMAGE)
else:
m.display.show(MOON_IMAGE)
Love Meter¶
Below is the solution this activity
from microbit import *
import random
# welcme text and image
display.scroll("LOVE METER",delay=100)
sleep(1000)
display.show(Image.HEART)
while True:
if pin0.is_touched():
love_meter = random.randint(0,100)
# heart animation to build anticipation
for i in range(8):
display.show(Image.HEART)
sleep(500)
display.show(Image.HEART_SMALL)
sleep(500)
# scroll delay will change the speed of scroll, default is 150ms
display.scroll(str(love_meter) + "%",delay=200)
# resets the micro:bit
elif button_a.was_pressed():
reset()
Magic 8¶
Below is the solution this activity
from microbit import *
import random
answers = [
"It is certain",
"It is decidedly so",
"Without a doubt",
"Yes, definitely",
"You may rely on it",
"As I see it, yes",
"Most likely",
"Outlook good",
"Yes",
"Signs point to yes",
"Reply hazy try again",
"Ask again later",
"Better not tell you now",
"Cannot predict now",
"Concentrate and ask again",
"Don't count on it"
"My reply is no",
"My sources say no",
"Outlook not so good",
"Very doubtful",
]
while True:
display.show("8")
if accelerometer.was_gesture("shake"):
display.clear()
sleep(1000)
display.scroll(random.choice(answers))
Morse Code¶
Below is the solution this activity
from microbit import *
import music
morse_code = { 'A':'.-', 'B':'-...', 'C':'---.', 'D':'-..', 'E':'.', 'F':'..-.', 'G':'..-.', 'H':'--.',
'I':'..','J':'.---','K':'-.-','L':'.-..','M':'--','N':'-.','O':'---','P':'.--.','Q':'--.-',
'R':'.-.','S':'...','T':'-','U':'..-','V':'...-','W':'.--','X':'-..-','Y':'-.--','Z':'--..'}
message = 'HELLO'
for i in message:
# show the letter
display.show(i)
sleep(200)
for j in morse_code[i]:
if j == '.':
# show dot and play short tone
display.show(j)
music.play(['C:1','R:2'])
else:
# show slash and play long tone
display.show(j)
music.play(['C:4','R:2'])
sleep(200)
Motion Detector¶
Below is the solution this activity
from microbit import *
# connect signal pin of PIR sensor to pin0
# connect + pin of buzzer to pin1
while True:
# for debugging, prints analog reading to REPL
print(pin0.read_analog())
sleep(200)
# checks if motion is detected and display stick figure image
if pin0.read_analog() > 200:
display.show(Image.STICKFIGURE)
# send high signal to pin1 to sound the buzzer
pin1.write_digital(1)
sleep(100)
else:
# display square image if no motion detected
display.show(Image.SQUARE)
# send low signal to pin1 to silence the buzzer
pin1.write_digital(0)
sleep(100)
Step Counter¶
Below is the solution this activity
from microbit import *
step_count = 0
# display initial count
display.show(step_count)
while True:
# count up if step is detected, and display on screen
if accelerometer.was_gesture('shake'):
step_count = step_count + 1
# wait=False means it will not wait for the scroll animation to count up
display.scroll(step_count,wait=False)
# if button a is pressed, it will display step count
if button_a.was_pressed():
display.scroll(step_count,wait=False)
# if button b is pressed, it will reset the micro:bit and start count from 0
if button_b.was_pressed():
reset()
Candle¶
from microbit import *
import random
lit = True
while True:
if microphone.was_event(SoundEvent.LOUD):
lit = not lit
sleep(500)
if lit:
display.show(Image(
"00900:"
"09990:"
"09990:"
"09990:"
"09990"))
sleep(150)
flicker = random.randint(1, 3)
if flicker != 2:
display.set_pixel(2,0,0)
display.set_pixel(flicker,0,9)
sleep(150)
else:
display.clear()
Soil Moisture Sensor¶
Here is the solution
from microbit import *
counter = 0
while True:
# check for soil moisture reading
reading = pin0.read_analog()
# for debugging, prints value to REPL
print(reading)
# if reading goes below 100, it will check first if it is consistent across 10 readings
# before displaying that it is time to water the plants
if reading < 100:
if counter > 10:
display.show(Image.SAD)
counter = counter + 1
# if reading is above 100 then it will display an image that it is still fine
# it will also reset the counter
else:
display.show(Image.HAPPY)
counter = 0
sleep(1000)
Traffic Survey Data Logging¶
# Imports go at the top
from microbit import *
import log
log.set_labels('car', 'motorcycle', 'truck')
display.show(Image.YES)
while True:
if button_a.is_pressed():
display.show(Image('00000:'
'00990:'
'09990:'
'09090:'
'00000'))
log.add({'car': 1})
sleep(500)
display.clear()
if button_b.is_pressed():
display.show(Image('00000:'
'09990:'
'99099:'
'99099:'
'00000'))
log.add({'motorcycle': 1})
sleep(500)
display.clear()
if pin_logo.is_touched():
display.show(Image('99000:'
'99999:'
'99999:'
'09090:'
'00000'))
log.add({'truck': 1})
sleep(500)
display.clear()
if button_a.is_pressed() and button_b.is_pressed():
log.delete()
display.show(Image.SKULL)
log.set_labels('car', 'motorcycle', 'truck')
sleep(500)
display.show(Image.YES)
Traffic Light¶
Below is the solution this activity
from microbit import *
while True:
# green light on to allow cars to pass
pin0.write_digital(1)
# when pedestrian presses button a
if button_a.was_pressed():
sleep(1000)
# turns off green light
pin0.write_digital(0)
# turns on amber light
pin1.write_digital(1)
sleep(3000)
# turns off amber and turns on red light
pin1.write_digital(0)
pin2.write_digital(1)
# wait for pedestrian to pass
sleep(7000)
# turns off red and blink amber for about 4 secs
pin2.write_digital(0)
for i in range(1,10):
pin1.write_digital(i%2)
sleep(500)
pin1.write_digital(0)
Txting Program¶
Below is the solution this activity
# Add your Python code here. E.g.
from microbit import *
import radio
import random
import microbit
#setup radio
radio.config(length=251, channel=53, power=4)
sending = 1
def Phone():
#initialise radio
radio.on()
while True:
msg = str(radio.receive())
global sending
if sending >= 2:
sending = 0
#select page
while sending == 1:
message = 0
messages = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '(', ')', '"', ':)', ':(']
global tosend
tosend = messages[message]
sentance = []
while True:
msg = str(radio.receive())
#prevents errors
if message >= int(len(messages)):
message = int(len(messages))
#scrolls message when received
if msg != 'None':
display.scroll(msg)
display.show(tosend)
#scrolls through characters
if microbit.pin0.is_touched():
message = message - 1
tosend = messages[message]
display.show(tosend, delay=200)
sleep(200)
if microbit.pin1.is_touched() and tosend != 9:
message = message + 1
tosend = messages[message]
display.show(tosend, delay=200)
sleep(200)
#adds character to list
if microbit.button_a.is_pressed():
sentance.append(tosend)
tosend = messages[message]
display.scroll(tosend, delay=50)
#sends list as string
if sending == 1 and microbit.button_b.is_pressed():
radio.send(''.join(sentance))
display.scroll(''.join(sentance))
sentance = []
break
break
Phone()
Electronic Voting Machine¶
Below is the solution this activity:
Electronic Voting Machine (1 or more micro:bit)
from microbit import *
import radio
# turns on radio and configure channel number
radio.on()
radio.config(channel=1)
# initialize count variables
count_A = 0
count_B = 0
welcome = 1
# function for welcome message on display
def welcome_message():
global welcome
if welcome:
display.scroll("Voting Machine",delay=60)
welcome = 0
# function to display vote chosen
def voted(choice):
global welcome
display.show(Image.YES)
sleep(300)
if choice:
display.show("A")
else:
display.show("B")
sleep(3000)
# function to check for button presses and tally the votes
def vote():
global count_A,count_B,welcome
if pin2.is_touched():
display.scroll("Count A=" + str(count_A) + " B="+ str(count_B), delay=100)
sleep(500)
welcome = 1
elif button_a.is_pressed():
count_A = count_A + 1
voted(1)
elif button_b.is_pressed():
count_B = count_B + 1
voted(0)
def send_data():
radio.send(str(count_A) + " " + str(count_B))
for i in range(8):
display.show(Image.DIAMOND_SMALL)
sleep(300)
display.show(Image.DIAMOND)
sleep(300)
# changing channel number since you can only send data once
radio.config(channel=0)
sleep(500)
# main program, where the functions are called
while True:
welcome_message()
display.show(Image.STICKFIGURE)
vote()
if pin0.is_touched():
send_data()
sleep(500)
Main Command Center
from microbit import *
import radio
# turning on radio function and configure channel number
radio.on()
radio.config(channel=1)
# initialize count for candidates
count_A = 0
count_B = 0
while True:
message = radio.receive()
if message != None:
# since message is a string with both votes delimited by space, so it needs to be splitted
# and converted to integer
msg_str = list(message.split(" "))
msg = [int(i) for i in msg_str]
# count is being done here
count_A = count_A + msg[0]
count_B = count_B + msg[1]
display.scroll("A=" + str(count_A) + " B=" + str(count_B))
else:
display.show(Image.SQUARE_SMALL)
# pressing button a will give you the tally of votes
if button_a.is_pressed():
display.scroll("A=" + str(count_A) + " B=" + str(count_B))
sleep(500)