arduino / arduino/ArduinoCore-avr

Wire: Inapporitate TWBR causes Integer Underflow if F_CPU < 1.8 MHz

Open
#119 1 comment 1 reaction 0 assignees View on GitHub
Dominant language
C
Stars
1.5k
Forks
1.1k
PR merge metrics
No merged PRs in 30d

Description

On the Arduino development platform, the high-level TwoWire interface is provided by the Wire library, which itself depends on the underlying code `utility/twi.c` to manipulate the microcontroller hardware. During initialization, TWI frequency prescaler (`TWBR`) is calculated and programmed to set SCL clock run at 100 KHz in `twi_init()` and `twi_setFrequency()` according to this formula:

TWBR = ((F_CPU / TWI_FREQ) - 16) / 2;

Where `F_CPU` is CPU frequency and `TWI_FREQ` is the target SCL frequency, default to 100 kHz under all circumstances.

However, it is flawed. If `F_CPU` is at 1 MHz, a negative value, `-3` will be calculated and set as the frequency prescaler. All frequencies that are slower than 1.8 MHz results an integer underflow, and program `TWBR` to a large value, causing extremely slow SCL frequency which affects usability of the bus.

The recommanded solution is to lower `TWI_FREQ` to the largest possible value under a low CPU frequency instead of trying 100 kHz, and provide a fallback if the formula gives unreasonable value, such as `TWBR = 2`.

We also need to ensure `TWBR` is not to low at other frequencies to stay within the spec, the comments stated *"TWBR should be 10 or higher for master mode"*, but I haven't checked the datasheet for more information.

Contributor guide

No contributing guide indexed for this repository

Research direction

Start in utility/twi.c at twi_init() and twi_setFrequency(), where TWBR is calculated from F_CPU and TWI_FREQ. Reproduce the calculation at CPU frequencies below 1.8 MHz and review the comment about TWBR being 10 or higher against the relevant datasheet. Done means low-frequency configurations avoid integer underflow and produce an appropriate SCL setting without violating the stated constraints.

Written by the indexing model from the issue text.

Assessment

Tech stack
c
Domain
embedded-iot
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.