mirror of https://github.com/ARMmbed/mbed-os.git
STM32: spi_frequency table index fix
In case of prescaler_rank was 0, a -1 index was being used, which resulted in initialization of the Init.BaudRatePrescaler with random values. Now let's better check index and avoid -1 operation, so that prescaler_rank can be only from 0 to "last_index".pull/3759/head
parent
65956d108e
commit
a8f6970a9d
|
@ -291,23 +291,28 @@ void spi_frequency(spi_t *obj, int hz) {
|
||||||
struct spi_s *spiobj = SPI_S(obj);
|
struct spi_s *spiobj = SPI_S(obj);
|
||||||
int spi_hz = 0;
|
int spi_hz = 0;
|
||||||
uint8_t prescaler_rank = 0;
|
uint8_t prescaler_rank = 0;
|
||||||
|
uint8_t last_index = (sizeof(baudrate_prescaler_table)/sizeof(baudrate_prescaler_table[0])) - 1;
|
||||||
SPI_HandleTypeDef *handle = &(spiobj->handle);
|
SPI_HandleTypeDef *handle = &(spiobj->handle);
|
||||||
|
|
||||||
/* Get the clock of the peripheral */
|
/* Calculate the spi clock for prescaler_rank 0: SPI_BAUDRATEPRESCALER_2 */
|
||||||
spi_hz = spi_get_clock_freq(obj);
|
spi_hz = spi_get_clock_freq(obj) / 2;
|
||||||
|
|
||||||
/* Define pre-scaler in order to get highest available frequency below requested frequency */
|
/* Define pre-scaler in order to get highest available frequency below requested frequency */
|
||||||
while ((spi_hz > hz) && (prescaler_rank < sizeof(baudrate_prescaler_table)/sizeof(baudrate_prescaler_table[0]))){
|
while ((spi_hz > hz) && (prescaler_rank < last_index)) {
|
||||||
spi_hz = spi_hz / 2;
|
spi_hz = spi_hz / 2;
|
||||||
prescaler_rank++;
|
prescaler_rank++;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (prescaler_rank <= sizeof(baudrate_prescaler_table)/sizeof(baudrate_prescaler_table[0])) {
|
/* Use the best fit pre-scaler */
|
||||||
handle->Init.BaudRatePrescaler = baudrate_prescaler_table[prescaler_rank-1];
|
handle->Init.BaudRatePrescaler = baudrate_prescaler_table[prescaler_rank];
|
||||||
} else {
|
|
||||||
error("Couldn't setup requested SPI frequency");
|
/* In case maximum pre-scaler still gives too high freq, raise an error */
|
||||||
|
if (spi_hz > hz) {
|
||||||
|
error("Couldn't set suitable spi freq: request:%d, lowest:%d\r\n", hz, spi_hz);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
DEBUG_PRINTF("spi_frequency, request:%d, select:%d\r\n", hz, spi_hz);
|
||||||
|
|
||||||
init_spi(obj);
|
init_spi(obj);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue