14. is_pressed()
Returns True if the specified button button is pressed,
and False otherwise.
was_pressed()
Returns True or False to indicate if the button was
pressed since the device started or the last time this
method was called.
get_presses()
Returns the running total of button presses, and
resets this total to zero before returning.
button_a button_b
https://create.withcode.uk/
Methods
22. while True:
frame += 1
# show pipe
display.show(i)
# flap if button a was pressed
if button_a.was_pressed():
speed = -8
# show score if button b was pressed
if button_b.was_pressed():
display.scroll("Score:" + str(score))
# accelerate down to terminal velocity
speed += 1
if speed > 2:
speed = 2
# move bird, but not off the edge
y += speed
if y > 99:
y = 99
if y < 0:
y = 0
# draw bird
led_y = int(y / 20)
display.set_pixel(1, led_y, 9)
# check for collision
if i.get_pixel(1, led_y) != 0:
display.show(Image.SAD)
sleep(500)
display.scroll("Score: " + str(score))
break
from microbit import *
import random
display.scroll("Get ready...")
# Game constants
DELAY = 20 # ms between each frame
FRAMES_PER_WALL_SHIFT = 20 # number of frames between each time a wall
moves a pixel to the left
FRAMES_PER_NEW_WALL = 100 # number of frames between each new wall
FRAMES_PER_SCORE = 50 # number of frames between score rising by 1
# Global variables
y = 50
speed = 0
score = 0
frame = 0
# Make an image that represents a pipe to dodge
def make_pipe():
i = Image("00003:00003:00003:00003:00003")
gap = random.randint(0,3) # random wall position
i.set_pixel(4, gap, 0) # blast a hole in the pipe
i.set_pixel(4, gap+1, 0)
return i
# create first pipe
i = make_pipe()
# Game loop
# move wall left
if(frame % FRAMES_PER_WALL_SHIFT == 0):
i = i.shift_left(1)
# create new wall
if(frame % FRAMES_PER_NEW_WALL == 0):
i = make_pipe()
# increase score
if(frame % FRAMES_PER_SCORE == 0):
score += 1
# wait 20ms
sleep(20)
23. Creation
BIRD
# Make an image that represents a pipe to dodge
def make_pipe():
i = Image("00003:00003:00003:00003:00003")
gap = random.randint(0,3) # random wall
position
i.set_pixel(4, gap, 0) # blast a hole in the
pipe
i.set_pixel(4, gap+1, 0)
return i
led_y = int(y / 20)
display.set_pixel(1, led_y,
9)
Variable y: y-position of bird
PIPE
24. Game mechanism
While True:
frame += 1
# move wall left
if(frame % FRAMES_PER_WALL_SHIFT == 0):
i = i.shift_left(1)
# create new wall
if(frame % FRAMES_PER_NEW_WALL == 0):
i = make_pipe()
# increase score
if(frame % FRAMES_PER_SCORE == 0):
score += 1
20
100
50
25. Gravity
# accelerate down to terminal velocity
speed += 1
if speed > 2:
speed = 2
#move bird
y += speed
bird
26. Small details to note
# flap if button a was
pressed
if button_a.was_pressed():
speed = -8
sleep(20)
33. End
The final score is scrolled across the microbit display at the end of it.
34. Radio Module
1.import radio
List of Radio Functions:
● radio.on
● radio.off
● radio.reset
radio.send_bytes(message)
radio.receive_bytes()
radio.config(kwarg*)
radio.send(message)
radio.receive(message)
(zilong soften sound aft we started talking)
https://github.com/Pyconmicrobit2017
https://create.withcode.uk/
(Zilong)
And… I will be your computing teacher for today!
Behave yourselves because I am the only thing standing between you and lunch, ok? xD
So why should we choose micro:bit? Well firstly, it is veeerryyy small. [hold on to a microbit] Compared to Raspberry Pi and Arduino, it is about half the size, but yet, it packs more power than the Arduino. We can use the buttons or accelerometer to give input. This is perfect to introduce beginners into the world of computing.
We can code the micro:bit using the graphical Blocks Editor, but since this is PyCon, we will use MicroPython to program the micro:bit. [switch slides that show subset] It is a subset of python created specifically to run on a microcontroller. So how do we begin? [switch slides]
We can start coding from the official website (http://microbit.org/code/), or if you want to do it offline, you can use https://codewith.mu/#download. But today, we are going to use the emulator on Create With Code (https://create.withcode.uk/) to show the output on the big screen. To follow along the way, you can visit this github link over here. The source codes of the demonstrations that we will be showcasing later on, are already uploaded in the github link.
[switch to site] So here we are at the site, we can see 2 lines of normal python code that we are all familiar with, and a few other features here. I’m going to run the code with ctrl+enter instead of pressing the button to speed things up.
I can follow the instructions and input a name and it will do exactly what the code does.
But I don’t see any micro:bit here. What I’m going to do is to first import everything from microbit [from microbit import *]. We know that microbit only have a small 5 by 5 display. So, we need to change the print function into display.scroll.
I run the file again and input the name. Now you can see the words being displayed by scrolling through the display
We have the output done. But our input is still a text box. While you can do this on the emulator, there isn’t really a textbox for you to fill in when you are dealing with the microbit in real life. So what inputs do we have?
Now I will invite my colleague up…
(Pearlyn)
Thank you Zilong. For the next segment, we will be looking at some of the basic components of micro:bit.
Thus far, we have written some codes that make the micro:bit do something and produce some output. But what about getting the microbit to react and receive inputs? In normal programs, users enter input using the keyboard. For the micro:bit: we don't really see any keyboard...
But we do see something else… [next slide]
(Pearlyn)
In micro:bit, the most obvious mean of input will be these 2 buttons labelled A and B here. Pressing these buttons is equivalent to inputting values. In this case, a True value if the button is pressed, and a False value otherwise.
(Pearlyn)
Besides is_pressed, we have other functions such as was_pressed and get_presses.
As their names imply, was_pressed checks if the button was pressed since run-time. And if it was, a true value will be returned. Else, a false value will return.
The function get_presses() however, has 2 functions. Firstly, it returns to us the total number of button presses. Secondly, it resets this total to a zero before returning.
So, how do we get MicroPython to react to these buttons?
It’s simple, like A,B,C actually. In fact, it’s exactly what I just said in English!
Let’s go through this once by running through a quick code together
(zilong switch to sites to do live code1)
(Zixin) To understand the following game, first we will start off with the basic concept of creating a variable, which in this case will be named ‘test’ and assign a respective image to it. Note that ‘Image’ is a built-in function in micro-python, and it takes arguments from left to right, top row to bottom row to create a 5 x 5 grid of varying intensities, with value 0 being lowest,or off, and 9 being the brightest. Hence, if I use display.show(Image( '07070:00000:00400:60006:06660')), can anyone guess what this is? Yep thats right, its a smiley face, Similarly, you can create an budget eiffel tower here or paint some abstract art with these functions, you can create endless images up to your imagination!
(Zixin) To understand the following game, first we will start off with the basic concept of creating a variable, which in this case will be named ‘test’ and assign a respective image to it. Note that ‘Image’ is a built-in function in micro-python, and it takes arguments from left to right, top row to bottom row to create a 5 x 5 grid of varying intensities, with value 0 being lowest,or off, and 9 being the brightest. Hence, if I use display.show(Image( '07070:00000:00400:60006:06660')), can anyone guess what this is? Yep thats right, its a smiley face, Similarly, you can create an budget eiffel tower here or paint some abstract art with these functions, you can create endless images up to your imagination!
For example, we can create a simple asteroid game using some python and a few minutes. To make a beautiful painting, we first need to have an empty canvas, and that is the same for python. For creating the game background for it to play on, we will first have to initialise a set of grids. Let us briefly import the microbit library, and the random module here to create the positions of the asteroids, because a game where the asteroids fall from only one place would be a bit boring to say the least. Since python is an object-oriented programming language, we will start by defining 2 variables, the asteroids, and the spaceship, as each holding a different value. So, after we define the variables, the asteroids, being generated at random, will move down every 0.7s in successive motion or through what we call loops. So grid 3, being the top grid, would be shifted down to the 2nd grid, and the 2nd grid would be shifted down to the first grid, down to 0. In doing so, the integer values each asteroid carries are carried over to the subsequent grid, thus forming a moving frame. And eventually right before the end of a loop, if the asteroid is right on top of the spaceship, then at the next instance, the value of asteroid that will carried downwards will not tally with the initial value of the spaceship grid, and if we look at line 13, if the value of the grid on top of the spaceship is 4, which is the inherent value of asteroids, it would be different from the 9 that the spaceship holds. And thus it will issue a ‘break’ command and the game will end. Simple as that.
(Zixin) This game uses an accelerometer to sense movement and angular rotations, but that is just one of many tools we can incorporate into microbits. Microbits can also be connected to buzzers, passive infrared sensors, crash sensors, to create, alarm boxes, lie detectors, blood pressure tester, mini gameboys, percussion instruments, music game keyboard, who knows? It creates endless possibilities to benefit human lives, and that is up to you all to figure out.
We have covered buttons, led displays, and input/outputs. If we take a closer look here, we notice that there’s something called the accelerometer here.
As its name suggests, an accelerometer measures instaneous acceleration of the micro:bit in units of milli-gals (gals are simply units of acceleration).
So what does the accelerometer do?
The accelerometer has 2 functions, to either 1. Measure movement or 2. Detect Gestures.
Firstly, the accelerometer measures movement along three axes:
X - tilting from left to right.
Y - tilting forwards and backwards.
Z - moving up and down
To get the positions, we can do a simple “get_y”method for the y-axis or “get_z” for the z axis.
Most accelerometers either has two axis or three axis. The benefits of having 3 axis like that of micro:bit would mean we can get a more accurate 3D positioning and comprehensive movement of the microbit, opening up a new box of possibilities to explore with the micro:bit.
The really interesting side-effect of having such a 3 axis accelerometer is the ability to detect gesture gesture detection. (nxt slide)
If you move your micro:bit in a certain way (as a gesture) then MicroPython is able to detect this.
All we have to do is to call the accelerometer object at the start (accelerometer._____) and micropython will be able to recognise the following gestures: up, down, left, right, face up, face down, freefall, 3g, 6g, 8g, shake.
This would be a much more convenient way rather than constantly toggling with x,y,z values. Do take note that gestures are always represented as strings. The names of the gestures are pretty self- explanatory- (up down, left right) 3g, 6g and 8g gestures would refer to when the micro:bit encounters such levels of g-force (like when an astronaut is launched into space).
Similarly to the x,y, z positions, to get the current gesture, we first call the accelerometer object, then we a current_gesture method.
Now that we’ve learned the accelerometer module and have some knowledge of the input/ output function in MicroPython for micro:bit, let’s move on to how it can possibly be applied in the real world.
For that, I will be showcasing to you one of the projects my teacher undertook for the Dunman High Air Weapons Club.
This was coded by one of our teachers for the Air Weapons Club.
As Microbit has a built-in accelerometer, this device captures the data calculated by the accelerometer when it starts.
The user has 5 seconds to get into a stable position. This is equivalent to adopting the aiming phase of air pistol shooting. The 5 seconds is marked by a countdown "clock" displayed on the microbit. (press reset)
At 5 seconds, the x, y and z of the accelerometer measurement are taken as the reference readings.
For the next 10 seconds, any deviation from the x, y and z reference readings will contribute points to the total score
The lower the total score, the better the user is able to maintain her balance.
The final score is scrolled across the microbit display at the end of it.
Micro:bits are like computers, just, much more smaller. And without a keyboard and a screen. But! Like computers, it has the ability to connect devices together via simple wireless networks.
How? (nxt slife)
Through the radio module!
Because it’s a built-in module, we would have to first access the module using “import radio”
From there, the radio has several functions:
Today we will jus be focussing on radio.send and radio.receive
Going back to the demonstration i’ve just shown, the radio module can actually be applied here. In this case, the radio module is programmed into a separate microbit to remotely restart the trial. 1 microbit sends signal, and the other receives. This way, the coach can actually use the microbit 1 to simultaneously restart a set of 5, or more, microbits at the same time.
And that’s it for the radio :)
To piece things together, we have looked at the basic components of microbit, namely the buttons, display, accelerometer and radio function. These are really simply the building blocks of any microbit programme and there is much much more to uncover. I hope this segment gave you a better understanding of the basic functions of microbits.
For now, I will invite Siyin to do a final demo on how we can extend these basic functionalities of microbit by connecting it with additional accessories.
I will now have zixin to wrap things up!,
(Siyin)
The first one provides a comprehensive overview on the use of microbits, where to buy them, and how to incorporate them into our daily lives if you are feeling extra creative.
The second is a Singapore-based company, which provides public courses, along with blogs and documentations, for people of all walks of life to explore microbits.
The 3rd and 4th are part of the Microbit Open Source Project (MOSP), which aims to keep micropython and codes for related microbit projects available to everyone, so as to
hopefully add on to one another’s ideas and create positive, meaningful changes to this world.
(zIXIN)
Now, after you have discovered the various uses and potentials of microbits, you might be wondering where can I possibly purchase them? Well worry no more, as this website provides you with more than enough information over Asia Pacific, from ICOSA tech in Malaysia, to TinkerAcademy in Singapore, to Classroom in China. along with
https://gethacking.com/products/micro-bit-tinker-kit (Shipping to Malaysia and Indonesia available)