; Super Game Boy packet transfer
; @entrada HL: Packet address
sgbpackettransfer:
ld a, [hl]
and %00000111 ; The three lower bits indicate the number of packets to send
ret z ; We return if there are no packets to send
ld b, a ; We store the number of packets to send
.sgbpackettransfer_0:
push bc
xor a
ld [rP1], a ; Initial pulse (Start write). P14 = LOW and P15 = LOW
ld a, P1F_4 | P1F_5
ld [rP1], a ; P14 = HIGH and P15 = HIGH between pulses
ld b, 16 ; Number of bytes per packet
.sgbpackettransfer_1:
ld e, 8 ; Bits per byte
ld a, [hli]
ld d, a ; Next byte of the packet
.sgbpackettransfer_2:
bit 0, d
ld a, P1F_4 ; P14 = HIGH and P15 = LOW (Write 1)
jr nz, .sgbpackettransfer_3
ld a, P1F_5 ; P14 = LOW and P15 = HIGH (Write 0)
.sgbpackettransfer_3:
ld [rP1], a ; We send one bit
ld a, P1F_4 | P1F_5
ld [rP1], a ; P14 = HIGH and P15 = HIGH between pulses
rr d ; We rotate the register so that the next bit goes to position 0
dec e
jr nz, .sgbpackettransfer_2; We jump while there are bits left to be sent
dec b
jr nz, .sgbpackettransfer_1; We jump while there are bytes left to be sent
ld a, P1F_5
ld [rP1], a ; Bit 129, stop bit (Write 0)
ld a, P1F_4 | P1F_5
ld [rP1], a ; P14 = HIGH and P15 = HIGH between pulses
call sgbpackettransfer_wait ; 280048 clock cycles are consumed (66.768646240234375 milliseconds) at 4.194304 mhz | 24 cycles
pop bc
dec b
ret z
jr .sgbpackettransfer_0 ; We jump while there are packets left to be sent
; 280024 clock cycles are consumed
sgbpackettransfer_wait:
ld de, 7000 ; 12 cycles
.sgbpackettransfer_wait_0:
nop ; 4 cycles
nop ; 4 cycles
nop ; 4 cycles
dec de ; 8 cycles
ld a, d ; 4 cycles
or e ; 4 cycles
jr nz, .sgbpackettransfer_wait_0 ; 12 cycles if jumps, 8 if not
ret ; 16 cycles