SPI Programming For AVR Microcontrollers

published: 23 November 2024 / updated 23 November 2024

Lire cette page en français

 

SPI Programming For AVR Microcontrollers

article: 31 oct. 2019 / mis à jour 31 oct. 2019

The SPI interface has already been used in this article: The SPI interface: management of an 8x8 LEDS display

Here is a video that explains the communication on SPI port between two ARDUINO NANO cards:

Listing appearing in the video:

\ SS    Pin10
\ MOSI  Pin11
\ MISO  Pin12
\ SCK   pin13
 
$4c constant SPCR  \ control reg
$4d constant SPSR  \ status reg
$4e constant SPDR  \ data reg
 
: SPI.enable    bit6 SPCR set ;
: SPI.disable   bit6 SPCR reset ;
 
: LSB.first   bit5 SPCR set ;
: MSB.first   bit5 SPCR reset ;
 
: Master.mode bit4 SPCR set ;
: Slave.mode  bit4 SPCR reset ;
 
\ SPI mode
 
: Mode0       bit3 SPCR reset   \ Idle CLK = 0
              bit2 SPCR reset ; \ Sample on leading edge
 
: Mode1       bit3 SPCR reset   \ Idle CLK = 0
              bit2 SPCR set   ; \ Sample on trailing edge
 
: Mode2       bit3 SPCR set     \ Idle CLK = 1
              bit2 SPCR reset ; \ Sample on trailing edge
 
: Mode3       bit3 SPCR set     \ Idle CLK = 1
              bit2 SPCR set   ; \ Sample on leading edge
 
\ SPI clock speed
 
: fosc/4      bit1 SPCR reset
              bit0 SPCR reset
              bit0 SPSR reset ;
 
: fosc/16     bit1 SPCR reset
              bit0 SPCR set
              bit0 SPSR reset ;
 
: fosc/64     bit1 SPCR set
              bit0 SPCR reset
              bit0 SPSR reset ;
 
: fosc/128    bit1 SPCR set
              bit0 SPCR set
              bit0 SPSR reset ;
 
: Wait.for.SPIF
                begin bit7 SPSR set? until ;
 
: SPI.write   \ SPI write and read happens together
                SPDR c!
                Wait.for.SPIF
                SPDR c@ ;
 
: Init.SPI
            SPCR clear
            Master.mode \ set master mode first then SPI.enable
            MSB.first
            Mode0
            fosc/64
            pin10 output  \ SS pin output when master
            pin13 output  \ CLK
            pin11 output  \ MO
            SPI.enable ;
 
: test      Init.SPI
            begin
                key
                SPI.write
                drop
            again ;