Cảm ơn mọi người đã giúp mình trả lời những câu hỏi trên. Hic hic đây là code mình viết, mình dùng UART để kiểm tra xem việc đọc/viết dữ liệu nhưng vẫn không thành công.
Mình trước đó đã có một code riêng để kiểm tra UART, nên mình khá chắc chắn vấn đề nằm ở cái SPI này...
Các cao thủ có thể nhìn qua code này rồi giúp em được không ạ? Cảm ơn mọi người nhiều nhiều!
Code:
;Instruction shortcuts:
.equ RDINS,3
.equ WRINS,2
.equ WRDI,4
.equ WREN,6
.equ RDSR,5
.equ WRSR,1
ADDR: .space 2 ;Current Memory address
TOSEND: .space 2
NUM: .space 2
RDATA: .space 2
OUTWORD: .space 2
call _spi_init
mov #0xFFFF,W0
mov W0,NUM
;WREN:
call cslow
mov #WREN,W0
mov W0,OUTWORD
call output
call cshigh
call cslow
mov #WRINS,W0
mov W0,OUTWORD
call output
;Write address:
mov ADDR,W0 ;MSB of address
swap W0
mov W0,OUTWORD
call output
mov ADDR,W0 ;LSB of address
mov W0,OUTWORD
call output
;Write data
mov NUM,W0 ;This would write only LSB
mov W0,OUTWORD
call output
call cshigh
;Polling:
poll:
call cslow
mov #RDSR,W0
mov W0,OUTWORD
call output
mov #0x0000,W0 ;Dummy send to read
mov W0,OUTWORD
call output
mov RDATA,W0
and #0x0001,W0 ;Is WIP bit clear?
bra nz,poll
call cshigh
send:
clr ADDR
memrd1:
call cslow
mov #RDINS,W0
mov W0,OUTWORD
call output
;Write address:
mov ADDR,W0 ;address MSB
swap W0
mov W0,OUTWORD
call output
mov ADDR,W0 ;address LSB
mov W0,OUTWORD
call output
mov #0x00,W0 ;Dummy write to retain clock
mov W0,OUTWORD
call output
call cshigh
mov RDATA,W0
mov W0,TOSEND
;Send to PC via UART
call chktr
mov TOSEND,W0
mov W0,U1TXREG
swap W0
call chktr
mov W0,U1TXREG
done:
bra done
;..............................................................................
;Subroutine: SPI Initialization
;..............................................................................
_spi_init:
mov #0x013E,W0 ;SS not used anyway
;SDO pin controlled by module
;Communication byte-wide
;Input sampled at middle of data output line
;CKE = 1: Output data changes on transition from CLK active to idle
;CKP = 0: Idle state for CLK at low level
;Master enable, scale: fsck = fcy/4 = 1MHz
mov W0,SPI1CON
bclr SPI1STAT,#SPIROV
bset SPI1STAT,#SPIEN
clr ADDR ;Set first memory address to write to: 0x0000
return
;Sending instructions to EEPROM
output:
mov OUTWORD,W8
mov W8,SPI1BUF
chktrans: ;Is transmit buffer empty??
mov SPI1STAT,W2
and #0x0002,W2
bra nz,chktrans
chkrd:
mov SPI1STAT,W2
and #0x0001,W2 ;Is receive buffer full?
bra z,chkrd
mov SPI1BUF,W8 ;Dump received data
mov W8,RDATA
bclr SPI1STAT,#SPIROV
return
cslow:
bclr PORTB,#RB2
return
cshigh:
bset PORTB,#RB2
return
chktr:
;Check if UART transmit buffer is full
mov U1STA,W2
and #0x0200,W2
bra nz,chktr
return