Skip to Content
Under the HoodEmulator InternalsZX Spectrum Next: the real-time clock

Real-Time Clock: A Watchman on Two Wires

Switch your Next off, put it in a drawer for a month, and switch it on again: it knows the date. The FPGA forgot everything the moment the power went, the SRAM is blank, the core has been loaded from flash all over again. So who was counting the seconds in the dark? The answer is the Next’s Real-Time Clock, the RTC: a clock that keeps the time and the date whether the machine is running or not.

A clock that survives the power switch matters more than it seems. An operating system that writes a file wants to stamp it with the date. A game can offer a puzzle of the day, a logger wants to say when something happened, and a program that needs a random seed has one ticking right there. None of this works with a clock that starts at midnight on 1 January every time you switch on, and the Spectrum never had any other kind.

You should know one chapter first. Memory, Ports and NextRegs: How the Z80N Reaches the Machine explains how the Next decodes its ports and how a NextReg switches a group of them off. Storage: an SD Card on a Serial Bus is worth a look too: it shows a serial bus that the hardware clocks for you, and this chapter shows one where you do the clocking yourself.

The road ahead

We start with the clock chip itself, which lives outside the FPGA on its own battery, and the two wires that connect it to the machine. Then come the two ports that hold those wires, and the rules of the conversation on them: how a message starts and stops, how bits travel and how the listener says “got it”. The heart of the chapter is the part where your program speaks those rules itself, one wire at a time, and the speed limit it must respect; if you read only one section, read that one. After that we open the clock’s registers, read the time through a snapshot, set it, use its spare memory, and see what a reset does to it.

The facts are for core 3.02.01 and the DS1307 real-time clock on the Next’s bus. The listings run at 3.5 MHz, the CPU’s speed after a reset, and every time given for them is for that speed.

A clock outside the machine

The Next’s clock is a small chip of its own, a DS1307, sitting on the board beside the FPGA. I like to call it the watchman: it stays awake on its own lamp while the house sleeps, and when you come down in the morning it tells you what time it is. It is not part of the core and no reset of the FPGA reaches it.

Three things keep it going:

  • A 32,768 Hz crystal. The number is 215, so fifteen halvings make exactly one pulse a second. Many quartz watches count from the same frequency for the same reason, which keeps the crystal cheap and easy to find, though some watches use other frequencies.
  • A battery input for a 3 V lithium cell, between 2.0 and 3.5 V. When the board’s own supply falls below the battery’s voltage, the chip switches over and keeps counting on less than half a microamp. A 48 mAh cell keeps it alive for more than ten years.
  • A guard at the door. While the supply is below 1.25 times the battery’s voltage, the chip ignores the bus altogether, so a machine that is powering up or down cannot scribble garbage over the time.

The watchman is only as good as his crystal. A crystal that is 20 parts in a million off gains or loses about 1.7 seconds a day, nearly a minute a month, so do not be surprised if the clock wants setting now and then.

Two wires, and nobody pushes

The watchman talks over I2C, the inter-integrated circuit bus: two wires that many chips can share. One wire, SCL, is the clock, which says when a bit is valid. The other, SDA, is the data, which says what the bit is.

The trick that makes sharing possible is that no chip ever drives a wire high. Each wire has a pull-up, a resistor to the supply, that holds it high when it is left alone. A chip can only do two things to a wire: pull it low, or let go. This is called open drain, and it means two chips can never fight, one pushing up while the other pulls down. If anybody pulls, the wire is low; it is high only when nobody pulls. An engineer would say the wire is the AND of everyone’s wishes.

SCLSDAsupplypull-upsFPGAports $103B, $113BDS1307the watchmaninternalconnectorPi’sGPIO 2, 3NextReg $A0 bit 3any device pulls a line low; none drives it high; a line is high only when nobody pulls
The Next’s I2C bus. The FPGA, the DS1307 and an internal connector each hang on both lines; pull-ups hold the lines high when nobody pulls them low. The Raspberry Pi’s GPIO 2 and 3 reach only the FPGA, through a pair of their own, once NextReg $A0 bit 3 joins them.

Three things share the bus on the board: the FPGA, the watchman and an internal connector for whatever an owner wants to add. The Raspberry Pi’s connector can join in too, though in a cleverer way than it looks. Bit 3 of the PI Peripheral Enable register, NextReg $A0, gives the Pi’s GPIO 2 (data) and GPIO 3 (clock) to the bus. The FPGA then pulls the Pi’s pins low whenever it pulls its own, and the lines your program reads are the AND of both sides. The Pi’s pins are not wired to the watchman, though: the FPGA stands between two buses and runs them both at once.

There is one more rule: the Next is always the master. It makes the clock, it starts every conversation and it ends it. The watchman only answers.

Two ports, one bit each

Each wire has its own port, and only bit 0 of each counts:

  • Port $103B is SCL, the clock.
  • Port $113B is SDA, the data.

A write of bit 0 = 0 makes the FPGA pull the wire low; bit 0 = 1 lets it go. A read gives $FE or $FF: bits 7–1 are always 1, and bit 0 is the wire itself, not what you wrote. That difference is the whole point. Write 1 to $113B and read it back, and you read 0 when the watchman is pulling the wire low: that is how you hear him. The same goes for the clock wire, so a program can see if another chip holds SCL low to ask for more time.

A reset, soft or hard, lets go of both wires. Bit 2 of the Internal Port Decoding Enables register, NextReg $83, switches both ports off: they then read $FF and ignore writes.

I find these two ports a lovely piece of minimalism. Many I2C controllers in other machines are whole chips, with shift registers, state machines and a page of registers. The Next gives you two wires and says: the protocol is your business.

The rules of the conversation

Since both wires rest high and anyone may pull, the chips need rules about who touches what, and when. There is one simple rule and two exceptions.

The rule: SDA changes only while SCL is low. The master puts a bit on SDA, raises SCL, and the listener reads SDA while SCL is high. Then the master lowers SCL and may change SDA for the next bit.

The exceptions are the brackets around a message, and they break the rule on purpose:

  • START: SDA falls while SCL is high. Every chip on the bus wakes up and listens.
  • STOP: SDA rises while SCL is high. The message is over and the bus is free.

Because a normal bit never changes SDA while SCL is high, nobody can mistake data for a bracket. A START inside a message, before any STOP, is a repeated START: it begins a new message without letting anybody else grab the bus in between.

Bytes go most significant bit first, and each byte gets a ninth clock pulse, the acknowledge. For that pulse the sender lets go of SDA and the receiver answers: pulled low is an ACK, “got it”; left high is a NACK, “no”, or “no more”. The first byte after a START is the address: seven bits saying which chip the master wants, and an eighth saying the direction, 0 for write and 1 for read. The watchman’s address is $68, so $D0 means “watchman, listen” and $D1 means “watchman, talk”.

SCLSDASTARTSTOP11010000ACKaddress $68writewatchman
START, the address byte $D0 and STOP, to scale in clock periods. SDA changes only while SCL is low, except at START and STOP, marked red, where it changes while SCL is high. The first seven bits are the address $68, most significant first; the eighth, 0, asks to write. On the ninth pulse the watchman pulls SDA low: the ACK, in orange.

A chip that is not addressed answers nothing, and nothing means a high SDA on the ninth pulse, a NACK. So the address byte doubles as a roll call: if nobody acknowledges $D0, there is no watchman on your bus. I always check that ACK before believing anything else the bus tells me.

Speaking the protocol yourself

The Next has no hardware that sends an I2C byte for you. Your program raises and lowers the two wires one OUT at a time, a technique called bit-banging. It sounds primitive, and it is, but it takes a page of code, and here it is. The routines use BC, DE, A and the flags, and keep HL.

START and STOP are three or four writes each. Both begin with the wires in a known state:

; START (also a repeated START): SDA, SCL high, ; SDA low while SCL is high, then SCL low I2cStart: ld bc,$113b ; SDA ld a,1 out (c),a ; let SDA go ld b,$10 ; SCL out (c),a ; let SCL go ld b,$11 xor a out (c),a ; SDA low: START ld b,$10 out (c),a ; SCL low ret ; STOP: SDA low, SCL high, then SDA high I2cStop: ld bc,$113b xor a out (c),a ; SDA low ld b,$10 inc a out (c),a ; let SCL go ld b,$11 out (c),a ; SDA high: STOP ret

Sending a byte is eight bits and a listen:

; send A, MSB first; A = the ACK bit (0 = ACK) I2cWrite: ld e,a ld d,8 ; eight bits WrBit: ld bc,$113b xor a rl e ; next bit into carry rla ; and into bit 0 out (c),a ; SDA = the bit ld b,$10 ld a,1 out (c),a ; SCL high: read me xor a out (c),a ; SCL low dec d jr nz,WrBit ld bc,$113b ld a,1 out (c),a ; let SDA go ld b,$10 out (c),a ; the ninth pulse ld b,$11 in a,(c) ; the answer and 1 ld e,a ld b,$10 xor a out (c),a ; SCL low ld a,e ret

And receiving one is the mirror image: you let go of SDA, clock eight times and read the wire at every pulse, then answer yourself.

; receive a byte into A; answer NACK if carry is ; set, ACK otherwise I2cRead: push af ; keep the carry ld bc,$113b ld a,1 out (c),a ; let SDA go ld d,8 ld e,0 RdBit: ld b,$10 ld a,1 out (c),a ; SCL high ld b,$11 in a,(c) ; read SDA rra ; bit 0 into carry rl e ; and into E ld b,$10 xor a out (c),a ; SCL low dec d jr nz,RdBit pop af ld a,0 rla ; A = carry: 0 ACK, 1 NACK ld b,$11 out (c),a ; our answer on SDA ld b,$10 ld a,1 out (c),a ; the ninth pulse xor a out (c),a ld b,$11 inc a out (c),a ; let SDA go ld a,e ret

How it works, the parts worth a second look:

  • Every bit of I2cWrite sets SDA first, then pulses SCL. The data is steady before the clock rises and stays steady until it falls: the rule, kept by the order of the OUTs.
  • For the acknowledge, the sender lets go. I2cWrite writes 1 to SDA before the ninth pulse, which does not make the wire high: it only stops pulling. The IN then reads whatever the watchman does.
  • I2cRead writes 1 to SDA once, at the start, and never touches it during the eight bits. The watchman pulls the wire for every 0 he sends; the 1s are the pull-up’s work.
  • The carry chooses the answer. Clear for ACK, “go on”; set for NACK, “that was the last one”. The watchman stops talking after a NACK and leaves SDA to you for the STOP.

How fast is too fast

The watchman is a 100 kHz chip: it runs I2C’s standard mode only, never the faster ones. For every pulse it asks for at least 4.0 µs with SCL high and 4.7 µs with SCL low. A START needs SCL high for 4.7 µs before SDA falls and 4.0 µs after; a STOP needs 4.7 µs of SCL high before SDA rises; and between a STOP and the next START the bus must rest for 4.7 µs.

Now look at I2cWrite at 3.5 MHz. A bit takes 96 T-states, 27.4 µs, which is about 36,500 bits a second, well under the limit. The tight spot is the clock’s high time: from the OUT that raises SCL to the one that lowers it there is an XOR A and an OUT, 16 T-states, 4.6 µs. That clears the 4.0 µs, but not by much. The ACK pulse of I2cRead is as short; no gap in these routines is shorter.

Here is the catch: the same 16 T-states last 2.3 µs at 7 MHz and 0.57 µs at 28 MHz, seven times too short. A Next running at full speed outruns the watchman with the very same code. My advice is the boring one: switch the CPU to 3.5 MHz with the CPU Speed register, NextReg $07, before you talk to the bus, and switch it back afterwards. A read of the whole time takes under 3 ms, so you lose almost nothing. If you would rather keep the speed, keep SCL high for at least 112 T-states and low for at least 132 at 28 MHz, and measure what you wrote.

The watchman’s registers

The watchman has 64 bytes, numbered $00 to $3F. The first eight hold the time and a control byte; the other 56 bytes are RAM, kept by the battery with the time.

The time is in BCD, binary-coded decimal: each 4-bit half of a byte holds one decimal digit, so 45 seconds is $45, not $2D. It is wasteful, but a program that prints the time only has to print two hex digits, and I suspect that was the whole idea. The spare bits carry switches:

reg 7 6 5 4 3 2 1 0 $00 CH [ tens of sec ][ seconds ] $01 0 [ tens of min ][ minutes ] $02 0 12 PM/20 10h [ hours ] $03 0 0 0 0 0 [ day 1-7 ] $04 0 0 [ tens ][ date ] $05 0 0 0 10m [ month ] $06 [ tens of year ][ year ] $07 OUT 0 0 SQWE 0 0 RS1 RS0
  • CH, clock halt, bit 7 of the seconds. When it is 1 the crystal stops and so does the time. A fresh chip comes up with CH set, so the first thing any program that sets the clock does is clear it.
  • The hours, bit 6, choose 12- or 24-hour mode. With bit 6 = 0, bit 5 is the second tens digit, for 20 to 23. With bit 6 = 1, bit 5 is PM, and the hours count 12, 1, 2 to 11; PM flips when 11 becomes 12, and the date moves on when 11 PM becomes 12 AM. After changing bit 6, write the hours again: the chip does not convert them.
  • The day of the week, 1 to 7, steps at midnight. Which day is 1 is up to the software: the watchman only counts, so pick a convention (Sunday = 1 is common) and stick to it.
  • The date, month and year roll over as a calendar should: 30 or 31 days, February 28 or 29, and the year from 99 to 00. The year is two digits, and every year divisible by four is a leap year, which is right for every year from 2000 to 2099. Somebody in 2100 will have to fix it.
  • The control register drives the chip’s square-wave pin: SQWE = 1 makes a square wave of 1 Hz, 4,096 Hz, 8,192 Hz or 32,768 Hz by RS1–RS0 (00 to 11); with SQWE = 0, the pin follows OUT. On the Next the watchman reaches the FPGA only through the two bus wires, so that pin cannot interrupt the Z80.

Reading the time

Reading a clock has a classic trap. Suppose it is 12:59:59 and you read the seconds, then the minutes, then the hours, and between the minutes and the hours the clock ticks: you get 13:59:59, an hour out. Every programmer of an old PC clock has met this bug.

The watchman avoids it with a snapshot. His counters run on their own, and on every START he copies them into a second set of registers. Everything you read over the bus comes from the snapshot, so all seven bytes belong to the same moment, however slowly you read them, while the real counters keep running underneath.

32,768 Hz÷ 32,768secondsminuteshoursday,datemonthyear1 Hzthe snapshot: copied on every START, read over the busthe counters keep running while a read takes its bytes from the snapshot
Inside the watchman. The crystal divided by 32,768 gives one pulse a second; each counter carries into the next. On every START the counters are copied into the snapshot, and a read over the bus takes its bytes from there, so the seven bytes of one read always belong to one moment.

A read is two messages joined by a repeated START. The first, addressed to $D0, writes one byte: the register pointer, the number of the register to start from. The second, addressed to $D1, reads: the watchman sends the register at the pointer, steps the pointer, and goes on for as long as you acknowledge. Your NACK on the last byte tells him to stop.

set the pointer to $00S$D0A$00Aread from $00 onSr$D1A$56A$34A$12A…$26NPsecondsminuteshoursyearS START, Sr repeated START, P STOP, A ACK (pulled low), N NACK (left high)blue: the Next sends; orange: the watchman sends
Reading the seven time registers. The first message sets the pointer to $00 and gets the watchman’s ACK for both bytes. A repeated START begins the second, addressed to read: the watchman sends the seconds, minutes, hours and so on, and the Next acknowledges every byte except the year, which gets a NACK before the STOP.

Here it is as code, on the routines above. It reads the seconds to the year into Time, in the registers’ order:

; read registers $00-$06 into Time (7 bytes) ReadTime: call I2cStart ld a,$d0 ; watchman, listen call I2cWrite xor a ; the pointer: $00 call I2cWrite call I2cStart ; repeated START ld a,$d1 ; watchman, talk call I2cWrite ld hl,Time ld b,6 ; six bytes with ACK RdNext: push bc or a ; carry clear: ACK call I2cRead ld (hl),a inc hl pop bc djnz RdNext scf ; carry set: NACK call I2cRead ; the year ld (hl),a jp I2cStop

At 3.5 MHz the whole read takes 10,058 T-states, 2.9 ms, about a seventh of a frame. On Friday, 18 September 2026 at 12:34:56, in 24-hour mode with Sunday as day 1, Time holds:

$56 $34 $12 $06 $18 $09 $26 sec min hr day dt mon yr

Notice the snapshot at work in a slower read. Start at 12:59:59, take the seconds and the minutes, then pause for over a second before the hours. You still get $12, because the hours came from the snapshot taken at the START; the next read, with its own START, gets 13:00:00.

Setting the clock

Setting is one message: START, $D0, the pointer, and then the bytes, each written to the register at the pointer before the pointer steps. With Time holding the seven bytes in the same order:

; write Time (7 bytes) into registers $00-$06 SetTime: call I2cStart ld a,$d0 ; watchman, listen call I2cWrite xor a ; from register $00 call I2cWrite ld hl,Time ld b,7 WrNext: push bc ld a,(hl) call I2cWrite inc hl pop bc djnz WrNext jp I2cStop

It takes 8,711 T-states, 2.5 ms. Two details make this the right way to do it:

  • Writing the seconds restarts the second. The divider that halves the crystal fifteen times is cleared, so the next tick comes a whole second after the write. Set the clock at 12:34:56 and it says 12:34:57 exactly one second later, not at some random moment within the second.
  • Write everything within one second of the seconds. A tick between your seconds and your hours could carry into the minutes you have not written yet. One message from register $00 up takes 2.5 ms, which settles it. The bytes are stored as each one is acknowledged, so a message broken off halfway keeps what it wrote.

And remember CH: the seconds byte you write has bit 7 clear, so the clock runs. Write $80 or more and it stops, which is also how you would freeze the time on purpose.

Fifty-six bytes that remember

Registers $08 to $3F are plain RAM, 56 bytes, read and written like the time and kept by the same battery. It is not much, but it is the only memory in the Next that survives the power switch without a file system: a high score, a setting, the date a program last ran. I would keep a byte or two of it as a signature, so your program can tell its own data from another program’s.

The pointer has two habits worth knowing:

  • It wraps from $3F to $00. Read four bytes from $3E and you get $3E, $3F, then the seconds and the minutes.
  • It stays where it was between messages. A read that starts with $D1 straight after the START, with no pointer written first, continues from the last pointer: a current address read. Useful, but I prefer writing the pointer every time; it costs one byte and guesses nothing.

Resets

No Next reset touches the watchman. A soft reset, a hard reset, loading a new core: the time keeps running and the RAM keeps its bytes, because the chip is not part of the FPGA and has its own power.

The FPGA’s side is another matter. A reset lets go of both wires, so the bus goes high, and it does not care what the watchman was doing at that moment. If he was in the middle of sending a 0, he is still holding SDA low, waiting for clock pulses that the reset will not send. He is not broken, only patient. Here is my advice for the first thing a program does on the bus: if SDA reads 0, pulse SCL until it reads 1 (nine pulses are always enough to finish any byte and its acknowledge), then send a STOP. After that the watchman is listening again, and your START will be heard.

What to take home

The Next’s real-time clock is a DS1307, the watchman, a chip outside the FPGA with a 32,768 Hz crystal and its own battery, so it keeps counting through power-off and every kind of reset. It talks over I2C: two open-drain wires, SCL and SDA, held high by pull-ups and pulled low by anyone who wants to, so a wire is the AND of everyone on it. Port $103B is SCL and port $113B is SDA; bit 0 of a write pulls or lets go, and bit 0 of a read is the wire itself. The Raspberry Pi’s GPIO 2 and 3 can join the bus through NextReg $A0 bit 3, and NextReg $83 bit 2 switches the ports off.

The Next is always the master, and the CPU does every step itself. SDA changes only while SCL is low, except for START and STOP, which change it while SCL is high. Bytes go most significant bit first, and a ninth pulse carries the acknowledge, low for yes. The watchman’s address is $68: $D0 to write, $D1 to read. He is a 100 kHz chip that wants 4.0 µs of SCL high and 4.7 µs low, which the routines here meet at 3.5 MHz and miss by a factor of seven at 28 MHz, so slow the CPU down or slow the code.

The registers are BCD: seconds with the clock-halt bit, minutes, hours with a 12/24-hour switch, a day of the week from 1 to 7, date, month, a two-digit year whose leap years are right until 2099, and a control byte for the square-wave pin. A read writes the pointer, then a repeated START reads on from it; every START takes a snapshot, so one read never mixes two moments. A write of the seconds restarts the second, and a whole time written in one message takes 2.5 ms. The other 56 bytes are RAM that survives everything, and the pointer wraps from $3F to $00. Clear CH, write the time in one go, read it in one go, and the watchman will tell you the hour for years on his little battery.

Last updated on