A great opportunity has cropped up for Arduino fans, Raspberry Pi fans or hobby electronics enthusiasts in general.
TechWeek Europe are calling for your office gadget ideas with an easy to enter competition. All you need to do is write a blog post about a gadget that would enrich your office life or if you're not the working type, you can make up an imaginary pencil-pushing schlub whose life you want to make that little bit easier.
A valid entry must include a shoping list of all the parts you'll need from RS Components you'll need to create your gadet, although you can use parts from other resellers if you have trouble finding them there.
Once posted, you should tweet the link @TechWeekEurope with the hashtag #OfficeGadget.
Winners will get £250 worth of components and the chance to turn their invention into a reality!
Personally my office weakness is organisation, and I never seem to have a handle on what I'm supposed to be doing and when. The simple solution to this is to write things down on a piece of paper and cross them off when they're done, but writing is boring and my hand writing is abysmal to say the least.
I'd love to combine a thermal printer with a Raspberry Pi and a Ruby web interface/task aggregator. When I turn up in the morning I'd like an RFID card about my person to signifiy my arrival and trigger a little receipt-paper print out of all the tasks I need to do. The same should happen when I come back from lunch, giving me an effortlessly organised morning and afternoon.
With some sort of basic scanning mechanism it would also be possible to tick tasks off and feed the receipt paper back into a computer to be disposed of, marking tasks as it goes.
I'd similarly like this concept to apply to tweets, but this is less an office thing and more a home setup; a simple printout of tweets in the morning with checkboxes for "favourite" and "re-tweet". Adding a cross in either of these boxes and feeding them back into the scanner would trigger the appropriate action. Possible? Yes! Easy? Not really, and certainly cost-prohibitive when it comes to parts.
An expansion to the office-based system would be a Raspberry Pi camera, letting the Pi see whether or not a detected person is coming or going and act accordingly. Letting staff log phone messages and other notes against their account, for print-out when they return would be cool, too.
Over the last few days I have been engrossed in tinkering with both the software to drive, and the Arduino-based firmware that lives on, the Hobbytronics Serial-TFT Board.
Following on from their great little Serial-VGA, the Serial-TFT board is a 1.8" TFT with an Arduino-compatible ATMega controller and can be used either stand-alone ( it has an ATMega 328 onboard ), with another Arduino, or can be mounted via a 26pin header right on top of your Raspberry Pi.
No matter how you use it, the Serial-TFT is always controlled using a simple, easy to implement Serial protocol with 14 commands ( or 15 in my modified version ).
Hobbytronics supply a digital clock example, but I quickly decided I could push the Serial-TFT further. This lead to an in-depth, often brute-force exploration of its capabilities, during which I pushed the poor little ATMega to its limits by thrashing it with circle drawing commands.
My project of choice was an analogue clock, which is a simple concept in theory but was actually quite tricky to implement on the Serial-TFT board. My eventual solution is far, far simpler than anything I tried while finding it, and basically involves redrawing all the clock hands on every tick, and drawing a line over ones that are no longer needed; ie when the second hand moves I first erase it with a line of the background colour, and then draw a new one in.
Re-drawing all three hands every second is the method that caused the fewest artefacts. As long as a hand isn't unecessarily erased, this doesn't cause any unwanted flicker.
I wasn't too keen on the default colours available on the Serial-TFT either, so I ripped out most of the colour handling code from the firmware and replaced it with an array. Currently I store 16 colours, all of which can be overwritten with new values using an additional command. This command is supported, and well documented, in my companion Python example code.
The Serial-TFT only supports 16-bit colours, but they're not an altogether bad representation of the 24-bit colours you'll likely use in most editor colour-schemes. Thus I have ported Solarized and whipped up a couple of themes of my own for good measure. To aid in your own porting, you can set new colours either as packed, 16-bit integers, RGB values or just a plain-ol string-based Hex colour like '#CC9966'
With text displaying on the Clockatoo, albeit poorly, there was one thing I couldn't resist doing; grabbing the latest tweets and displaying them on the 4-digit, 7-segment display as a sort of Raspberry-Pi-Buzz-Eye-Catchy-Notification-Thing.
After putting together a hacky abomination involving Ruby's "t" Gem, a Python script to push its stdin to the 7-segment display and a kludge of a shell script that runs the former through "sed" before piping it into the latter, I started writing this post. Upon realising the sheer insanity of this solution, I searched for a more graceful one and found it in Tweepy.
Before we go any further, you should head on over to https://dev.twitter.com/apps, log in with your Twitter account ( or a new one specifically for this kind of tinkering ), create an App and set it up for read access.
Tweepy is, as you might have guessed, a Python library facilitating Twitter access. It's not as easy to get set up as "t", which includes a step-by-step process for authentication. You're in luck, however; I've done all the tricky OAuth nonsense and wrapped it up in a handy script you can use:
#!/usr/bin/python
import tweepy
print 'You must create a new application at dev.twitter.com'
print 'Once you have done this, find the secret/key under details'
consumer_key = raw_input("Enter your consumer key: ")
consumer_secret = raw_input("Enter your consumer secret: ")
auth = tweepy.OAuthHandler(consumer_key,consumer_secret)
print 'Please enter this URL into your browser and follow the instructions:'
print auth.get_authorization_url()
access_token = raw_input("Enter your access token ( PIN ): ")
auth.get_access_token(access_token)
print 'Your authentication details (save these!):'
print 'key: ' + auth.access_token.key
print 'secret: ' + auth.access_token.secret
After you've installed tweepy, grab this script and run it to set up your OAuth access. The profoundly lazy can:
Once you've got OAuth set up, the world of Twitter is your oyster. This is the script I used to get my timeline onto the 7-segment display:
#!/usr/bin/python
import tweepy
consumer_key = "YOUR CONSUMER KEY HERE"
consumer_secret = "YOUR CONSUMER SECRET HERE"
access_key = "YOUR ACCESS KEY HERE"
access_secret = "YOUR ACCESS SECRET HERE"
auth = tweepy.OAuthHandler(consumer_key,consumer_secret)
auth.set_access_token(access_key,access_secret)
api = tweepy.API(auth)
home_timeline = api.home_timeline()
import sys
# This should be the path to my Geekroo-Product-Clockatoo fork
# Be sure to use the right RX.0 folder for your Pi revision
# Find the fork at: https://github.com/Gadgetoid/Geekroo-Product-Clockatoo
sys.path.append('../Geekroo-Product-Clockatoo/R2.0')
from Raspi_7Segment import SevenSegment
segment = SevenSegment(address=0x70)
# Display all tweets in your home_timeline on the 7 seg display
for tweet in home_timeline:
print("Displaying text: " + tweet.text)
segment.writeTextString(tweet.text)
Be sure to edit in your application details and authentication details!
Once you're set up, you can simply type ./tweepy and your twitter feed should appear on your Clockatoo board! Bear in mind that each post will take about 30 seconds to display. You can tweak the script to display faster or slower as necessary, but consider limiting the number of tweets you display and their frequency if you want it to be readable!
When I first set up this blog, I happened upon Thin and assumed it to be the best solution for serving it up to the web. I was wrong. Thin is great, and has its place, but it has a simple requirement that the Pi isn't well suited to satisfy; it needs a load balancer.
Thin seems aimed at running one or more instance of an application on one or more ports, on one or more servers, and letting an Apache, or other, load balancer sort out the chaos into a single web front-end. This is great in principle, but for something as lightweight as this blog, on a Raspberry Pi no less... it just doesn't really work out. I could spool up muliple "thins" with no problem, and proxy them with Apache using a load-balancer. But performance was pretty poor. A load balancer is an extra step, and clearly a step to much for the Pi!
Running one instance of your application isn't great, either. Unless you fudge together something with async-sinatra, any request to your application will prevent it answering other requests until it's done. IE: your application will be single-threaded, and if there's more than just you using it, it'll run poorly, very poorly.
Enter Passenger. Passenger handles the task of running multiple instances of your application pretty much transparently. For anything you'd want to run on the Pi, the defaults seem to suffice. It runs beautifully as a plugin to Nginx (a great little HTTP server) which it will even download, compile, install and configure for you. To actually get a site up and running once it's done its thing is dead simple, and getting an init script set up isn't much trickier.
Getting Started
First up you're going to need Ruby. I highly recommend setting up RVM and installing Ruby 1.9.x, but I wont cover the installation of these in this guide. See rvm.io. For the lazy, you can probably just run:
Once your Ruby weapon of choice is installed and ready, you'll need to install Passenger. You can do this pretty easily with:
gem install passenger
The gem will download and install itself, along with a few tools for getting set up with various HTTP servers.
Installing Nginx
Getting Nginx installed is then as simple as running:
sudo passenger-install-nginx-module
Or if you used RVM:
rvmsudo passenger-install-nginx-module
This installer script will tell you how to install any dependencies you might be missing.
Once you've solved any dependency woes, you'll be prompted for an install prefix. I use "/usr/nginx" instead of "/opt/nginx" to be awkward.
Note: I found that Nginx wouldn't compile on my 256mb Pi due to a lack of memory. I had to migrate everything to my Rev 2 Pi. Your mileage may vary, however!
Configuring your first application
Setting up your first application and getting it to serve pages to the web is simple. You need to open "/usr/nginx/conf/nginx.conf". If you open this with vim you can hit shift+G to skip to the bottom. Here you should put something along the lines of:
Make sure you point the "root" to the "public" directory of your Sinatra or Rails application, and make sure you have a config.ru ready to go. I also set up a Gemfile for each of my Apps, Passenger will check this and try to use the listed gems; throwing errors if they're not available. If you get in the habit of using a Gemfile, you can simply run "bundle install" if you need to move your App to a new Pi.
When you're happy that your application is running stably, I'd recommend you save your SD card a little wear by adding the following to your nginx.conf:
error_log /dev/null; access_log off;
You can now start nginx using /usr/nginx/sbin/nginx. If you want to stop or reload Nginx you can use the "-s" (signal) switch like so: /usr/nginx/sbin/nginx -s reload
Advanced Server Setup
If you want to configure new sites without dipping into nginx.conf you should add this line below the closing } at the bottom of nginx.conf:
include /usr/nginx/servers/*.conf
Make sure you also make the /usr/nginx/servers/ directory, and simply place your server configs there in .conf files. Rename them to .off or .conf.off and they wont be loaded when you reload Nginx!
If you've not heard of the Geekroo Clockatoo, and tend to use your Pi for network related things (website hosting, IRC bouncers, DNS/mail server), then I'd like to introduce the Clockatoo as the one thing you should have permenantly seated on your Pi.
Why? Because it's a clean, simple and very elegant put together way of getting some basic visual feedback from your Pi.
The Clockatoo combines a simple 4-digit, 7-segment display with a Real-time clock, an alarm buzzer and an optional ( meaning you're going to need to solder headers onto both your Pi and the Clockatoo ) Pi reset button.
All the complexity of driving a 7-segment display is abstracted away with a driver chip that you can interface over i2c. Geekroo provide an example library in Python which grabs the system time and displays it on the display.
One of the obvious omissions from Geekroo's own library is text. If you think you can't display text on a 7-segment display, you'd be wrong. The human-brain should never be underestimated, and it's marvellous just how distorted a set of characters we can readily, and easily understand.
So, I've modified the Clockatoo library to include text support and a basic hello world/uptime example. As demonstrated in the example, displaying text is now as simple as:
The delay controls the speed at which characters scroll off to the left. 0.2 seconds is a comfortable speed.
I also decided to play with the buzzer on the Clockatoo. Documentation is still scant, but with a bit of trial and error I found it on WiringPi pin 7 ( GPIO pin 4 ) and had it making infuriating noises in no time with WiringPi's softTone functions. You can find a demonstration of this on my Pinout microsite at: http://pi.gadgetoid.com/pinout/clockatoo
The real-time clock is the last thing I plan to play with. It's not actually needed or even used in the basic Clockatoo examples, and is generally most useful with Pi's that are not connected to the internet.
My plans for the Clockatoo are simple; it'll stay permenantly connected to the Pi hosting this blog. In fact, at the moment it's stacked on top of the 1-Wire board from ABElectronics.co.uk so I can use the display to provide notifications of my blog status, the ambient temperature, the time, tweets to it's own Twitter account and more!
Note: Yes, you can stack the Clockatoo on top of ABElectronics boards, but it's a little awkward! Any board using I2C that doesn't use address 0x70 ( the LED display ) or 0x68 ( the realtime clock ), or GPIO pin 4 should be fine.
I've never been the biggest fan of programming books, or educational books in general for that matter. But I accept they have their place as an ambient, screen-free, easy to pick up and leaf through reference to various subjects of interest. I've enjoyed taking a break from my screen and leafing through Raspberry Pi For Dummies.
The Raspberry Pi seems a particularly awkward subject on which to author a book. It's part of an extremely rapidly changing community, which is outputting rapidly changing software and constantly endeavouring to make it easier for the beginner to get started and do beginnery things.
Many parts of this "For Dummies" book are clearly targeted at the beginner, and such beginnery things, and thus they suffer from the same problems any static media does; they don't update when the best way to do something changes or becomes easier.
This isn't necessarily a bad thing in the world of Pi, though, because making beginnery things easier is a sure-fire way to keep a beginner a beginner.
The initial chapters, following basic setup, are rife with exploration of the Linux operating system- basic stuff that every Pi user should know! From using GIMP to playing audio, to browsing the web; it's surprisingly comprehensive when it comes to real beginnery stuff that most of us SSH-using, programming-heavy users will never see, touch or care about.
There's also a crash course in HTML, a curious thing to find but not an entirely unwelcome tibit considering my own personal learning journey with the Pi has involved dabbling in a dozen languages. And I think everyone should get at least some exposure to HTML these days.
The book, unsurprisingly, explores using the GPIO header. It does this in a slightly over-ambitious way, however, and presents step-by-step instructions for building a physical marble-maze game with a software back-end which is actually a pretty cool project. It's a far cry from the make-an-LED-blink basics you might expect, and I doubt any reader would follow through with this particular project. It's inspirational, though, and demonstrates the sort of things you can do if you put your mind, and Pi, to it.
GPIO gets even more exciting with chapters covering building and interfacing with your own analogue IO board. The die-hard learner will find these extremely rewarding, but it's all too easy to simply pick an IO board for anything you might need from the numerous emerging sellers.
The GPIO access examples involve Python and RPi.GPIO. Having personally dropped the ball on language ports of WiringPi and watched it subsequently loose traction over far more frequently updated and better supported rivals I can't really complain. But it would be nice to have some explanation of RPi.GPIOs rivals, or even a nod to WiringPi. But there are none to be found! I'm a firm believer in Ruby on the Pi, and really enjoy hacking together basic hardware-to-website scripts; Raspberry Pi For Dummies doesn't really cover this. Nor does it cover WiringPi in any form, even its pure C form which is reasonably well documented and excellent for the slightly more advanced beginner and would-be C programmer.
While I'm not a fan of Python ( although I'm warming to it, as I develop WiringPi-Python and a myriad of other things in the language ), I was pleased to find some great little guides to Pygame nestled within Raspberry Pi For Dummies. There's also a chapter on Scratch with which I am not terribly familiar; suffice to say, there are things that even I can learn from this book!
Overall, the Raspberry Pi For Dummies book is an eclectic mix, just like anything Pi-related, of educational goodness which all but the most advanced of users will find something interesting within. Personally I've learned a handful of bits and bobs from it already, and am eager to let it guide me through some interesting things I might otherwise have passed up.
Yes, the chapters covering setup and general usage of the Pi Operating System will surely be redundant within a year, probably less, but there's plenty of enduring, insightful and useful content within Raspberry Pi For Dummies to make it worth picking up.
My only real complaint is the prevailence of Python. If there's any mention of other languages, it's sufficiently obscure as to be ineffective. It puts across the message that the Pi is a Python-only club, which couldn't be further from the truth!
There are no shortage of Raspberry Pi IO board manufacturers out there. An entire cottage industry has sprung up around the low cost device to cater for any interface demands the tinkerer or professional might ever have.
AB electronics are one of the more interesting such companies. They manufacturer their own boards in the UK using equipment they built themselves. This is heartening, as Britain's once great manufacturing reputation is a shadow of its former self.
I'm currently playing with a variety of Raspberry Pi boards from AB electronics, which you can find here.
Specifically I have the i-Wire Pi board with a temperature sensor ( it's very easy to use after you install the 1-Wire filesystem driver, you just cat a file! ), the Delta-Sigma Pi ADC, the RTC Pi Real-time Clock Module and the IO Pi 32 Channel Port expander which uses a pair of MCP23017 chips that are directly supported in WiringPi2. As far as digital IO goes, the dual MCP23017 IO Pi 32 should set you up pretty well; if you need more than 32 inputs/outputs then I'd love to know what project you're working on.
On the face of it, AB Electronics boards look pretty much the same as any other IO board, but they have a trick up their sleeve; they stack. Most of the boards use I2C, which is daisy-chainable, and these boards include three jumpers for setting a distinct I2C address for each IC. Simply stack them on top of each other and you'll have what I lovingly dub a "Leaning Tower Of Pi".
The leaning wont be around for long, however, as AB Electronics are in the process of revising their board design to use the mounting hole, and standoffs, to secure a stack of IO boards to the Pi. When compared to solutions like Quick2Wire, or anything else using rinnob cables the AB Electronics boards are extremely neat and tidy and produce a very small footprint. You'll struggle to find a case that fits around the Pi and a selection of IO boards, though!
Another great thing about the stackable system is that you can plug a ribbon cable into the top ( or, in my case, a PiBorg LEDBorg ) and put whatever pins the IO boards don't use to other uses.
The LEDBorg proved an excellent device to top off the AB electronics IO boards. I was able to script up the output of the temperature sensor to produce a variable colour LED readout. This is a pretty simple setup, but at least it demonstrates that the sensor works as intended.
I could also use the output from 3 analogue sensors, adjusted accordingly, to control the brightness of the 3 LEDs within the LEDBorg RGB LED. I spent a long time trying to write a C module for WiringPi to support the MCP3424 ICs on the Delta Sigma Pi board, but thus far I haven't had much luck reading back the multi-byte voltage value.
Rubyists fear not, I am not neglecting my language of choice, merely leading the charge with Python which, frankly, nets me a lot more feedback than its under-utilised cousin.
Many fixes and inclusions that have gone into the Python version of WiringPi2 have made their way into the Ruby version, too, but it lacks somewhat in completeness at the moment; I simply haven't had the time to flesh out the class wrapper.
If you've not yet heard of WiringPi2, and want to know what makes it so awesome, head on over to Gordon's new site specifically for this Arduino-wiring-like GPIO library for the Raspberry Pi: http://wiringpi.com/
After work I took a trip to the postal depot to hand some more import duty over to "the man" for my clearly labelled review samples. But I didn't mind. I walked another mile and a bit to pick up cash because they don't take credit cards. But I didn't mind. The reason I didn't mind is because the parcel I was collecting came from GadgetFactory, the guys behind the awe-inspiring Papilio.
I've been waiting for a Papilio One to turn up for a little while now, and I'm not kidding when I say it's one of my most anticipated samples ever. Unlike pretty much everything else I've tested it's not a tablet computer, or a high-end speaker, or a great video-game, not at all, it's a little slice of potential.
The potential of the Papilio comes from its many, many guises. You see the FPGA, or Field Programmable Gate Array, at the heart of this magical little board can be reconfigured to reproduce a variety of actual hardware configurations; one of these is an Arduino-on-steroids; ZPUino, but that's just the tip of the ice-berg.
My first foray into the Papilio has come in the form of the RetroCade Arcade Synth which came already plugged onto the Papilio Pro board and looked simply so enticing that I couldn't help but give it a try. A couple of hours of tinkering later, and I was up and running. "Tinkering?" I hear you say. No, this isn't a bad thing; tinkering with the RetroCade was a gentle introduction to just how flexible it can be, and has given me inspiration for my own future changes.
Windows "Hate"
Before even getting the RetroCade sofware installed I had to juggle with Windows 8 so that the drivers would install. Now I don't dislike Windows 8, but it was a chore booting into the UEFI Firmware Settings to disable "Secure Boot" so that I could follow the guide to getting everything set up.
The drivers come in the RetroCade installer package, but at time of writing it was last updated about 3 months ago and I needed to grab several updated components separately. These were the Papilio Loader GUI and the latest RetroCade Synth bit file.
The next hurdle was actually getting everything working as expected. My setup involved the Papilio Pro with RetroCade attached, hooked up to a USB to MIDI adaptor. I then connected a 61-key USB controller and used the RetroCade desktop software to route my keyboard through to the RetroCade's input. This worked a treat, except that pressing any key would result in an indefinite sustain; not good!
The fix for my particular problem, a slightly mad feature of MIDI where NoteOff messages can instead be NoteOn messages with a velocity of 0, could be found on the RetroCade forum and this is where things got interesting...
Tweaking The Software
The beauty of the RetroCade is not that is incorporates an FPGA clone of the legendary Commodore 64 SID and Yamaha YN-2169 chip, but that both these hardware implementations, and the Arduino-like Sketch used to drive them are completely open and user-editable.
Fixing the RetroCade to support my perculiar keyboard was a simple case of loading the modified Arduino IDE, pasting in some fixes from the forums, tweaking appropriately, and saving.
This has given me a taste for synthesizer hacking, and I'd love to try my hand at adding some live-performance functionality like keyboard splits and fast patch/channel changing.
Playing with the RetroCade was a nice, Friday-friendly introduction to Papilio and once everything was up and running it was really a joy to play. The synthesizer is alarmingly powerful, and exudes nostalgia, but the software has both room for improvement and the opportunity for any user to delve in and make those improvements.
Since setting up my Pi as an IRC bouncer, I've been using Shroud BNC. Much chatter on the subject of IRC bouncers, however, has convinced me that this may not be the best of the bunch. And with the name "znc" popping up so frequently, I couldn't resist giving it a try.
Getting ZNC up and running on the Pi is straight forward enough, but getting it installed as a service and running at boot should your Pi's power be interrupted is a little trickier. This guide will touch upon my experiences installing it on Raspbian.
Getting Started
To get started is simple, just "sudo apt-get install znc znc-extra". Once installed you should run "znc --makeconf" and follow the simple config setup steps.
ZNC will prompt you for a port and various other options, but you'll likely want to skip SSL and IPV6 and keep your listen host blank because your Pi probably only has one IP-address anyway.
You wont need to enable any ZNC Global Modules, the defaults are partyline and webadmin. Both of these are unecessary for a single-user bouncer setup. However, I have heard the webadmin is a great way for beginners to get a handle on ZNC configuration.
"makeconf" will also prompt you for a username and password. These will be used later for logging into the bouncer, and are nothing to do with any IRC servers or nicks you might have registered.
For the best experience opt for the user modules keepnick, kickrejoin and nickserv.
Finally, fi you're aiming to chat on the #raspberrypi channel you'll need to pick the host "irc.freenode.net". The default port will suffice.
Installing ZNC as a Service
That's the easy bit sorted, now for setting up ZNC as a service. You should more or less be able to punch in these commands:
You'll then need to fire up vim (or your editor of choice) and create an init script. You can do this with "sudo vim /etc/init.d/znc" and should paste in the script from here: http://wiki.znc.in/Running_ZNC_as_a_system_daemon. Once you've done this, you'll need to replace all references to "/var/lib" with "/usr/lib" this can be trivially accomplished with a substitute in VIM: %s/var\/lib/usr\/lib/g
You'll also need to modify the permissions on the init script as follows:
sudo chmod 755 /etc/init.d/znc
Finally, ZNC needs to drop a pid file for the init script to know if it's running or not. Open up /usr/lib/znc/configs/znc.conf and paste "PidFile = /var/run/znc/znc.pid" at the top.
Now you can start the service and set it to run on boot:
sudo service znc start sudo chkconfig znc on
Getting Connected/Final Configuration
To connect to your shiny new bouncer fire up your IRC client and use: /server your-raspberry-pi-ip:port znc-username:znc-password
Once connected you can access a host of admin functions, for a list just msg help to the *admin user: "/msg *admin help"
One thing you should do is tell the nickserv module your nick password, this is easily done with: "/msg *nickserv set yourpassword" Note the asterisk before nickserv!
Now that you're all set, you can enjoy dropping in and out of IRC at your leisure while ZNC keeps an optional playback buffer to stop you missing interesting conversation. It's also great for using IRC across multiple computers.
elwirecraft.co.uk were kind enough to send some electroluminescent wire my way for general tinkering and electrical mishaps. I originally planned to try it out with Bare Conductive Paint, but had some amount of trouble getting this to work; the paint is quite highly resistive in thin traces, which doesn't bode well for the high-voltage, low-current A/C power supply that EL wire demands.
In the bundle of EL goodies, I had a sound-activated, battery powered, portable driver. Suffice to say, I decided to hack it and had somewhat of an adventure. I'm going to start with the end result, a video of the EL wire pulsating happily to the tune of a WiringPi softTone. Okay it doesn't make any sound, but the WiringPi softTone function is ideal for modulating the A/C.
I often find myself consulting a page or graphic for a particular pinout, be it WiringPi's pin numbering system, which pins are UART and I2C or a myriad of other functions, there's never really been one clear and concise place to consult for a particular pin function.
I decided to try and solve this in two ways. The first is my new, interactive pinout micro-site: http://pi.gadgetoid.com/pinout. This is targeted at modern browser/tablets and provides not only the basic pinout, but descriptions of the various different functions, overlays to show you different pinouts and more. Give it a try!
The second, is to borrow a good old fashioned paper trick that's been floating around the internet, one I have mentioned before; a paper pin overlay!
WiringPi's unique pin assignment scheme demands a unique overlay, so without further ado here you go:
It looks good printed out, although my printer leaves much to be desired. I chose coloured bars to clearly highlight the Power/Ground and separate them from the pin functions.
It's no secret that my WiringPi- libraries have been hideously out of date and for months. But some awesome work by Gordon Henderson has spurred me back into action.
First and foremost, those of you still loyal to the old WiringPi, and my old, well publicised and well used wrappers will be pleased to hear that I'm going to give them a little TLC and try to fix 'em up, push them to PyPi and have a nose through the various different issues reported to see if I can find any resolution.
Second, WiringPi 2. WiringPi 2 includes a great new feature, or I should call it a concept, which allows you to easily set up IO expanders and write to them as if they were a normal GPIO pin. No poking values into registers, of fussing about with the nuances of SPI or I2C. Just dial in the address of your MCP23017 or the pins of your shift register and use their pins like you would any other GPIO pins.
A simple example of this is as follows:
import wiringpi2
pin_base = 65
i2c_addr = 0x20
pins = [65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80]
wiringpi2.wiringPiSetup()
wiringpi2.mcp23017Setup(pin_base,i2c_addr)
for pin in pins:
wiringpi2.pinMode(pin,1)
wiringpi2.digitalWrite(pin,1)
Gordon dubs these brilliant little helpers "Extensions" and they make chaining a metric ton of IO expanders onto your Pi absurdly easy.
To demonstrate just how conceptually awesome this is, here's some of the code I wrote when first playing with the MCP23017:
def portA
"0x%x" % ( ( @leds & FIRST_BYTE ) >> 8 )
end
def portB
"0x%x" % ( @leds & SECOND_BYTE )
end
def ledOn( led )
led = LEDMAP[ led ]
@leds = @leds | led
updatePorts
end
def ledOff( led )
led = LEDMAP[ led ]
@leds = @leds & ~led
updatePorts
end
def updatePorts
system 'i2cset -y 1 0x20 0x12 ' + portA + ' && i2cset -y 1 0x20 0x13 ' + portB
end
Ignoring the differences between Python and Ruby, this code is hideous. But I'm not going to complain, because it taught me a lot about how the MCP23017 chip actually works; and that's a good thing.
Anyway. Moving swiftly back to WiringPi 2. You can install it right now on your Pi with:
sudo pip install wiringpi2
If you have a hobbytronics IO expander or a quick2wire board with an IO expander you can get started with my example above and be rocking 16 additional IO pins with ease. Otherwise, WiringPi works pretty much how you'd expect for built-in GPIO. If you have trouble installing the Python version, tell me not Gordon!
Gordon has a new website for WiringPi inbound, you can find it here: http://wiringpi.com/
I have pushed the WiringPi2-Python source up to GitHub, which you can find here: https://github.com/Gadgetoid/WiringPi2-Python. Please note that it's early days for WiringPi 2, and my code is definitely not perfect, bug free and feature complete.
Possibly my first real soldering project, unless you count the much simpler GPIO expander kits I put together. The Raspberry Pi Ladder Board is a great into to soldering and an even better intro to Raspberry Pi GPIO. It also looks pretty! It's not quite a rainbow, but it's close enough.
The 10 LEDs and 4 buttons are plenty to get started with and are handy for testing basic GPIO access from scripts.
I've taken the time now to liberally photograph my board but still haven't yet put together any Ruby examples for it. They're in my todo list, but I'm spending some time brushing up my Ruby skills so I don't end up creating bad examples.
In preparation for playing with the Papilio Pro and diving into VHDL or Verilog, I decided to further my understanding of processor architecture. Armed with the brilliant and free app Logisim, a Microprocessor Design Wikibook and a guide to logisim I set about learning how processors work, how they digest instructions and how they perform various actions.
The result is certainly not the best, most complete microprocessor ever put together in Logisim, but it was enough for me to learn the fundamentals.
To back it up I created my own assembly language, used to instruct the simulated processor to add, subtract and compare numbers. Here's an example ( prettyprint will choke on this imaginary language somewhat ):
start:
LN ACC 0x1
LN GP1 128
LN GP2 128
badger:
CMP ACC GP1 -- Compare accumulator to GP1
JUMP EQL done -- Jump to done if equal
ADD ACC -- Add accumulator to itself
JUMP UN dostuff -- Unconditional jump out to dostuff
LOOP badger
done:
MV GP4 ACC -- Move the value of accumulator into GP4
LOOP start -- Loop program indefinitely
dostuff: -- Pointless pseudo subroutine
SUB GP2 GP2 ACC -- Subtract accumulator from GP2 and save result into GP2
JUMP UN badger -- Return to our loop
To actually run this code within Logisim, I created a counterpart compiler written in Ruby. It digests the instructions into hex and outputs into a .bin format that can be loaded directly into a Logisim ROM component. Nifty! You can download my Ruby assembly compiler here but it's by no means complete or even sane.
I found that the key to successfully putting together a design in Logisim was to throw away the tedious task of wiring things up, and make liberal use of "Tunnels". A tunnel in Logisim is simply a labelled signal which you can pop up anywhere on your canvas with ease. Labelling signals also makes them crystal clear, making things easier to wire up and debug.
I also cheated somewhat, and used a counter to create a 5 stage clock. Effectively creating distinct signals for Prep, Load, Act, Save, Next which I use to trigger various events. This abstracts away the complexity of timing and rising/falling edge, making it easier to get started on the logic itself.
My Microprocessor has 8-bit general purpose registers, all of which are addressable, a latching CMP operation, functional conditional and unconditional jump instructions and, of course, the ability to add or subtract values saved in registers from each other. Not exactly useful, but educational.
I make liberal use of "off-the-shelf" Logisim components like registers, counters, adders, ROM and decoders to speed up simulation. It's really important that you learn what these do, and how they do it, before you go any further! Circuit Coder on the iPad is a fantastic way to get started with the fundamentals.
Another one of the many, many things that the Pi has spurred me into learning is digital logic. This involves things such as binary, logic gates and many other wonderous, low-level things that are now obscured deep, deep down within the incomprehensible complexity of modern computers.
One of the problems I've found when tinkering with digital logic is that I couldn't fit enough breadboards in my house to experiment with low-level logic physically. But fortunately there's been a solution to this problem floating around for a few decades: the programmable gate array.
The programmable gate array, or PGA, more recently known as FPGA ( most are field-programmable, meaning the consumer or manufacturer using the chip can configure it as needed ), is basically a large box of logic lego. It's an enthusiasts dream, and integrates the equivient of several square meters of breadboard covered in logic ICs into something the size of a postage stamp.
By "programming" the FPGA you are simply making connections between these logic ICs, as you would with jump leads on a breadboard. It's a lot less magic than it sounds, and effectively just involves lots of tiny little switches that interconnect the logic blocks in the pattern that, ideally, best implements your design.
Deciding exactly how to configure the FPGA is, alas, not the role of the chip itself, but rather a monolithic (8GB download and 15GB installed) software package from Xilinx which contains detailed information about the logic blocks in every FPGA they produce. Your design is written in HDL or Verilog and several processing steps distil your code into a place-and-route plan that maps it out onto the actual "fabric" of the FPGA.
It's not until recently, with the Papilio entering the scene, that FPGAs, and the resources to learn with them, have really been available to hobbyists. Yes, there have been plenty of educational units around, but the Papilio delivers a much more Arduino-like ( in fact, it can even run Arduino sketches! ) solution that's more paletable and approachable for the amateur.
The Papilio is much like the Pi in this respect. It's not so much a product, as a nucleas for a community learning a specific topic and it has already succeeded greatly in bringing FPGA tinkerers together. Gadget Factory have also shown they're committed to making the Papilio fun and interesting, and I need point no further than the RetroCade Synth to prove this.
The Papilio implements a Xilinx FPGA, and Xilinx, eager to get young minds engaged with their products, make a free version of their software available.
I'm hoping to pick up a Papilio Pro when they become a little easier to obtain in the UK. And will likely grab the LogicStart MegaWing, as I've already started reading through Mike Field's free PDF ebook and feel confident that I can get the examples up and running, and go from there. You can grab this book here Intro To Spartan FPGA.
I've just made a significant number of tweaks to the code behind pi.gadgetoid.com, in an effort to make it more robust and more responsive.
There's a not-so-small chance that I've managed to achieve the opposite, so if you find this blog quirky and unresponsive... sorry! I'll no-doubt fix it in good time.
I have implemented Rack::Cache, both because it's easy to do and because, I believe at least, it's more standard-compliant approach to caching will couple well with CloudFlare.
Most other changes involve tidying up the organic mess of code which constitutes this blog, plus some vanity tweaks allowing me to add author and date information to posts.
With the Quick2Wire board and port expander both assembled and liberally photographed I decided to set about testing, specifically, the Port Expander board. It interests me more than the vanailla Quick2Wire board, which is basicaly not much more than a method of protecting the Raspberry Pi's GPIO and providing a platform to hook up all the useful stuff.
The Port Expander offers 16 additional inputs/outputs through the great little MCP23017 chip. Each IO pin can be individually assigned as an input/output, can have a weak pull-up resistor enabled and can handle interrupts. It's a very fully-featured chip and you should read the datasheet to learn more. It really isn't all that hard to understand.
I used a handful of methods to get i2c up and running, from Quick2Wire's own Python library, which worked well but frustrated me with Pythonness. Diving over to Ruby I first used system calls to i2cset, expressed Port A and Port B of the MCP23017 as two bytes in a 16bit integer and used bitwise operations to turn on/off pins and extract the relevant byte of information for each port. This lead to ugly things like: "0x%x" % ( ( @leds & FIRST_BYTE ) >> 8 )
Using the i2c library I was able to ressurect my Ruby Binary Clock example and patch it to work with the MCP23017 using this drop-in, but by no means feature-complete, replacement for "gpio.rb":
class Gpio
require 'i2c'
@i2c = I2C.create('/dev/i2c-1')
@mcp = I2C::Drivers::MCP23017.new(@i2c,0x20)
def self.mode( pin, mode )
@mcp.mode( pin, mode )
end
def self.write( pin, value )
@mcp.write( pin, value )
end
end
The MCP23017 driver in Andec's i2c library is beautifully easy to use. It needs only an instance of I2C and a device address, and will then expose PortA and PortB as a single continous series of pins numbered 0 to 15. A quick tweak of the pin numberings in my clock example, and it was up and running perfectly. I used 14 of the 16 available pins on the Port Expander, and will have to experiment with adding buttons on the remaining two.
The Quick2Wire Port Expander is a brilliant board that will save you having to fiddle with shift registers or other ICs to expand your IO.
My only gripe with it is the arrangement of the PortA and PortB headers, which are a little close together for comfortably stuffing jump wires into. Personally I'd prefer them either side of the board, or arranged in a single row.
The MCP2307 is extremely easy to understand and program once you get over the initial setup hurdle, although the Quick2Wire python examples are a little thin on the ground. It took Gordon Drogon's C example before I really grokked the chip and how to use it.
Download my mcp-clock.rb binary clock example. You will need 14 LEDs coupled with suitable resistors and connected to pins 2-15 of the Port Expander to see it in action. You can use the ground connection on the GPIO header of the main Quick2Wire board.
I finally found the time and inclination to sit down and solder together the Quick2Wire Port Expander. It was considerably easier than I thought it might be, and required only patience, careful following of the instructions and gratuitous use of blue-tac, a trick learned from the masterful Gordon Henderson.
Most of the components have fairly obvious places in the Port Expander kit, but I followed the assembly guide so I'd avoid any silly mishaps like incorrectly orientated diodes or box headers.
The kit has 15 parts to solder, totalling over 80 solder joints and took me around an hour to finish.
The heart of the board is a 16-bit MCP23017 i2C parallel port expander, the same chip as found on the Raspberry Pi Port Expander Board. It offers 16 additional I/O pins which are broken out into two rows of 8 female headers suitable for male-to-male jump wire connections to a breadboard, or jump wires at a pinch.
Following Gordon's tips from his ladder board assembly video I secured each part with blue-tac and finished each joint in 3-4 seconds.
Once I'd finished soldering, I dabbed off any remaining blu-tac and inspected the finished product.
The back is the usual mess of burnt flux or PCB, but from the front it's a work of art.
I haven't been able to test the Port Expander, I've yet to solder the main board together, but the results look promising. You can buy the Port Expander on its own for under £10 or, at time of writing, grab the Port Expander Combo Kit up for £22.66. This is a little more expensive than simply grabbing the GPIO breakout board and MCP23017 expander from HobbyTronics, but the Quick2Wire board offers much more potential, a Python library and a shiny new Analogue Board.
If you follow RaspberryPi.org, you've probably already come across this. But I feel the need to reiterate it here. The Raspberry Leaf is one of those ideas that seems utterly obvious in retrospect, but requires the right person at the right time to come up with it.
With the release of the Minecraft Raspberry Pi Edition I have been spurred into action. Albeit it's probably not the brand of action I should be spurred into right now ( soldering the Quick2Wire boards ), it's something I've wanted to do since hearing of the Pi edition's TCP API. Yes, I have begun writing a client library in Ruby which you can see in progress here: https://github.com/Gadgetoid/Ruby-mcapi/
It's early days yet. I plan to wrap it up into a Ruby gem and create some more complex examples and useful helper functions that should aid complex manipulations of the Minecraft environment from within Ruby.
Thus far I've no idea just what sort of command rate the API can handle. I've been throwing things at my Pi from the command library on a laptop and have found commands failing when attempting to execute them quickly with no error checking. This is where helper functions come in; when setting a block it makes sense to read back that blocks location to ensure it has actually changed.
Yup, Minecraft now has an official Pi port. Complete with some nifty functionality that allows you to program your game environment in your language of choice. More to follow once I've downloaded and begun to tinker!
I can see the Pi Ladder board coming in handy as a physical interface to the Minecraft world, we'll have to see!
I have been eying my Pi for the last few days, wondering if it's still alive. Only today did I check this site, to find it kept barely alive by Cloudflare. A bit of fiddling with cables later, and the Pi lives once again. Though the uptime has, naturally, been reset.
The Pi makes a great low-cost, low-power platform to prime a much more powerful web caching solution ( like Cloudflare ) from home. It's now powering what's fast becoming my most succesful web endeavour in terms of traffic. Not bad.
The realtime stats, however, are not cached. And I think that's why my Pi was struggling a little. I'll have to slow them down drastically.
I've finally found the time to update the Bootstrap version driving this blog. You should notice better readiblity ( the text is bigger ) but not much else.
Using the small pagination variation, plus some jQuery wizardry I've also "progressively enhanced" my blog navigation so that it's split down into managable pages. As you scroll down you should notice the nav paginate as it needs to, always showing you the currently visible article.
If you want to jump to an historic article, simply paginate and click away.
I think this is a fluid and natural navigation device, but it'll likely only work for around twice the number of articles I have currently. Any more than that, and it could get a little tricky to dig around for things of interest.
I'm considering enhancing it further with a jQuery keyword search, allowing the nav to be filtered-as-you-type, and may try to tidy it up and release it as a plugin to compliment ScrollSpy.
I've had in my possession for the last few weeks a Quick2Wire kit waiting patiently to be soldered-up and reviewed. Sadly I've just not had the time to do it yet, and I must thank Romilly for not calling me out on this… yet!
The Quick2Wire combo kit is an excellent expandable and extensible breakout kit for those wishing to do some serious IO on the Raspberry Pi without resorting to an Arduino to handle the workload.
It's available to order now and will cost between £26.77 and £31.91 depending on your location. This sounds a little on the pricey side, but you've got to take into consideration the fact that it's produced in much lower volumes than the Pi itself. This price should also include VAT and delivery.
The combo kit boasts a number of features including the all important GPIO pin protection, using diodes and resistors to catch incorrect voltages and overcurrent. It also includes a 3.3v regulator connected to the Pi's 5v supply, delivering a much more useful 3.3v power supply than the very limited 3.3v pin on the Pi itself. I've used a regulator from 5v down to 3.3v when hooking up an Arduino to my Pi, and must attest to its usefulness.
The port expander delivers an extra 16 GPIO pins over and above the 8 on the board itself, and you can drive all of these using Gordon's excellent wiringPi. See Gordon's post for more information.
Once up and running I plan to make sure you can use the Quick2Wire board from my wiringPi wrappers ( which I'm very, very aware are getting a little neglected! ), this should hopefully make it an easy and familiar device for existing users to pick up and play with.
I get a lot of people asking how I've put together the live system info on this very website. It's a lot easier than it looks to pull off, and I've opted to go a slightly more complex route than is sufficient. I use Ruby, Thin, EventMachine and other things that I'm assuming a basic knowledge of in this brief guide, in most cases you're best adapting the below code to your own language and server choices, but I'm aiming to write a more complete Ruby guide soon.
In its basic form, the stats are simply pumped out as HTML with the rest of the page and update only when you refresh the page. The only complexity here is the system commands needed to extract free disk space and memory. If you're a Rubyist, you can get everything you need with the following code ( which was previously shown in my post: Using the Palm m500 as a Raspberry Pi LCD ):
To make things more exciting, however, I wrapped up this code in a WebSocket server, using EventMachine's WebSocket library and just a little touch of MemCache to try and avoid the poor Pi being DDoS'd. You can see the full Ruby file here: http://pi.gadgetoid.co.uk/code/Socket.rb
I run this using the "Thin" Ruby server, with a yml file something like this:
In my several month absense from all things Raspberry Pi, I have neglected to enthuse about a number of great little projects which I have quietly noted and then, admittedly, forgotten about.
Gordon ( of WiringPi fame amongst other things ) has produced one such project in the guide of the Raspberry Pi Ladder board, a great little starer board that puts an onus on low cost and simplicity, yet offers an excellent introduction to Raspberry Pi GPIO and a surprising amount of potential for something that comprises only a very tidily presented 10 LEDs and 4 switches.
You can pick up the kit for a paltry £5.99 from Tandy and in addition to offering a GPIO starting point it's a great little introduction to through-hole soldering that even I could confidently cobble together.
I hope to get my hands on one soon, for a full review, a redux of my Ruby Binary Clock with shiny new features and a photo diary of my abysmal soldering skills.
While the second meetup was a little too close to Christmas for some of us not to be escaping early to attempt last minute shopping, it was a great chance to catch up with what's going on in the RPi world and meet a few new people.
Most notably was an appearance by Romilly Cocking of Quick2Wire fame, showing off an interesting Quick2Wire setup with an I2C analogue board driving an LED bargraph. I hadn't previously paid much attention to Quick2Wire ( or, in fact, anything much Pi over the last few months ), but now I'm throughly interested in the concept, and eager to get my hands on some boards to see just what I can achieve.
The second meeting was also underpinned by a real lack of any particular goal or project, but this isn't really a big issue at the moment. It's clear things are getting warmed up, and it's still an interesting event and a great place to meet like-minded individuals.
Norwich RPi now has a fledgling Subreddit which should help keep ideas ticking over between meetings, and the next meeting should be happening within about 3 months time.
I tested the Hobbytronics GPIO breakout board a few weeks ago, and found its ability to connect to a port expander promising. What it lacked, however, was the ability to regulate the 5v of the Pi down to the commonly used, and fairly important, 3.3v that facilitates the right logic levels for many sensors and, of course, the Pi itself.
I showed photos of my breadboard built out with such a regulator ( you'll find them on this blog ), and pointed out that the Pi can't really provide a decent amount of power from its onboard 3.3v regulator.
The result is the Breakout Board Pro; which includes an onboard, 500mA, 3.3v regulator that should be more than enough for powering an Arduino, Graphic LCD, sensors and other bits 'n' bobs.
This is great news for PiDuino users, because an ATMega 328 will run happily from this 3.3v and communicate with the Pi without wasting breadboard space on logic level converters and voltage regulator circuits.
Naturally I have a breakout board pro kit on the way, and will update this blog with a review of it in action as a direct replacement for my regular breakout and voltage regulator powering the Graphic LCD with RGB backlight which I mentioned before.
I've hooked up the beautiful Negative LCD I picked up from HobbyTronics to my new broken-out PiDuino setup.
Whilst I have not yet tweaked the Pi to send anything sane over its serial line ( the serial terminal is still enabled ) I have added a 3.3v voltage regulator to my breakout breadboard, and an Arduino running at 16Mhz/3.3v to drive the ST7565 with a Sketch that accepts messages over serial and displays them with a flashing alert backlight.
The reason for using a voltage regulator circuit is simple; the Pi's 3.3v GPIO pin only supplies 50mA max, and I'm definitely going to exeed that during my tinkering.
The serial terminal lead to some interesting garbage on the LCD. Over the next few days I plan to write a Raspberry Pi counterpart to this setup, delivering notifications with custom backlight colours to match each service. There are a few simple challenges to overcome, including trying to get the brightness of each backlight colour consistent with the others and successfully fading one colour authentically into the other without giving the poor Arduino a floating-point headache.
Although I may not have posted an update for a while, I've still kept myself abreast of the Pi and the various recent developments, and I'm still waiting for my second, hopefully Welsh manufactured, Pi to arrive. This will allow me a little more opportunity to hack around without disturbing this blog, which has now been hosted uninterrupted for 100 days on my Raspberry Pi.
Yesterday I soldered up the Pi GPIO breakout board and IO expansion board, and this morning I removed the SKPang case from my Pi, which doesn't fit a ribbon cable particularly well, and built the PiBow up around my running Pi. So, let's tackle these various different additions to my Pi armoury in no particular order.
A small mod with wire cutters let the ribbon cable pass unhindered
First up, the PiBow. Is an attractive and cleverly engineered case which fits my Pi like a glove. It was easy enough to assemble around the running Pi, and the multi-layered construction makes for a very durable and very attractive case for toting the Pi around in a bag. Where it fell short, however, was the cut out for a GPIO ribbon cable. My cable either had atypically large connectors on the ends, or wasn't flexible enough, but I had to take the layer of the PiBow with a little groove for the ribbon cable and snip out a portion of the plastic. Ultimately, though, it was easy to do, and didn't ruin the look of the PiBow so it's not a huge complaint.
The PiBow is good enough that I'm considering picking up a second one for my second Pi, I haven't yet seen another case that I particularly like yet. The PiBow really shows up the grey ribbon cable though, so I'm going to cave in and find a rainbow alternative.
Next up, the HobbyTronics GPIO breakout board. Its a simple piece of kit which adapts the ribbon connection to a breadboard-friendly set of headers. Unlike the basic Adafruit Pi Cobbler, however, the HobbyTronics board includes an additional header which breaks out power, data and clock lines onto which the Port Expander board can be connected.
I soldered the headers underneath to keep things tidy and avoid needing to trim the pins
The expansion board is i2c and can be daisy-chained to provide more IO than you could possibly know what to do with. It also includes a socket, so you can pop the MCP23017 chip out and use it on a breadboard if you're so inclined.
I was baffled by the fact that the included male and female headers didn't line up when placed on the port expander and GPIO breakout, but a quick look at the HobbyTronics website suggests pulling the male pins out of their plastic support and soldering them on individually. I did this, and plugged the pins into the female header while soldering to keep them lined up. I also soldered the headers underneath the boards, both because I think it looks better, and leaves the pin labels visible for future hackery.
I also found that soldering them on top would cause problems with the abnormally long male pins touching the breadboard when the boards are inserted all the way.
The GPIO breakout and port expander eat up a lot of room, so a 830 point breadboard is about the minimum you can get away with, without connecting the two with jump leads.
With the low price and fairly simple construction ( any surface mount components are already soldered on ) these boards are an excellent and good value addition to your Pi. Just be wary that the GPIO breakout board does not include any additional protection for your Pi's GPIO pins. I'm pretty terrible at soldering, but still managed to assemble both quickly. Using a piece of old strip-board to align the headers made it easy, just pop the headers into the strip-board and pop the board on top to solder. You can also use breadboard for this, but I don't trust myself with plastic around a soldering iron!
It may not look it, but to the eye this screen is beautifully crisp and readible from a fair distance
The ST7565 LCD is something I've been waiting to get my hands upon for a while. The negative model in particular works beautifully with the RGB backlight and can quite easily be adjusted to a super black positive LCD by inverting the contents of the buffer before sending it to the screen ( you can do this easily by subtracting each byte from 255 ). Its actually quite a lot more readable when inverted.
Gratuitous wiring joins the Arduino and ST7565, but plenty of IO remains
Unfortunately the RGB backlight makes it very hard to achieve a consistent brightness when fading between colours, and it also requires PWM which I wouldn't entrust the Pi to provide directly. Fortunately the Arduino is a dab hand at things like this, and I will use one of my breadboard ATMega chips as a smart PWM driver, accepting colours over serial and handling the transition between whatever colour is currently displayed and the new one requested.
Ultimately the Arduino is a brilliant stand-in for various IO expanders, handling ADC, PWM and digital IO with ease and lending a bit of intelligence, stability and autonomy to these processes.
The successor to the iControlPad has gone live on KickStarter with a goal of $150,000. I leant my arty skills to creating the new and more appealing visual design of the iControlPad2, and am eager to see it succeed. I would be most grateful if you could hit up the KickStarter page, and pledge us to success!
Today marked the first of Norwich's Raspberry Pi meetups and with 14ish people turning up, I think we can chalk it up as a success. Dubbed NorwichRPi, the group has brought together like-minded enthusiasts from all walks of life, and even snared a couple of passers-by who had heard of the Pi. The House cafe on St Benedicts have been excellent hosts providing good food, good coffee and a good atmosphere.
This has been a great opportunity to get a feel for the creative and technical underbelly of Norwich, and it has been made abundantly clear that we are in dire need of an assigned, 24/7 hacker-space ( or maker-space ) where we can gather and embark on community projects, share our experiences and perhaps deliver some education to those interested in the things we love.
There are many people currently engaged into making such a space possible. With any luck the Pi will continue to bring people together, and perhaps we can base some electronics/artistic projects upon it in the future; hopefully in a brand-shiny-new Norwich hackerspace.
In the interim, I implore any Norwich readers to give NorwichRPi a chance. It was a great opportunity to meet new people with similar interests and new ideas about what we could achieve with the Pi. As the group becomes more established, we'll likely have an informal itinerary for meetings and try to actually do something constructive. The choice of venue, specifically not a pub, makes the group far more inclusive than the likes of ALUG or Norwich 2600 and prevents folks simply drinking and chatting; not that those are bad things, of course!
If you're in the UK and eager to get your hands on Raspberry Pi accessories from a good local reseller then you might want to check out the HobbyTronics.co.uk Raspberry Pi section.
With GPIO ribbon cables available in two lengths, plus the Humble Pi Prototyping Board, the Slice of Pi prototyping board, the Serial VGA Monitor Adaptor and a glut of handy compatible ICs for expanding or protecting your GPIO port, it's a pretty good place to pimp your Pi.
I also recommend picking up an Arduino breadboard kit, plus a handful of any components which interest you. I've had a lot of fun hooking the Arduino up to the Pi, and they make a great pair with the strengths of one complimenting the weaknesses of the other. I run my own "breadboarduino" at 3.3v so it can interface directly with the Raspberry Pi
The accessories economy around the Pi is booming, and cases aren't the only thing to explode forth in droves from the community. Aside from shields of various shapes and sizes, one particular entrepreneur by the name of Rick Winscot has created a low-profile MicroSD adaptor which gets rid of that pesky protruding MicroSD
The project is already a smash-hit on KickStarter, with 8x the target funding at time of writing. You can pick up your own MicroSD adaptor for $12, two for $20 and each additional $10 will net you an extra one.
No word yet on whether or not the adaptor will fit inside the gorgeous PiBow case, but it certainly fits in the Adafruit Pi Box, if a little snugly.
Mounting an image with multiple partitions is somewhat disinginuous on Linux by default, but you can make things much easier in one of two ways. The following worked for me in Debian Squeeze on the Pi. You can either:
rmmod loop modprobe loop max_part=63
Or, if loop is compiled into your kernel, you will need to add loop.max_part=63 to your config.txt on Pi, or your kernel options on a desktop/laptop.
This makes loop mounting disks with multiple partitions a breeze, the partitions will show up as /dev/loopXp0, /dev/loopXp1 and so on. To mount an image to loop you should:
losetup /dev/loop0 your-os-image.img mount /dev/loop0p2 /mnt
In this example, /dev/loop0p2 should be the linux partition of your Raspberry Pi image. You can now rsync this to an external hard drive, or extract data if it's a backup.
If all else fails you can use kpartx, which makes it much simpler to mount disk images:
apt-get install kpartx kpartx -v -a your-os-image.img
I've pushed a new version of WiringPi up to RubyGems containing a couple of fixes in Gordon's C library, and some fixed bindings generated by a newer version of SWIG. This should build successfully on Raspbian.
Gordon's working away on some awesome new updates to WiringPi which will introduce /sys/class/gpio support and the ability to produce GPIO-based applications which don't require root access. His gpio binary has already been updated with two new functions to export/unexport the /sys/class/gpio interfaces.
I'll be wrapping up this new functionality as soon as it's available and benchmarking it against current shared-memory performance.
It's likely that WiringPython will need similar fixes to the bindings so that it compiles successfully on Raspbian, I'll do this when I merge in the upcoming changes.
Gordon strikes again, releasing a new WiringPi which not only includes the ShiftOut functions I was attempting to add, but also a whole delightful library of Serial goodness.
I've rolled both of these things into a new version of the WiringPi gem, which has also undergone some significant architectural changes favouring a more Object Orientated design. I've incremented the major version to reflect this.
To use GPIO functions you should create an instance of the WiringPi::GPIO class:
And to use Serial functions, use the Serial class:
require 'wiringpi' s = WiringPi::Serial.new('/dev/ttyAMA0',9600) s.serialPuts('Hello world!') s.serialClose
I've also wrapped up GPIO.shiftOut with an handy, more Ruby-friendly function shiftOutArray. This takes an array of 1s and 0s and shifts them out as bytes automatically.
After throwing together the WiringPi Ruby Gem, I figured it might be prudent to find something to do with it. Having previously cobbled together a 4-digit, 7 segment display, two shift registers a darlington array and a jungle of wires, transistors and resistors I decided to pop off the ATMega which I had driving it and hook up the Pi instead.
I decided to use the Pi's 5v line, adjusted via a 3.3v regulator. This lets me draw a full unrestrained ~500mA, which is my 1.3A power supply minus the current draw from the rest of the board. ( the 3v3 pin, by comparison, can only supply 50mA )
I then hooked up the Latch, Clock and Data pins for the shift registers to GPIO 17, 21 and 22 respectively. These correspond to WiringPi pins 0, 2 and 3 (yes these weird pin numbers hurt my brain, too ).
Driving the Shift register in Ruby was then trivial, even more so with the addition of a shiftOut function to my WiringPi wrapper library. shiftOut takes a Data Pin, Clock Pin and Latch Pin followed by an array of bits ( represented by a 1 or 0 in this case ) which it will push out in the order given to it. A shiftOut call looks a little like this:
For the sake of simplicity, I force the specified pins to output mode in the shiftOut function so be wary if you're somehow using them for a return signal.
At the moment shiftOut isn't available in the WiringPi gem, but a new version will land once I've got it working nicely as a pure C function rather than a somewhat sluggish helper in the Ruby wrapper.
Thanks in no small part to the excellent work of Gordon on his inspired WiringPi library, which I use for pretty much all my GPIO access, I present the WiringPi Ruby Gem
To install, simply "gem install wiringpi"
WiringPi is a library which seeks to make GPIO access on the Pi a very similar affair to that on the Arduino by providing simple read/write/mode language constructs.
It's pretty alpha at the moment, but as far as I know it works. Thank Gordon for all the hard work, I just figured out how to wrap it for Ruby and pack it up into a Gem file for ease of installation. With any luck it'll actually work for you, nobody has yet told me yay or nay.
Documentation will follow soon, but it's all pretty straight forward. By including a simple Ruby wrapper I've taken care of sanity checking inputs and calling the initWiringPi function for you. One caveat; you still need to run your Ruby scripts as root if you want them to be able to access the GPIO with the methods WiringPi uses. To do this you'll most likely need to call: "rvmsudo ruby myfile.rb", and you can play about with WiringPi with "rvmsudo irb" (assuming you use RVM, that is!)
Reading and writing to the GPIO pins is done like so:
I have a few little helpers planned for managing things like shift registers. If you want to get started shifting-out already, then I use something like this:
require 'wiringpi'
DATA_PIN = 2
CLOCK_PIN = 3
LATCH_PIN = 0
WiringPi.mode(DATA_PIN,OUTPUT);
WiringPi.mode(CLOCK_PIN,OUTPUT);
WiringPi.mode(LATCH_PIN,OUTPUT);
def shiftout(bits)
WiringPi.write(LATCH_PIN,LOW);
bits.each do |bit|
WiringPi.write(CLOCK_PIN,LOW);
WiringPi.write(DATA_PIN,bit);
WiringPi.write(CLOCK_PIN,HIGH);
end
WiringPi.write(LATCH_PIN,HIGH);
end
# Output an array of 16 ones or zeros ( two shift registers )
shiftout [0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0]
# You can also do this
shiftout [HIGH, HIGH, LOW, LOW, HIGH, HIGH, LOW, LOW]
Update: If you want real VGA out on the Pi, you can try the Pi-View from Element14. It's the official HDMI to VGA adaptor for the Pi's HDMI output and doesn't require a separate power supply. Check it out at ModMyPi: https://www.modmypi.com/pi-vew-raspberry-pi-hdmi-to-vga-converter. Pi-View supports real output at resolutions up to 1080p
For all those who have complained about the Pi lacking VGA ouput, this isn't what you're looking for, but it's damned near close.
Hobbytronics have produced a Serial VGA Monitor Driver board which couples a female VGA connector with a Propellor P8X32A to drive it. The Propellor is an interesting little chip, and the VGA Driver board can be reprogrammed via serial (using an FTDI breakout board) like any other dev board. Although most of the P8X32A's IO is either tied up by the VGA output or simply denied any headers or easy way of being connected.
Still, when coupled with an ATMega and some tweaks to fire up its return TX line ot get the two talking a potent combination could be made, and directly connecting this board to the Raspberry Pi, which should be capable of powering it too, would give a pretty useful basic VGA output for monitoring, terminal interaction and even simple games.
A very straightforward protocol is used over serial, using only the TX line of the host to send commands. It has basic "window" creation features supporting up to 9 windows to which text can be written individually. The total real-estate is 100 x 50 characters, enough for a whole host of information.
At £24, it's not entirely unreasonable for such a niche breakout, specially considering its highly hackable nature. It looks like a handy way to add an auxiliary status monitor display to the Pi, leaving the primary display ( if you even have one connected! ) free for your X desktop.
If there's one thing that everyone agrees would be a cool addition to the Raspberry Pi, it's an LCD. There are plenty of breakout board endowed LCDs on the market in a variety of styles, sizes, resolutions and capabilities... but I, for one, found myself a little overwhelmed by the choice.
Enter the Palm m500. I had one knocking around, it has an LCD. Surely I could work with this?
Incidentally, it was easier than I thought. Once I'd cast the idea of gutting the m500 for its LCD and attempting to bitbang it to life, or find a datasheet somewhere online telling me how to use it directly, I found a handy little PalmOS app called PalmOrb.
PalmOrb makes your PalmOS device emulate an LCD. A Matrix Orbital LK204-25 LCD to be specific. This is a serial LCD, but fortunately can be used with USB using your Palm dock to make things easier.
Setting up is as simple as downloading and installing PalmOrb on your device, firing it up, picking USB mode in the settings and then finding your favourite LCD driver to send it data goodness.
To drive the Palm running PalmOrb I chose lcdproc, installing it is a simple "apt-get install lcdproc" away on Debian, and configuring isn't much trickier. Following the instructions on the PalmOrb page I got everything up and running in a jiffy. I used /dev/ttyUSB1 which was one of the two entries to appear when the Palm is connected. Using /dev/ttyUSB0 seemed to crash PalmOrb.
Finally, I ran lcdproc with a command like "lcdproc C M L G D U K". The end result is this:
Okay, it's not very impressive, but it's a cheap and easy way to get a status LCD connected if you have a spare PalmOS device and USB dock kicking around. For the more enterprising of hacker, PalmOrb also supports data over IR and Bluetooth, the latter potentially allowing a nice wireless status monitor
There is another way to get this sort of setup. If you've got a spare old phone, tablet or iPod touch then you can set up a status monitor similar to mine and simply open it as a webpage on your device. Easy as pie wireless LCD output! You could even stream an image or framebuffer capture if you're feeling brave.
For those who want to persue the latter option, here's the messy code I use to get system stats in my Ruby websocket service:
The Pi isn't really a piece of hardware, or a foundation, or even a gathering of like-minded people working toward a single important goal. At its very core it is an idea or an inspiration, and there's little doubt that it's inspired me to try a whole variety of things I'd previously been ignorant of.
My Arduino tinkering began with a desire to protect my Pi from more GPIO fiddling. After hooking up LEDs to the GPIO header, throwing together the binary clock and getting everything up and running, I wanted to try something more advanced. But getting too advanced can put the Pi at risk. That's not to say I didn't manage to hook up and drive a couple of shift registers from the Pi, modifying my Ruby Binary Clock code to light the LEDs through them. But that's a tale for another time!
Not wanting to make things easy for myself, and wishing to avoid the temptation of shields, I dived straight into the whole Breadboarduino concept. I picked up a great kit at Hobbytronics.co.uk which combines a fully featured USB to serial breakout board with an 830 point breadboard, an ATMega 328 ( the chip on, for example, the Arduino Duo ) and all the support components and wires. It also came with a printed guide which made getting it all going a breeze.
The Breadboarduino is a great concept as it gives you much more flexibility over your Arduino build and size. You can stick everything on a 400 point breadboard and still have room for a voltage regulator and a small IC ( but not the USB to serial adaptor! ), or you can go nuts on a bigger breadboard. I've put together the Breadboarduino on a 400, 830 and 1660 board thus far for various projects.
Having hooked up a 4 digit multiplexed 7-segment display via a stupendous array of transistors, built a small IR circuit, read an SD card using just a breadboard and jump wires and various other silly things I'm now looking to pick up an LCD and use the Arduino in the way I originally envisioned when buying it; as a buffer between the Raspberry Pi and some shiny components. Watch this space for more adventures.
Unless you're faithful to a particular distribution, sooner or later curiosity will get the better of you and you'll likely want to try another flavour of Linux on your Pi.
To avoid the hassle of swapping SD cards, you can take advantage of XECLoader. It's an experimental bootloader for the Pi which presents a customisable menu of boot options.
Before you start slapping XECLoader into /boot and restarting your Pi, you should know that it's not for beginners. Kernels used must be stripped of the first32k, and your mileage may vary getting Raspbian up and running ( I've failed thus far ). If you plan to boot from an external hard drive, you'll also need to make sure your Kernel supports this.
At time of writing I've successfully got both Debian and Fedora up and running, although Fedora is a little flaky.
From my assorted tests, an external hard-drive gives marginally better performance than a good SD card with tweaks, but you pay for this with a loss of portability and an increased power footprint. I've been fiddling with scripts to detect the lack of a hard-drive at startup, and boot from the SD-card instead but haven't yet come up with something polished enough.
Not to be confused with "IRC", LIRC stands for Linux Infrared Remote Control. It is, as you might have guessed from the name, a suite of tools and drivers geared at getting your infrared remote gear to work with Linux.
Now, alas, I can not regale you with tales of custom-built IR recievers because I happened to have a Philips eHome Infrared Reciever knocking about from an old media-center PC. Getting it to work with Debian on the Pi was a little tricky, however, and this is an exercise I will leave to you. I'd rather talk about getting the working remote doing fancy things in Ruby. Ultimately, though, I didn't really get it working myself; bootc came to my rescue with his cutting-edge kernel for the Pi, which supported my reciever out of the box.
You also need to set up your remote, and for that you can either delve into the pre-configured remotes and hope yours is there, or fire up irrecord and record and name each button.
Once working, the fun begins. LIRC comes with some handy tools which do a number of nifty things in response to remote control button presses. irpty emulates a terminal and forwards remote commands to whatever application you choose to run inside it, irexec can execute commands in response to button presses, and most useful of all for Ruby is ircat which outputs commands to STDOUT.
All of these utilities require a config file which stipulates which command is executed in response to which button. This is usually at ~/.lircrc and has a simple syntax which is well documented at lirc.org. Here's a snippet from mine, specifically for ircat:
begin
button = ok
prog = clock
config = blink
end
begin
button = stop
prog = clock
config = exit
end
I've kept it simple, touching only 3 of the available options. The only mystifying option, "prog", is the program name which I pass into ircat, and effectively creates a group of commands for that particular application. "button" is the name of the remote button, and "config" is the string that ircat will print to its STDOUT in response to that button. Easy!
Now, I mentioned passing a program name to ircat, this should match the program name that you've used in your settings. Ultimately you will be doing something like this from Ruby: "ircat clock --config=/home/pi/.lircrc"
The config file is referenced explicitly because I run clock.rb as root so it can access the GPIO.
I suspect you're eager to see how this works in Ruby, so here we go ( excuse my gratuitous overuse of @@ class variables ):
require 'pty'
@@commands = Array.new
# Spawn an ircat thread for sexy remote commands
if @@ircat.nil?
@@ircat = Thread.start do
PTY.spawn("ircat clock --config=/home/pi/.lircrc") do |r,w,pid|
@@pid = pid
r.each { |line| @@commands.push line.chomp! }
end
end
end
The code really is as simple as it looks. Start a new thread and use PTY to run the ircat "prog". Every time ircat outputs a command to its STDOUT, PTY will slurp it up and append it to the end of the @@commands queue using Array.push. The .chomp! removes any nasty trailing spaces and makes checking the commands simpler.
To process the commands simply .shift ( grab the first item of ) the array, and run it through a case statement or run it through a command processor. Once you've got the command, acting on it is the easy bit. As an example, I used commands to enable my remote to play/pause the clock, and turn on/off individual LEDs ( with the number keys ). The possibilities are endless once you've hooked your script up to an IR remote.
Pushing the boat out to C, another lanuage which I've somehow avoided becoming familiar with, I decided to re-write my Ruby LED Binary Clock entirely in C. The code isn't brilliant, with a glut of consecutive "if" statements to determine which LEDs should be turned on. But it works!
Here's a snippet outlining a new idea I had whilst working in C, phasing the "off" phase of the LEDs to give a cool, pulsing up/down effect.
slept = 0;
for(x = 13;x >= 0;x--)
{
int status;
int led = leds[ x ];
status = digitalRead( led );
if( status == 1 )
{
slept += 20000;
digitalWrite (led, LOW);
usleep( 20000 );
}
}
usleep( 300000 - slept );
There are 14 LEDs being turned on with a 50ms delay between each one for a maximum time of 700ms (if all LEDs were to be lit) to turn them on. Thus I had 300ms left to turn them all off, so I used a delay of 20ms.
Always eager to use the Raspberry Pi as an excuse to push my knowledge of programming and hardware, I decided to go on a little journey into the mystifying world of ARM Assembly.
Following the guide from
http://savannah.nongnu.org/projects/pgubook/
I set about rewriting the Intel? Assembly in the examples to the ARM equivilent. I had some difficulty accessing the array of numbers in the find-the-largest-number example, but eventually overcame it with sheer determination and a lot of fumbling through any references to ARM assembly I could turn up on Google. The resulting, not exactly brilliant, code with amends suggested by Tufty is as follows:
.data
data_items:
.long 3,67,34,222,45,75,54,245,34,44,33,22,11,66,0
msg:
.ascii "Finding Largest Number\n"
len = . - msg
.text
.code 32
.globl _start
_start:
mov r0, #0x000001 @ Not sure why we put a 1 here
ldr r1, =msg @ Put the msg address in r1
ldr r2, =len @ And the len in r1
mov r7, #0x000004 @ And the syscall for write in the r7
svc #0x000000
ldr r4,=data_items @ Load address of data_items into r4
mov r5,#0x000000 @ Start our r5 counter at 0
ldr r0,[r4,r5,LSL #0x000002]@ Load from data_items r4 with offset r5 and multiplier of 2
start_loop:
cmp r1,#0x000000 @ Check for end of list 0
beq loop_exit @ Exit if we've hit 0
add r5,r5,#0x000001 @ Increment our counter
ldr r1,[r4,r5,LSL #0x000002]@ Load the next data_items into r1
cmp r1,r0 @ Compare
ble start_loop @ Branch to the start of our loop if less or equal
mov r0,r1 @ Move r1 to r0 if its greater
b start_loop @ Loop!
loop_exit:
mov r1,#0x000000
mov r4,#0x000000
mov r5,#0x000000
mov r7,#0x000001 @ 1 is the syscall for exit
svc #0x000000
Building and running the file is fairly simple, excepting the cryptic CPU name which I
retrieved from the forums
thanks to tufty. Just run the following commands, assuming your code is in the file big.s:
as -g -mcpu=arm1176jzf-s -o big.o big.s ld -o big big.o ./big echo $?
That last line, echo $?, should display the exit code that big returned. In the above example, it'll be 245 because that's the largest number.
To keep strain on my Raspberry Pi to a minimum, this site is memcached via Ruby
memcache-client
I created a simple wrapper around the client to cache blocks of output code, it's so terse and elegant that I feel I must share:
require 'memcache'
CACHE = MemCache.new 'localhost:11211'
def cache( key, expiry = 0 )
if cached.nil?
cached = yield
CACHE.set key, cached, expiry
end
cached
end
cache( 'mypage', 300 ) do
# Some complex page output!
'hello!'
end
See how it works? Ruby allows a method call to wrap a "block" of code, and the method can yield control to that block when told to do so.
In this case, we check our MemCache for a cached instance of the code output, and where it doesn't exist we yield to the block, capture its output, cache for 5 minutes and return that output. If it's already cached, we simply return the cached version.
As soon as I got my hands on the Pi, I knew I needed to exploit those GPIO pins and do something I'd never attempted before; light up some LEDs, whee!
The result of my hackery, Ruby RPi Binary Clock, uses WiringPi, Ruby and a copious amount of LEDs and jump leads to create a 14 LED binary clock that shows the hour, minutes and day of the week.
# A small snippet from clock.rb
# showing the dec->binary conversion
@@mydays.each do |number,led|
if day >= number
Gpio.write(led,ON)
day = day - number
sleep(delay)
slept = slept + delay
end
break unless day > 0
end
Whilst sharing my Pi over the internet, I discovered a need to hard-reset it from time to time due to the various software which was being tested.
My first thought was some sort of clever microcontroller-based solution for power-cycling the Pi on demand, but there were several technical hurdles and gaps in my knowledge to overcome to implement this solution.
Enter Kripton, who points out that the Broadcom BCM2708 has a hardware watchdog which, with a simple kernel module and watchdog daemon, can automatically reset the Pi when it freezes and even in a variety of other situations.
To get watchdog up and running, you'll first need to:
sudo modprobe bcm2708_wdog sudo vi /etc/modules # Add the line "bcm2708_wdog"
Next you need watchdog, a daemon which does little more than send /dev/watchdog a heartbeat every 10 seconds. It can also run arbitrary executables which do things like ping a server, and can trigger reboot when they fail.
sudo apt-get install watchdog chkconfig watchdog on sudo /etc/init.d/watchdog start
You should also configure watchdog:
sudo vi /etc/watchdog.conf # Uncomment the line watchdog-device = /dev/watchdog # You might also want to uncomment max-load-1, or add something like "max-load-1 = 24" to reset your Pi if the load average exceeds 24 in any 1-minute span.
Finally, make sure you've not got any crucial processes running and ensure you deactivate any swap partitions or files, then test your watchdog with a nasty forkbomb:
: (){ :|:& };:
This will ultimately cause a kernel panic and, if everything is set up correctly, your Pi will reboot a few seconds later.