Skip to content

Commit 4b850e2

Browse files
authored
Merge pull request #3759 from LMESTM/fix_spi_freq
STM32: spi_frequency table index fix
2 parents 3c3e04f + a8f6970 commit 4b850e2

File tree

1 file changed

+12
-7
lines changed

1 file changed

+12
-7
lines changed

targets/TARGET_STM/stm_spi_api.c

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -291,23 +291,28 @@ void spi_frequency(spi_t *obj, int hz) {
291291
struct spi_s *spiobj = SPI_S(obj);
292292
int spi_hz = 0;
293293
uint8_t prescaler_rank = 0;
294+
uint8_t last_index = (sizeof(baudrate_prescaler_table)/sizeof(baudrate_prescaler_table[0])) - 1;
294295
SPI_HandleTypeDef *handle = &(spiobj->handle);
295296

296-
/* Get the clock of the peripheral */
297-
spi_hz = spi_get_clock_freq(obj);
297+
/* Calculate the spi clock for prescaler_rank 0: SPI_BAUDRATEPRESCALER_2 */
298+
spi_hz = spi_get_clock_freq(obj) / 2;
298299

299300
/* Define pre-scaler in order to get highest available frequency below requested frequency */
300-
while ((spi_hz > hz) && (prescaler_rank < sizeof(baudrate_prescaler_table)/sizeof(baudrate_prescaler_table[0]))){
301+
while ((spi_hz > hz) && (prescaler_rank < last_index)) {
301302
spi_hz = spi_hz / 2;
302303
prescaler_rank++;
303304
}
304305

305-
if (prescaler_rank <= sizeof(baudrate_prescaler_table)/sizeof(baudrate_prescaler_table[0])) {
306-
handle->Init.BaudRatePrescaler = baudrate_prescaler_table[prescaler_rank-1];
307-
} else {
308-
error("Couldn't setup requested SPI frequency");
306+
/* Use the best fit pre-scaler */
307+
handle->Init.BaudRatePrescaler = baudrate_prescaler_table[prescaler_rank];
308+
309+
/* In case maximum pre-scaler still gives too high freq, raise an error */
310+
if (spi_hz > hz) {
311+
error("Couldn't set suitable spi freq: request:%d, lowest:%d\r\n", hz, spi_hz);
309312
}
310313

314+
DEBUG_PRINTF("spi_frequency, request:%d, select:%d\r\n", hz, spi_hz);
315+
311316
init_spi(obj);
312317
}
313318

0 commit comments

Comments
 (0)