wiringPi Pin numbering

I’m asked many times why wiringPi has its own pin numbering scheme for the Raspberry Pi, rather than use the native hardware pin numbering (which is can also use, along with the physical pin numbers)..

The answers are simple…

  • Firstly… In the very first published diagram of the GPIO connector on the eLinux wiki site the user-usable GPIO pins were numbered zero through seven. So I thought that was fine and I added mappings into wiringPi to make them do just this – after all, in any program you could now run  simple loop from 0 to 7 to access all pins – e.g. to light up 8 LEDs. (Note that this diagram has since been re-drawn and no-longer numbers them from 0 to 7)
  • Secondly… To try to encourage Arduino users over to the Pi – wiringPi makes it somewhat easy here too. In Arduino land, we don’t talk about port C, bit 7, we talk about “pin 13” (and in almost All Arduinos “pin 13” is the notification LED – the ones you use for your very first “blink” program – the underlying Arduino wiring library hides the actual hardware port and bits from you).
  • Continuing on… When the Pi hardware was changed, the foundation re-provisioned 3 pins on the original 26-way connector. If you stuck to wiringPi pin numbers you were fine and you didn’t need to change your programs as the pins numbers didn’t change, but if you were using the native pin numbers, then you needed to work out what board revision you are using, then re-map the pins in your own code.

So there you have it. That’s why wiringPi has 3 pin numbering modes. Please read the fine manual for the ways to use each mode.

A rude awakening

So early evening last night (Saturday 19th Match), a nearby neighbours power went off… They called Western Power who at about 9pm decided that it was an emergency… Due to a young person being in the affected house.

So at about 1:45am, Sunday morning a crew from Keir turned up and started digging with power tools.

This more or less woke up the whole street. Several neighbours went outside to complain, but the workmen were somewhat non-caring and carried on making a noise. They kept on making a noise for about an hour or so before leaving.

So no-one in the street got much sleep.

The worst part? They didn’t need to dig at all. Upon inspection to see what they’d done, I found none of their digging was directly connected with restoring the power to the affected house. To fix their power, they ran a temporary cable from a street-side junction box into the house through their letter box (and presumably into their consumer unit)

power3This is the view down the street. The barriers at the right is where the power cable is tapped into:

power1This is the power tap – the cable went down the street into the house:

power2Let there be power!

The proper fix has started at about 5pm on Sunday afternoon. More people from Western Power and Keir have turned up. It’s now nearly 7pm and they’re still digging.

power4Mini digger and operator hard at work…

It has been a fairly tiring time here. Who knows how much longer they’ll go on. Worse – the questions I’m asking is why? Why did they have to dig this up at 2am on Sunday morning? Why are they now digging at 7pm? Why couldn’t they have run the temporary cable and left it until Monday?

I think it’s fair to say that Western Power and their contractors are not the best loved people here tonight.

Raspberry Pi v3

On the first birthday of the Raspberry Pi (That’s the first anniversary of the original February 29th launch!) The fantastic foundation brings out the Model B v3.

Features over and above the existing Pi Model B v2:

  • Wi-Fi and Bluetooth (Bluetooth Low Energy/BLE)
  • Upgraded power handling – capable of handling 2.5 amps at 5v over the board. You need a good PSU then you can run lots of USB and GPIO things.
  • 1.2Ghz (fixed, not OC for now)
  • 64-bit ARM v8.
  • $35 – around £26 to £27 in the UK.

Physically it’s the same size, same mounting holes, GPIO connector, etc. as the B+ and v2. The only obvious difference is the location of the LEDs. However a quick test shows that the LEDs will show through the side of the official Pi case and most of the ones with transparent lids and sides won’t be an issue either (e.g. Pimoroni Coupé case)

Images

Here it is next to a Model B v2 for comparison. The v3 is the one on the left

pi23A quick glance doesn’t show anything much, but look to the top-right of the board – the LEDs on the v2 have been moved to the top-left of the v3 board on the v3 and in their place on the v3 is the chip antennae for the Wi-Fi and Bluetooth interface. (The support ICs, etc. for that are underneath the board)

More details on the new features

Power

The on-board power distribution can handle up to 2.5 amps at 5v now and USB power control has been dropped – it’s fixed at 1.2 amps, so make sure you have a good PSU capable of delivering over 2 amps if you want to make full use of it – I did a test and had 4 other Raspberry Pi’s being powered off the USB ports.

USB over current detection is still present and will show up in the logs should you exceeded the overall 1.2 amp limit.

Wi-Fi

The Wi-Fi is not connected to the existing USB interface. It’s on an interface of it’s own – It is using the SDIO interface via the GPIO so it won’t use any precious USB bandwidth. This should improve performance for those using the Pi as a Wi-Fi access point, if nothing else.

Some quick benchmarks have shown speeds of 40Mb/sec via Wi-Fi.

Bluetooth Low Energy

The BLE interface runs off one of the Pi’s serial ports. It has 2 serial ports and only one has been exposed via the GPIO previously. I understand it’s actually running off the original one, which is now using the secondary, but some internal munging has happened to keep that as /dev/ttyAMA0 for user applications.

64-bit

Raspbian hasn’t yet been updated to make use of the 64-bit cores… Give it time.

Misc. details

In some informal chats with the boffins at Pi HQ they mention running out of GPIO pins used for the Wi-Fi and BLE interfaces, and so the LEDs and under-voltage signal, etc. are on a separate GPIO expander controlled by the GPU. There is no USB power control it’s now fixed at 1.2A. I’ll try to clarify this when they manage to get some spare time to breathe after the work required to get this to product!

wiringPi

wiringPi has been updated and it will be available via apt-get/update shortly, but for now you can get it directly via the downloads method on the wiringPi website.

And well that’s that! Happy Birthday Raspberry Pi. And still for $35 too.

Raspberry Pi controlled Oven

So as well as technology, I love baking – to the extent that I bake stuff to sell with all the shenanigans that goes with that. Local authority inspections, food hygiene certificates, insurance, blah….

Some bread I made … (Devon Honey Spelt if interested)

And then one day I foolishly thought it might be  good idea to combine my love of geekery and technology with my love of baking… And stuck a Raspberry Pi to the side of one of my ovens. I did have a couple of reasons to do it (other than because I can) one is to cook meringues at a cool 60°C and another is to bake some bread that requires a gently cooling oven from about 200°C to about 100°C over a period of about 6-10 hours. I’ve not done that yet, but it’s on the cards. Meanwhile…

Here it is:

ovenPiSo that’s an A+ model in a nice Pimoroni case with an Adafruit perma proto-plate on-top with some “stuff” to control the oven stuck on the side of the oven with some Blu-Tack for now. It’s powered up – stays online all the time now (I had issues with an old Wi-Fi dongle, replaced it with one of the Foundation approved ones and it’s been rock-solid since then). The three thin  cables go to thermocouples inside the oven compartment and the grey cable goes to a SSR (Solid State Relay) inside the top of the oven. The Green LED is actually a bi-colour LED wired across 2 GPIO pins with a resistor. It can be off, green, red or if I could be bothered to write code to alternate the pins, a sort of muddy yellow. I just use it to indicate the heater being on (red) or off (green).

So how do you control an oven? Lets break it down into steps. One thing I was interested in was just how rubbish my oven really was. I already knew where the hot spots were (the bottom of the oven is hotter than the top – who’d have thought that?) and how unevenly it cooked as well as just how approximate the temperature dial was (plus or minus a fruit cake) so the first task was to measure the temperatures. Most of the temperature sensors you see people plugging into the Pi are only good to about 120°C or thereabouts. I wanted something that was good to 300°C or more. (This oven maxes out at 250, but I have others that go to 300…)

Thermocouples are the ideal thing here, but they’re somewhat different from your usual semiconductor sensor. They work by exploiting the fact that when you put 2 different metals next to each other they will generate a voltage. A tiny voltage, but a voltage none the less. It also turns out that the voltage varys in a reasonably linear way according to the temperature. So all we need is to plug the thermocouple into a suitable amplifier, digitise the result and read it into the Pi. This is somewhat simplified and you’ll hear people bleat on about “cold junction compensation” blah, blah blah, and other stuff, but the trick here is to use a chip that does all that for you. The MAX31855 is such a chip and Adafruit have a neat little breakout board which has the chip on a breakout board with terminals for the sensor and pins to hook up the digital side. Being based in the UK, I bought them from a UK distributor of Adafruit products, SKPang along with some Type K thermocouples. (Thermocouples come in different types depending on the materials used and so-on).

So after testing these and fixing the wiringPi max31855 driver I soldered some onto an Adafruit perma proto-plate and tested it.

Now here’s a little problem – I wanted to use three thermocouples. Great. The MAX31855 is an SPI device. Also great. The Pi only has 2 SPI channels. Not so great. Ah well. My solution was to use 3 other ordinary GPIO pins as the CE lines to the 3 devices. This works well.

So why three sensors? Initially I was interested in just how bad the oven temperature varies over the interior, then I thought about redundancy – and here’s an issue: Confucius says: “Man with one thermometer knows exact temperature. Man with 2, never sure …” Well, maybe he didn’t, but you know what I mean. Fortunately there are some fairly standard ways of dealing with this. One way is a simple “voting logic” approach. You read the sensors and you pick the 2 that are closest then average those 2 to get the temperature. You also apply some heuristics to check the third sensor to see just how far away from the average it is – and can then use that information to print an error message if it goes too far away, or just log it for another day.

This worked well, but it wasn’t without problems – when the oven got to a stable temperature, the odd-sensor-out changed and the resulting 2 sensor average jumped a little – not much, but enough to cause some issues with the control loop. In the end I dropped it and just averaged all three sensors and built in some heuristics to check for a sensor going too far off-course. This works well. There are other algorithms to read and sense and generate the oven temperature, but for a little hobby project this is good enough for now.

So I started to produce graphs using the existing mechanical/capillary tube sensor. These sensors work by having a sealed tube and a sensor with a spring behind it. The power of the spring is determined by the rotary knob. When the sensor pushed hard enough the switch inside the knob clicks and the heater turns off…. Until it cools down a little, then the oven turns back on again and the process repeats for the duration.

This is how the majority of domestic (and some commercial!) ovens work. It’s a somewhat crude system, but it’s tried and tested and been in-use for decades.

So just how crude? Here is a graph:

ovenRunThis is a single run of the oven. Y Axis is temperature in °C * 10 and the X axis is time in second.

I started with the Pi set to 50°C and ran it for for time (half an hour or so) then I used the ovens mechanical controller to take it to 200°C … As you see it’s somewhat hotter than 200 and lots of wibbly wobbly temperature swings. After 20 minutes of this, I turned the ovens controller to zero and opened the door for a few minutes, then told the Pi to control it to 200°C and closed the door. It gets up to 200°C fairly quickly, overshoots by a degree or 2, then settles down – it’s better than +/- 1°C at that point.

The next little dip is when I opened the door to load up a tray of mince pies – well it is Christmas time after all.. There is another dip about 15 minutes later when I opened the door to turn the tray, then a couple of minutes after that when I took the tray out and turned it all off.

mincePieOne of the mince pies that it cooked during that run.

Read more about my thoughts on mince pies here …

After initially measuring the temperatures and being somewhat surprised at just how crude (and inaccurate) the existing controller was, the next step was to control the oven. The oven heater is 2.2Kw and 230v, so this isn’t really anything you want to fiddle with unless you are 100% confident you know what you’re doing. My background from 25+ years back was factory automation, designing & building robotic transfer mechanisms, controlling machine tools and so on. I’m comfortable with my ability to control stuff like that, so controlling a simple heater ought to be relatively easy.

And it is. But DO NOT try this yourself unless you are fully confident of you own ability. I will not present any photos of what my system looks like inside the oven – if you want to do this, then you are on your own, however I will write about what I used and how I did it, but no code, sorry. (It’s written in BASIC, anyway)

I chose an off-the-shelf SSR (solid state relay) unit. I went for a 40 amp device with heatsink. These devices have been about for a very long time and are not that efficient and dropping 2v at 10 amps is a power loss of 20 watts which you have to get rid off – inside an already warm cavity above the oven chamber. The heatsink is bolted to the frame of the oven and the high voltage terminals wired across the existing thermostat switch. This makes it simple to use – and with the Pi turned off I can still use the existing thermostat.

The low voltage side of the SSR is connected directly to the Pi. This is nothing more than a resistor and LED (inside the SSR) so all the Pi has to so is provide 3.3v and a few milliamps to turn of the LED that forms part of the opto isolator inside the SSR.

An advantage of the SSR I used was zero crossing detection. Simply put the thing only turns on or off when he mains cycle crosses zero – either way up or down. The advantage of that is that it vastly reduces electrical noise. No clicks on nearby radios. A side effect of that is limiting the minimum time I can turn the power on for – one half cycle or (at the UKs 50Hz) a 100th of a second. In practice this isn’t an issue as the minimum time I’m going to turn the heater on for is in the order of 1/10th of a second.

More on safety

The oven has a built-in over temperature cut-out and additionally has a simple mechanical timer. I use the timer – wind it up to 100 minutes so that if the worst were to happen and it did overheat and the cut-out didn’t trip, then hopefully for no more than that time.

Now there’s just the little issue of controlling the oven temperature… There are many standard algorithms but the usual one is often called PID or three-term controller. PID stands for Proportional (multiply the error by a constant to get the new output), Integral (looks at the magnitude and duration of the error) and Derivative (look at the rate of change of the error). The error here is the difference in measured temperature against the desired temperature. There is some interesting calculus to execute the PID control, but in a program its really only 3 lines of code.

A down-side is that a PID algorithm needs to be tuned. There are several standard ways to tune the algorithm – most involve sitting down and working through the parameters, tweaking one at a time and checking the graphs and there are some auto-tune algorithms too. I adapted an auto-tune algorithm, but it didn’t work very well, so I sat down and made a few approximations to the tuning parameters then tweaked them after a few real runs. It’s not yet perfect, but more than good enough to bake a sponge cake. Currently it overshoots by a degree or 2 (this is more apparent at lower temperatures) but it isn’t an issue whatsoever.

I suppose some of you are still asking: Why? And the answer is because it’s fun and because I can.

Look out for another exciting episode of my Pi controlled oven when I’ll be doing a video and showing you how to make a simple loaf of bread…

4 Pi’s on my screen… What?

4pisA quad-core Raspberry Pi?

Sure. Why not. Put 4 x ARMv7 Cortex-A4 cores on the chip and lets give it 1GB of RAM while we’re at it.

pi2And here it is. The Pi v2.

Unlike all previous Raspberry Pi’s the memory chip is now on the reverse, but otherwise this Pi is exactly the same layout as the current B+ so all your old (and new!) cases remain the same.

So is it faster? You bet… A simple benchmark:

Compile my RTB BASIC interpreter – on a B+ it takes nearly 3 minutes from scratch. In the Pi 2 using a single core that compile time drops to 1 minute and 9 seconds. Using all 4 cores, the compile time drops to a mere 21 seconds! That’s nearly NINE times faster than an existing Pi! Obviously not everything will go faster, and to make full use of that speed, you’ll need to write programs that are multi-threaded – no easy task, but the potential is there.

Want to see /proc/cpuinfo? Here it is:

processor : 0
model name : ARMv7 Processor rev 5 (v7l)
Features : half thumb fastmult vfp edsp vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm 
CPU implementer : 0x41
CPU architecture: 7
CPU variant : 0x0
CPU part : 0xc07
CPU revision : 5

processor : 1
model name : ARMv7 Processor rev 5 (v7l)
Features : half thumb fastmult vfp edsp vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm 
CPU implementer : 0x41
CPU architecture: 7
CPU variant : 0x0
CPU part : 0xc07
CPU revision : 5

processor : 2
model name : ARMv7 Processor rev 5 (v7l)
Features : half thumb fastmult vfp edsp vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm 
CPU implementer : 0x41
CPU architecture: 7
CPU variant : 0x0
CPU part : 0xc07
CPU revision : 5

processor : 3
model name : ARMv7 Processor rev 5 (v7l)
Features : half thumb fastmult vfp edsp vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm 
CPU implementer : 0x41
CPU architecture: 7
CPU variant : 0x0
CPU part : 0xc07
CPU revision : 5

Hardware : BCM2708
Revision : 0010
Serial : 000000000884752a

And here are the first few lines of ‘top’ while I’m at it: (Press ‘1’ to get the CPU lines if trying this yourself)

top - 22:58:18 up 19 min, 1 user, load average: 0.00, 0.06, 0.06
Tasks: 74 total, 1 running, 73 sleeping, 0 stopped, 0 zombie
%Cpu0 : 0.0 us, 0.0 sy, 0.0 ni,100.0 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
%Cpu1 : 0.0 us, 0.0 sy, 0.0 ni,100.0 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
%Cpu2 : 0.0 us, 0.3 sy, 0.0 ni, 99.7 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
%Cpu3 : 0.0 us, 0.0 sy, 0.0 ni,100.0 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
KiB Mem: 764060 total, 76048 used, 688012 free, 9964 buffers
KiB Swap: 102396 total, 0 used, 102396 free, 40072 cached

In brief

This is the Raspberry Pi you’ve all been waiting for – and I know a lot of people will be saying it’s the Raspberry Pi that should have been three years ago, but you have to start somewhere. I do not believe this could have been possible without all the existing sales and support over the past few years. Proof, in anyone needed it that there is a need for a computer like this. A computer that can help develop and nurture the next generation of computer scientists, programmers and day to day users, just as the micros of the 70’s and 80’s did for us older folks.

Well done to everyone at the Raspberry Pi foundation! What a fantastic addition to the family.

GPIO

And before I forget it – a HUGE thanks to Eben and the Foundation for allowing me a sneak peak of the Pi v2 so I can make sure my wiringPi librarys work on the v2.

The GPIO is the same as before, however the peripheral base address has changed and wiringPi has been updated to reflect this change. Please fetch a new version of wiringPi (make sure you have version 2.24) and off you go. It auto-detects which Pi you’re on and does the right thing.

And on the 49th day, it stopped…

I’ve had two people recently email me regarding their Raspberry Pi sensor monitoring projects stop after 49 days… The reason is simple, the solution slightly more complex, so what’s going on?

The wiringPi GPIO library has a function: millis() which returns an unsigned 32-bit integer representing the number of milliseconds since your program started (or more accurately since your program last called one of the wiringPiSetup() functions). A few quick sums demonstrates that this counter wraps round after about 49 days, so programs that naively add a fixed number into the result of millis() to get the next time then test millis() > nextTime  will fail after 49 days…

And for at least one case, I’m the guilty one here – in my maxdetect code (used for the rht03 and similar sensors) I use millis() to make sure the next time we access the hardware is inside the datasheet limits. (The datasheet suggests not reading more than once every 2 seconds).

It’s easy to pass blame and not have any idea what’s going on – C for example doesn’t flag any warnings of integer overflow for example… However solutions to integer overflow problems are well understood and not complex.

So I’m working on a fix to the maxdetect code (which needs re-writing anyway), but if you’re using millis() in your own application, and it stops after 49 days, then now you know why!

And a quick note to say – uptime – 49 days – who says the Raspberry Pi isn’t reliable, but others should note that this issue is applicable to Adruinos and other microcontrollers too! More-so if you are using the micros() function which wraps after 71 minutes!

Testing & Setting the USB current limiter on the Raspberry Pi B+

One of the features of the new Raspberry Pi B+ is improved power handling – particularly round the USB interfaces. There is a device connected to the power to the USB ports that is quite clever – it controls the power and “soft starts” the peripherals plugged in. This helps to reduce any brown-outs on the main Pi supply, so reducing the chance of the Pi rebooting when you plug in a USB peripheral with the Pi turned on.

Additionally, it can also limit the total current drawn by the USB peripherals. This is 600mA by default, but can be increased to 1.2A via software.

Warning: DO NOT do this on a whim. Only do this if you are absolutely sure that you need to do it!

But if you do need it, then “How?” I hear you ask… Well, simple… There are 2 ways.

The first way is via a new option in /boot/config.txt. Currently you can add:

safe_mode_gpio=4

but note that this will become:

max_usb_current=1

in subsequent updates. To do that requires a reboot of your Pi, however there is a 2nd way and that’s in software – because the actual switch is controlled via the Pi’s GPIO, we can do it from the command-line after the Pi has booted:

BCM_GPIO pin number 38 is the magic control pin.

Using the wiringPi gpio command, you can do the following:

gpio -g write 38 0
gpio -g mode 38 out

You may think I’m doing this the wrong way round, but you want to make sure you’re not switching it high accidentally, so we make sure the output is going to be low when we force the pin to output mode, and low (or 0) is the default 600mA limit.

To increase the limit to 1.2A:

gpio -g write 38 1

The next version of wiringPi will feature a built-in function of the gpio command to read and set the USB current limiter, but for now, if you need to set it high, then that’s what you can do.

And as always please make sure you use a good quality power supply for your Pi! I’ve seen more problems caused by people using cheap wall-warts that can barely power a Pi, let alone any USB peripherals.

My test rig for this involved getting my B+ to power 2 other Pi’s via the USB ports on the B+. With the default 600mA setting, the Pi’s would not boot – they powered up, tripped the limiter which powered them down again for a second or 2, then the process repeated. With the limit set to 1.2A they both powered up and booted at the same time without a hitch.

I really don’t recommend you do this – or if you do something similar, don’t let it run too long. Also, keep an eye on the Red power LED – if you see this flickering it means that something is causing the power supply to “brown out”. Hopefully not enough to reboot the Pi, but it’s something to watch out for when you plug USB peripherals in

b+powerExcuse the somewhat chaotic nature of this photo – just trying to cram everything in. The B+ is being powered by an Anker 15,000mAh USB battery charger unit – it was the first 2A PSU I had to hand … Works a treat!

A quick look at the new Raspberry Pi model B+

Much excitement here at Drogon towers as I have a new Raspberry Pi – the model B+

b+

So what’s a B+ and how does it differ from the B? Here is a quick list of the main differences:

  • USB: 4 ports instead of 2
  • USB Power limiting – switchable from 600mA to 1.2A.
  • GPIO: 26 usable pins instead of 17 (21 on the Rev 2)
  • GPIO: No “P5/P6” connector that was present on the model B.
  • Composite video routed via the 3.5mm jack used for audio.
  • Micro SD card.
  • Round corners on the PCB!
  • Proper mounting holes.
  • Improved power supply – 2 amp polyfuse on the input and SMPS 3.3 and 1.8v generators to replace the linear ones on the existing Pi, along with some new widgetry round the audio output to improve the signal there. It saves up to 1 watt according to the boffins at Pi HQ!
  • Low power indicator.

Those are the main differences as far as most people will be concerned. The combined composite video and audio is (I understand!) a popular connection on phones, tablets, etc. The same HDMI, CSI (Camera) and DSI (Display) ports as the current Model B.

The power is an area of big improvement – I’m told the routing on the board is much improved with more power available to the USB sockets – providing your power supply is capable (please buy a good PSU from a reputable dealer!) Also, the USB sockets have been blocked from “back-powering” the rest of the Pi – presumably to prevent any issues with external powered hubs and so on.

The low voltage indicator will turn the power LED OFF if the supply voltage is lower than 4.7 volts. Buy good quality power supplies!

A quick note on the GPIO: There are actually 2 more pins in the connector – the original I2C bus that appeared on the Revision 1 boards, however this comes with a warning that the bootloader actively probes them, looking for an I2C eeprom device, to be used for further configuration by the bootloader, so connecting anything to them is not advised.

Notes:

wiringPi has been updated to reflect the new board revision in /proc/cpuinfo (currently it reads 0010).

Software: Well, no change there, really. Same SoC/CPU and memory, so no changes, really.

GPIO: The additional GPIO pins can be used for:  PWM (Both channels!) and additional GPIO clocks. Access to the 4 PCM signals is also possible, so I2S is easy to access, so lack of the P5/P6 connector on the model B shouldn’t be an issue.

On the GPIO front – the Ethernet socket is a few mm back into the board which may affect the positioning of some GPIO add-on boards that are wide enough to touch the Ethernet socket.

Conclusion

I think it’s a great and logical progression to the Pi! It’s compatible software and hardware wise – most existing GPIO devices will plug right on-top (may have to wiggle a ribbon cable in though for e.g. my original ladder board, the Gertboard, “cobbler cable” any anything else that uses a ribbon cable, but most of the boards I have which sit on-top all seem to fit and work just fine. (A notable exception is the PiFace board which was designed to fit round the Ethernet and USB sockets) More GPIO pins are always going to be good, and you can never have enough USB ports (Get a good power supply!)

And to finish, here is a photo of the B and B+ next to each other: They’re in the new Pimoroni Coupé cases. Excellent cases – protects the Pi and lets you use the GPIO to place boards on-top.

b-b+Note the GPIO pin numbers (BCM format) are given on the case top. Really handy!

And just because I can – here is the Pi driving 28 LEDs:

pi28ledsYes, I know. Don’t draw more than 50mA through to SoC, and there are 2 pins there that I really shouldn’t use (the first I2C bus), but hey, there it is!

 

LMC – The Little Man Computer on the Raspberry Pi

From the Wikipedia entry:

The Little Man Computer (LMC) is an instructional model of a computer, created by Dr. Stuart Madnick in 1965. The LMC is generally used to teach students, because it models a simple von Neumann architecture computer – which has all of the basic features of a modern computer. It can be programmed in machine code (albeit in decimal rather than binary) or assembly code.

This implementation is written using RTB on the Raspberry Pi and allows manual data entry via the computer control panel or you can use the built-in assembler to load files in its assembly language.

I have added some extensions to LMC to modernise it from its 1965 roots. The first is the JSR and RET instructions. JSR is Jump to Subroutine and RET is return. In keeping with the simplicity of the system, there is only one register to store the program counter for the RET address.  The other additions are for the Raspberry Pi’s GPIO. You can read a pin or set a pin to high or low. See the examples for details.

The RTB/Raspberry Pi implementation features three running modes – one is slow and runs at 10 instructions per second. This allows you to visually see the memory and accumulator changing as well as the program flow, the second is fast mode – the output register is updated, but that’s all, and finally you can single-step a program.

Download and Install

First you need RTB installing on your Raspberry Pi. See here for full details.

Obtaining the LMC software and examples:

cd
git clone git://git.drogon.net/lmc

that will create a directory called lmc and download the code and examples into it. Once that’s complere you can start rtb and load the code and off you go:

cd lmc
rtb

(then inside RTB)

load lmc
run

And you should see the main computer screen:

lmcThe main memory array is in the middle (full of random numbers at start time), the indicators on the right are Run (Green), Error (Red) and Input (Yellow). All are shown in their “off” state here.

The Yellow number and text in the middle is the current instruction or data that the program counter is pointing to and the bottom four boxes contain the program counter and saved program counter values, the calculator (accumulator) and the input and output registers.

When the program is running in slow-mode, the current instruction is highlighted in Pink with the disassembly also in Pink.

lmc2This is the LMC screen at the end of a run of the multiply.lmc program when asked to multiply 6 by 7.

Operation

The LMC is controlled by simple key-presses. On the main screen, you can move the active location (memory address highlighted in Yellow) using the arrow keys. To manually enter data or an instruction just type the numbers – the memory locations will only take the last 3 digits typed. Entering 1234 will result in 234 being placed into the memory location. Use the minus key (-) to negate the value. Pressing the Enter key moves to the next memory location.

Note some commands are case-sensitive.

  • Z (Capital Z) Zeros the computer.
  • R (Capital R) Runs the program from location 0 at full speed. Only the output register is updated in this mode.
  • r (Lower case r) Runs the program from location 0 in slow mode. This is a rate of 10 instructions per second with the display being dynamically updated as the program runs.
  • S (Upper or lower case) Single-Steps the program from the current program counter. (ie. if you need to start it at location zero, then you need to move the highlighted location to zero first)
  • L (Upper or lower case) loads in a new assembly program (ie. with mnemonics, not binary code!)
  • A (Upper or lower case) Assembles the previously loaded program into  the numerical form and stores it in the LMC memory.

The reason there are separate Load and Assemble commands is because a running program may alter its data, so a 2nd run of the same program may start off with the wrong values unless you write additional code to correctly initialise a location, or separate locations containing constants and variables. With the separate commands here, you can load a program once, assemble and run it many times.

So typically, you would load a program once (L command), Zero the memory (Z), Assemble the program which loads it into memory (A) then run it.

Programs may be edited using any text editor you are familiar with. I’d suggest using nano if you are new to text editing on the Raspberry Pi.

During a program run, pressing the space-bar will stop the program. This works at all times, even when waiting for input.

When the program executes an INP instruction, execution is paused and you can enter a number into the Input register location in the same way as entering a number in the main memory array. Terminate number entry with the Enter key. Pressing the space-bar at this point will abort the program run.

Architecture

The LMC has 100 memory locations (called mailboxes in the original documentation), one program counter, one calculator (or accumulator in modern terms) and (as an extension here), one saved program counter for the JSR/RET instructions. The calculator/accumulator and the memory locations can hold a number from -999 to 999 and the program counter (and save program counter) can hold memory addresses from 0 to 99.

Additionally there is an input register and an output register. Programs can stop and read from the input register (keyboard entry) or post a value to the output register at any time.

There are many online references for LMC, but I will put the table of op-codes here for reference (And you can see them in the program itself with the F2 key)

Opcode Mnemonic Instruction Description
000 HLT Halt Stops program execution. It’s time for the little man to take a coffee break!
1xx ADD Subtract Adds the value of the memory location xx to the calculator and stores the result back in the calculator.
2xx SUB Subtract Subtracts the value of the memory location xx from the calculator and stores the result back in the calculator.
3xx STA Store Stores the value in the calculator into memory location xx.
4xx JSR Jump to Subroutine (Extension) The program counter is incremented, stored in the saves program counter register and a jump is performed to the memory location xx.
5xx LDA Load Loads the value held in memory location xx into the calculator (accumulator)
6xx BRA Branch Copies the address xx into the program counter. ie. the next instruction executed will be the one in memory location xx.
7xx BRZ Branch if Zero Tests the calculator (accumulator) and if it is zero, then the branch to memory location xx is taken.
8xx BRP Branch if Positive Tests the calculator (accumulator) and if it is positive (>= 0) then the branch to memory location xx is taken.
901 INP Input Reads the value from the input register into the calculator. Program execution is halted while the user types the value into the computer.
902 OUT Output Copies the value in the calculator (accumulator) to the output register.
903 RET Return (Extension) Returns from a subroutine after the JSR instruction. This copies the value in the saves program counter into the program counter.
910 GIN GPIO Input (Extension) Reads the value of the GPIO pin addressed by the calculator into the calculator. The result will be 1 or 0.
911 GHI GPIO Output Hi (Extension) Writes a 1/High value on the GPIO pin addressed by the contents of the calculator.
912 GLO GPIO Output Lo (Extension) Writes a 0/Low value on the GPIO pin addressed by the contents of the calculator.

In addition to the above, there are 2 extra mnemonics used by the assembler. The first is DAT which is used to pre-load a memory location with a data value and the second is ORG. This is an extension which changes the location of the store pointer at program assembly time. Normally it starts at zero and is incremented for every instruction, but using this, you can place instructions and data at any location. This may be used to help view the data section in the run-time display of the computer which is arranged in 10 columns of 10 memory locations.

GPIO Access

The pin numbers used are the wiringPi pin numbers by default. If you want to use the native BCM pin numbers then you need to start RTB with the -g flag. To use the P1 numbers then start wiringPi with the -1 flag. (These are the same flags used to control the gpio program) Note that the BCM pin numbers are different between Rev 1 and 2 boards.

To simplify the GPIO access, there is no pin direction control – the GIN, GHI and GLO commands will set the directions as required.

Examples

There are a few examples provided:

  • countd.lmc
  • square.lmc

These are the examples in the LMC Wikipedia page. I have changed the square.lmc program to use the ORG pseudo instruction to place the constants and variables starting at location 90. That separates them from the program code so you can more easily see them changing as the program runs.

  • multiply.lmc
  • divide.lmc

Example to multiply and divide 2 numbers together. The program stops and you enter the first, then the second number and it calculates the result. (first * second, or first / second)

  • blink.lmc
  • blink8.lmc

Blink is the ubiquitous blink example which flashes the LED on pin 0 (BCM_GPIO 17). Blink8 does a simple sequence of the first 8 pins/LEDs. (wiringPi numbers 0-7) I tested it on my ladder board. If you have a Pibrella board, then blink will toggle the Yellow LED. blink8 will run on it, but would need changing (left as an exercise to the user 🙂

  • pibrella.lmc

If you have a Pibrella board from Pimoroni plugged into your Pi, then this is a very simple traffic light program. Run it is slow mode. When started, it will light the Green LED and wait for the button to be pushed. When pushed, it will cycle green -> Yellow -> Red, then wait for 5 seconds or so, then cycle back again. It’s also a demonstration of the JSR/RET op-codes too.

A Visit to the Center for Computing History

I had a few hours to spare today while I’m in Cambridge, so I decided to pay a visit to the Center for Computing History and what an exciting place it is! (Well, for an old geek like me that is!)

The Center for Computing history is a museum and charity, supported by your donations, so if you’re in Cambridge do pay it a visit if you can – it’s chock-full of … well … “stuff”. More Stuff, and even more stuff! (and behind the stuff – yes, you guessed it, even more stuff!)

When you think of museums, you think of places with stuffy old exhibits, but computing … well, it’s not that old, really. Sure, we have examples of computing devices or ideas centurys old, but for some – it’s still in our living memory – but it’s still important to preserve it all, especially as it changes so rapidly – e.g. today I saw some old computers that I never knew existed, yet they were built only 20-30 years ago!

As well as exhibiting computers (almost all are working too!), there is a great display of calculators (mechanical and electronic) and old gaming consoles – probably almost every single one including an old Atari Pong game. I wasn’t into console games that much – the Atari 2600 was about where I stopped, but I was amazed to found out that there were so many!

Go and sit in the Classroom of the 80’s – dozens of BBC Micros all working, enter BASIC programs into them, the PET, The Apple II and anything else turned on. Play on the Domesday machine – a BBC Micro and video disc combination – providing pictures and data from 1980’s Britain, controlled by a BBC Micro and trackball.

It would take too long to even think about listing the exhibits I saw here, but I took a few photos of things that are relevant to my computing life (so far!) Also – look at some of the exhibits – recognise them on TV? If you do, it’s highly likely they came from here, so if you’re planning a TV/Film type of thing and want some retro computers – this is the place to come!

The frst computer I really used a lot was the Apple II – and there are many here – this one is only display:

Apple //eThis is an Apple //e which was a follow on from the original Apple II computer. The 2 5.25″ floppy drives above it have a capacity of 130KB each (yes, Kilo Bytes!)

After the Apple II came the Apple ///

Apple ///I’ve only ever seen one other of these – in a computer shop in Edinburgh many many years ago! They didn’t sell too well, being eventually replaced by the Macintosh range of computers.

The Jupiter Ace:

jupiter AceAn interesting oddity was the Jupiter Ace. Designed by some of the Sinclair ZX Spectrum designers, it ran Forth rather than the more popular BASIC of the day. (Early 1980’s).  Sales were very low (under 10,000?)

In the late 1970’s three computers really stood out – the Apple II, Tandy TRS-80 and the Commodore PET. Early PETs had a somewhat odd keyboard, but they were an all-in-one solution with integrated storage (compact cassette) and VDU:

PET 2001This is one of the very early PET-2001’s with the calculator style keyboards. These were replaced with a bigger keyboard and the tape storage replaced with an external disk drive unit.

As well as some of the newer computers (new as in the last 35 years here!) there are a few older exhibits – Some old Ferranti Atlas computers, DEC PDP8 and 11’s and an Elliot 903. (Which I took a photo off, but didn’t check at the time, only to find now that it’s too badly out of focus to use) I had a summer job programming an Elliot 903 in about 1980 – even though it’s a computer that originated in the mid 1960s!

However is are a couple of old blasts from the past:

delayLineThis is a delay-line memory storage device. The principle is simple; Take a long piece of wire, connect a beeper to one end, and a sensor at the other. Pulse the beeper and wait for it to turn up at the far end, then feed that pulse back into the wire. The trick here is that you can send many pulses down the wire before the first one pops out at the end (speed of sound and all that). Keep them being re-generated and fed back in and you have a memory unit. It’s not fast, but devices like this did work and were in-use in many systems. (The predecessor to these were mercury columns!) This one stores about 1000 bytes.

Moving on a few years, we have:

coreThis is magnetic core memory. The link to it on the Computer museum site is here. It’s very old, hand made, possibly for an experimental computer or calculator. If you look closely, you can see the magnetic cores and the wires threaded through them. This block stores 20 x 14 = 28 bits of data… Later computers had much smaller cores and capacities up to 2 megabytes.

Our favorite British computer company, Acorn is well represented in the museum – starting with the Acorn System 1:

acorn1After the System 1, there was the Atom:

acornAtomwhich was the forerunner to the Acorn Proton – or as we know it; the BBC Micro:

masterCompactThis version is actually a Master Compact – a version of the BBC Master which was the successor to the BBC Micro in a separate keyboard + system case unit.

The history of Acorn is well documented and everyone in the world knows about them – or should do as the “A” in the ARM processor that powers their phone, set-top box, Raspberry Pi and a host of other devices stands for Acorn. (as in Acorn Risc Machine)

Finally, something that never made it:

phoebeThis was the last computer in the Acorn business range – codename “Phoebe”. It’s remarkable as it is an ARM based system supporting multiple CPUs and the now industry standard PCI slots for expansion – as well as a relatively modern and fast graphics system. Literally a day before the launch, Acorn decided to withdraw from the business market and concentrate on other things.

So there you are – just some of my highlights of a visit to the Center for Computing History in Cambridge. If you have time to spare, then go and visit and experience everything. (And if Jason is about, tell him I sent you and ask for a quick peek from the top of the stairs 😉