From 26d33658ead77388cdcd261d9ad2ad679bb5cdad Mon Sep 17 00:00:00 2001 From: Jeff Epler Date: Fri, 20 Aug 2021 14:05:40 -0500 Subject: [PATCH] samd: diagnose out of range I2C frequency The frequency divisor is limited to 255, which gives 48MHz/2/255 ~= 94.1kHz as the lowest speed. Without this change, values below this cut-off gave higher frequencies instead, which didn't appear to have any relation to the frequency value requested. Closes: #4883 --- ports/atmel-samd/common-hal/busio/I2C.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/ports/atmel-samd/common-hal/busio/I2C.c b/ports/atmel-samd/common-hal/busio/I2C.c index d5a8f36f6a..39aa6c9e97 100644 --- a/ports/atmel-samd/common-hal/busio/I2C.c +++ b/ports/atmel-samd/common-hal/busio/I2C.c @@ -119,6 +119,13 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, // clkrate is always 0. baud_rate is in kHz. // Frequency must be set before the I2C device is enabled. + // The maximum frequency divisor gives a clock rate of around 48MHz/2/255 + // but set_baudrate does not diagnose this problem. (This is not the + // exact cutoff, but no frequency well under 100kHz is available) + if (frequency < 95000) { + mp_raise_ValueError(translate("Unsupported baudrate")); + } + if (i2c_m_sync_set_baudrate(&self->i2c_desc, 0, frequency / 1000) != ERR_NONE) { reset_pin_number(sda->number); reset_pin_number(scl->number);