Sub topic 2
Standard, Fast and Other Bus Speeds
This chapter assumes you know Arduino sketch structure (setup() and loop()), the Serial Monitor, and hexadecimal numbers. You should already have at least one I2C device wired to SDA and SCL.
Speed modes
The clock line, SCL, sets how fast bits move across the bus. The I2C specification defines several modes:
| Mode | Clock rate | Typical use |
|---|---|---|
| Standard | 100 kHz | Default on most Arduino boards |
| Fast | 400 kHz | Most modern sensors and displays |
| Fast-mode Plus | 1 MHz | Devices with strong bus drivers |
| High-speed | 3.4 MHz | Devices that explicitly support it |
Faster clocks shorten each transaction, but they leave less margin. Pull-up resistors must pull the lines high quickly, so long or heavily loaded wires can fail at 400 kHz even though they work at 100 kHz.
Using the Wire library
The Wire library handles the protocol. Call Wire.begin() once to join the bus as a controller, then call Wire.setClock() to set the speed.
#include <Wire.h>
void setup() {
Serial.begin(9600);
Wire.begin();
Wire.setClock(400000); // 400 kHz Fast mode
}
void loop() {
}Finding devices with a bus scanner
A scanner tries each 7-bit address and reports the ones that acknowledge. endTransmission() returns 0 when a device answers.
#include <Wire.h>
void setup() {
Serial.begin(9600);
Wire.begin();
Wire.setClock(100000);
}
void loop() {
for (byte address = 1; address < 127; address++) {
Wire.beginTransmission(address);
if (Wire.endTransmission() == 0) {
Serial.print("Device found at 0x");
if (address < 16) Serial.print('0');
Serial.println(address, HEX);
}
}
Serial.println("Scan done");
delay(5000);
}Reading and writing registers
Most sensors expose data in numbered registers. To read one, write the register number, then request the bytes. Using endTransmission(false) keeps the bus open with a repeated START.
#include <Wire.h>
bool readRegister16(uint8_t address, uint8_t reg, uint16_t &value) {
Wire.beginTransmission(address);
Wire.write(reg);
if (Wire.endTransmission(false) != 0) return false;
if (Wire.requestFrom(address, (uint8_t)2) != 2) return false;
value = (uint16_t)Wire.read() << 8;
value |= Wire.read();
return true;
}Exercise
A sensor fails at 400 kHz but works at 100 kHz. Name two physical causes to check.
Show answer
Long or heavy wiring that adds capacitance, and pull-up resistors that are too large to pull the lines high in time.