Category Archives: Raspberry Pi

Raspberry Pi related stuff

Well thats annoying – Pi I2C Woes & HAL

Well thats not quite what I said when I found my bug about 15 mins ago but same sort of general meaning.

We are using the Pi in more and more things and in order to make it easier i’ve been writing our own HAL to make using the GPIO and onboard perhipherals easy to use, wrapping up things that others kinda did, adding new bits and dropping in native support for our hardware. Its been going well hen a few weeks back I hit a reoad block or two.

The first is repeated start, the long answer is that using the IO wrappers for I2c you cant do it. Looking deeper into it the Python lib fudges it too by doing a bulk read so no biggie there. Its no fixable, easilly worked around and in many ways a bulk read is a nicer way to do it.

The second was driving me nuts. I couldnt write a register. I could select it, but the perhiperal always sent 0. After a few hours of head scratching I had to get on with other work and its only today I’ve been able to get back to it.

The long and short of it is that I was trying to be too clever and not thinking about it in a *nix manner. I was opening the bus and then assuming that I could move addresses round as I needed to talk to things, turns out that doesnt work (It may be tied in with the above too). Changing the target address once you’ve set it seems to bugger up the driver and it then sits and sulks. I’m not sure why this should be so but it does. Assigning a new file handle for each device (FPOpen()) and then setting the address works so it looks like thats the way I need to do this. The upshot is that the whole I2C section of the HAL (which to be fair wasnt written) needs redoing. It also points to some issues that were going on with the IMU on the Tezero platform too so its another point in the argument to moving Tezero onto the HAL.

So what does work?
Well GPIO mapping, control and I/O all works a treat. The HAL will map out SPI/UART/I2C pins if the perhipheral is in use. Getting hold of interrupts is hard in Lazarus without scripting bits of Python to do it. The HAL now fudges it by using a thread to monitor the pins. As you assign interrupts to a pin no interrupts = no CPU time used. With all available GPIOs running with interrupts the CPU load doesnt register so thats good. There is a FIFO system in there so a long IRQ handler wont hang the queue.

And to go?
Support ofr specific perhipherals is next. How far I’ll go is uncertain but as the HAL is going down in the Touchdown kits I may go as far as adding specific I2C device support. What is definately going in is support for things like thumbwheels and our TRNet bus system on UART0

Can I have a copy?
Not yet, I’m still testing, but soon 🙂 When its about it’ll be released on

Pi & Lazarus I2C

I’ve been asked a few times now how we got I2C working without third party code. The reality is that thanks to the way Linux handles drivers it’s pretty easy and I’d expect direct access to 1 wire to be the same (We have bridges with FIFOs, parasitic power etc so we  dont need to try it)

First make sure you can talk to your I2C decvice with I2Ctools. Theres loads of info on this, off you go and hunt it down.

latest versions of Raspbian use a new way of handling devices, make sure you use a tutorial that matches the way your system is setup as simply uncmmenting things in the modules blacklist may not be enough.

You shouldnt be running code as root, developing, yes, running as an end product, no. There are arguments against developing too but thats not why this article is here.  By default only root has access to I2C and we need to change that if your apps are going to work in userland. Its easy to do. Say we want pi to be able to do it:

sudo groupadd i2c pi

Now we can use the standard FPOpen(), FPRead(), FPWrite() to do the job.

  DEV_IMU : integer;
addr : byte;

This is the handle for the fle we are about to open and addr is the target device address on the bus

procedure openI2c;
   count : integer;
   data: byte;
   reg : byte;
  DEV_IMU:= fpopen(‘/dev/i2c’,O_RDWR);
  if DEV_IMU= -1 then begin
             // we couldn’t open the bus
else begin
// associate this handle with an address on the bus
fpioCTL(DEV_IMU,1795, pointer(addr));


Now to read:

function readbyte(reg:word):word
    count : integer;
   data : byte;
// we have to write before the read to send the register we want
     count := fpwrite(DEV_IMU,reg,1);
     if count <> 1 then begin
              // we couldnt do the write!
// now read
    count := fpread(DEV_IMU,data,1);
     if count =0 then begin
              // nothing came back
  else result := data;

And the write is easy enough. The read is write then read as we always nbeed to send the target register out. In the case of a write we can do this ‘back to back’

procedure writebyte(reg,data:byte)
    buffer : array [1..2] of byte;
    count : integer;
     buffer[1] := reg;
     buffer[2] := data;
     count := fpwrite(DEV_IMU,buffer,2);
     if count <> 2 then begin
              // write failed
     else // write ok

This should have you up and running in no time.

Security Through Obscurity…

Time and time again we are told the above doesnt work and yet it still happens, why and why is it important.

In the process of our big tracker project I’ve been looking at packages that do the job already and also a number of control systems. Bearing in mins what these do, there is no security on most of it and token security on one of them. You may think that this isnt a big thing and in most cases it isnt, but there are good reasons it is. So lets take a look at two culprits…

Veichle control Systems:
I’ve looked at three of these in the last few days and one thing is common with all three. No encryption, no ability to detect errors and no authentication. For the best part this isnt a huge problem, in fact its a boon, I know how all three work and can talk to them. However the bar is set low and any of them can be subverted easilly. In the case of the first two I looked out you wouldnt gain a lot past the ability to turn things on and off but the potential is there. The third is a fully integrated system and is designed to control all aspects of the vehicle including battery management and its also designed to be linked to an onboard computer, now here there is scope for trouble. The system concerned could easilly be subverted by malware and then the fun begins. Further digging on this one turns up no encryption is used on the comms link to the office either, but it gets worse…

Of the dispatch and tracking systems looked at not one uses encryption, for the more basic ones this means simply you can rap the tracking data out of the air and at least one was fooled easilly to connect to a wifi network and forwd the unencrypted traffic over my network, patient details, addresses etc all in the clear. This means that this data can also be modified so this particular system couldbe subverted pretty easilly with a laptop and either data creamed off and used for nefarious means (ask someone how expensive ambulance kit is!) or worse. Tracking data can be falsified, fed back to the base meaning the veichle doesnt show as being where it belongs and uh-oh, the SOS button isnt going to help if someone jumps the ‘bus’

There is no excuse for this. None at all and the scary thing is that the same can be found in Automotive systems from the factory and has recently been found in Avionics systems too!

Serial channels can simply and effectively be secured. Even our most basic bus system, TRNet uses authentication and device tracking mechanisms. If a device doesnt authenticate, its ignored, even if it does it must be recognised on the bus else the system, will lock the bus out. This is done by a few dozen lines of code and although it could be subverted with a moderate amoun of effort you’d need access to a lot of information to get started. This also allows us to give a mechanism for making sure the bus is reliable. Scarilly all but one of the three systems we looked at just kept sending the same data over and over again with no control path back to the master. Although it’ll work it means bit flips can happen in transmission and may be ignored (no CRC/Checksum used) and there is a wealth of data for someone to grab and decode.

Data channels running over a network should also be secured and only links trusted should be used. Again this is basic common sense and doesnt take a lot of code, for this application we are using a pretty hardcore authentication system based on AES but its neither difficult to do or expensive. With the system we have both ends of the chain must be compromised and in such a way that pe-encrypted data is grabbed, key shifts mean that just grabbing the encrypted stream and a session key wont help you, even if you do grab a key you need the previous key to use it so good luck.

There is still a strong sense in the embedded and bespoke software/hardware market that no one is interested in specialist applications, wont try and thus you dont need to bother about security above making it convoluted. This is fallacy, the value of the equipment on an ambulance is truly amazing to those not in the know so gaining the ability to send such a veichle to a false location of your choice, disabling its tracking  and ability to call for help is going to be of interest.


PPPppppppppickup a modem…..

Apologies to non UK readers, the pun above wont make much sense…

The issue with PPPD is persisting. However I think I have it cracked.

I need to get PPPD up, running and connected, during this I need to know what it’s up to, I also need to know when it stops so I can force it back up.

First PPPD has the ‘persist’ option to do this, however I need to have control over it as I will be doing other QOS monitoring above the LCP monitoring done by PPPD so I’ll probobly kill it off before it thinks its had a problem.

Next up, there is some support for doing this, I can tell that PPPD is up and running by looking in /var/run but this just says its running. Worse still this doesnt help before PPPD starts nor does it tell me that the link is there. Off we go to two provided scripts in /etc/PPPD.

IP-UP runs once the link is up and running, IP-DOWN surprisingly, runs when the link goes down. So the first attempt we drop a file in /tmp to say that we are up and remove it when we are down. So we now know that PPPD is up and when its connected and when it goes away. Sadly this still leaves us a problem. When the scripts to bring the modem up run, they are forked elswhere and PPPD doesnt generate a PID till the CHAT script hands over. This means going by the fles and PID our program thinks the link is still down and will be trying to bring it back. Pesky, harmless but fills the logs with rubbish.

We are using the PON/POFF scripts so for now we will edit /usr/bin/pon. We will leave POFF alone as the interface going down will clear out the files. In /usr/bin/pon we now drop a file called pppstarting.sem to indicate that we got to the end of the startup script OK and we are now going to attempt to dial.

This all works provided the modem is present. if not it all breaks as as yet I cant find out how to deal with this and take out the pppstarting.

Both PFSense and SmoothWall seem to do the same sort of thing so I may go and pick apart their PPP scripts for ideas.

There may also be a need to loop back the power LED to the PI as helpfully, the power button needs to be toggled, there is no way to know if its on or off witout talking to the modem.

Promiscuous Ports, Power and unstable PPP

Well the tracker system went out on the road earlier and it was an unmitigated disaster. Mainly due to power issues, the PI2, relay board, controller board, GPS, IMU and GPRS board draw a fair bit of juice, and its more than the poxy USB charger can supply. I’m frankly not that surprised.

It highlighted that it doesnt take that much to start making things trip up power wise, the system does have power monitoring and I may start looking towards some more intellegent form of power management. On top of that automotive power is dirty, its ful of noise and spikes and you can only gurantee it’ll be somewhere between 11V and 15V which isnt good for electronics. Add to that a 20 year old dirty cigar lighter socket, a cheap chineese PSU running at/above its limit and all hell breaks loose. First up then we need to get things cleaned up. I have a sketch for a PSU on my desk but that needs refining as it’ll form part of a new board to replace a goodly chunk of the wiring. For now I’ve gone over to a 2A LM2596 switching regulator module and thats helped with supply stiffness and clenliness. Behind this are two nice reservoir caps, enough to give everything about a second of power to cover brown outs. Its possible I may need to look into batteries however the final unit should be wired to the battery directly which should protect it from load shedding devices on crank over. Ideally I’d like the M25012 to hold the power to the Pi off till it knows all is well. The system now supplies the power for the monitor as well and has the ability to isolate it, this should help,

Next issue, the bloody TTY’s keep moving. It seems that unlike Windows USB devices are always installed in the order they are found, every time, Windows remebers where a device is and all is well, for example, plug in two USB com ports and windows will splat them on COM3 and COM4, every time those devices are in those USB ports they will from henceforth ALWAYS get those IDs. Linux, or at least Rasbian, doesnt. It seems to assign them on first come fist served basis which means that its luck of the draw if you get ttyUSB0 for the first device or ttyUSB1. Moving any USB device around before a reboot seems to muck this up and this isnt helpful.

The answer seems to be here: although note that udevinfo is actually a symlink whereit exists and it wont work on Raspbian, you want udevadm info instead 🙂 Its also possible to use PID/VID and serial numbers to do this. Now as the final will use either a hub and 4 devices OR a single 4 port I’m anticipating further pain with this 🙁 However for now the bridge and GPS adaptor use different VIDs and PIDs so the following works :

tail -f /var/log/messages and plug each device in, make a note of the PID and VID (they are displayed)

sudo nano /etc/udev/rules.d/51-usbserial.rules and add:
KERNEL==”ttyUSB[0-9]*”, ATTRS{idVendor}==”1a86″, ATTRS{idProduct}==”7523″, SYMLINK+=”trnet0″, GROUP=”tty”, MODE=”0600″
KERNEL==”ttyUSB[0-9]*”, ATTRS{idVendor}==”067b”, ATTRS{idProduct}==”2303″, SYMLINK+=”sgps”, GROUP=”tty”, MODE=”0600″

You can see where the PID and VID need to go. Save, exit and unplug everything. Once you plug them in the symlinks you chose (In my case trnet0 and sgps will be created in /dev. These simlinks will always point to these PID and VIDs. Now with identical devices this wont work, there are other ID’s you can use such as serial number although these need to be programmed using the vendors utility.

PPP works but there are some issues. Nameley right now we dont know if its up or down. I need to work out a way to deal with this and maybe some scripting to keep it up. I have now worked out how to get control of PPP and know what is going on. First starting and stopping are easy. Make sure your application is running with priviliges to be able to do this, adding the user to the ‘dip’ group should be enough. Then you can use to run pon and poff. To specifiy the profile use process.addparameters.add(‘<profilenamehere>’); and normally you’ll be wanting to run /usr/bin/pon or poff.

Next up modify /etc/ppp/ip-up. Before the line PPP_TTYNA ME=… line add:

echo $4,$5 > /tmp/pppup.sem
chown pi /tmp/pppup.sem

The chown assigns access to the pi user, you could give the rights to anyone. Now once PPP comes up pppup.sem will be dropped in /tmp/ the $4 and $5 will mean the file contains the local IP and gateway IP seperated by a comma.

In ip-down add the line rm /tmp/pppup.sem in towards the top and this will remove the file when the link goes down.

It may be worth removing this file if present at boot as a crash/power failure may leave it behind.




Tracker Troubles

This one is more notes to me, but someone may find it handy.

First up getting the test suite on this tracker/remote control system was not as clean cut as it should have been. Turns out Lazarus sockets doesnt do DNS so you cant just call a hostname, rather than bombing out with an error it just hard locks or ocasionally segfaults. TWSocket can handle this and as I want to get as close as possible I think there is going to need to be a wrapper around this. I also think a TpersistantSocket may be of uses where the socket has a FIFO and will attemnpt to reconnect on loss. Much thinking on this.

Next up, hours lost trying to work out why Traccar wont talk to the diag software when it was up, turns out that I discovered two things. Firstly, had I looked at the NMEA spec and paid attention I’d have seen that the spec uses * as a reserved char for the checksum and it isnt supplied in a new field as I was doing. This was leading to a ‘,’ being added to the ID and Traccar (being helpful) Silently bins it and the packet. Traccar is going to be going under the knife when this is all done. Secodnly, nothing in the world either a) agrees on how to make a checksum and b) actually uses it so it can be ignored. Traccar assumes its garbage and bins it. Save yourself some work when coding for the T55 protocol and dont bother.

Next up, PPP

Loads of tutrials on how to make this work, how to talk to the SIM900/908 and none of them seem to work. I had this workin before I wiped the SD card annoyingly so back to work. I ended up using PPPConfig in the end, WVDial doesnt seem to like these modems and indeed, wont detect them. Most PPP configs almost work failing with errors that no one have ever seen SO FrankenPPP was born. I’ll pop the details up later because I know others are trying to do this. In short, run through PPPconfig and then trash the resultant CHAT file, its broken, something in there makes the SIM900 fall over with an odd error message. Its likeley a CRLF where it shouldnt be, a missing ‘ or something I just couldnt see. Roll your own or use the one I paste and all will be well.

Next up, default gateways. Theres a touc of open source snobbery going on here. ‘Unable to Replace Default Gateway’ will be in your logs and nothing will work. Ask online and the standard response is ‘Yup thats right BECAUSE YOU ARE AN IMBECILE AND HAVE A DEFAULT GATEWAY!’

Thats all the help you are going to get.

Not helpful, you see MOST boards are going to be setup like this and this unit will be chipped and changed from LAN to WAN frequently so this needs fixing. I havent looked at the scripts yet but there are up and down scripts. Firstly I need to drop a semaphore anyway to give me the interface state but also this is a good place to fix this gateway issue. O2 (whom I dont reccomend for this) use Private IP addresses for their network (3 and EE dont for sure) so be aware of this. Do an ifconfig and see what gateway ppp0 is giving.  For me it was

Run a terminal and these two commands will fix it…

sudo route del default
sudo route add default gw ppp0

This now means all will go out the PPP interface. Now this isnt helpful when it all falls on its face so when you are done do it again to make it right for your network again (I’m 99.0/24):

sudo route del default
sudo route add default gw eth0


Having been out and tested this it seems that this default gateway silliness is caused by DHCPCD, however its entireley correct as you’ll want to get on the net and play about while you are working and thus you need this route here. However if the board isnt plugged in, DHCPCD doesnt even try, thereis no default route and PPP behaves as it should. It now makes me wonder if I even need to do this and shouldnt just make a script for when I’m in dev mode.

These should go in the PPP up and down scripts, but I’ve not gotten there YET


P1 3.5″ Touchscreen

This is just my notes on getting this up and running. I’d purchased a 3.2″ touchscreen to work with a Pi used on a project. However they supplied a precopiled ISO image rather than drivers and instructions so this is my notes from taking it apart to work with my own image. First up, get a keyboard on it and open a terminal (this is horrid with such little screen real estate)

sudo apt-get install xrdp

Will get the RDC server onto it then you can use remote desktop to get in there, much nicer and easier to use. user is pi and password raspberry (the defaults)

First going after config.txt, it seems there is nothing in there, how annoying.

cmdline.txt does seem to have some extra bits :

fbcon=map:1 fbcon=font:PrFont6x11

This looks like its worth investigating. This seems to be passing info to the FBTFT driver, there’s  some info here. This also identifies this as the BCM2708 SPI Display controller and if you look at the docs that line is given as needing to be added. SO if we look through that driver info we should be able to find where the display is setup…

So we now need to look at /etc/modules. We might even find the touch driver in here too…

This file is VERY different to the stock file. The first, obvious changes are that SPI and I2c are enabled, I’d imagine the corresponding blacklist options have been removed too. Now we have lines for FBTFT, FLEXTFT and ADS7846_device all of which are part of the above site. This is handy as it means likeley all you need is here. In theory as the modules have been merged into the main tree you *should* have these already.

So the lines we need seem to be:

fbtft_device name=flexfb gpios=dc:22,reset:27 speed=48000000

flexfb width=320 height=240 buswidth=8 init=-1,0xCB,0x39,0x2C,0x00,0x34,0x02,-1,0xCF,0x00,0XC1,0X30,-1,0xE8,0x85,0x00,0x78,-1,0xEA,0x00,0x00,-1,0xED,0x64,0x03,0X12,0X81,-1,0xF7,0x20,-1,0xC0,0x23,-1,0xC1,0x10,-1,0xC5,0x3e,0x28,-1,0xC7,0x86,-1,0×36,0x28,-1,0x3A,0x55,-1,0xB1,0x00,0x18,-1,0xB6,0x08,0x82,0x27,-1,0xF2,0x00,-1,0×26,0x01,-1,0xE0,0x0F,0x31,0x2B,0x0C,0x0E,0x08,0x4E,0xF1,0x37,0x07,0x10,0x03,0x0E,0x09,0x00,-1,0XE1,0x00,0x0E,0x14,0x03,0x11,0x07,0x31,0xC1,0x48,0x08,0x0F,0x0C,0x31,0x36,0x0F,-1,0×11,-2,120,-1,0×29,-1,0x2c,-3

ads7846_device model=7846 cs=1 gpio_pendown=17  speed=1000000 keep_vref_on=1 swap_xy=0 pressure_max=255 x_plate_ohms=60 x_min=200 x_max=3900 y_min=200 y_max=3900

Thats quite a mouthful so there is a copy of the working modules file. Check it against yours and copy and paste whats needed in rather than do this all by hand. If you are going to edit this on a Windows machine please use notepad++ as it’ll save you a lot of pain.

Interestingly it looks like there are dfeined setup modes for other displays here such as the Adafruit one which makes adding things way easier. It may be worth looking into this as looks way easier than the above mess.

Next up we need to chek inittab…

Interestingly they havent made any changes here. This should mean that the pi’s main console is still intact. I dont have anything on my desk to plu into right now so I cant verif this but it does leave a way into the system is something breaks. There is a reccomended line but it does look like it would disable the main console. Now the quesion is, where is whatever is running on that screen coming from? The other place would be rc.local and its not from there. The next step now is to make these changes on the dev system and see what happens.

Getting X running isnt too hard now. You’ll need to move the fbturbo framebuffer somewhere else. If you dont X will just bomb out with no screens found.

mv /usr/share/X11/xorg.conf.d/99-fbturbo.conf ~

This will drop it into your home dir. You’ll want this to re-enable it later.

export FRAMEBUFFER=/dev/fb1 startx

*should* now get you an x-session. Have fin with that touch screen as its probobly way out of whack 🙂 CTRL+C and come out.

mkdir /etc/X11/xorg.conf.d

My stock Raspbian didnt have this directory, the updated did so you might not need to do this. In there create 99-calibration.conf and put the following in there…

Section “InputClass”
Identifier      “calibration”
MatchProduct    “ADS7846 Touchscreen”
Option  “Calibration”   “215 3735 3938 370”
Option  “SwapAxes”      “1”

save and then try to start X again. With any luck you should have a working touchscreen. Note that while this is all pretty similar to the Adafruit unit it’s different enough that if you use their walkthrough it wont work.


Learning Curve, well right angle…

I’m working on a tracker system for a customer. Now my C++ isnt that good and my ARM assembler isnt up to somthing quite so heavy (Its not JUST a tracker) so I looked at other platforms to use.

In the end I’ve settled on the Pi, not least because its not a huge stretch to do what I need to to in the basic programming tools available.  I need to open two serial ports, fire up PPPD and then do some rudimentary data processing and split one of the serial ports.

After some fiddling PPPD behaves and the pi can connect to the Internet on its own over GSM. Non trivial but PPPD is an old foe and it was beaten into submission. The hardware was built and tested and the whole thing mounted up on a plate ready for some serious dev work…

During the tinkering I found out that there was a working Pascal compiler, I know Pascal, I know it VERY well and can do a lot with it, then I found the Delphi like IDE, Lazarus. In a few mins I was away. Turns out the repository versions are very old, cue having to download and compile from scratch.

This didnt go entirely well and took 8 hours and many false starts but in the end I got there, more faffing and I have an x86 dev box that actually compiles in under a week.

A fight then ensued to get workign serial port access and I *think* I’ve done that so now I have the unit talking to the GPS already.

Asynchronus TCP… Thats taking longer…

This does open the way to a lot of porting of my apps over to Linux, something I have been wanting to do for a while. It also opens up a serious number of possibilities with Pi and Beaglebone for us. So many projects opened up.


Tracking & Dispatch

We’re coming to get you…

I’ve been asked to look into a tracking and dispatch system for a customer. Now those of you that know me/my company know that we’ve done this on a number of ocasions, the most recent version being Touchdown’s Mesopod system.

All of these units have used dedicated functional units to do each step, a GPRS Modem , A Firewall/router (The pod combines these), and a client device. Now for this one we are going to try something different…..Its all going in one unit.

The design breif we have pulls in a lot of old tech for us, GPS, 3/4G networking, Sensor systems, Chassis electrical interfaces, message passing and databse applications, in that lot there is no scary new ground. Its the client.

A typical system like the Mesopod uses a BSD/Linux based Firewall system. Off the shelf, free and pretty simple. We’ve not bothered ourselves too much with this, it’ll also look after the VPN back to base and in the past its almost always been an Atom based unit of some kind. The Client? Win XPe, the only version of XP tht we can still use. But it all works. We have a huge toolbox of apps for sharing GPS units, grabbing data from our boards, providing multiple serial streams and so much more. Theres only one big problem…We are going ARM on this one.


This means we have a problem, in fact, a very large probelem. SO what software in our toolbox to we have to use here…erm, stuff all. Thats right girls and boys we have NOTHING and worse, theres pretty much nothing off the shelf we can use either.

This isnt as bad as it seems to start off with. You see the first step is we will be using Debian Linux. Right off the bad I can talk to the display, anything I need to hang off of I2c, databases, the GPRS modem, touchscreens, GPS modules, ethernet etc so thats a HUGE swathe of work done. As a comparison the last time we used ARM we programmed it in assembler/C and just getting the touchscreen up took a few days. Here I had the target system up and browsing the net in 30 mins. So the first part of this adventure is wiring everything up and making it all talk, I can do that, I am good at that…


Now the trick is going to be more scheduling and priority, learning how to break other peoples code and ah yes, I do need to write a little of our own for the client too. I’ll be using Chassi s interface boards I already designed to find out whats going on with the veichle and to turn things on and off. I will need to write drivers for this and I’ll need to find another serial port as I’m going to be using the ones I have already, in fact I already have a board of FT232’s in my minds eye.

Its going to be a bit of a challange. The idea is to end up with a nice small box and a 7/10″ touchscreen that chatters away to the head office and can talk to GPSGate server niceley too and just tie up all the bits niceley. Its also going to be our first project with any amount of Linux coding involved so that will be fun too 🙂