Monday, December 14, 2015

RGB LED pixel ring with Raspberry Pi, Crumble and CodeBug

I've seen the Adafruit RGB LEDs in a number of projects and thought they were very cool. From doing some research they are controlled using a WS2812 and there are a number of sellers selling strips and rings based on the same driver and RGB LEDs.

On a recent trawl of eBay I came across the following RGB LED Ring 24 Bit WS2812B 5050 RGB LED with Integrated Driver 
24 pixel RGB LED ring

When it arrived I'd to solder a few wires to it.  5V, GBD and DI (in).  These pixels are controlled using a custom one wire protocol, so all 24 or more LEDs can be controlled with 1 pin.  There is also a DO (out) which allows you to chain the rings. Taking the DO from the first and attaching to the DI of the second.

Over the past year I've acquired a Crumble and a CodeBug in addition to the Raspberry Pi
Both the Crumble and CodeBug use a block based programming system and have the ability to control RGB LEDs, so to test the ring I started with the Crumble as it was nearest to me. I put together a short little program and it worked.  The code below is v2 with a small animation on collision.  For the Crumble it's connection D that you attach the LEDs to.

Crumble Code

Once I was sure it worked I noticed that CodeBug had an RGB LED example that I hadn't seen before. They call them GlowBugs. The web interface has the option for enabling the Star which attaches to the header and 5 or 10 GlowBugs. I enabled 10, did the code to make 10 change colour and it worked perfectly.  The great thing with the CodeBug is it is programmed using a web interface, nothing to install. When you do a download you just drag and drop the file to the CodeBug which is seen as a drive and that's it. No drivers or funky settings needed.
Since I had nothing to lose I set the counter to 24 to see if it would drive all 24 LEDs. Again success. So, the CodeBug can handle more than the pre-selected 10.  For the CodeBug it's connection 3 that you attach the LEDs to. You have to click the cog in the emulator  pane on the left and enable the GlowBug for them to work.

CodeBug Code 

That's 2 platform down.  Just the Raspberry Pi to go.
As mentioned above the protocol for these LEDs is custom and my understanding is timing specific and so getting it to work on the Raspberry Pi may be more difficult.

Then Twitter and the great +ForToffee  came to my rescue. with the following Tweet.

So, the UnicornHat from Pimoroni also uses the WS2812, brilliant. These guys usually have good libraries and code so I found it on GitHub

From the I used the curl command to do the install.

\curl -sS | bash

This was on an updated Jessie on a Raspberry Pi 2 and it installed perfectly.
I went to the examples folder and ran  This is expecting an 8x8 matrix, but even on a 24 pixel ring it looked great.
One thing not noted, pr that I couldn't find is that the LEDs are connectioned to BCM pin 18, the hardware PWM pin.

Once it worked I then had to figure out how to address each pixel individually. 
As you'd expect the UnicornHat code is all designed for an 8x8 matrix and not a circle, so running the LEDs from 1-24 caused the actual LEDS to light up out of sequence..I thought I was going to have to do some kind of look up to match the X,Y for the matrix code with the individual LEDs but then looking at the GitHub repo there was more details on the WS2812 code.

At the bottom of the was the following reference.

Based Upon rpi_ws281x

Unicorn HAT is based upon a modified, Pi 2 compatible version of the RPi ws281x Library by Jeremy Garff.
The library was modified by Richard Hirst.

So, I checked Richard Hirst's GitHub and found an example that didn't look too complicated.

OK, at first sight it looked complicated, but after reading it a bit I figured it out.
Colours are done in HEX
Line 16 in the code sets the number of LED. I changed this to 24 and ran the code.
Worked first time.

Looking at the code again.
Lined 25 - 35 are just setting up some preset colours.  

So, change line 16 to set the number of LEDs and lines 25-35 if you want to pre-set colours.

Other than this all code up to line 67 doesn't need to be touched.
It just works and my motto is if it aint broke don't fix it.

The try: just cycles through the LEDs setting their colours 

The two key commands in this block are. 

ws.ws2811_led_set(channel, i, color)
This sets a colour for LED i (Note LED numbers start from zero)

resp = ws.ws2811_render(leds)
This command actually does the setting.
So, if you want to change a number of LEDs at the same time use the ws.ws2811_led_set command for each LED and then run a single ws.ws2811_render command to actual set the LEDs.

After modifying the code I could control each LED.

In summary these RGB LED rings work just like Neopixel with the WS2812 driver. 
They work great with Crumble, CodeBug and Raspberry Pi. Coding is easy and special set up is only required for the Raspberry Pi, but with the UnicornHat library install it's really easy to get working with python.

These LED rings if driving a lot of the LEDs with bright colours can use a lot of power. I'd recommend powering from an external 5V supply. The Crumble specifically will not power them from the USB through the Crumble.
I have a Crumble battery holder for 3 x AA batteries that I used for each of the setups to power the LEDs, For the Crumble and CodeBug the batteries also powered the boards as well.  While for the Raspberry Pi I used an external 5V supply for the Raspberry Pi and the batteries for the LEDs making sure to connect the ground pins together to ensure that the whole circuit has the same GND reference.
I don't know how the actual UnicornHat powers the LEDs when on the Raspberry Pi

Side Note:
I haven't tested with Arduino yet, but since these things have been controlled by Arduino for years already I expect it to just work.  I have a Digispark ATTINY85 that is really small and is suppose to work as well since it's basically a minimal Arduino compatible.  So, will give that a try.

Thursday, November 12, 2015

Codebug - Flashing LED tree made with conductive paint

Last year I made some conductive paint using this Instructable.  For me 50:25 by weight, paint to graphite powder works great. Make sure to stir in slowly otherwise the graphite powder will fly.
With this mix the paint is easy to apply yet has good conductivity.
It worked great and I used it at a Raspberry Jam to make flashing LED eyes for Halloween.

Since then the paint has been abandoned until my eldest daughter mentioned she was making circuits in school yesterday and I said I'd try to make them flashing LED Christmas Tree pictures.
This got a thumbs up from my daughters so the pressure was on.

Using Inkscape I drew a simple Christmas Tree with a place to put 7 LEDs.
Nice and simple and easy to print on A4 card.  I made the baubles the shape of a physical LED so you can see which way to place the LEDs on the sheet. All the negative (ground, cathode) sides in the middle making it easier to connect all to GND later.
PNG Version.
Links to PDF and SVG 

With the drawing done I added the LEDs.  6 to the green tips and a yellow one in the star.  I had 2mm LEDs to hand so that's what I used.  For the real thing I plan to use 5mm as the effect should be better.

I found pre-bending the LED leads at right angles so they are pointing down when in places made it easier to  get the LED to stand up at the front.  I also made small holes using a pin to push the LED leads through.  It's hard to push LEDs through 300gsm card as the leads don't have a point.

Once this was done I turned over the card.  Left the ground side for each LED pointing down and turned the positive side (anode) out at right angles pointing to the edge.  Once done I used a small piece of tape to keep the LEDs in place.
Tip.  Push the leads down to they push against the card. It's means the leads lie flat making them easier to hold on with just paint.

Back of the card
As I mentioned the conductive paint had spent the last year drying so was a bit sticky meaning the paint job is less than smooth.  I have since revived the paint with a little bit of water so for the kids it should be much easier to paint.

The bar down the middle is the ground tied to all the LEDs.  The other lines are for the positive side of each LED.
If you want all wires to be at the bottom then you may have to adjust the SVG in Inkscape to only print one Tree per A4 landscape card.

To test I thought I'd use a Codebug I got in the Kickstarter and hardly used it since. They are no on sale at CPC Farnell
With the help of Twitter people (I didn't declare the legs as outputs at the top of my code) I put together the following program. Link to CodeBug site for project

CodeBug code
Once all this was done the LEDs flashed. Yeah!.

For this project I wired up the LEDs so the top and bottom on one side are paired with the middle one on the other side and vice versa and the star LED on a leg of it's own.
This only uses three  (3) legs on the CodeBug,s o the 4th one (3) in the code is redundant.  I just left it in there in case I can figure out a more exciting way to use 4 outputs to flash 7 LEDs.

Very Short video of the final tree.

Next I want to wire up to a Raspberry Pi to enable interactive input and independent control of all the LEDs and maybe play a Christmas tune as well.

Sidenote; Some might be asking where the current limiting resistor is.  It's the paint.  The conductive paint has a higher resistance than wire and so it is acting like the current limiting resistor.

Friday, October 9, 2015

9th Egham Jam – Show and Tell Competition – Prizes donated by 4tronixs

I think we might be coming to the end of the Prize announcements.
So, last but not least are the Prizes donated by 4tronixs.

Robot lovers Prizes from 4tronixs

These prizes are especially situated to the robots lovers.

Each Prize includes:

The PlayHat includes a 3x3 full colour neopixel LED matrix, 4 big buttons and a buzzer.
Great for programming with the Raspberry Pi. This is just begging out for a game of Simon to be created.

PiRoCon and iBoost64 This board is great. Te PiRoCon  plugs right on top of the Raspberry P and gives you all the additional electronics needs to drive motors.
Motors are fun things. When they start they draw a lot of  power (think of train pulling out of the station. It needs far more power to get going then it does to keep itself moving.  Same thing for motors).  This mean if you want to drive motors you need extra circuitry to do it safely without damaging your Raspberry Pi.  The PiRoCon is one of the best solutions for this for the Raspberry Pi.

In addition to motors drawing a lot of power when they start and stop they can also affect the voltage and current of electronics drawing from the same power supply.  This can cause difficulties in getting good readings or accurate control.  This is where the iBoost64 comes in.  It cleans up the signals and makes them good without affecting the rest of the circuit.  Ideal for robots where there can be a lot of stopping and starting of motors as well as reading of external sensors for line following or object avoidance.

With the combination of the PiRoCon and iBoost64 you have the electronics to get that robot built.
If working in Scratch the current ScratchGPIO library from Simon Walters supports the PiRoCon.

If you have robots you will need power.  The final 2 boards are a 1 way and 4 way charger board for Li-Po batteries.  These are great batteries for robotic as they store lots of energy and give out a consistent voltage.  Cheap batteries have a power curve that means they very quickly drop from the maximum voltage which can cause lots of problems with motors.  Li-Po batteries are the ones used in high quality remote control cars.
Unfortunately you can't just plug a Li-Po battery into your normal battery charger due to the way they work so custom chargers are usually provided or need to be purchased with the battery.  These great little boards mean you can use a standard 5V microUSB power supply to charge the batteries.  This is the same type of power supply used for the Raspberry Pi, meaning if you are building a Raspberry Pi based robot you will already have the correct power supply.
There are 2 different boards included.  A 1 way, so it can charge 1 battery and a 4 way which can change 4 batteries at the same time.  Giving you more than enough power for your laser guided, GPS tracking, missile shooting, web cam streaming, grabber, digger, flame thrower robot. Or maybe just a line following robot.

From the picture you can see they also provided some pens.

Thank you 4tronixs for the prizes.

Thursday, October 8, 2015

9th Egham Jam – Show and Tell Competition – Prizes donated by RasP.IO

With the Egham Jam on this Sunday ( it's lovely to be see the prizes are still coming in.

This time from RasP,IO who product a number of really useful and practical accessories for the Raspberry Pi.

RasP.IO Breakout / 40 pin portsplus2/26 pin ports

The Ports boards are 26 and 40 pin versions so perfect fit for both types of Raspberry Pi.

The Breakout gives you easier access to the GPIO pins and allows you to use male/male jumper wires just like Arduino, so ideal if you're like me and have a load of these already and very few male/female jumper wires. It also gives the same labeling as per the original RasP.IO ports boards. The current model available is the 26 pin version which will fit on the 40 pin B+/2.

In addition RasP.IO ran a Kickstarter for their gpioruler for the B+/2 40 pin Raspberry Pi. I supported the 4 ruler pledge and will be providing one for each prize pack.

GPIO Ruler

+Alex Eames the man behind RasP.IO has also done some fantastic videos on the Raspberry Pi that you see at

Here's looking forward to a fantastic event.
See previous posts for other prizes for Sunday.

Tuesday, August 25, 2015

9th Egham Jam – Show and Tell Competition – Prizes donated by Innovation in Education

The good news keeps in coming

Yesterday another pack of prizes arrived in the post for the next Egham Raspberry Jam Show and Tell Competition. to register to attend and if you wish to have a chance of winning the prizes to bring along your Project to Show off.

Two (2) PiTrol kits from Innovation in Education were waiting fro me.
These are great kits as they allow you to build your own game controller with the instructions giving step by step details on how to solder it and then a snake game is also provided that works with the controller directly.

Kit of parts
Finished PiTrol

Nevil Hunt is the lead person at Innovation in Education and I have had the pleasure of meeting him at a few Egham Jams where he has come along with the PiTrol, 7 Segments of Pi and PiDapter (link from PiTrol site)

7 Segments of Pi is another simple idea that really captures the imagination. As the name states it is a large 7 segment display and button that you solder from a kit and then code is provided to play a game  

The PiDaptor allows you to connect 2 PiTrols to the one Raspberry Pi.

Each of these kits is great for learning to solder and with the provided code gives the owner the ability to understand how to read inputs from the GPIO pins and use it to play games.  Who doesn't want to play games on their Raspberry Pi.

In the case of The PiTrol prize once it has been soldered up I'd expect it would be possible to then get the controller to work with the many game emulators out there and possibly with the excellent RetroPi emulation system.

The Prize Pool is getting bigger and I'm still hoping to add a few more before the event.

Friday, August 14, 2015

9th Egham Jam – Show and Tell Competition – Prizes donated by Pimoroni

I really love the postal service as today another package arrived with prizes for the Show and Tell competition at the next Egham Jam on the 11th October.

This time from wonderful people at Pimoroni.
If you've been around the Raspberry Pi world for any amount of time the Pimoroni name will have popped up on your radar.

Assuming my facts are correct they are responsible for
Raspberry Pi Logo - yes that one.
Pibow Rainbow Case and now in many other colour variations
Unicorn Hat RGB LED matrix
Picade - Complete kit to make your own mini arcade machine

They also support the Picademy work and are very active in supporting the community and provide detailed tutorials.

Specifically for the Show and Tell Competition they have provided 2 'Kit for the Book' sets

Kit for Adventures in Raspberry Pi by Carrie Anne Philbin (Book Link)
Kit for Adventures in Minecraft by David Whale and Martin O'Hanlon (Book Link)

Along with an Explorer Hat Pro and Explorer Hat Pro Parts Kit  for more fun making and lovely stickers. My favourite is 'I broke it better'

So if you have these books are considering getting them these kits include all the components and parts you need to make full use of the electronics based projects that are provided in the books.

With the Eben Upton signed cases from the Raspberry Pi Foundation, Deluxe Snap Rovers from Cyntech and now the Pimoroni  prizes the Prize Pool for the Competition is growing rapidly.

If you wish to enter the competition just have a project to show at the next Egham Jam on the 11th of October.  To attend (either showing or just visiting) please register on the Eventbrite page.

Thursday, August 13, 2015

9th Egham Jam – Show and Tell Competition – Prizes donated by Cyntech

Wow!  I’m stunned. Cyntech are amazing.

For the Egham Raspberry Jam on the 11th of October there will be a Show and Tell Competition with all prizes donated and the Cyntech prizes arrived today.

Cyntech have been supporting the Raspberry Pi since the start and are a great place to get your accessories and kits. They are an Adafruit dealer in the UK and also do a full range of parts for making your own projects.  A lot of the products on their website also include details on how to use them.

Cyntech sent a pair of Deluxe Snap Rovers.  Once for each competition category.

These beauties sell for about £80.00 each and are a great introduction to electronics, and robotics.  The circuits just snap together making them really easy to build and adapt.  The kit comes with all the parts and a guide showing how to make a whole range of different circuits.  Unfortunately, it doesn’t shoot lasers, but has the second best thing. It shoots foam discs!

Also, looking at the construction once the guides provided are completed this thing really looks like it could be seriously upgraded with a Raspberry Pi , a PiCamera  and some more LEDs

These kits are far beyond what I had expected and in addition to the already announced Raspberry Pi Official cases signed by Eben Upton the Show and Tell Competition is looking like one well worth winning.

If you have registered already for the Event and haven’t started building there is loads of time. If you’ve not registered then guess what over half the tickets are already gone with 2 months to go.

Registration and more details on the Eventbrite Page:

Looking forward to seeing all the amazing projects being shown and also seeing these fantastic rovers being built, used and hacked.

Monday, August 10, 2015

9th Egham Raspberry Jam - 11th October 2015

The 9th Egham Raspberry Jam is going to be on the 11th of October.
As always it is free to attend you just have to register on the Eventbrite page.

For this Jam we are doing something very special.
We are running a Show and Tell Competition, so bring your projects along for the chance of winning some amazing prizes.
There will be 2 categories.
Under 16
16 and over

We are still finalising the prize pool.
First into the prize bundle is an Eben Upton signed Official Raspberry Pi case.
These have been donated by the Raspberry Pi people and are real collectors items with Eben's signature.

More prizes to be confirmed as we get closer to the Jam.

Really looking forward to seeing the projects on the day.

Saturday, July 4, 2015

Flappy Brain - Cambridge Jam Raspberry Pi project

At the last Egham Raspberry Jam I showed the Mindflex game EEG Brainwave reader (CNET article from when it was launched : displaying bar graphs for the different brainwave signals.  It was interesting but served no real purpose other than to show the EEG was doing something. Even got a mention on the Linux Luddites Podcast (

So, for the Cambridge Raspberry Jam I wanted to get the EEG reader to be used for something.  I decided it had to be a single signal and immediately Flappy Birds came to mind.
Nice simple one button game.
Decision made I went about coding the game in Python on the Raspberry Pi.  I had already done the work to get the EEG

To hack the Mindflex and get it working with an Arduino I used this great guide and the code from the following article:
This articles gives a lot of detailed background on the Mindflex and how it as well as lovely clear pictures showing where the TX and GND wires need to be attached.
For strain relief the article uses hot glue.  I wrapped the wires around the already in place knot so the wires could not be pulled no matter what.

The Processing code provided didn't work for me on the Raspberry Pi and that's the main reason I had to code up my own visualisation program.

The example I used to send the data is BrainSerialTest with one small modification. I commented out the following line as it caused the import and breaking out of the variable in Python to fail.  (Limit of my coding ability showing):

To read this from Python I had to install pyserial as it wasn't installed by default using the following commands.

apt-get update
apt-get install python-serial

You will have to use sudo for this. I left it out from the commands so that  you have to make the decision to run the commands

With the Mindflex hacked, and hooked to the Arduino and then sending it's data over serial I did the code to visualise the data.  Here is the Python code  I used on the Raspberry Pi for the last Egham Raspberry Jam

import serial
import pygame
# initialise pygame

# Define the colors we will use in RGB format
black = [ 0, 0, 0]
white = [255,255,255]
red = [255, 0, 0]
blue = [0,0,255]
darkBlue = [0,0,128]
pink = [255,200,255]
green = [0,255,0]
orange = [255,102,0]
brown = [153,102,0]
yellow = [255,255,0]
purple = [128,0,128]

# Set the font for the text. Windows computer so usd Ariel

myfont = pygame.font.SysFont("OpenDyslexic", 18)

# Set the height and width of the screen
# Fill the screen White
# Put something in the application Bar
pygame.display.set_caption("Serial Mind reader")

done = False
div = 2000
fatt = 20
fmed = 20
fdelta = 20
ftheta = 20
flalpha = 20
fhalpha = 20
flbeta = 20
fhbeta = 20
flgamma = 20
fhgamma = 20

ser = serial.Serial('/dev/ttyUSB0',9600)

# Clear the serial input buffer

pygame.draw.rect(screen, white, (0,0,800,600), 0)

while done == False:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:

    data = ser.readline()

    signal,att,med,delta,theta,lalpha,halpha,lbeta,hbeta,lgamma,hgamma = data.split(",")

    print signal
    print att
    print data

#  clear screen before putting new square on it 
    pygame.draw.rect(screen, white, (0,0,800,600), 0)

    fatt = int(att)
    fmed = int(med)
    fdelta = int(delta)
    ftheta = int(theta)
    flalpha = int(lalpha)
    fhalpha = int(halpha)
    flbeta = int(lbeta)
    fhbeta = int(hbeta)
    flgamma = int(lgamma)
    fhgamma = int(hgamma)

    pygame.draw.rect(screen, red, (1,600-(fatt*4),75,fatt*4), 0)
    pygame.draw.rect(screen, blue, (76,600-(fmed*4),75,fmed*4), 0)
    pygame.draw.rect(screen, pink, (152,600-(fdelta/div/2),75,(fdelta/div/2)), 0)
    pygame.draw.rect(screen, green, (227,600-(ftheta/div),75,(ftheta/div)), 0)
    pygame.draw.rect(screen, orange, (303,600-(flalpha/div),75,(flalpha/div)), 0)
    pygame.draw.rect(screen, darkBlue, (379,600-(fhalpha/div),75,(fhalpha/div)), 0)
    pygame.draw.rect(screen, brown, (455,600-(flbeta/div),75,(flbeta/div)), 0)
    pygame.draw.rect(screen, black, (531,600-(fhbeta/div),75,(fhbeta/div)), 0)
    pygame.draw.rect(screen, yellow, (607,600-(flgamma/div),75,(flgamma/div)), 0)
    pygame.draw.rect(screen, purple, (683,600-(fhgamma/div),75,(fhgamma/div)), 0)

    screen.blit(myfont.render("Attention",1,black), (4, 1))
    screen.blit(myfont.render("Mediation",1,black), (79, 1))
    screen.blit(myfont.render("Delta",1,black), (155, 1))
    screen.blit(myfont.render("Theta",1,black), (230, 1))
    screen.blit(myfont.render("Low Alpha",1,black), (306, 1))
    screen.blit(myfont.render("High Alpha",1,black), (382, 1))
    screen.blit(myfont.render("Low Beta",1,black), (458, 1))
    screen.blit(myfont.render("High Beta",1,black), (534, 1))
    screen.blit(myfont.render("Low Gamma",1,black), (610, 1))
    screen.blit(myfont.render("High Gamma",1,black), (686, 1))
# show the whole thing

pygame.quit ()

As a side note. I did a D&T day at my kids school where I used this code for a Year 1 demonstration. All the kids got to see their brainwaves bouncing around as they moves, did maths and recited poems.  It even went really flat when the kids closed their eyes and calmed down.   Some of the kids had to wait so long that they missed their morning break for the opportunity to see their brains waves bouncing around,

Next onto getting the Flappy Birds inspired game (for the purest you could say helicopter inspired) game working.
I thought myself to code in the 80's on a Commodore 64 and to be honest I haven't updated my skills since, so doing the same in Python was a new challenge for me.
Fortunately, I read an article in Linux Format Issue 112 from December 2008 that made a top down racer using Python and Pygame in 100 lines of code.
Yes, using a tutorial from over 7 years ago.  I may not be great at coding but I do hoard useful bits of knowledge.  I bought the Mindflex from eBay in September 2014 and did nothing with it until January.  Another bit of my electronics stash.

The Racer game if you think about it is the same but more complex than the Flappy Brain game with a few differences.
Racer scrolls vertically, Flappy  Brain scrolls horizontally.  That's just changing the value of the X variable instead of the Y variable
Then it's just change some of the graphics.

Once I figured out the Racer code I worked out the bits I could throw away and then bits I had to keep as well as worked out how to modify the code to do what I needed.

This took me a while to work through again due to a lack of knowledge or practice.

In the end I created the final game that was shown at the Cambridge Raspberry Jam.

Code Below:

from pygame import *
import random
import time
import serial

# set up the serial port
ser = serial.Serial('/dev/ttyUSB0',9600)

# Clear the serial input buffer

# variables for colours 
black = [ 0, 0, 0]
white = [255,255,255]
red = [255, 0, 0]
blue = [0,0,255]
darkBlue = [0,0,128]
pink = [255,200,255]
green = [0,255,0]
orange = [255,102,0]
brown = [153,102,0]
yellow = [255,255,0]
purple = [128,0,128]

# gap in wall
gap  = 200

# width and height of screen 
width = 1000
height = 600
count_gap = int(height/gap)

# 0 = hard, 1 = easier, 2 is easiest
difficulty = 2

# class to create sprites and render them
class Sprite:
    def __init__(self,xpos,ypos,filename):
        self.x = xpos
        self.y = ypos
        self.bitmap = image.load(filename)
    def render(self):

# screen size
# initialise pygame

# create the screen (window)
screen = display.set_mode(size)

# Caption to go at the top of the window
display.set_caption("Flappy EEG 2")

# set the music, its volume and start to play. -1 means infinite loop"Pinky_and_the_Brain.ogg")

# crreate sound for crash
crasheffect = mixer.Sound("ouch.ogg")

# fill the screen with blue, update the screen
# not really required but I like it

# create the sprites for the brain, columns and the background image

playerbrain = Sprite(20,200,"brain_75.png")
column1 = Sprite(1200,100,"column1.png")
column2 = Sprite(1200,100,"column2.png")
background = Sprite(0,0,"background.png")

# set fonts for different purposes
scorefont = font.Font(None,60)
datafont = font.Font(None,20)
overfont = font.Font(None,100)

# set default values for some variables
score = 0
maxscore = 0
quit = 0
gameover = 0

# master loop for the program. If quit == 0 then exit program
while quit == 0:
# flush the serial port of all data to begin fresh

    gameover = 0

# set the height of top column
    column1.y = (random.randrange(0,(count_gap))*gap)-800

# set the height of the bottom column
    column2.y = column1.y + 800 + gap

# start of loop (using while) to move the columns

# start off screen to the right
    x = width +50

# x>-100 means still valid (yes there is a minus in there)
# gameover when collision
# quit selected. either pressed q or click x on window
    while x >-100 and gameover == 0 and quit == 0:

# increment the score and if higher than maxscore make maxscore = score
        score = score + 1
        if score > maxscore:
            maxscore = score

# update columns location and set x positions
        x = x - 50
        column1.x = x
        column2.x =x  

        data = ser.readline()
#        print data

        signal,att,med,delta,theta,lalpha,halpha,lbeta,hbeta,lgamma,hgamma = data.split(",")

        print "signal: " + signal
        print "attention: " + att
        print "data: " + data
        intatt = int(att)
        if intatt > 90:
            intatt = 90   
        brainpos = intatt * 6
# set brain location based att (attention)

# is intatt near the gap above 
        if brainpos < column1.y +800 and brainpos > column1.y + 800 - (difficulty * 10):
            playerbrain.y = column1.y +800 +70
            print "brain near top and moved down!"
# is intatt near gap bottom
        elif brainpos > column2.y-75 and brainpos < column2.y + (difficulty * 10):
            playerbrain.y = column1.y +800 +70
            print "brain near bottom and moved up!"

            playerbrain.y = brainpos
            print "brain where is should be"

#        print playerbrain.y

# display some information on screen
        screen.blit(scorefont.render("Score: "+ str(score),1,white), (100, 5))
        screen.blit(scorefont.render("High Score: "+ str(maxscore),1,white), (400, 5))

        screen.blit(datafont.render("signal: "+ signal,1,white), (5, 570))
        screen.blit(datafont.render("attention: "+ att,1,white), (150, 570))

        screen.blit(datafont.render("playerbrain.y: "+ str(brainpos),1,white), (250, 570))
        screen.blit(datafont.render("column1.y: "+ str(column1.y+800),1,white), (500, 570))
        screen.blit(datafont.render("difficulty: "+ str(difficulty),1,white), (650, 570))


#        print playerbrain.y

# collision dection
        if ((playerbrain.y < column1.y+801 or playerbrain.y > column2.y-74) and (x <150 and x > 20)):
            print "BUMP"
            gameover = 1

# check if clicked x on window to exit 
        for ourevent in event.get():
            if ourevent.type == QUIT:
                quit = 1

# has key been pressed. K_q is to quit 
            if ourevent.type == KEYDOWN:
                if ourevent.key == K_DOWN:
                    playerbrain.y = playerbrain.y+10

                if ourevent.key == K_UP:
                    playerbrain.y = playerbrain.y-10

                if ourevent.key == K_q:
                    quit = 1 

# if game over show message
    while gameover == 1 and quit == 0:
        screen.blit(overfont.render("GAME OVER",1,yellow), (380, 260))

# then wait for a key to pressed  before starting again
        for ourevent in event.get():
            if ourevent.type == KEYDOWN:
                if ourevent.key == K_0:
                    difficulty = 0
                    score = 0
                    gameover = 0

                if ourevent.key == K_1:
                    difficulty = 1
                    score = 0
                    gameover = 0

                if ourevent.key == K_2:
                    difficulty = 2
                    score = 0
                    gameover = 0

                if ourevent.key == K_SPACE:
                    score = 0
                    gameover = 0

                if ourevent.key == K_q:
                    quit = 1 
                    score = 0
                    gameover = 0

The sharp eyed amongst you will recognise the bits taken from the Racer game and the bits taken from the original visualisation code I create.

I added the ability to Quit the game by pressing 'q' and also 3 difficulty levels. On the Game Over screen press 1, 2, or 3 with the higher number being easier.
It does this by widening the readings that will get you through the gap.

At the Cambridge Raspberry Jam I had the pleasure of meeting Alex Eames who brought us to HDMIPi and also the RasPi IO Duino which was another successful Kickstarter and is now for general sale.  Alex did a great video which you can see below.

Following this the project was picked up by the Raspberry Pi Foundation and featured on their Blog ( and most recently was featured as The MagPi Magazine Issue 35 in their Amazing Pi Projects List (
The MagPi magazine is a a resource for everybody with a Raspberry Pi. It includes articles, project details and tutorials in everything from Scratch, to Python and C++ and has software and hardware projects.  Also, they announced recently that it is going to become a physical magazine soon and be available to buy in shops as well as the current PDF download and acces through the Apple App Store and Google Play stores.

It's been a fun few months and to me is an example of what can be done if you take advantage of the resources out there if you have idea.  For this project I used some great code and guide to hack the Mindflex.  Code from a 2008 Linux Format article and some previous work I did to figure out how to read serial data on the Raspberry Pi.

I will be bringing Flappy Brain to the next Egham Raspberry Jam. It is on the 12th of July 2015 and as always is free to attend.  All that's required is to register beforehand on the Eventbrite page.

Maybe I'll see you there.