added spi hal functions

This commit is contained in:
Robin Müller 2021-06-03 14:03:38 +02:00
parent 22384aec6a
commit dc6327b909
No known key found for this signature in database
GPG Key ID: 71B58F8A3CDFA9AC
3 changed files with 35 additions and 1 deletions

View File

@ -21,7 +21,7 @@ GyroL3GD20H::GyroL3GD20H(SPI_HandleTypeDef *spiHandle): spiHandle(spiHandle) {
ReturnValue_t GyroL3GD20H::initialize() { ReturnValue_t GyroL3GD20H::initialize() {
// Configure the SPI peripheral // Configure the SPI peripheral
spiHandle->Instance = SPI1; spiHandle->Instance = SPI1;
spiHandle->Init.BaudRatePrescaler = SPI_GetPrescaler(HAL_RCC_GetHCLKFreq(), 3900000); spiHandle->Init.BaudRatePrescaler = spi::getPrescaler(HAL_RCC_GetHCLKFreq(), 3900000);
spiHandle->Init.Direction = SPI_DIRECTION_2LINES; spiHandle->Init.Direction = SPI_DIRECTION_2LINES;
spi::assignSpiMode(spi::SpiModes::MODE_3, spiHandle); spi::assignSpiMode(spi::SpiModes::MODE_3, spiHandle);
spiHandle->Init.DataSize = SPI_DATASIZE_8BIT; spiHandle->Init.DataSize = SPI_DATASIZE_8BIT;

View File

@ -24,3 +24,29 @@ void spi::assignSpiMode(SpiModes spiMode, SPI_HandleTypeDef *spiHandle) {
} }
} }
} }
uint32_t spi::getPrescaler(uint32_t clock_src_freq, uint32_t baudrate_mbps) {
uint32_t divisor = 0;
uint32_t spi_clk = clock_src_freq;
uint32_t presc = 0;
static const uint32_t baudrate[] = {
SPI_BAUDRATEPRESCALER_2,
SPI_BAUDRATEPRESCALER_4,
SPI_BAUDRATEPRESCALER_8,
SPI_BAUDRATEPRESCALER_16,
SPI_BAUDRATEPRESCALER_32,
SPI_BAUDRATEPRESCALER_64,
SPI_BAUDRATEPRESCALER_128,
SPI_BAUDRATEPRESCALER_256,
};
while( spi_clk > baudrate_mbps) {
presc = baudrate[divisor];
if (++divisor > 7)
break;
spi_clk = ( spi_clk >> 1);
}
return presc;
}

View File

@ -10,6 +10,14 @@ namespace spi {
void assignSpiMode(SpiModes spiMode, SPI_HandleTypeDef* spiHandle); void assignSpiMode(SpiModes spiMode, SPI_HandleTypeDef* spiHandle);
/**
* @brief Set SPI frequency to calculate correspondent baud-rate prescaler.
* @param clock_src_freq Frequency of clock source
* @param baudrate_mbps Baudrate to set to set
* @retval Baudrate prescaler
*/
uint32_t getPrescaler(uint32_t clock_src_freq, uint32_t baudrate_mbps);
} }