Tuesday, 20 September 2016

Microbit making Minecraft Earthquakes

In this tutorial you are going to connect your Microbit up to your Raspberry Pi and program them so that when your Microbit is shaken it creates an earthquake in Minecraft.

This is part of a workshop I delivered at PyConUK 2016 - download the complete worksheet.

You are going to connect your micro:bit’s pins to the Raspberry Pi gpio pins using some cables and crocodile clips; programs on the micro@bit and Raspberry Pi will make Steve shake in Minecraft.

Install mu
To put you python program on your Micro:bit you will need the editor mu.

Open a Terminal (Menu > Accessories > Terminal) and type:
sudo apt-get update
sudo apt-get install mu
Angry micro:bit
The first task is to program your micro:bit so it gets angry when it's shaken.
  • Connect your micro:bit to the Raspberry Pi using the USB cable.
  • Open mu to create a new Python program for your micro:bit by clicking on Menu > Programming > mu.
  • Click New and type the following code into the editor.
from microbit import *
while True:
    if accelerometer.current_gesture() == "shake":
  • Click Flash to put your program on your micro:bit.
When the yellow light on the back of your micro:bit stops flashing your program will run.
You should see a happy face on your micro:bit - until it’s shaken!

Any errors will be scrolled on your micro:bit’s leds; if you get an error check your code carefully.

Now you need to finish your micro:bit program so that it turns pin 0 on and off when it's shaken
  • Go back to Mu and modify your program so that it turns pins 0 on (1) and off (0) when shaken.
from microbit import *
while True:
    if accelerometer.current_gesture() == "shake":
  • Click Flash to put your program on your micro:bit.
Connect it up
Next you will use a jumper cable and a crocodile clip to connect your micro:bit to the Raspberry Pi.
  • Connect the jumper cable to GPIO17 on the Raspberry Pi
  • Clip the crocodile clip to the end of the jumper cable
  • Clip the other end of the crocodile clip to pin0 on the micro:bit

Shake Steve
You now need to create your Minecraft program to shake Steve when the micro:bit is shaken and pin0 is set to 1.
  • Click Menu > Games > Minecraft: Pi Edition to run the game.
  • Click Start Game, then click Create New (or choose an existing one) to enter a world:
  • Press ESC to go back to the Minecraft menu but leave the game playing.
  • Open Python IDLE by clicking Menu > Programming > Python 3.
  • Use File > New Window to create a new program and save it as ‘mc_micro.py’.
  • Type the following code into the program to import the modules you will need
from mcpi.minecraft import Minecraft
from gpiozero import DigitalInputDevice
from time import sleep
  • Create a connection to Minecraft using the code.
mc = Minecraft.create()
  • Post a message to the chat window.
mc.postToChat("Micromine bitcraft earthquake")
  • Run your program by clicking Run > Run Module.
You should see your message appear in the Minecraft chat window.

Any errors will be displayed in the Python Shell in red.

Update your program to shake Steve, by adding the following code at the bottom of your program.
  • Create a pin which is connected to Pi GPIO 17 and micro:bit pin 0.
pin0 = DigitalInputDevice(17)
  • Create a loop which constants gets Steve’s position.
while True:
    pos = mc.player.getPos()
  • If pin0 is on (1) it adds 0.5 to Steve’s height (y).
    if pin0.value == 1:
        pos.y = pos.y + 0.5
  • Run your program by clicking Run > Run Module.
Shake your micro:bit and Steve will be shaken in Minecraft.

Can you change the program so that it creates a more realistic earthquake by adding random values to the x, y, z values.

Complete the worksheet from PyConUK 2016 which includes using the micro:bit buttons to makes blocks disappear and appear.

Friday, 17 June 2016

Mayhem 2 - an open source cave shooter

I recently ported an abandoned version the classic amiga game, Mayhem, to the Raspberry Pi - I did this exclusively so I could play the game with my friend, Lee, using RetroPie.

Since then myself and Lee, an artist for sumo digital, have been modding the game, adding new levels, features and controls - it now really is Mayhem 2.

Mayhem 2 is available for Windows and Raspberry Pi.

I'm hoping there will be lots more features and changes to the game over the coming months, if anyone has any idea's or would like to contribute it would be great to hear from you.


Mayhem 2 is a multiplayer (2 - 4) flight shooter with a really simple objective - destroy your opponents before they destroy you.

Your ship has limited fuel which will run down when you boost, if you run out you will be unable to control your ship, to refuel, land on any flat surface.

You can protect yourself from attack using your shields which will stop all bullets, be careful though your shields run down quickly and you wont be able to boost while your shields are on.

Power -ups are dropped (sometimes) when a player is destroyed (by either crashing or being shot) and when collected will give you a temporary boost such as a triple-shot weapon, better shields or more thrust.

New levels have been added including new ones with no edges, where you can seamlessly fly across the edge of the map.


Levels 1-3 are the original game levels, all other levels are new to Mayhem 2.

DCA are anti spaceship guns which will fire at the player if they get too close.

Wall collision can be turned off for new players to get used to the controls and playing the game.


Mayhem 2 supports  joystick and keyboard control, joystick controls can be configured via the main menu.

Default joystick controls, assume an "xbox / ps like" joystick:

Stick 1Left / Right
Button 1 (A)Thrust
Button 2 (B)Shield
Button 6 (RB)Fire

If joysticks are connected, they are used as the players controls, if there are less than 4 joysticks connected, keys are used for the rest of the players in order:

2leftrightpad delpad 0pad enter


For windows:

Download the zip file from https://github.com/martinohanlon/mayhem/archive/master.zip, open and copy mayhem-master to a folder.

Double click Mayhem2.exe in the mayhem-master folder.

Note - You maybe presented with message saying that the application was stopped from starting as it is unrecognised, click 'more info' and and choose 'run anyway'.

For Raspberry Pi:

Open a terminal and type:
sudo apt-get install liballegro4.4 liballegro4-dev
git clone https://github.com/martinohanlon/mayhem-pi
Run using:
cd mayhem-pi

The full source code is available on GitHub for Windows and Raspberry Pi.

Thursday, 19 May 2016

Raspberry Pi - Playing a Sound File with Python

A question I get asked a lot in Picademy is how to I play a sound file using Python.

Using just whats on the standard Raspbian image the easiest way, IMO, is to use Pygame.

This small code snippet below shows you how. Just put the wav file in the same place as your program.

import pygame
from time import sleep

#Initialise pygame and the mixer

#load the sound file
mysound = pygame.mixer.Sound("mysound.wav")

#play the sound file for 10 seconds and then stop it

You will have to use wav files, as opposed to other sounds files such as mp3, ogg, etc - use media.io to convert them.

Tuesday, 12 April 2016

Mayhem, Amiga game, ported to Raspberry Pi

Update - I've taken Mayhem forward to create Mayhem 2.

I had a Commodore Amiga and a game I played, a lot, was Mayhem, its a multiplayer (2-4) shooter - imagine multiplayer asteroids, with gravity, fuel and shields!

It was ported to the PC in 2002 by devpack who released the code in 2011 on github and google code which is where I picked it up and ported it to the Raspberry Pi.

This is the port, but check out the original Amiga game.

I got some help from the Raspberry Pi forums in getting it to compile then it was case of sorting out a few case sensitive filename bugs (it was original written for Windows!) and tracking down a bug in the original code which was causing a memory access error and segmentation fault.

The code is on github.com/martinohanlon/mayhem-pi.

sudo apt-get install liballegro4.4 liballegro4-dev
git clone https://github.com/martinohanlon/mayhem-pi

cd mayhem-pi

Player 1 - z, x, c, v, g
Player 2 - left, right, pad del, pad 0, pad enter
Player 3 - b, n, 'comma', m, l
Player 4 - y, u, o, i, 0
Change level - 1, 2, 3

If you want to modify the game, I've got a couple of things on my list, you can recompile it with.
cd mayhem-pi

Sunday, 27 March 2016

Raspberry Pi - Take screenshots of Minecraft

If you going to take a screenshot of Minecraft: Pi edition (or anything else for that matter), I really like a command line utility called raspi2png, its simple and screenshots images which have been created using the GPU (like games) as well.

Open a terminal and clone the repository from github:
cd ~
git clone https://github.com/AndrewFromMelbourne/raspi2png

Change directory to raspi2png and run the program's help to show all the options:
cd ~/raspi2png
./raspi2png --help
Usage: raspi2png [--pngname name] [--width ] [--height ] [--compression ] 
[--delay ] [--display ] [--stdout] [--help]

    --pngname,-p - name of png file to create (default is snapshot.png)
    --height,-h - image height (default is screen height)
    --width,-w - image width (default is screen width)
    --compression,-c - PNG compression level (0 - 9)
    --delay,-d - delay in seconds (default 0)
    --display,-D - Raspberry Pi display number (default 0)
    --stdout,-s - write file to stdout
    --help,-H - print this usage information

To take screenshot you have to use the -p option and pass an image filename:
./raspi2png -p myscreenshot.png
Another really useful option is -d to delay when to take the picture, this enables you to get the screen ready for a shot - to take a picture delayed by 10 seconds:
./raspi2png -p mydelayedshot.png -d 10
The image files will be created in the ~/raspi2png directory - if you want them in a different directory use a full path:
./raspi2png -p /home/pi/mydir/myscreenshot.png
If you use a filename which already exists raspi2png will overwrite the file without warning and the old image will be lost.

Fyi - I wrote this blog post using a Raspberry Pi 3...  First time I've used a Pi to write about a Pi - thats progress!

Friday, 25 March 2016

Microbit - get data from USB

As part of my Minecraft, a Microbit and an X-Wing project, I used the USB to read data from the Microbit's accelerometer and buttons to make the X-Wing move.

@NCSComputing on twitter has started re-using the code to make other things happen, so thought it would be a good idea to write up how it works, so others can do the same.

To make this work you need one program which runs on the Microbit and prints data and a second runs on your computer (a Raspberry Pi, PC, Mac, anything with a USB port) which reads the data via a serial connection.

See github.com/martinohanlon/microbit-serial for the code for both of these programs.

The Microbit
The microbitreaddata.py python program runs on the Microbit, gets the data and prints it to the output, which in this case is the USB serial connection, and should be flashed to your computer using the Python editor:
from microbit import *


def get_data():
    x, y, z = accelerometer.get_x(), accelerometer.get_y(), accelerometer.get_z()
    a, b = button_a.was_pressed(), button_b.was_pressed()
    print(x, y, z, a, b)

def run():
 while True:


Your Computer
The clientreaddata.py python program runs on the computer and reads the data using pyserial:
import serial

#the port will depend on your computer
#for a raspberry pi it will probably be /dev/ttyACM0
#PORT = "/dev/ttyACM0"
#for windows it will be COM(something)

BAUD = 115200

s = serial.Serial(PORT)
s.baudrate = BAUD
s.parity   = serial.PARITY_NONE
s.databits = serial.EIGHTBITS
s.stopbits = serial.STOPBITS_ONE

    while True:
        #read a line from the microbit, decode it and
        # strip the whitespace at the end
        data = s.readline().rstrip()

        #split the accelerometer data into x, y, z
        data_s = data.split(" ")
        x, y, z = data_s[0], data_s[1], data_s[2]
        a, b = data_s[3], data_s[4]

The values of the accelerometer will be put into the variables x, y, z and the buttons in a & b.

Setting the PORT
You will have to change the PORT variable in the clientreaddata.py program to the comm port that the Microbit is connected to on your computer.

For a Raspberry Pi it is probably "/dev/ttyACM0", in the event it isn't, unplug the Microbit and run:
ls /dev/tty*

Then plug the Microbit and run the command again, the new device which appears will be the port of your Microbit.

For Windows it will be "COM#", the # being a number, the easiest way is to look in Device Manager for the "mBed Serial Port (COM#)"

Raspberry Pi gpiozero holdable button

The current release of gpiozero doesn't have the support to hold a button down e.g. when a button is pressed and then held down for 1 second something happens.

This is really useful when building hardware projects and you want 1 button to do 2 things, say turn something on when pressed, and turn off when held down.

I needed this for a project so I thought I would create a new HoldableButton class using gpiozero. Hopefully this will be incorporated into gpiozero, but until then you can use the class below.

The code is also available here as a gist.

You will need to add the HoldableButton class to your Python program:
from gpiozero import Button
from threading import Timer

class HoldableButton(Button):
    def __init__(self, pin=None, pull_up=True, bounce_time=None, 
                 hold_time=1, repeat=False): 

        super(HoldableButton, self).__init__(pin, pull_up, bounce_time)

        # Set Button when_pressed and when_released to call local functions
        # cant use super() as it doesn't support setters
        Button.when_pressed.fset(self, self._when_button_pressed)
        Button.when_released.fset(self, self._when_button_released)

        self._when_held = None
        self._when_pressed = None
        self._when_released = None
        self._is_held = False

        self.hold_time = hold_time
        self.repeat = repeat
        self._held_timer = None

    #override button when_pressed and when_released
    def when_pressed(self):
        return self._when_pressed

    def when_pressed(self, value):
        self._when_pressed = value

    def when_released(self):
        return self._when_released

    def when_released(self, value):
        self._when_released = value

    def when_held(self):
        return self._when_held

    def when_held(self, value):
        self._when_held = value

    def is_held(self):
        return self._is_held

    def _when_button_pressed(self):
        if self._when_pressed != None:

    def _when_button_released(self):
        self._is_held = False
        if self._when_released != None:

    def _start_hold(self):
        self._held_timer = Timer(self.hold_time, self._button_held)

    def _stop_hold(self):
        if self._held_timer != None:

    def _button_held(self):
        self._is_held = True
        if self._when_held != None:
            if self.repeat and self.is_pressed:
Using the HoldableButton class is pretty simple, similar to the gpiozero Button class and can be swapped for the Button class with no other changes.
holdbutton = HoldableButton(pin, hold_time = 1, repeat = False)
You have to pass a pin number and optional hold_time and repeat values:
  • hold_time - is the number of seconds after the button is pressed before the button is consider 'held'
  • repeat - is a boolean and if set to True will occur 'button held' events to be repeated after each hold_time
You can use all the same methods and properties of the Button class, when_pressed, when_released, is_pressed, etc.

There are 2 additional properties is_held, which will return a boolean stating whether the button has been held down for the 'hold_time' and when_held which when assigned a function will cause the function to be called when the button is held down.
def myheldfunction():
    print("button held")

holdbutton.when_held = myheldfunction
Now when a button is held down, the function will be called and "button held" printed.