Skip to content
systemcoding.dev
Embedded

Set the Arduino I2C clock to 400 kHz with Wire.setClock

Raise the Arduino I2C bus to 400 kHz by calling Wire.setClock(400000) after Wire.begin, and see what TWBR holds on a 16 MHz ATmega328P.

1 min read
Summarize in AI

The default Wire clock is 100 kHz. Most sensors and OLED controllers accept 400 kHz Fast-mode, which cuts the time of a full-screen update by about a factor of four. Call Wire.setClock() after Wire.begin(), because begin() resets the speed.

cpp
#include <Wire.h>

void setup() {
  Serial.begin(115200);
  Wire.begin();
  Serial.print("TWBR at 100 kHz: ");
  Serial.println(TWBR);
  Wire.setClock(400000);
  Serial.print("TWBR at 400 kHz: ");
  Serial.println(TWBR);
}

void loop() {}

On an Uno with the AVR core 1.8.x, the bit rate register follows TWBR = (F_CPU / freq - 16) / 2 with the prescaler at 1, so 16 MHz gives these values:

Text
TWBR at 100 kHz: 72
TWBR at 400 kHz: 12

Every device on the bus must support Fast-mode, or the slowest one sets the limit. Fast-mode also asks for a faster rise time, 300 ns against 1000 ns in the I2C-bus specification, so pull-ups that were fine at 100 kHz may now be too weak. If readings turn to garbage after the change, check the pull-ups before blaming the code.

Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.