The Need for a Real-Time Clock
The Z80’s internal clock is only useful for instruction timing. It cannot track actual time (hours, minutes, days). A Real-Time Clock (RTC) is a separate, dedicated chip (like the DS1307 or MC146818) that contains its own crystal oscillator and often a small battery to maintain time even when the main computer is powered off.
Communication: Indexed I/O
The Z80 communicates with an RTC chip using a method called indexed I/O (similar to how the AY sound chip works). The RTC has a set of internal registers (e.g., 0-12) that store the seconds, minutes, hours, day, date, and control flags.
The Two-Step Process:
- Select Index/Address: Write the number of the RTC register you want to read (e.g., register 0 for seconds) to the RTC’s Address Port.
- Read/Write Data: Read or write the actual time value from the RTC’s Data Port.
Generic RTC Ports Example:
Assume an RTC is mapped to I/O ports B0H
(Address Port) and B1H
(Data Port).
Reading the Current Second
To read the current value of the Seconds register (typically register index 0):
RTC_ADDR_PORT EQU 0B0H
RTC_DATA_PORT EQU 0B1H
READ_SECONDS:
; 1. Select the Seconds Register (Index 0)
LD A, 00H ; A ← Register 0
OUT (RTC_ADDR_PORT), A ; Write 0 to the Address Port
; 2. Read the data from the Data Port
IN A, (RTC_DATA_PORT) ; A ← Value of the Seconds Register
; The value in A is usually BCD and needs conversion (see next step).
RET
Dealing with BCD Time Values
RTC chips almost always store time data (seconds, minutes, hours) in BCD (Binary-Coded Decimal) format (as discussed in Part 9).
Conversion Required: If the RTC returns 35H
for seconds, it means 35 seconds. If you want to use this number for standard binary math or display, you must convert the BCD back into binary using multiplication and bitwise logic.
Example: Converting Seconds from BCD to Binary
; Assume A holds BCD seconds (e.g., 35H)
; 1. Get the tens digit (3)
PUSH AF
AND 0F0H ; Mask off the low nibble (A = 30H)
RRCA ; RRCA / RRCA / RRCA / RRCA
RRCA / RRCA / RRCA / RRCA ; 4 right rotations → A = 03H (the tens digit)
LD C, A ; C ← 3
; 2. Multiply tens digit by 10
; ... (Code performs C × 10)
; 3. Add the ones digit
POP AF
AND 0FH ; Mask off the high nibble (A = 05H)
ADD A, C ; A ← 30 + 5. A now holds 35 decimal in binary.
RET