Touchy Subject

Touch Interface

Learn It

  • The Micro:bit also has three general purpose input/output (called GPIO) connectors along the bottom of the unit. They're labelled 0, 1 and 2. There's also a connector that outputs a steady 3 volts (imagintively labelled 3V) and a connection to the negative end of the power supply (labelled GND).
  • We can use these as touch switches too.

Try It

  • Upload the following code to your Micro:bit:
from microbit import *

while True:
    if pin0.is_touched():
	display.show(Image.HAPPY)
    elif pin1.is_touched():
	display.show(Image.SAD)
    elif pin2.is_touched():
	display.show(Image.ASLEEP)
  • To test the program, hold the GND pin with one hand, then touch the 0, 1 and 2 pins with a fingertip on the other hand. Cool, eh?
  • If you're unsure of anything covered so far, this video tutorial will take you through it:

Accelerometer

Learn It

  • There are other sensors on the Micro:bit too. The accelerometer detects how level the Micro:bit is. It can measure in the x, y and z axis.
  • The amount of angle is measured in milli-g’s. A flat, level Micro:bit would report 0, with +25 or -25 being noticably angled.

Code It

  • Lets write some code!
from microbit import *

while True:
    x_acc = accelerometer.get_x()
    display.clear()

    if x_acc > 25:
	# set_pixel parameters are (xPos, yPos, LEDbrightness)
	display.set_pixel(4, 2, 9)
    elif x_acc < -25:
	display.set_pixel(0, 2, 9)
    else:
	display.set_pixel(2, 2, 9)
  • This program reads the x-axis angle of the Micro:bit, then lights an LED as appropriate. Approaching our code like this means that the y-axis is tricky to handle at the same time.
  • With variables, we could also handle the y axis too, though. This way, we could tilt both left-right and up-down. Let's write some pseudocode:
X=0
Y=0

WHILE True:
    x_acc = ACCELEROMETER X READING
    y_acc = ACCELEROMETER Y READING

    IF x_acc > 25 THEN
	X=4
    ELSE IF x_acc < -25:
	X=0
    ELSE:
	X=2
    END IF

    IF y_acc > 25 THEN
	Y=4
    ELSE IF y_acc < -25
	Y=0
    ELSE
	Y=2
    END IF

    CLEAR THE DISPLAY
    TURN ON THE LED AT POSITION X, Y.
END WHILE
  • If you're struggling with the concepts here, the video tutorial may be useful:

Badge It

  • Silver: Write the program shown above in MicroPython, and test it on your Micro:bit. Upload your code to BournetoLearn.com when done.
  • Gold: Use If statements to add code to use the 'in between' LEDs.
    • Hint: You might need to work from about 40 to -40 rather than 25 to -25.
  • Platinum: Write a race game. The player has to tilt the Micro:bit up and down 20 times, then a smiley face is shown. Players on different Micro:bits can compete to see who's fastest.
    • Bonus challenge: Make the game count down 3-2-1 before the race starts.

Validate