Basic setup for XMEGA devices
The SPI module will be set up as master:
- SPI on PORTD
- 1MHz SPI clock speed
- Slave Chip Select connected on PORTD pin 1
- SPI mode 0 (data on rising clock edge)
Workflow
Example code
Add to application C-file (e.g. main.c):
void spi_init_pins(void)
{
}
void spi_init_module(void)
{
};
}
Workflow
- Ensure that conf_spi_master.h is present for the driver.
- Note
- This file is only for the driver and should not be included by the user. In this example the file can be left empty.
- Initialize the pins used by the SPI interface (this initialization is for the ATxmega32A4U device).
- Set the pin used for slave select as output high:
- Enable pull-up on own chip select (SS):
- Attention
- If this pin is pulled low the SPI module will go into slave mode.
- Set MOSI and SCL as output high, and set MISO as input:
- Define the SPI device configuration struct to describe which pin the slave select (slave chip select) is connected to, in this case the slave select pin has been connected to PORTD pin 1 (PD1):
- Initialize the SPI module, in this case SPI on PORTD has been chosen:
- Setup the SPI master module for a specific device:
- Note
- The last argument, which is zero in this case, can be ignored and is only included for compatibility purposes.
- Then enable the SPI:
Usage steps
Example code
Add to, e.g., the main loop in the application C-file:
uint8_t data_buffer[1] = {0xAA};
};
Workflow
- Create a buffer for data to be sent/received on the SPI bus, in this case a single byte buffer is used. The buffer can be of arbitrary size as long as there is space left in SRAM:
uint8_t data_buffer[1] = {0xAA};
- Define the SPI device configuration struct to describe which pin the slave select (slave chip select) is connected to, in this case the slave select pin has been connected to PORTD pin 1 (PD1):
- Note
- As this struct is the same for both the initializing part and the usage part it could be a good idea to make the struct global, and hence accessible for both the initializing part and usage part. Another solution could be to create the struct in the main function and pass the address of the struct to the spi_init_module() function, e.g.:
void spi_init_module(
struct spi_device *spi_device_conf)
{
...
...
}
- Write data to the SPI slave device, in this case write one byte from the data_buffer:
- Read data from the SPI slave device, in this case read one byte and put it into the data_buffer:
- Attention
- As the SPI works as a shift register so that data is shifted in at the same time as data is shifted out a read operation will mean that a dummy byte CONFIG_SPI_MASTER_DUMMY is written to the SPI bus. CONFIG_SPI_MASTER_DUMMY defaults to 0xFF, but can be changed by defining it inside the conf_spi_master.h file.
- When read and write operations is done de-select the slave: