Stephen Smith's Blog

Musings on Machine Learning…

Archive for November 2017

Playing Music by Writing Code

leave a comment »


The standard Raspbian Linux for the Raspberry Pi comes with an interesting program called Sonic Pi. This program lets you create music by writing code, the goal is that the coding is easy enough that anyone can learn it, and that you can code fast enough to play a live performance by writing the code as you go along, including jamming with other musicians. From my coding experience there is always a lot of pressure to write code faster, but here you need to write the next bit of code and stay on beat.

I was interested in this, primarily to use as a drum machine to accompany by very beginner guitar playing. Basically something a bit more interesting than a metronome. Sonic Pi will run on Windows, MacOS and Linux, but one of the goals of the program was to be as accessible as possible, so hopefully even low income school districts or third world countries can afford a Raspberry Pi or two.

Learning to Code

Like many programs on the Raspberry Pi, Sonic Pi is a backdoor way to try and get kids to learn how to code. Writing code to create music has been around since electronic synthesizers became digital, but how to do this was quite technical and required a lot of (then) expensive equipment. Sonic Pi comes with a lot sampled sounds so you can go quite far without a good sampler.

The programming language is based on Ruby and can do some quite powerful things. The emphasis in Sonic Pi tends to be on fairly straight forward functional programming and it recommended that you only use what is documented for Sonic Pi, but people have discovered hidden Ruby features that work if you try them.

The Sonic Pi language is described as a strongly timed language (a play on other strong typed languages) since music is all about timing and Sonic Pi is brilliant in how it keeps everything in time.

The language keeps things simply, so hopefully if a student can think musically then they can transfer that skill into programming via the Sonic Pi language. The hope being that this is a more interesting entry point to programming than say learning sorting algorithms.

The program is designed to be interactive, have lots of help and typical IDE type features like auto-complete. There is a vibrant online community and tons of examples. Additionally there is a free book available here.

Live Performances

People actually use their Raspberry Pi running Sonic Pi as a musical instrument. This isn’t just running a program they wrote previously for people to listen to. This is actually writing the code as people listen. It isn’t always a solo performance either, it could include jamming with other musicians either playing Sonic Pi or playing regular musical instruments.

The key part of the language to support this is the live loop, where you have a loop playing the music (or code) and it allows you to update the code and have the new code seamlessly take effect whenever you like without causing a break in the music.

This usage is often called live coding and there are actual clubs that have events where this happens called algoraves.

It’s hard to explain this, but if you check out some of the YouTube videos of such performances it’s easy to get the idea. A good introduction is Sam Aaron’s presentation at OSCON on how to start coding and playing Sonic Pi. Here is a Sonic Pi performance covering Daft Punk. Here is a jam session with a guitarist. And another example.

Some Code

At the most basic level you can get some noise out of Sonic Pi just by running the one line program:

play 100

This just plays a beep which decays to nothing. You can add another note with:

play 100
play 75

This actually plays the two notes at the same time, since the program doesn’t stop and wait for the first note to finish. To play the two notes one after the other we would do something like:

play 100
sleep 1
play 75

The notes are actual midi numbers from 0 to 254. The following diagram shows how they relate to the notes from a piano keyboard.

Beeps are all well and good, but you can get much more interesting notes by playing the built in samples. For instance:

sample :bd_haus
sleep 1
sample :ambi_choir

We aren’t very musical yet, but if we put it in a live_loop then it will play over and over.

live_loop :mySong do
    sample :bd_haus
    sample :ambi_choir
    sleep 1

Now we’re playing music and with the live_loop we can modify the code and when we hit run it seamlessly starts playing the new code allowing us to perform live by writing code.

Rather than including a lot of source code in this article, for more examples I’ll just provide a couple of links. Note that if you Google around, there are a lot of Sonic Pi samples that you can have a look at. A good little drum machine bit of code is this one. Since Sonic Pi is based on Ruby you can use Ruby string processing to convert ascii drum tabs into music as done here.


Sonic Pi is a pretty cool program. Basically you get a fairly sophisticated music synthesizer with your inexpensive Raspberry Pi. It’s fun to play with, and perhaps will motivate a few more kids to pick up coding. After all if you do learn how to program in Ruby with this, then you are well on your way to being a highly employable Ruby on Rails web developer. Combined with Scratch, the Raspberry Pi really offers some innovative ways to teach coding to students.

Written by smist08

November 25, 2017 at 9:25 pm

Retro-Gaming on the Raspberry Pi

with 3 comments


Retro-gaming is really popular right now as exemplified by how hot the Nintendo SNES classic gaming systems are which outsold both the PS4 and XBox One last month. However you can put together a similar gaming system with a Raspberry Pi, some game controllers and a bit of software. This isn’t as easy as just buying an SNES Classic, but you get access to way more games, and games on way more platforms. In this article we’ll start to look at the retro-gaming world on a Raspberry Pi system.


RetroPie is a bit of glue that combines many open source gaming projects into one system that is easy to install and get running. It includes dozens of emulators for many older gaming system from Nintendo, Sega, Atari, Colecovision and Sony. It also includes dozens of emulators for older computer systems including Apple II, Atari ST, Commodore 64 and Amiga, Radio Shack TRS-80, MS-DOS, Apple Macintosh, Amstrad, ZX Spectrum and the TI-99. Its really amazing how many of these old systems have active communities creating and maintaining these emulators. Many are configurations of some overarching all in one emulators, but nevertheless it’s amazing what you can run.

You can configure the system to give you a menu of games to run, or to just autorun one particular game on startup. The system also prefers getting all input from the game controller (which could be a keyboard). Combined these allow people to build their own arcade game boxes.

There is quite a community of DIYers building these themselves from scratch, along with all sorts of kits being available. The other nice thing is that nearly everything in the Raspberry Pi marketplaces is quite affordable.


Although you can use a keyboard to do most things it isn’t ideal. You will probably want a proper game controller fairly quickly. Fortunately these are readily available and quite cheap. Note that out of all the systems that are emulated, most had different controllers, so you probably want a controller close to your favorite system, or you might like to buy a collection of  controllers.

Another reason to use a game controller is that if you use the keyboard, then some game controllers require mapping a lot of keys to buttons and this can then interfere with keyboard usage if it is used as well (more for computer emulations like an Apple II or Commodore Amiga).


So what games can you play? The easiest games to play with Retropie are the games that can be installed from the Retropie package manager. These are all open source games that have been ported to the Raspberry Pi (ie they are natively compiled for the ARM processor). You might think yuck, open source games aren’t good. But you would be wrong, because several software publishers have open sourced their old games as an act of goodwill to their fans. These include games by ID Software including Doom, Quake and Castle Wolfenstein. I found all these games work exceedingly well and I enjoy playing them again.

Next if you install the SNES emulator from the package manager, it is now installed but has no games and there aren’t any games for this in the package manager. This then leads us into the murky world of abandonware. Basically there are websites that contain games from companies that no longer exist. After all how many Atari ST or Commodore Amiga game publishers are still in business? These sites have downloads for many games that you can copy to the Raspberry Pi and run. I say murky because copyright law in different countries have different views on the legality of copyrighted materials, when the copyright holder is no longer around. Anyway you can make your own judgement. If you do have an old SNES system for instance and play games you own then many people consider this ok too. Anyway this topic is up to you. But pretty well every old game you can think of is available this way.


With the computer emulations, you can just run games like the console games, but these tend to be a bit more problematic, since you need to deal with multiple floppy disks (usually hard disks don’t work for games), and many games have copy protections or non-standard disk drivers that can mess up the emulation, so results will vary. I found you can get quite a bit working but it tends to take a bit of fiddling with settings to make things work.

The other cool thing you can do with the computer emulators is just run the old computer software. For instance I used to have an Apple II+ computer that I bought with the money from my first University coop work term. It’s fun to just run Applesoft in the emulator and play with good old Applesoft Basic again. One interesting thing is that by default the emulator is configured to run at ¼ speed. This is so the games play about the same as on an original Apple IIe. This shows how good the emulator is that is can emulate an Apple running 4 times the speed of the original on a little $35 piece of kit.


Retro-gaming is a lot of fun and you can certainly waste a lot of time. They don’t have the high resolution realistic graphics that you can get out of a modern computer with a graphics coprocessor, but a lot of these games were groundbreaking and a lot of the actual gaming elements haven’t changed. If you have an inkling to play old arcade games like Space Invaders, Dig Dug or Ms. PacMan then this is a great way to play around. A lot of these emulators will run on regular PCs or Macs, but there is something fun about doing it on a little 35 dollar Raspberry Pi.


Written by smist08

November 22, 2017 at 4:23 pm

Breadboarding with my Raspberry Pi

with 10 comments


One of the cool things about the Raspberry Pi is that it has a set of general purpose input/output (GPIO) pins. Many Raspberry Pi starter kits (including my Canakit) come with a breadboard and few simple electronic components you can play with. In this article I’ll talk about connecting up some LED lights and controlling them from both Python and Scratch. Below is a bit of a hazy picture of my Raspberry Pi hooked up to the breadboard and a Scratch program running.

Here is a closer look at the breadboard with a few LEDs and resistors connected.

You don’t need to do this for many standard tasks, after all the Pi has four USB ports, Wifi, Bluetooth, HDMI, sound/composite video and ethernet ports. But the GPIO port is great for electronic enthusiasts, hobbyists and educators to get their hands dirty playing with electronic components.

Hooking up an LED

Each GPIO pin can be individually controlled and will provide 3.3V when activated. It is then specified to keep the current under 16mA or you can damage the circuits. My kit came with a number of 220 Ohm resistors and by Ohm’s law these would case the current to be 3.3V/220Ω = 15mA, so just right. You need to have a resistor in series with the LED since the LED’s resistance is quite low (typically around 13 Ohms and variable). I connected 3 LEDs and for each LED you connect a wire from a GPIO pin (in this case I used 17, 27 and 22) to the positive lead of the LED then you connect the negative side to a resistor and the other side of the resistor to the -3.3V line on the breadboard. Really quite simple.


It’s quite simple to control the GPIO pins via a Python package. You just need to import RPi.GPIO and you can get going. This package came pre-installed so all I had to do was write some lines of code and away it went. Basically I just need to set the mode for since the package supports a few different boards and chipsets, then configure the pins I’m using for output. Then I just need to turn the LEDs on and off. You need to add some sleep statements or the whole thing executes faster than you can see.


Scratch is a very simple and visual programming language/environment developed by the MIT Education Department. It is used to teach programming to students as young as in kindergarten. It is really amazing the animations and games that kids can produce with this system. It comes pre-installed on the Raspberry Pi and you can also control the GPIO pins with it, just like you can in Python. You have to run the GPIO server from the edit menu and then you use the broadcast statement to control the GPIO functions. Here is the Scratch version of the simple Python program displayed above.

More on the GPIO

The GPIO has 26 pins, two are +3.3V, two are +5V, 5 are ground and then that leaves 17 as general GPIO pins.

In the same way we configured the pins for output to control LEDs you can configure them for input and then for instance read the setting of a switch.

However this isn’t all there is to GPIO, besides the functions we’ve talked about so far, which are rather limited, a number of the pins have “alternate” functions that you can select programatically. For instance pins 3 and 5 can support the I2C standard that allows two microchips to talk to eachother. There are pins that can support two serial ports which are handy for connecting to radios or printers. There are pins that can support PWM and PPM which are handy for controlling electical motors.


The Raspberry Pi 3 is a very versatile device. It runs a most Linux software and has a very flexible architecture allowing it to interface to a great many devices. It has four USB ports, Wifi, Internet and Bluetooth. Plus there is the general purpose GPIO bus that allows a great deal of flexibility to interface the Pi to almost anything. That is why you see Raspberry Pi’s built as the brains of drones, robots, home security systems, information kiosks and so much more.


Written by smist08

November 15, 2017 at 9:14 pm

Posted in raspberry pi

Tagged with , ,

Playing with my Raspberry Pi

with 5 comments


I do most of my work (like writing this blog posting) on my MacBook Air laptop. I used to have a good desktop computer for running various longer running processes or playing games. Last year the desktop packed it in (it was getting old anyway), so since then I’ve just been using my laptop. I wondered if I should get another desktop and run Ubuntu on it, since that is good for machine learning, but I wondered if it was worth price. Meanwhile I was intrigued with everything I see people doing with Raspberry Pi’s. So I figured why not just get a Raspberry Pi and see if I can do the same things with it as I did with my desktop. Plus I thought it would be fun to learn about the Pi and that it would be a good toy to play with.


Since I’m new to the Raspberry Pi, I figured the best way to get started was to order one of the starter kits. This way I’d be able to get up and running quicker and get everything I needed in one shot. I had a credit with Amazon, so I ordered one of the Canakits from there. It included the Raspberry Pi 3, a microSD card with Raspbian Linux, a case, a power supply, an electronics breadboard, some leds and resistors, heat sinks and an HDMI cable. Then I needed to supply a monitor, a USB keyboard and a USB mouse (which I had lying around).

Setting up was quite easy, though the quick setup instructions were missing a few steps like what to do with the heatsinks (which was obvious) or how to connect the breadboard. Setup was really just install the Raspberry Pi motherboard in the case, add the heat sinks, insert the microSD card and then connect the various cables.

As soon as I powered it on, it displayed an operating system selection and installation menu (with only one choice), so clicked install and 10 minutes later I was logged in and running Raspbian.

The quick setup guide then recommends you set your locale and change the default password, but they don’t tell you the existing password, which a quick Google reveals as “Raspberry”. Then I connected to our Wifi network and I was up and running. I could browse the Internet using Chromium, I could run Mathematica (a free Raspberry version comes pre-installed), run a Linux terminal session. All rather painless and fairly straight forward.

I was quite impressed how quickly it went and how powerful a computer I had up and running costing less than $100 (for everything) and how easy the installation and setup process was.


I was extremely pleased with how much software the Raspberry Pi came with pre-installed. This was all on the provided 32Gig card, which with a few extra things installed, I still have 28Gig free. Amazingly compact. Some of the pre-installed software includes:

  • Mathematica. Great for Math students and to promote Mathematica. Runs from the Wolfram Language which is interesting in itself.
  • Python 2 and 3 (more on the pain of having Python 2 later).
  • LibreOffice. A full MS Office like suite of programs.
  • Lots of accessories like file manager, calculator, image viewer, etc.
  • Chromium web browser.
  • Two Java IDEs.
  • Sonic Pi music synthesizer.
  • Terminal command prompt.
  • Minecraft and some Python games.
  • Scratch programming environment.

Plus there is an add/remove software program where you can easily add many more open source Pi programs. You can also use the Linux apt-get command to get many other pre-compiled packages.

Generally I would say this is a very complete set of software for any student, hobbyist or even office worker.


I use Python as my main goto programming language these days and generally I use a number of scientific and machine learning libraries. So I tried installing these. Usually I just use pip3 and away things go (at least on my Mac). However doing this caused pip3 to download the C++/Fortran source code and to try to compile it, which failed. I then Googled around on how to best install these packages.

Unfortunately most of the Google results were how to do this for Python 2, which I didn’t want. It will be so nice when Python 2 finally is discontinued and stops confusing everything. I wanted these for Python 3. Before you start you should update apt-get’s list of available software and upgrade all the packages on your machine. You can do this with:

sudo apt-get update        # Fetches the list of available updates
sudo apt-get upgrade       # Strictly upgrades the current packages

What I found is I could get most of what I wanted using apt-get. I got most of what I wanted with:

sudo apt-get install python3-numpy
sudo apt-get install python3-scipy
sudo apt-get install python3-matplotlib
sudo apt-get install python3-pandas

However I couldn’t find and apt-get module for SciKit Learn the machine learning library. So I tried pip3 and it did work even though it downloaded the source code and compiled it.

pip3 install sklearn –upgrade

Now I had all the scientific programming power of the standard Python libraries. Note that since the Raspberry Pi only has 1Gig RAM and the SD Card only has twenty something Gig free, you can’t really run large machine learning tasks. However if they do fit within the Pi then it is a very inexpensive way to do these computations. What a lot of people do is build clusters of Raspberry Pi’s that work together. I’ve seen articles on how University labs have built supercomputers out of hundreds or Pi’s all put together in a cluster. Further they run quite sophisticated software like Hadoop, Docker and Kubernetes to orchestrate the whole thing.


I now have the Raspberry Pi up and running and I’m enjoying playing with Mathematica and Sonic Pi. I’m doing a bit of Python programming and browsing the Internet. Quite an amazing little device. I’m also impressed with how much it can do for such a low cost. As other vendors like Apple, Microsoft, HP and Dell try to push people into more and more expensive desktops and laptops, it will be interesting to see how many people revolt and switch to the far more inexpensive DIY type solutions. Note that there are vendors that make things like Raspberry Pi complete desktop computers at quite a low cost as well.

Written by smist08

November 11, 2017 at 9:35 pm