I'm writing an emulator for the MOS 6502 processor.
In order to test it, I decided to run the ROM from the Apple 1.
The Apple 1 uses a Motorola MC6820 PIA (Peripheral Interface Adapter) for communication between the CPU and the keyboard/display.
I'm trying to emulate the MC6820 so I can have keyboard support, but I'm having trouble understanding how it is supposed to work.
Memory is mapped the following way:
0xD010: Keyboard Data
0xD011: Keyboard Control Register
0xD012: Display Data
0xD013: Display Control Register
The ROM does the following, with original comments:
LDY #$7F ; Mask for DSP data direction register.
STY $D012 ; Set it up.
LDA #$A7 ; KBD and DSP control register mask.
STA $D011 ; Enable interrupts, set CA1, CB1, for
STA $D013 ; positive edge sense/output mode.
... ; Other initialization code...
NEXTCHAR LDA $D011 ; Key ready?
BPL NEXTCHAR ; Loop until ready.
At reset, all bits on the PIA will be 0.
As bit 3 (DDR) of the control registers are 0, a data write will end up in the corresponding data direction register.
So:
LDY #$7F
STY $D012
Will write 0x7F
into the data direction register B, configuring bits 0-6 as outputs.
This is for the display.
Then the value 0xA7
is written to control registers A and B:
LDA #$A7
STA $D011
STA $D013
I'm already having trouble understanding this.
Based on the documentation, bits of the control registers are:
| 7 | 6 | 5, 4, 3 | 2 | 1, 0 |
| IRQ1 | IRQ2 | C2 Control | DDR | C1 Control |
| 1 | 0 | 1 0 0 | 1 | 1 1 | => `0xA7`
DDR bit is set to 1, so data read/write will end up in the output register A or B and no longer in the data direction register A or B.
But why the other flags?
And what happens on the PIA at this exact time?
When the ROM checks for a key press:
LDA $D011 ; Key ready?
BPL NEXTCHAR ; Loop until ready.
It checks if bit 7 of the control register is set, meaning it shouldn't be set until a key is pressed.
But it has initially be set to 1 with the value 0xA7
.
So how was it reset?
Does setting 0xA7
generate an interrupt, making the CPU read the value, as, as I understand, a read by the CPU should clear the IRQ flags?