Introduction
The I2C (Inter-Integrated Circuit) protocol is a popular means of communication between various sensors and devices. In this tutorial, we will learn how to create an I2C scanner using the CONTROLLINO MICRO, which is useful for detecting the I2C addresses of devices connected to your microcontroller.
Prerequisites
- Installed Arduino IDE.
- CONTROLLINO MICRO board.
Example Code
Please grab the following example .ino file from Github:
Step-by-Step Guide
Step 1: Setup the Arduino Environment
- Connect your MICRO to your computer.
- Open the Arduino IDE.
- Ensure that the appropriate board and port are selected in the Tools menu.
Step 2: Understanding the Code
The Setup Function
void setup()
{
Wire.setSDA(PIN_WIRE0_SDA);
Wire.setSCL(PIN_WIRE0_SCL);
Wire.begin();
Serial.begin(9600);
while (!Serial);
Serial.println("\nI2C Scanner");
}
Wire.setSDA()
andWire.setSCL()
: Sets the SDA (data line) and SCL (clock line) pins for I2C communication.Wire.begin()
: Initializes the I2C bus.Serial.begin(9600)
: Starts serial communication at 9600 baud rate.Serial.println("\nI2C Scanner")
: Prints a message to the Serial Monitor.
The Loop Function
void loop()
{
byte error, address;
int nDevices;
Serial.println("Scanning...");
nDevices = 0;
for (address = 1; address < 127; address++)
{
Wire.beginTransmission(address);
error = Wire.endTransmission();
if (error == 0)
{
// Device found
}
else if (error == 4)
{
// Unknown error
}
}
// Print scan results
delay(5000); // Wait for next scan
}
- Scans I2C addresses from 1 to 126.
Wire.beginTransmission(address)
: Starts transmission to a device ataddress
.error = Wire.endTransmission()
: Ends the transmission and returns an error status.- If
error
is 0, an I2C device is found. - If
error
is 4, there’s an unknown error at the address.
Step 3: Hardware Setup
- Connect your I2C device(s) to the CONTROLLINO MICRO.
- Ensure proper connections for SDA and SCL lines, along with power and ground.
Step 4: Using the I2C Scanner
- Open the Serial Monitor in the Arduino IDE.
- Set the baud rate to 9600.
- Observe the output. The scanner will list the addresses of detected I2C devices.
Step 5: Interpreting Results
- Addresses will be displayed in hexadecimal format.
- Note down the addresses of your I2C devices for use in your projects.
Conclusion
This tutorial has guided you through setting up an I2C scanner on the CONTROLLINO MICRO. This tool is invaluable for troubleshooting and setting up I2C communication with various sensors and peripherals.