Showing posts with label Raspberry Jam. Show all posts
Showing posts with label Raspberry Jam. Show all posts

Tuesday, August 21, 2018

Shakey Shakey - a game using title switches

For the most recent Egham Raspberry Jam @EghamJam we did two workshops.
One was NoPi Blinky, making LEDs blink without any programming. More to come on this as during the workshop we found a few typos.

The other was Shakey Shakey.

For the workshops my goal is to do something slightly different that not only teaches the attendees something new from either a programming or electronics standpoint but also shows them creative options.

Shakey Shakey was based around really simple tilt switches.  They're basically a small tube with a contact inside that moves as you tilt the tube.  Really simple and really cheap. On eBay UK they're about £1.50 for 20. So, ideal when you need a bunch for the Jam
Tilt Switch

The only other things needed then were some female-female jumper wires and some 2 core wire.
I cut the female-female wires in 2 giving me a pair of wires that had the female connectors on one end and bare wire the other.  Cut the 2 core wire into about 150cm lengths and used them to connect the switch to the other wires giving a nice long wire for the kids to shake without (hopefully) unplugging the wires or pulling on the Raspberry Pi.

With the hardware sorted I them did the worksheet which is available to download from GitHub along with other Jam worksheets.

Shakey Shakey worksheet
The worksheet goes through:

  • Connecting a tilt switch
  • Python code to read the switch and display how many times it connects
  • Adding a pause to deal with debouncing
  • Adding a second tilt switch
  • Updating the code so the switches have to be activated alternatively
  • Final update of the code to add a timeline making it into a game

We had a full workshop and the kids who took parts seemed to really enjoy the coding and then playing the new game they created.

At the end I challenged the participants to come back to the next Egham Raspberry Jam (21st October 2018) with their own program that uses the same tilt switch controllers.  The worksheet at the end gives some suggestions.  Here's looking forward to the 21st of October to see what fantastic creative ideas the kids come up with.





Tuesday, July 19, 2016

Toy crane controlled from Raspberry Pi Zero with SenseHat using Scratch


Since the micro:bit was launched one of the demos that I kept seeing was the toy crane controlled using the motion sensing in the micro:bit.  The kids loved it and was very interactive.

Since the SenseHat on the Raspberry Pi has the motion sensors built in I thought this would a good project for a Raspberry Jam.

So, off I went to Home Bargains and bought a crane. From the picture, definitely the right age for me.  This crane is normally controlled using two levers on the hand controller. It can rotate and raise/lower the bucket.

Didn't come with the hard hat
First order of business was to figure out the wiring and cut the cable as the final build would be battery powered to work the same as the micro:bit version.


Cut the red wire

From above the wiring is:
VCC - Red wire
GND - Brown wire (not black)

Rotate motor 
Orange and Yellow

Crane lift motor
Blue and Green.

For turning and crane the direction it goes depends on how you wire it up and how your code works so some adjusting may be needed later.

To make sure I had this right I tested by touching Red to Orange and Brown to Yellow. Crane rotated one way. Swapped wires around and crane rotated the other way.
Red to Blue and Brown to Green, Bucket went down. Swapped wires around and bucket went up.

Wiring confirmed and tested.

As the Raspberry Pi isn't designed to control motors directly I needed a small motor controller.
The L9110s looked perfect for the job. Smaller than the L298N that I usually use so would be easier to accommodate in the final box.

L9110s motor controller
The 2 terminal blocks on the left in the image are for the motors.
On the right are the control pins and power.
Top 2 connections are control for Motor A
Bottom 2 connections are control for Motor B
Then in the middle are VCC and GND

NOTE: A really important thing is to make sure when using multiple boards that all the GND lines are tied together so that all the voltages have the same base reference.  Otherwise strange things can happen.

I wired up the motors. Turning uses GPIO 5 and GPIO 6 on the Raspberry Pi and Motor B on the L9110s while lifting uses GPIO 27 and GPIO 17 and Motor A.

Again did some simple code to see if it would work from Scratch. Initially manually moving with the keyboard.  It worked great and I brought it along to the Egham Jam in April 2016.  As the organiser of the Jam I was a bit delinquent in taking pictures so the only one I have is of the crane, bottom left in the booth of the car before I went to the event. I promise the kids loved it and it was a massive hit, really. Actually, I had a different project called ZeroBall that was finished so it took most of my time.

Bottom leftis the crane
There were two technical reason I didn't have it all set up with motion sensing and coded in Scratch for the Jam.

  1. The SenseHat covers all the GPIO pins meaning I couldn't get at the pins to attach the wires for the motor controller.  So, I could get the readings from the SenseHat but couldn't control the motors.
  2. The Scratch at the time had a problem whereby it didn't support AddOn board. 


The first problem was solved with Stacking Headers and great tutorial from Keith's Pi Tutorials even has a video.
Also, a great reference site for Raspberry Pi board pin usage is pinout.xyz.  They have loads of boards listed and this is where I got the details for the pins used on the SenseHat

Stackable Headers. Note the high tech blutac for holding it all in the tub


The second problem of Scratch not working at all with AddOn boards was reported and fixed in the May 2016 Raspbian update.

With the purchase of Stackable Headers from The Pi Hut and a freshly imaged SD card both of these technical problems were overcome and the way forward was sorted for the SenseHat to be used to control the crane.

Since I wanted it to be battery powered the Raspberry Pi Zero was the obvious choice as it is low power. Only thing is Scratch is a GUI program and so I needed a desktop environment to run it (If you can run Scratch code without a GUI I'd love to know, but I suspect it kind of defeats the purpose of a drag and drop interface if you run it from the command line)

To overcome this I used a USB wifi dongle to connect over the network to the PiZero and then on a laptop used RealVNC to get a desktop. Since this was going to be shown at the first Wimbledon Raspberry Jam I didn't know if I would have a wifi network to connect to so I brought my own in the shape of a VoCore. A one inch cubed wireless router running openWRT.  I backed this as a crowdfunding thing a while back and all I've used it for it to create a local wifi hotspot.  At the Jams I can even power it from a powered Raspberry Pi USB port.

Side Notes:
I think the number is the manufacturing order of the original batch and I've never seen one with a number lower than 26.
The VoCore is only the top layer. The rest is an add-on that gives you USB, Ethernet, microUSB power socket and a microSD slot.  IT also has it's own GPIO pins so can be used for embedded projects.

Vocore. Basically, the guts of a wifi router
Obviously, as this was going to be standalone it had to be battery powered. I'd been picking up these 18650 Lithium Ion batteries in Poundworld and thought 4 of these in a case would make a decent power supply for the day.  No idea why when I cracked them open one was pink.  The battery case was from eBay and it all snapped together really easily.
The case has 2 USB ports for power so could power the Raspberry Pi and the VoCore at the same time.

Batteries in their original cases

Batteries in their new case


I mentioned above that all the Grounds need to be tied together.  In this instance I have 3 circuits that need to all have the same GND. Crane, L9110s and Raspberry Pi Zero (The SenseHat is take care of through the Pi Zero)
I tied the Crane GND (Brown wire directly to Pin 39 on the Raspberry Pi, then the GND pin on the L9110s was tied to Pin 6 on the Raspberry Pi.  In this way all 3 had a common GND.

It's good to be aware that in a circuit all GND can usually be treated as the same point. Especially for such low power and low frequency signals.  If this was a high power high frequency circuit then the trace length between the different GND points could case harmonics.  I cannot think of a project using the Pi that I would do where the length of the trace between GND pins would be a problem


So, now I have power, local network, a way to run Scratch so people can see the code and all the bits wired up. Last of all was the actual Scratch code.

From the image you'll see the code isn't very complex.  The main thing I'd to figure out was which one of the sensors I needed to read. It's the Accelerometer.
I believe the range is -4095 to + 4095 on each axis.
When the program is run a base "flat' reading for Lifter and Turning is taken so any movement in the sensor doesn't carry from one person to the next.  This is what the middle block of code does.
The block of code on the right is there if it all goes wrong and I can just press [space] to turn off the motors.

Th middle block is where the magic happens.  It checks if Accelerometer X is 1000 less or 1000 more than the flat reading for Lifter and/or Turning and then activates the appropriate motor to either turn the crane or raise/lower the bucket.

Not shown below is a second costume for the crane that just says "Put Pi on a flat surface" at the start of the calibration.


If you're not up for trying to copy the code from the image you can download the Scratch code from GitHub.

To make it hand held I stuffed all the bits in to a plastic Chinese takeaway box.  You can see the L9110s on the left, wifi dongle on a short microUSD to USB cable and the SenseHat with the Stackable Headers so the wires for the motor controller can could be added.

Finally, here is a boy totally engrossed in playing with the crane at the Wimbledon Jam.  It all ended really well.

Hours of fun transporting monkey from one place to another









Friday, January 29, 2016

Zero Ball - a game using Raspberry Pi, GPIO Zero some LDRs and very little building skills


Update: 3rd March 2017.  I resurrected ZeroBall today in preparation for Guildford Innovate on Saturday and did a video.



Trivia: Previously ZeroBall ran from a Raspberry Pi A+.  With the new PiZero W I thought it would be perfect to pair with the NexDock.  The NexDock has Bluetooth keyboard and trackpad and the PiZero W now has Bluetooth, so can be paired to the keyboard easily.  Making a nice compact solution.

On with the actual blog post.

For the recent Egham Raspberry Jam that I organised the theme was Gamification.
I already posted about sensecave a Raspberry Pi Sense Hat game  but I wanted to do something a bit more physical and real world.

That got me thinking about Fairgrounds and the kinds of games you play there.
The final decision was a ball throwing game.  Get the ball in the cups and you get points.  For those who watch US teen movies the principle is similar to beer pong, but without the beer and with points and scores....

Next exercise was to figure out how to detect a ping pong ball going into a cup.
I spent a lovely afternoon trying out PIR (Passive Infrared Sensor) sensors at  HackWimbledon. If you're near Wimbledon in the UK check them out. Great bunch of people and the events are every 2 weeks on a Saturday.

After an enjoyable day I figured out the PIR sensors are great for detecting movement of animals including people, but no use for my requirement as they even  tripped if the ball passed over the cup since the amount of infra-red light changed.  Tweeted when it failed. Luckily there was still a month to the Jam.


I now have six PIR that I can use for a different project. ;-)

With PIR out of the question the alternatives I considered were a switch or an LDR (Light Dependent Resistor) .  Both had their advantages and disadvantages.
Switch digital and easy to read and wire up, but most switches would need more force than a ping pong ball would provide.
LDR would give a great reading but is an analogue device which the Raspberry Pi cannot handled without additional circuitry

In the end despite needing extra circuitry I went with the LDR.
To get a reading from an LDR you have to create a voltage divider circuit so you can get a different voltage depending on the relative resistance values of the 2 resistors used.

Here's a great guide on voltage dividers and using an LDR

The next thing was to get the analogue reading from the voltage divider into a the Raspberry Pi in a format that it could use.  My initial thoughts were to use the analog inputs on an Arduino and then send the data over serial to the Raspberry Pi.  Considered Arduino as I have used them a bunch and knew what to do, but in the end I decided this would be over kill.  Why use a microcontroller to read analogue when there is a nice little chip that can do the same and people way smarter than me have already got it working with the Raspberry Pi.

May I introduce you to the MCP3008. An 8 channel, 10 bit analog to digital converter which communicates with the host over SPI.

Since SPI and the MCP3008 were all new to me I did the Google and found an great article by Raspberry Pi Spy. This guide explains exactly how to wire up the MCP3008/Pi and also RPI.GPIO code.
Using this I tested the LDR and it worked perfectly.  Looks like all systems are go on the project.

Then I saw that gpiozero has built in support for the MCP3008 and decided for the final project to take advantage of the ease of use brought by gpiozero.
A little test and it all worked again.  :-)

So, electronically everything works.  I can use voltage dividers with an LDR and resistor along with an MCP3008 to read the sensors and then using gpiozero read the values over SPI.

So, I began construction.

Firstly, soldering the Raspberry side headers from the MCP3008 on a strip board.

When I did this I made a mistake.  I should have left more room on the Pi wiring side of the MCP3008.  There is no need for the chip to be this close to the edge, with only one hole for the wire to be attached.  This will come back and cause me problems later...

Once this was done I moved on to creating the voltage dividers.  Since there are 6 cups, 6 resistors and LDRs are needed.


In the picture above the left side is VCC (3V3 from the Raspberry Pi), right side is GND.  Each 10k Ohm resistor is soldered to VCC on the left and then to one of the MCP3008 input pins.  The LDRs will then be connected from the MCP3008 input pin to GND to create the divider.

I did a quick test using one LDR to make sure I did this right. Image below shows it wired to the Raspberry Pi.  I used a model A+ as there isn't a requirement for network or more power. Yes, I wired it all up to power and stuff for testing.



After this the need was to add the wiring for the LDRs.  That's 6 connections with 2 wires for each.


This is already starting to look a bit more complicated than the small breadboard projects I've done before.  Looking at the image above you will see 6 black wires from the top edge (GND) and 6 orange wires tied to each MCP3008 input line.

All that was missing for the voltage dividers to be complete was to add the LDR for each line.

Since this is a physical build the LDRs need to be embedded in a plastic cup.  I also needed the LDRs to be flat against the cup to make it register a passing ball without obstructing the path of the ball.



This is the first time the sensor is actually in a cup so I can check if the ping pong ball passing is detected  correctly for the purpose. More testing of a single cup.


It worked and it worked amazing well.  That's 1 cup wired up.  Now just the other 5.


All wired up.  A bit fiddly  keeping the other cups out of the way while soldering and working with all wires the same colours to make sure I wired the correct ones for each LDR.

I had great fun at this time setting the cups up and throwing balls into them.  My kids loved it too. The fact they wanted to keep doing it even when all that happened was the number on a terminal screen updated when it happened made me think the build would actually result in a compelling game.

With the electronics sorted it was onto the bit that was new to me. The physical build.  I heard foam board was easy to work with and sturdy so went with that. Another new thing for me.

I cut holes in the foam board and inserted the cups. Using tape to hold them in place.

top, pretty side
bottom, business side.

As I mentioned the physical build is not something I do regularly, so I didn't have a lot of tools to hand to finesse the build.  My main tools were a sharp knife, glue and tape.

Once built I again did some testing and it all worked.

The top is sloped, so the balls roll back to the player. A layer is underneath, again to have the balls roll back to the player.

In the picture below you can I see a piece on the top to direct the ping pong balls to the bottom right so the returned balls will always be in the same place.  For the layer underneath the same happens. Balls return to the bottom right.


Last requirement of course was the software. I mentioned it used gpiozero for the MCP3008.  For SPI to work you have to run your code as root using sudo.
I wanted the game to feel like a fairground, so music and sound effects were essential as well as a score board.   All coded in Python.  To make this easy (for me) I used Pygame for the display, keyboard input to start a new game and also to play the background music and sound effects when a ball goes in a cup.  If you haven't used Pygame on the Raspberry Pi before then check out their recently released Make Games with Python Essentials book that is available in print, PDF, iOS and Android app.

Electronics sorted, physical build done, programming all completed.  Ready for the Egham Raspberry Jam on the 17th of January. 
As I was packing the night before I thought it best to test my projects as usually for me something goes wrong on the day and since I had the time (rare for me) doing some testing seemed like a good idea.  Ahhhh!!!!.  It didn't work.  I was checking the code and the terminal output.  No readings from any of the sensors. 
On looking at the circuit board a couple of the wires had broken off.  Remember I mentioned my thing about not leaving enough space on the Raspberry Pi side of the stripboard.  

I again went to Twitter an got some some great advise from Alan O'Donohoe and Pete Lomas






You have to love the Raspberry Pi Community. Within a few hours I had exactly the advise I needed to get my project fixed perfectly.  But I had 1 day left and didn't leave enough room to do what they advised so I ignore their advice this time. Soldered the wires back on and crossed my fingers that it would all hold together.


On the day of the Jam the game was very popular.  Great write up from Richard Savill who is well worth following as he does some great Raspberry Pi projects and Kickstarters. With lots of kids and adults playing with it.  When a few kids gathered around the game they would just drop the ball straight in the cups to get the points and hear the sound effects.



Overall, I'm very happy with the final game.  The build is a bit rough around the edges but works great.  The code held up and the kids played it all afternoon which was the desired outcome.   I also had a number of conversations with adults and kids about the code and the electronics involved, so hopefully helped a few of them to learn something new and consider their own Raspberry Pi projects.







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 (http://eghamjam9.eventbrite.com) 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 http://raspi.tv

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.  http://eghamjam9.eventbrite.com 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. http://learn.pimoroni.com/

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.  http://eghamjam9.eventbrite.com




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.  http://eghamjam9.eventbrite.com

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 : http://www.cnet.com/uk/news/moving-objects-with-mattels-brainwave-reading-mindflex/) 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 (https://linuxluddites.com/shows/episode-41/)


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: http://frontiernerds.com/brain-hack.
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):
        Serial.println(brain.readErrors());

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
pygame.init()

# 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
size=[800,600]
screen=pygame.display.set_mode(size)
# Fill the screen White
screen.fill(white)
# Put something in the application Bar
pygame.display.set_caption("Serial Mind reader")
pygame.display.update()

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
ser.flushInput()

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


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

    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)
    pygame.display.update()


    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.display.update()

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. http://www.linuxformat.com/includes/download.php?PDF=LXF112.tut_code.pdf
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
ser.flushInput()

# 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.blit(self.bitmap,(self.x,self.y))

# screen size
size=[width,height]
# initialise pygame
init()

# 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
mixer.music.load("Pinky_and_the_Brain.ogg")
mixer.music.set_volume(0.5)
mixer.music.play(-1)

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


# fill the screen with blue, update the screen
# not really required but I like it
screen.fill(blue)
display.update()
#time.sleep(1)

# 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
    ser.flushInput()

    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!"

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


#        print playerbrain.y
        background.render()
        playerbrain.render()
        column1.render()
        column2.render() 

# 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))

        display.update()

#        print playerbrain.y

# collision dection
        if ((playerbrain.y < column1.y+801 or playerbrain.y > column2.y-74) and (x <150 and x > 20)):
            mixer.music.stop()
            mixer.Sound.play(crasheffect)
            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))
        display.update()

# 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
                    mixer.music.play(-1)

                if ourevent.key == K_1:
                    difficulty = 1
                    score = 0
                    gameover = 0
                    mixer.music.play(-1)

                if ourevent.key == K_2:
                    difficulty = 2
                    score = 0
                    gameover = 0
                    mixer.music.play(-1)

                if ourevent.key == K_SPACE:
                    score = 0
                    gameover = 0
                    mixer.music.play(-1)

                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 (https://www.raspberrypi.org/flappy-brain/) and most recently was featured as The MagPi Magazine Issue 35 in their Amazing Pi Projects List (https://www.raspberrypi.org/magpi/)
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.
http://eghamjam8.eventbrite.com

Maybe I'll see you there.