This is the quick start guide for the SPI - Serial Peripheral Interface, with step-by-step instructions on how to configure and use the driver for a specific use case.
The code examples can be copied into e.g the main application loop or any other function that will need to control the SPI
Basic setup
The SPI module will be set up as master:
- SPI on module SPI0
- 1MHz SPI clock speed
- Slave Chip Select connected on NPCS1
- 8 bits per transfer
- SPI mode 0 (data on rising clock edge)
Prerequisites
This module requires the following drivers
Setup steps
Example code
Add to application C-file (e.g. main.c):
#define SPI_EXAMPLE (&AVR32_SPI0)
#define SPI_SLAVECHIP_NUMBER (1)
SPI_SLAVECHIP_NUMBER,
1000000,
8,
periods).
0,
0,
1,
another
1
};
void spi_init_module(void)
{
}
Workflow
- Ensure that board_init() has configured selected I/Os for SPI function.
- Ensure that sysclk_init() is called at the beginning of the main function.
- Define an alias for the SPI module you want to use :
#define SPI_EXAMPLE (&AVR32_SPI0)
- Define an alias for the slave device SPI module you want to use :
#define SPI_SLAVECHIP_NUMBER (1)
- Create an spi_options_t structure for the your slave device : This configure the SPI module to suit the SPI format of the slave device you want to communicate with
SPI_SLAVECHIP_NUMBER,
1000000,
8,
0,
0,
1,
1
};
- Write the initialization function to setup the module :
void spi_init_module(void)
{
}
- Note
- The last argument of spi_setupChipReg, is the PBA Clock frequency This frequency is given by the sysclk module and is used to compute the correct baudrate for the SPI.
- Call the initialization routine from your application.
Usage steps
Example code
Use in application C-file:
uint16_t txdata;
uint16_t rxdata;
...
spi_selectChip(SPI_EXAMPLE, SPI_SLAVECHIP_NUMBER);
;
txdata=0xD7;
;
txdata=0x00;
;
Workflow
- Create two buffers for data to be sent/received on the SPI bus,
uint16_t txdata;
uint16_t rxdata;
- Call the spi_selectChip routine to enable the chip select line for the slave you want to communicate with.
- Wait for the SPI transmitter to be ready before sending data
- Set and send the data to slave txdata is set 0xD7 (= AT45DBX_CMDC_RD_STATUS_REG) which is a status read command to an Atmel SPI memory chip.
- Then wait for the data to be sent by SPI module
- As the SPI works as a shift register, data is shifted in at the same time as data is shifted out. A read operation will mean that a dummy byte is written to the SPI bus and data is read at the same time. As we are sending, we have to check again for the SPI module to be ready before sending and also check for the completion of this send operation.
- Now the dummy data is sent the value of the receive register is the data from slave
- When read and write operations is done, de-select the slave:
- Now you can use the data read from the slave which is in rxdata
if(rxdata<0x3C)
do_something();