From 35973473d3aebc8b680d92de026966852d8aae4b Mon Sep 17 00:00:00 2001 From: Byron Lathi Date: Thu, 10 Mar 2022 12:14:07 -0600 Subject: [PATCH] Change spi_write_byte to spi_byte the SPI module reads and writes at the same time. If you don't want to write a value, then write all zeros or whatever the device you are communicating with wants. --- sw/spi.h | 2 +- sw/spi.s | 22 ++++++++++++++++++---- sw/tests/test_main.c | 22 +++++++++++++++++++--- 3 files changed, 38 insertions(+), 8 deletions(-) diff --git a/sw/spi.h b/sw/spi.h index 22ebed1..3723290 100644 --- a/sw/spi.h +++ b/sw/spi.h @@ -3,6 +3,6 @@ #include -void spi_write_byte(uint8_t); +uint8_t spi_byte(uint8_t); #endif \ No newline at end of file diff --git a/sw/spi.s b/sw/spi.s index f4c0e7a..f2e9002 100644 --- a/sw/spi.s +++ b/sw/spi.s @@ -1,6 +1,6 @@ .include "io.inc65" -.export _spi_write_byte +.export _spi_byte .importzp sp, sreg, regsave, regbank .importzp tmp1, tmp2, tmp3, tmp4, ptr1, ptr2, ptr3, ptr4 @@ -10,31 +10,45 @@ SPI_SCLK = $01 SPI_SSn = $02 SPI_MOSI = $04 +SPI_MISO = $08 ; Write a single byte to the SPI device ; @in A The byte to write +; @out A The read byte -_spi_write_byte: +_spi_byte: phx ; Save regs phy + ldy #$00 sta tmp1 ; Save value into tmp1 lda #$80 tax @loop: bit tmp1 ; Check if high bit set beq @1 - lda #SPI_MOSI ; Bit not set. + 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 + inc tmp2 +@2: clc ; Shift previous value left + tya ; Add current value + asl + adc tmp2 + tay ; Move read value back to y txa lsr ; Select next bit tax bne @loop ; Stop when mask is 0 lda #SPI_SSn ; Raise Slave Select sta BB_SPI_BASE - ply ; Restore regs + tya ; Get read value from y + ply plx rts ; Return diff --git a/sw/tests/test_main.c b/sw/tests/test_main.c index e3da992..c9eef39 100644 --- a/sw/tests/test_main.c +++ b/sw/tests/test_main.c @@ -1,10 +1,26 @@ #include +#include + #include +char retval; + int main(void) { - printf("Starting spi_write_byte test...\n"); - spi_write_byte(0xa5); - printf("Done!\n"); + printf("Setting SPI location to 0x02\n"); + *(uint8_t*)0x7ff0 = 2; + if (!(*(uint8_t*)0x7ff0 == 2)) { + printf("Expected 0x02 at 0x7ff0\n"); + return 1; + } + printf("Done!\n\n"); + + printf("Starting spi_byte test...\n"); + retval = spi_byte(0xa5); + if (retval != 0) { + printf("Expected 0 return value from spi_byte\n"); + return 1; + } + printf("Done! %x\n", retval); return 0; } \ No newline at end of file