arduino / ArduinoCore-samd

Arduino Core for SAMD21 CPU
GNU Lesser General Public License v2.1
467 stars 715 forks source link

Where does the formula of BAUD comes from in SERCOM::initMasterWIRE( uint32_t baudrate ) #719

Open rawlines opened 1 month ago

rawlines commented 1 month ago

I've read in SAMD21 datasheet that the frequency generated for the I2C SCL line depends on the BAUD register.

Accoring to the documentation, this field should be generated using the following ecuations:

Bits 7:0 – BAUD[7:0] Master Baud Rate This bit field is used to derive the SCL high time if BAUD.BAUDLOW is non-zero. If BAUD.BAUDLOW is zero, BAUD will be used to generate both high and low periods of the SCL. For more information on how to calculate the frequency, see SERCOM 25.6.2.3 Clock Generation – Baud-Rate Generator.

I've seen in the code inside this method that clock frequency is generated using the following line:

// Synchronous arithmetic baudrate
  sercom->I2CM.BAUD.bit.BAUD = SystemCoreClock / ( 2 * baudrate) - 5 - (((SystemCoreClock / 1000000) * WIRE_RISE_TIME_NANOSECONDS) / (2 * 1000));

I was willing to know where this ecuation comes from as in the documentation says that for Synchronous baudrate the following ecuation should be used: image

From that point of view, should that line be something like this?:

// Synchronous arithmetic baudrate
  sercom->I2CM.BAUD.bit.BAUD = SystemCoreClock / ( 2 * baudrate) - 1;

The datasheet: https://ww1.microchip.com/downloads/en/DeviceDoc/SAM_D21_DA1_Family_DataSheet_DS40001882F.pdf, page 412-413

rawlines commented 1 month ago

Ok, i've found htat the existing forumula is the result of clearing the BAUD variable in the following equation:

image

The result after clearing is:

sercom->I2CM.BAUD.bit.BAUD = SystemCoreClock / (2 * baudrate) - 5 - ((SystemCoreClock * WIRE_RISE_TIME_NANOSECONDS) / 2);

I'll assume that you are dividing by 1000000 SysctemCoreClock and then multiplying by 1000 for unit conversion purposes, But another thing. This formula will work only if BAUD.BAUDLOW is 0, is it worth it to add the following line before the formula?

sercom->I2CM.BAUD.bit.BAUDLOW = 0;