I2C Communication with Arduino
Clarus Goldsmith, June 2024
Last updated
Clarus Goldsmith, June 2024
Last updated
The physical interface of I2C has two lines: SDA and SCL. SCL (Serial Clock) is the bus master's clock signal, and SDA (Serial Data) is the data signal.
All Arduino boards have two pins that function as SCL and SDA.
For the OpenCM, SCL is D24 and SDA is D25.
Because I2C relies on pulling the voltage down to communicate, you need to supply voltage to the lines using pull-up resistors. Otherwise there's no voltage to pull down, and the communication won't work. I recommend placing the resistors directly connecting to the input pins of whatever device you're communicating with.
The resistance value required will vary depending on the communication speed you're using. I2C has four possible speeds:
Standard
100 Kbit/s
Full Speed
400 Kbit/s
Fast
1 Mbit/s
High Speed
3.2 Mbit/s
For standard speed with a single device, I have found that 2kΩ resistors work well. For multiple devices, a lower resistance might be required.
Wire comes pre-installed with Arduino.
To use, must include this line at the start of the code, before setup:
During setup, include:
A write command to a device using Wire should always be in the form:
Where address
and value
are variables set by the user. This block of code functions as follows:
Line 1: Begins assembling the command signal for the device of address address
on the I2C bus.
Line 2: Instruction bit; tells the peripheral (formerly known as 'slave') device this is a write command. To specify a read command instead, replace with a 1. However, read commands generally do not follow the same structure as write commands. See the Arduino reference materials on the requestFrom()
command for more details.
Line 3: The commanded value (e.g., the wiper value for a digital potentiometer). Must be given in binary, which is what the byte() function does in this line.
Line 4: Ends the command and sends it. The errorID
variable stores the return message from endTransmission()
, which is an integer between 0-5. A return of 0 indicates the command was received successfully. Otherwise, some sort of error occurred. Consult the Arduino reference materials to determine exactly what went wrong if receiving an error between 1-5.