diff --git a/sw/spi.h b/sw/spi.h index 3723290..254a75b 100644 --- a/sw/spi.h +++ b/sw/spi.h @@ -4,5 +4,6 @@ #include uint8_t spi_byte(uint8_t); +uint16_t spi_word(uint16_t); #endif \ No newline at end of file diff --git a/sw/spi.s b/sw/spi.s index f2e9002..b4181ea 100644 --- a/sw/spi.s +++ b/sw/spi.s @@ -1,6 +1,7 @@ .include "io.inc65" .export _spi_byte +.export _spi_word .importzp sp, sreg, regsave, regbank .importzp tmp1, tmp2, tmp3, tmp4, ptr1, ptr2, ptr3, ptr4 @@ -13,7 +14,7 @@ SPI_MOSI = $04 SPI_MISO = $08 -; Write a single byte to the SPI device +; Read and write a single byte from the SPI device ; @in A The byte to write ; @out A The read byte @@ -52,3 +53,55 @@ _spi_byte: ply plx rts ; Return + + +; Read and write 16 bits from the SPI device +; @in AX The word to write +; @out AX The read word + +_spi_word: + phy + ldy #$00 + sta tmp1 ; Save value into tmp1 + stx tmp2 + lda #$02 + sta tmp4 + +@byte: lda #$80 + tax +@loop: bit tmp1 ; Check if high bit set + beq @1 + lda #SPI_MOSI ; Bit not set. + bra @1 +@1: lda #$00 ; Bit set + sta BB_SPI_BASE ; Write data + adc #SPI_SCLK + sta BB_SPI_BASE ; Write clock + stz tmp2 + lda BB_SPI_BASE ; Check MISO value + and #SPI_MISO + beq @2 + tya + asl + inc + bra @3 +@2: tya ; Add current value + asl +@3: tay ; Move read value back to y + txa + lsr ; Select next bit + tax + bne @loop ; Stop when mask is 0 + + lda tmp2 ; Switch to second byte + sta tmp1 + sty tmp3 ; Store read data in tmp3 + dec tmp4 + bne @byte + + lda #SPI_SSn ; Raise Slave Select + sta BB_SPI_BASE + tya ; Get read value from y + ldx tmp3 + ply + rts ; Return \ No newline at end of file diff --git a/sw/tests/test_main.c b/sw/tests/test_main.c index c9eef39..ff292c6 100644 --- a/sw/tests/test_main.c +++ b/sw/tests/test_main.c @@ -3,7 +3,7 @@ #include -char retval; +uint16_t retval; int main(void) { @@ -21,6 +21,15 @@ int main(void) printf("Expected 0 return value from spi_byte\n"); return 1; } + printf("Done! %x\n\n", retval); + + printf("Starting spi_word test...\n"); + retval = spi_word(0xa5a5); + if (retval != 0) { + printf("Expected 0 return value from spi_word.\n"); + printf("Got: %x\n\n", retval); + return 1; + } printf("Done! %x\n", retval); return 0; } \ No newline at end of file