Category Archives: Raspberry Pi

Emulating a Z80 RC2014 with CPM and IDE drives via an SD card

The RC2040

Ive always loved Z80’s Even before programming in high level languages I was had compiling Z80 code on a Nascom1

Recently I’ve discovered the world of emulated Z80’s via the emulator written for linux by Alan Cox (Etched Pixels) ( This allows various configurations of Z80 RC2014 ( machines to be emulated (along with 8080 8086 and may other 8 and 16 bit processors)

My C code was rather rusty and I wanted a project to re teach me the basics.

Starting with the Etched pixels code I quickly got it running on a Raspberry PI Zero and added a few simple peripherals.

Z80 Emulated RC2014 driving a colour OLED display from BASIC

Which is all fine, but well it was, all a bit easy.

Not So easy

So, I was looking for a project to play with the RP2040, ideal, apart from The RP2040 doesn’t give a linux OS, It doesn’t have any storage (other than its own flash) and it only has 240K of memory.

To emulate a CPM system you need a minimum of 64K (plus a switchable ROM) some form of storage, ideally removable. Some way of loading the ROM (although this can be compiled in as an image) and a serial terminal.

Well the serial terminal is easy, there are 4 plus USB to play with, although all of the emulation uses STDIO uniquely, which is only partially supported on a PI Pico in C

As I was only interested in the Z80 bits of the emulation and only with the peripherals commonly supported on an RC2014. I started on the Raspberry pi, removing all of the other non z80 library’s and the other peripherals I wouldn’t need.

This was easy, rip a bit out, patch the code so it didn’t require it, edit the make file, recompile, test. Repeat until you have a basic Z80 emulated machine.


The ROM, I temporally coded into C via the linux xxd command, from one of the factory ROM’s available on the RC2014 git hub.

The next problem is that the emulator as configured uses 512K of ram (RC2014 – 512k ROM 512k RAM Module) to emulate a paged ram card. As the RC2040 only has 240K of memory I needed to remove the Ram/Ram paged memory code and replace it with a 64K ram/Rom paged emulation (RC2014 64k RAM Module and RC2014 Pageable ROM Module), that will only take at max 128K. It also must allow for the ROM to be paged out to allow the bootloader to be installed at 0x0000.

Using the compiled ROM I could easily fill an array of uint_8 with a ROM image, and switch using port 0x38 as a RC2014


CPM was emulated using the EtchedPixels code for a removable CF card. The Binary is readily available already configured to boot on an RC2014 again from the RC2014 git hub

From the CPM source image (.img) file, you need to make an IDE file system onto a .cf file. using CPMtools. Details are towards the bottom of this page under “CP/M Application Disks”

Luckily this CF file can again easily be tested by loading up the image using the RPI z80 linux emulator.

SD Card

Of course the Pico doesn’t have any storage like a CF card and the 3.3v bus makes interfacing to a 5v CF difficult, but there is the possibility of using a SD card via SPI.

Luckily there is a library for SD cards which works with the PICO no-OS-FatFS-SD-SPI-RPi-Pico

Working through the example was straight forward and gives a great way to test your SD card connections and if required, format a fat32 SD card.

The connections to the SD card are simple, 4 wires and power.

PICO Z80 Emulation test bed.

PICO or bust

At this point there is no way we can test the code on a RPI, so we need to dive into the PICO.

Compiling the code to the PICO without IDE support was surprisingly straightforward. All that was required was to replace the TX/RX STDIO calls with a call to the PICO UART. Unfortunately there was no easy non-blocking call to the receive queue using the USB serial. So initially the input/output was all via the hardware serial port.

I tackled the SD card next, making a simple bit of code to read a 64K rom image from the CD card directly into the ROM array, so I could remove the horrible compiled C ROM. The ROM images came directly from the RC2014 Factory ROM images on Git hub.

Buttons and switches

To make the ROM selection easier I added three switches to emulate the RC2014 A13, A14, & A15 ROM select jumpers, This meant I could easily switch between ROM starting addresses when loading from a rom image.

As I was adding switches, I decided to add a few buttons. which give me a Z80 reset and a dump RAM initially as a hex dump to the terminal, and latterly as a .bin file into the CD card for debugging.

To allow for a switch-less operation for the switches / buttons to work you need to ground GPIO 22, otherwise the RC2040 will run with switch-less defaults( currently CPM ROM and USB serial)


I changed the IDE library to use the FatFS-SD-SPI-RPi-Pico file system and pointed it to load the .cf image from the card.

After A LOT of playing around with the differences in read/write and seek, plus RAM/ROM switching and serial problems. It finally loaded 🙂

I also found that if I disabled the RAM/ROM switching on a emulated z80 reset (from the button), I could warm boot into CPM, bonus…


More Serial fun

Eventually I sorted the problems with the blocking USB serial by writing an interrupt driven routine that fills its own circular buffer, so now (from a switch) you can select which serial port you prefer.

Tiny Rc2040

If you don’t need the switches/ buttons, you can run it without, using a Pimoroni Tiny 2040 using the USB serial, making the smallest z80 CPM machine, ever (unless you know different?)


Make your own

All of the files to emulate a Z80 with IDE on SD are available via git hub

Unfortunately I haven’t quite solved the Serial issues yet. The serial interface(s) will only take characters as a really slow rate. If you are going to cut/paste code into the RC2040 you will need to add in a 40mS (or longer delay) into your terminal program.

Serial issues are much improved. If added a block to the RX char circular buffer code that will only allow char RX, if the ACIA isn’t currently in an interrupt and added a fake interrupt to drive the USB RX circular buffer in the same way as the UART RX

Added SIO support and some bodges to delay the emulated interrupts to allow serial as fast as the Z80 emulation can cope with.

Using Terra term I can now drop files onto the RC2040 with only a 1ms TX delay.

Continued here

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