Flotilla-controlled Raspberry Pi internet radio

As you may know, I love making internet radios! I’ve been rediscovering the Flotilla modular physical computing devices lately, and as my first Python project with Flotilla it made sense to… make a radio with lovely controls.

Here’s what I used:

  • A Raspberry Pi 3 with updated Jesse Raspbian installed and an internet connection
  • A TV as a display and audio output (you can use powered speakers or headphones just as easily for the audio output).
  • A Pimoroni Flotilla Dock, Touch buttons, Slider, 8×8 Matrix display and rotary Dial – though you could do a bare bones version with just the Touch buttons.

First up I had to install mpc and mpd which I use to play radio streams:

sudo apt-get install mpc mpd

I had lot of problems on this new Pi with mpc & mpd hanging when I changed channels a few times – something I’d not experienced previously making Raspberry Pi radios with older versions of Raspbian. Here’s how to fix this: first open the mpd config file with nano like this:
sudo nano /etc/mpd.conf

Then edit these lines to remove some # signs (uncomment) and change the mixer_type from hardware to software so it looks like this:

audio_output {
type "alsa"
name "My ALSA Device"
device "hw:0,0" # optional
mixer_type "software" # optional
mixer_device "default" # optional
mixer_control "PCM" # optional
mixer_index "0" # optional
}

Now add some radio station URLs using the mpc add command. I added Radio 1, BBC World Service News, FIP and Radio 4. For example to add FIP I typed
mpc add http://chai5she.cdn.dvmr.fr/fip-midfi.mp3

You can find BBC radio URLs on my big list here.

You need 4 stations only as you only have 4 buttons for presets. They get added in order but you can check your list of presets by typing
mpc playlist

And you can change the order using the move command, for example to move station 4 to preset 2 just type:
mpc move 4 2

Then I wrote some Python code to talk to the Flotilla modules and play radio stations. Once I’d got mpc working properly the hardest thing was getting numbers on the Matrix display. I am very grateful to veryalien for their help on the Pimoroni forum getting this to work.

I made the radio graphic by sketching it out on graph paper and converting each row to binary (bottom row first!) then hexadecimal and added it to the list that contains the font for digits 1-4 as pinched from the Pimoroni javascript code for Rockpool.

Before running any Python code with Flotilla you have to stop the Flotilla daemon from running on the Pi by typing the following command:
sudo service flotillad stop

Then plug in your Flotilla modules and run the Python code below. You should see a little radio icon appear on the Matrix display to let you know it’s working. The slider adjusts the display brightness, the rotary Dial adjusts the volume, the Matrix display shows a number 1-4 to let you know which preset is selected (though you could easily have scrolling text with the station name – see the Pimoroni forum for details). Ctrl-c on the keyboard will stop the radio, clear the display and exit the script.

Happy listening!

#!/usr/bin/env python

# simple internet radio
# Script by Giles Booth x
# adapted from motor control script by Tanya Fish
# www.suppertime.co.uk/blogmywiki
# stop flotilla daemon before running Python with Flotilla

import os
import sys
import flotilla

# radio logo and font for digits 1-4
digits = [
    [0xff,0x81,0xad,0x81,0xff,0x02,0x04,0x08],
    [0x00,0xfc,0x30,0x30,0x30,0x30,0x70,0x30],
    [0x00,0xfc,0xcc,0x60,0x38,0x0c,0xcc,0x78],
    [0x00,0x78,0xcc,0x0c,0x38,0x0c,0xcc,0x78],
    [0x00,0x1e,0x0c,0xfe,0xcc,0x6c,0x3c,0x1c]
    ]

# Looks for the dock, and all of the modules we need
# attached to the dock so we can talk to them.

dock = flotilla.Client()
print("Client connected...")

while not dock.ready:
    pass

print("Finding modules...")
touch = dock.first(flotilla.Touch)
matrix = dock.first(flotilla.Matrix)
dial = dock.first(flotilla.Dial)
slider = dock.first(flotilla.Slider)

if touch is None or matrix is None or dial is None or slider is None:
    print("Some modules required were not found...")
    dock.stop()
    sys.exit(1)
else:
    print("Found. Running...")

os.system("mpc load")
dial_val = 0

# set initial brightness and radio logo
brightness = max(int((slider.position/1023.0)*100.0),1)
matrix.clear()
matrix.set_brightness(brightness)
for row in range(0, 8):
    for col in range(0, 8):
        if digits[0][row] & (1 << col):
            matrix.set_pixel(col, 7-row, 1)
matrix.update()

# Starts the loop going so it keeps working until we stop it
try:
    while True:

        new_brightness = max(int((slider.position/1023.0)*100.0),1)
        if new_brightness != brightness:
            brightness = new_brightness
            matrix.set_brightness(brightness)
            matrix.update()

# volume control using dial
        new_dial_val = int(float(dial.data[0])/10.23)
        if new_dial_val != dial_val:
            dial_val = new_dial_val
            os.system("mpc volume " + str(dial_val))

# Looks for a Touch module and listens for an input

        if touch.one:
            os.system("mpc play 1")
            matrix.clear()
            for row in range(0, 8):
                for col in range(0, 8):
                    if digits[1][row] & (1 << col):
                        matrix.set_pixel(col, 7-row, 1)
            matrix.update()

        if touch.two:
            os.system("mpc play 2")
            matrix.clear()
            for row in range(0, 8):
                for col in range(0, 8):
                    if digits[2][row] & (1 << col):
                        matrix.set_pixel(col, 7-row, 1)
            matrix.update()

        if touch.three:
            os.system("mpc play 3")
            matrix.clear()
            for row in range(0, 8):
                for col in range(0, 8):
                    if digits[3][row] & (1 << col):
                        matrix.set_pixel(col, 7-row, 1)
            matrix.update()

        if touch.four:
            os.system("mpc play 4")
            matrix.clear()
            for row in range(0, 8):
                for col in range(0, 8):
                    if digits[4][row] & (1 << col):
                        matrix.set_pixel(col, 7-row, 1)
            matrix.update()

# This listens for a keyboard interrupt, which is Ctrl+C and can stop the program
except KeyboardInterrupt:
    os.system("mpc stop")
    matrix.clear()
    matrix.update()
    print("Stopping Flotilla...")
    dock.stop()
Posted in radio, Raspberry Pi, Raspbian | Tagged , , , | Leave a comment

Rediscovering Flotilla

Back in 2015 I backed Pimoroni’s Flotilla modular physical computing devices on Kickstarter and got an early set. I had some fun exploring it, but the software and support materials weren”t quite ready at the time and I started a new job where I spent most of my time in KS3 and KS4 and my Flotilla kit lay neglected.

Flotilla comes into home port!

I’m about to start a new job as a primary school digital learning co-ordinator, and so I dug out my Flotilla bits as I they might be useful teaching physical computing in a simple way with attractive modular components.

First I updated firmware by using the excellent installation script on a fresh Raspberry Pi with up-to-date Raspbian:
curl https://get.pimoroni.com/flotilla | bash
This process updated the firmware on the Flotilla ‘dock’ – the main hub all the tentacles and sensors and output devices plug into, and it also installs all the software.

Setting sail with Flotilla

There are three main routes into doing things with your Flotilla. The first, and simplest, is the Cookbook: http://learn.flotil.la/cookbook. This appears to be written in Javascript and requires an internet connection but allows younger, or inexperienced, children to explore Flotilla’s modules using web-based games and activities. You do need all the right bits for each project though. My early large starter kit had the required modules for the Balance, Bat & Ball, Marble Maze, Moodlight, Reaction Time, and Virtual Pet games. Annoyingly I don’t have a light module I can’t run the weather station nor the Noise Maker despite having the plastic engraved plates for it.

The Reaction Time game is one of the simplest to set up and worked really well. The Rainbow LED lights change colour after a pause and up to 4 players compete to press their button first.

I really enjoyed the Marble Maze – tilt to guide a ball round a maze. Nothing you can’t do with a BBC Microbit, but the 8×8 matrix display is very bright and there’s something very pleasing about sticking a motion sensor on the back of it with blutak, discovering you have it on back to front and making your own little widget. Bat and Ball (Pong) just using a slider and rotary knob as paddles was surprisingly addictive too.

The second way of using your Flotilla is Rockpool – this does not require internet access, it runs as a local service in browser, and appears as under ‘Programming’ and ‘Education’ in the Raspberry Pi start menu.

Here you link inputs to outputs using a graphical interface, and you can add random number inputs, sine waves, square waves and modify them in quite sophisticated ways. For example, it’s very easy to wire up a slider to change colour and a dial to modify brightness:

Here I get changes in temperature to change colour of rainbow LED strip:

And in this example I made a random wandering pixel roaming around the 8×8 LED display matrix:

I did find that if I took browser focus away from Rockpool it really slowed down, but generally it worked well. You can do a lot here to make machines that work in real time, but – unless I’m missing something – there is no actual ‘programming’ here; you can’t make IF, THEN decisions and as such I don’t think you can create a game in Rockpool. I’m happy to be corrected if I’m wrong. I would love to give these toys to a small group of KS2 children to see what they can make – children are always far more creative and imaginative than me.

The Third Way is to use the Python IDE. I’ve not looked at this yet, but it would clearly address the lack of traditional programming. However, I sense a bit of a problem here. The Flotilla modules are beautifully-designed, highly attractive, tactile and will appeal very much to primary school age children, it will teach them about inputs and outputs, sensors and physical computing devices. – but it does not seem teach them programming in terms of sequence or selection. Python may be beyond the reach of most Primary aged children (although I intend to try to challenge this idea in my own teaching next year).

I think to be truly successful, Flotilla needs some kind of block programming environment (if one doesn’t already exist) to enable Primary aged children to not only make their own physical computing devices but program them in a way that supports the Computing curriculum.

Posted in computers, education, ICT, Raspberry Pi, Raspbian | Tagged , , , | 2 Comments

Raspberry Pi Wiimote Paint

People have done some cool stuff controlling Raspberry Pi robots with Nintendo Wiimotes. Now I don’t have any robot bits, but I do have an old Wii sitting unloved upstairs, so I found the remote, put batteries in it and started to think about what I could do.

I can’t drive a robot, but I can drive a turtle – a virtual Python graphics turtle. So I made a paint program that is controlled using a Wiimote. I based the code on the excellent example on the Raspberry Pi Spy web site – Python code below.

You are in effect driving the turtle, and as such I think this is possibly quite useful for teaching how Python turtles work as you have to think from the Turtle’s point of view: if it’s facing down you need to turn right to go left. I’ve added some code to get readings from the accelerometer to turn left & right as well as using the left & right arrow buttons.

Here’s what I did in order:

  • Found an original Nintendo Wii remote (NOT a Wii U!), put fresh batteries in it.
  • Got a fresh Raspberry Pi 3 (thank you Picademy!) with the current version of Raspbian – this has Bluetooth built in, no dongles needed.
  • Installed the cwiid library by typing sudo apt-get install python-cwiid in the Terminal.
  • Paired the Wiimote to the Pi by turning on Bluetooth on the Pi using the desktop GUI and making the Pi discoverable, and pressing the red button on the Wiimote.
  • Ran the Python code below in IDLE Python 2 – I used Python 2 because that’s what the original code used and the way I installed cwiid only made the library visible in Python 2.

Here’s how to use the program:

  • Run it in Python 2. Press the 1 & 2 buttons at the same time on the Wiimote and wait.
  • Move your turtle forward and backwards using the up & down arrows.
  • The left and right arrows rotate – but do not move – your turtle in increments of 5 degrees.
  • You can tilt the Wiimote left to turn left, tilt right to turn right.
  • Press A to change colour.
  • Press 2 to make the the line thicker, 1 to make it thinner.
  • Press + for pen up, – for pen down.
  • Press B to toggle ‘turbo’ mode – the turtle moves further with each press.
  • Press the home button to return your turtle to the middle of the screen.
  • Press home and B together to clear the screen (and get a little rumble!).
  • Press – and + together to quit the program (and get a bigger rumble).

Lots could be added to this – using the accelerometer for motion or clearing or changing colour, implement an undo, add background colours, more colours… and I’d really love to be able to have a Jackson Pollock paint spatter mode! Any ideas on how to code that gratefully received.

#!/usr/bin/python
# based on
# wii_remote_1.py
# Connect a Nintendo Wii Remote via Bluetooth
# and  read the button states in Python.
#
# Original Project URL :
# http://www.raspberrypi-spy.co.uk/?p=1101
#
# Author : Matt Hawkins
# Date   : 30/01/2013

# Modified by Giles Booth July 2017 to add paint program
# www.suppertime.co.uk/blogmywiki

# -----------------------
# Import required Python libraries
# -----------------------
import cwiid
import time
import turtle

button_delay = 0.1

print 'Press 1 + 2 on your Wii Remote now ...'
time.sleep(1)

# Connect to the Wii Remote. If it times out
# then quit.
try:
  wii=cwiid.Wiimote()
except RuntimeError:
  print "Error opening wiimote connection"
  quit()

print 'Wii Remote connected...\n'
print 'Press some buttons!\n'
print 'Press PLUS and MINUS together to disconnect and quit.\n'

wii.rpt_mode = cwiid.RPT_BTN | cwiid.RPT_ACC
fred = turtle.Turtle()
distance = 5
turn = 5
colourlist = ['red','orange','yellow','green','blue','purple','violet','black']
ink = 7
width = 1

while True:

  buttons = wii.state['buttons']
  AccVar = wii.state['acc']

  # detect extreme left & right tilt for turning
  if AccVar[0] < 100:
    fred.left(turn)
    print 'tilt left'
    print 'heading',fred.heading()

  if AccVar[0] > 140:
    fred.right(turn)
    print 'tilt right'
    print 'heading',fred.heading()

  # If Plus and Minus buttons pressed
  # together then rumble and quit.
  if (buttons - cwiid.BTN_PLUS - cwiid.BTN_MINUS == 0):
    print '\nClosing connection ...'
    wii.rumble = 1
    time.sleep(1)
    wii.rumble = 0
    exit(wii)  

  # If Home and B buttons pressed
  # together then rumble briefly and clear screen.
  if (buttons - cwiid.BTN_HOME - cwiid.BTN_B == 0):
    print 'Clear screen'
    wii.rumble = 1
    time.sleep(0.5)
    wii.rumble = 0
    fred.clear()

  # Check if other buttons are pressed by
  # doing a bitwise AND of the buttons number
  # and the predefined constant for that button.
  if (buttons & cwiid.BTN_LEFT):
    print 'rotate left', turn
    fred.left(turn)
    print 'heading',fred.heading()
    time.sleep(button_delay)         

  if(buttons & cwiid.BTN_RIGHT):
    print 'rotate right',turn
    fred.right(turn)
    print 'heading',fred.heading()
    time.sleep(button_delay)          

  if (buttons & cwiid.BTN_UP):
    print 'move forward',distance
    fred.forward(distance)
    time.sleep(button_delay)          

  if (buttons & cwiid.BTN_DOWN):
    print 'move backward', distance
    fred.backward(distance)
    time.sleep(button_delay)  

  if (buttons & cwiid.BTN_1):
    width = width - 1
    if width < 1:
      width = 1
    print 'thinner line',width
    fred.pensize(width)
    time.sleep(button_delay)          

  if (buttons & cwiid.BTN_2):
    width = width + 1
    print 'thicker line',width
    fred.width(width)
    time.sleep(button_delay)          

  if (buttons & cwiid.BTN_A):
    ink = ink + 1
    if ink > 7:
      ink = 0
    fred.color(colourlist[ink])
    print 'colour',colourlist[ink]
    time.sleep(button_delay)          

  if (buttons & cwiid.BTN_B):
    if distance == 5:
      distance = 10
      print 'turbo mode'
    else:
      distance = 5
      print 'normal mode'

    time.sleep(button_delay)          

  if (buttons & cwiid.BTN_HOME):
    if fred.isdown():
      fred.penup()
      fred.home()
      fred.pendown()
    else:
      fred.home()
    print 'Home'
    time.sleep(button_delay)           

  if (buttons & cwiid.BTN_MINUS):
    print 'pen down'
    fred.pendown()
    time.sleep(button_delay)   

  if (buttons & cwiid.BTN_PLUS):
    print 'penup'
    fred.penup()
    time.sleep(button_delay)
Posted in computers, education, ICT, Raspberry Pi, Wii | Tagged , , , , | 1 Comment

Robot poetry and storytelling in Scratch

There’s nothing new under the sun, and this is an old idea that went down incredibly well: generating random stories and poems by picking random words from word banks. I am grateful for my former colleague Cassie Wise for suggesting I do this for an interview lesson, which jogged my mind about Seymour Papert’s example in Mindstorms – which I translated into Python last summer:

Anyway, here are two cross-curricular English/Computing activities which would suit KS2 or KS3. I did the poetry in year 6 and the stories in year 5 and they were very engaging indeed. The computing concepts are simple but include random choices, list data structures, sequencing and possible concatenation of strings.

Robot Poetry

Robot storytelling

If you use these resources or have done something similar, I would love to hear your ideas and experiences.

Posted in education, ICT | Tagged , , , | Leave a comment

Simplest Scratch game?

Give a group of Year 9 girls the option to do some coding or watch a film at the end of term, and you think they’d want to watch a film.

Well not the last ever class I taught at my current school! They wanted to do some Scratch, some out of nostalgia because they hadn’t done it for years, and some because they had never done any Scratch coding.

On the spur of the moment I had to come up with what I thought was the simplest possible game I could, but keep it open-ended enough to challenge those who’d done some Scratch before. It was a fascinating lesson for me, and here’s the game I came up with. Use the mouse to help hungry bear eat the flying tacos, avoid the ladybirds! (Requires Flash).

It would clearly work with children much younger than year 9 (I did something similar with a year 4 class) but it was fascinating to see how something so simple kept Year 9s engaged for a double lesson. I’d love to know what you think!

Click here for a PDF of step-by-step instructions.

Posted in education, ICT | Tagged , , , | Leave a comment