Category Archives: Raspberry Pi

PIZero Tesla Coils at the RI Christmas Lectures

Earlier this month it was my great honor to be invited to demonstrate the PI zero tesla coils at the Royal institution Christmas lectures.

The Christmas lectures were a Christmas institution when I was growing up and they formed a great part of my education, especially the ones by Eric Lathwaite. This year is their 80th televised Christmas Lecture, I’m sure in that time it has inspired the lives of many many children to investigate science, and long may it continue to do so.

Behinds the scenes at the lectures was incredible, the organised chaos that was happening was untrue. There were 20+ experiments in the lecture (the first of three) and moving them in and out of the theater was a very well choreographed scientific dance.

I have every admiration to the RI and Windfall Films that produce it.

Walking in to the theater and standing where Faraday and not to forget, Tesla himself had lectured, I can’t explain the feeling. Oh, and the 350+ kids watching you… No Pressure…

The theater is incredible, it’s so much smaller than it looks on TV, add three cameras, a lecturer and 10+ support staff (dressed in black), it doesn’t leave much room for demonstrations that need a couple of meters exclusion zone for safety.

What will be featured on the lecture on Boxing day, not a clue, as is usual with any filming, its down to the final edit.

Even if I don’t make it on to the show, watch anyway well worth it for kids of all ages.

Behind the Ri Christmas Lectures- Show 01, 2016 Mark Parker – Standup Maths (warm up guy)

This Lecture is the first to go out BBC4 20:00 Boxing day 2016

The video is now available at



Details of the PiZero Tesla coils 

RPI I2C interface to Microchip embedded uP – Clock stretching

If you are going to implement I2C to an embedded uP read this first

If you are using a Microchip uP you might want to continue reading.

Here is the problem, Raspberry Pi’s I2C software can’t cope with slave clock stretching, not a problem if you can service the data request quickly, well you would have thought not anyway. Unfortunately Microchip’s hardware (using a PIC18F14K50 and many others)  always puts in a small clock stretch for a slave transmit, even if you disable clock stretching with the SEN bit.   A thorough read of the data sheet gives you a clue “The ACK pulse will be sent on the ninth bit and pin SCK/SCL is held low regardless of SEN“.

So data transmission TO the PIC works fine (if you can deal with the I2C data quickly enough), but for Slave data transmit TO the RPI you get errors. The problem is, they are random and depend on the exact timing of the I2C bus and uP speed.

This clock stretch only happens after the address byte and before the transmission data. It causes a short or missing clock pulse (as the RPI ignores the presence of the clock held low by the slave) as in the transition of bytes 3 &4  of data in the oscilloscope capture below.


So how do we work around this, well to be honest there isn’t a total solution. (that I’ve found) the best that I have achieved is to change the I2C clock speed  so the timing of a clock stretch happens when the clock is already low and tweak the uP interrupt software.

The clock speed change is unfortunately a trial and error process whilst monitoring the data (and probably watching with a scope). To change the I2C bus speed with a newer PI distro, you need to edit the /boot/config.txt and edit or add the line “dtparam=i2c1_baudrate=clockspeed” try clock speeds from 20000 to 400000 and follow by a reboot of the PI to make the changes active.

The bus clock speed that will work will vary with the microprocessor speed,  so there is no single solution. With my setup 200Khz and 50Khz works well (uP clock @32Mhz) where 400khz and 100khz is a total wright off.

I have also changed the I2C code in the PIC18F14K50 to give a fast set of the  BF flag after data transmission which helps minimise the clock hold time.

if (PIR1bits.SSPIF) {
        if (!SSPSTATbits.D_NOT_A) {
            // Slave Address
            i2c_byte_count = 0;

            if (SSPSTATbits.BF) {
                // Discard slave address
                sspBuf = SSPBUF;    // Clear BF

            if (SSPSTATbits.R_NOT_W) {
                // Reading - read from register map
                SSPCON1bits.WCOL = 0;
                SSPBUF           = i2c_reg_map[i2c_reg_addr++];

        } else {
            // Data bytes

            if (SSPSTATbits.BF) {
                sspBuf = SSPBUF;    // Clear BF

            if (SSPSTATbits.R_NOT_W) {
                // Multi-byte read - advance to next address
                SSPCON1bits.WCOL = 0;
                SSPBUF           = i2c_reg_map[i2c_reg_addr++];
            } else {

                if (i2c_byte_count == 1) {
                    // First write byte is register address
                    i2c_reg_addr = sspBuf;
                } else {
                    // Write to register address - auto advance
                    //   to allow multiple bytes to be written
                    i2c_reg_map[i2c_reg_addr++] = sspBuf;
        SSPCON1bits.CKP = 1;            // Release clock
        // Limit address to size of register map
        i2c_reg_addr %= sizeof(i2c_reg_map);

        // Finally
        PIR1bits.SSPIF  = 0;            // Clear MSSP interrupt flag

With these changes, I have got (as the adverts say) up to 100% TX from a slave without error. This is about the best we can do until either Microchip change their hardware, or RPI write a I2C handler that supports clock stretch.


Headless Raspberry PI (PIZero) setup

The PIZero Simple setup without network or monitor. (Requires some prior knowledge of RS232 adapters and serial port setup)

First start by getting a PI SD image I used Raspian Jesse Light

Install into a sd card and make sure it runs (green light at least)

With a 3.3v RS232 adapter connect earth and RX/TX to your PI. Be careful some adapters are only 5V and will damage your PI’s UART pins.


Setup your PC (I use Tera Term) serial adapter for 115200, 7 bits, even parity, 1 stop bit.

Boot your PI

If you get a screen of gobbledegook then good, otherwise swap your TX and RX around. When the gobbledegook has finished, press return a couple of times, and you should get a login prompt.

For some reason the console and boot up output at different baud rates (Caused by auto baud rate detect, settings above amended so this shouldn’t happen now)

Configure your PI the usual way. You will need some network to get your updates, but apart from that you have a working PI.

If you are brave (or idle) you can connect the +5v line from your serial adapter to power your PI too so you don’t need another usb power lead. Just be very careful that you attach it to the correct pins, otherwise your PI will be damaged.


Useful links.

(although I found the baud rate setting wrong everywhere I looked. Either auto baud rate detect at work, or it changes from distro to distro)

Element 14 no display using the raspberry pi serial console

RPi Serial Connection



The baud rate is auto detected, the native speed is 115200 (amended above) The auto detection only happens at the login prompt. The auto detection won’t pick up changes in bits/stop bits/ or parity. You can change the console getty port/speed/parity settings look at RPi serial connection above.


If you have a wifi adapter and micro USB to USB lead, you can connect to WIFI. After connecting via RS232 edit the file /etc/wpa_supplicant/wpa_supplicant.conf using sudo nano

add in the lines


and reboot the pi sudo shutdown -r

re log in to the pi and type ifconfig to fins the wifi IP address. 
Then you can ssh to your PI and even better update the software.

Note : for Pi 3. You may need some changes to get the headless conf working, especially at non default baudrates, take a look at








I2C control of LCD Display using YwRobot LCM1602 V2 & Raspberry PI

Using the YwRobot to control a 20×4 line display via I2C on a Raspberry PI, what could be easier.
PI display
Well, If all of the code was only for an arduino and there being no actual documentation or wiring diagram. Note: Example code IS NOT documentation.

Hey Ho, After some playing around I found the pin arrangement

addr, en,rw,rs,d4,d5,d6,d7,bl
0x27, 2, 1, 0, 4, 5, 6, 7, 3

0x27 is the i2c port address (bus 1 on newer PI’s)

I found this code snippet for a different set of boards×2-lcd-with-raspberry-pi.html which was near, but made the display backlight flash and no text output.

So the hacking started…

Basically all of the control lines were on different pins, and I needed to control the backlight (via a wrapper on the i2c write code)
import smbus
from time import *

# Modified from×2-lcd-with-raspberry-pi.html to run
# 20×4 line display with YwRobot LCM1602 IIC V1 backpack

# General i2c device class so that other devices can be added easily
class i2c_device:
def __init__(self, addr, port):
self.addr = addr
self.bus = smbus.SMBus(port)

def write(self, byte):
self.bus.write_byte(self.addr, byte)

def read(self):
return self.bus.read_byte(self.addr)

def read_nbytes_data(self, data, n): # For sequential reads > 1 byte
return self.bus.read_i2c_block_data(self.addr, data, n)

class lcd:
#initializes objects and lcd
Port definitions
addr, en,rw,rs,d4,d5,d6,d7,bl
0x27, 2, 1, 0, 4, 5, 6, 7, 3


def __init__(self, addr, port):
self.lcd_device = i2c_device(addr, port)

self.backlight=1; #default to backlight on

def lcd_init(self):
#set 4 bit mode
self.lcd_device_writebl(0x30) #write


#wrapper to self.lcd_device.write fir backlight control
def lcd_device_writebl(self,value):
if self.backlight:
self.lcd_device.write(value | 0x08);

# control backlight on=1 or off=0
def lcd_backlight(self,on):

# clocks EN to latch command
def lcd_strobe(self):
#bit 2
self.lcd_device_writebl(( | 0x04))
self.lcd_device_writebl(( & 0xFB))

# write a command to lcd
def lcd_write(self, cmd):
self.lcd_device_writebl((cmd >> 4)<<4)
self.lcd_device_writebl((cmd & 0x0F)<<4) self.lcd_strobe() # self.lcd_device_writebl(0x0) # write a character to lcd (or character rom) def lcd_write_char(self, charvalue): self.lcd_device_writebl((0x01 | (charvalue >> 4)<<4))
self.lcd_device_writebl((0x01 | (charvalue & 0x0F)<<4))

# put char function
def lcd_putc(self, char):

# put string function
def lcd_puts(self, stringin, line):
if line == 1:
if line == 2:
if line == 3:
if line == 4:

string=stringin + ” ” #blank out rest of line
string=string[0:20];#limit lines to 20 char

for char in string:

# clear lcd and set to home
def lcd_clear(self):

def lcd_cursoroff(self):
self.lcd_write(0x0c) #cursor and blink off

# add custom characters (0 – 7)
def lcd_load_custon_chars(self, fontdata):
for char in fontdata:
for line in char:




Preventing (or at least reducing) SD corruption on Raspberry PI


Read for more info

The biggest offender for Filesystem writes on any linux system is logging. If you are like me, you don’t really look at /var/log after a recycle anyways. This area, and /var/run, a location where lock files, pid files and other “stuff” shows up, are the most common areas for mess-ups. Take a look at your blinking FS light on the board. Our goal is to make that light stay off as long as possible.

Set up tmpfs mounts for worst offenders.

The following two lines should be added to /etc/fstab:

none        /var/run        tmpfs   size=1M,noatime         00
none        /var/log        tmpfs   size=1M,noatime         00

There’s more, however. By default, linux also records when a file was last accessed.
That means that every time you read a file, the SD card is written to. That is no good! Luckily, you can specify the “noatime” option to disable this filesystem feature. I use this flag generously.

Also, for good measure, i set /boot to read-only. There’s really no need to regularly update this, and you can come back here and change it to “defaults” and reboot when you need to do something.

After this, /etc/fstab should look as follows:

proc            /proc               proc    defaults                    0   0
/dev/mmcblk0p1  /boot               vfat    ro,noatime                  0   2
/dev/mmcblk0p2  /                   ext4    defaults,noatime            0   1
none        /var/run        tmpfs   size=1M,noatime             0   0
none        /var/log        tmpfs   size=1M,noatime             0   0

Go ahead and reboot now to see things come up. Check the Filesystem light on your raspberry pi after it’s fully booted. You should see no blinking at all.

Disable swapping

One protection against SD card corruption is an optional, but potentially “I’m glad i did that” change to disable swapping.

The raspberry pi uses dphys-swapfile to control swapping. It dynamically creates a swap partition based on the available RAM. This tool needs to be used to turn off swap, and then needs to be removed from startup.

Run the following commands to disable swapping forever on your system:

sudo dphys-swapfile swapoff
sudo dphys-swapfile uninstall
sudo update-rc.d dphys-swapfile remove

After doing this, call free -m in order to see your memory usage:

pi@raspberrypi ~ $ free -m
             total       used       free     shared    buffers     cached
Mem:           438         59        378          0          9         27
-/+ buffers/cache:         22        416
Swap:            0          0          0

If you reboot, and run a free -m again, you should still see swap at 0. Now we don’t have to worry about tmpfs filesystems swapping out to hard disk!


Read for more info

EMPi – Raspberry Pi

A raspberry Pi that will stand the most intense electromagnetic and electro static environments and cope with EMP (Electro Magnetic Pulse). The sort of environment around tesla coils.


I started with a Pi and a Adafruit Pi-Plate. My first job was to create a optic-fibre link (115Kb/s) for comms to my tesla coils and it also doubles up as a remote and insulated tty console for the PI. The chips I used for the fibre are the Avago 1524/2524 1Mb/s fibre transmitter/receiver.

20140801_132030 20140801_132520






The transmitter is driven from a Microchip TC4428 which takes the 3.3v TX to 5V and gives the current drive for the TX LED .The RX is level shifted and inverted using a BC337 (update – a speed up cap was added to the base as at 115kb Rx errors were seen)


Img_20140815_3184 Img_20140815_3182






I realised that the Pi would have to run on its own power supply, so 6 rechargeable AA cells giving 7.2V were added, along with a 7805 regulator to give 5V for the Pi and a couple of diodes to allow the batteries to smoothly take over when the external power was removed.

As the power connector is open to the EM noise on the out side of the case, there is a diode , a cap and a 30V TVS across the power input.

It also became apparent that there was no way of cleanly switching off the Pi without connecting a network or terminal. So I added a button and a script to shutdown the Pi (although not cut the power).

A Pi Cam was attached and bolted to the case, A small hole lets it see the outside world without letting in too much radiation. I also added in a sedcond button which allows the camera to be turned on and off. The script makes the camera take photos every 10 seconds. (I hope to add video too)














I added a removable panel that cover’s the USB, Ethernet and Fibre ports. This is not ideal as I can’t close it fully when I’m running on fibre.

I also added a shutter that goes across the external power/charging connector to further protect the circuits.

20140814_175821 20140814_181113










A quick test proved that the Pi can run when sat on top of a small tesla coil.


Img-2014-08-14-173A11a Img-2014-08-14-173A10a








The camera also worked, but the breakout was too close for the camera to give good photos.








A monocle (50mm lens with 50mm focal length) was added







Giving a couple of goodish photos of the discharge from under the breakout point. (breakout is the wiggly black line to the LHS)