Skip to main content

Arduino - I2C Discovery

· One min read

This tutorial explains how to discover i2c devices such as the SSD1306 and GY-21P.

From a high level overview, i2c allows to create a signal line of communication between multiple devices without having to physically address them. This is extremely useful for projects that might not have many ports on the device, but need to manage multiple peripherals.

Supplies

  • (1) esp8266
  • (1) GY-21
  • (1) SSD1306
  • (6) Jumper wires

Setup

Coding

For this project, we are using the following libraries:

  1. Adafruit_SSD1306

Flash settings

  • Board: NodeMCU 1.0 (ESP-12E Module)
  • CPU Frequency: 80MHZ
  • Upload Speed: 115200
info

In the example below you can see a line for display.begin(SSD1306_SWITCHCAPVCC, 0x3C). 0x3C is the address that we are going to communicate with the display over i2c! We can discover other devices and use i2c to display that via our screen!

#include <Wire.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

void setup() {
Serial.begin(115200);

Wire.begin(D1, D2);

if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;);
}

display.clearDisplay();
display.setTextColor(WHITE);
}

void Scanner() {
Serial.println();
Serial.println("I2C scanner. Scanning ...");
byte count = 0;

display.setTextSize(.75);
display.setCursor(0, 0);
display.println("Found Addresses:");

Wire.begin();
for (byte i = 8; i < 120; i++) {
Wire.beginTransmission(i); // Begin I2C transmission Address (i)
if (Wire.endTransmission() == 0) // Receive 0 = success (ACK response)
{
display.print(i, DEC);
display.print(" (0x");
display.print(i, HEX); // PCF8574 7 bit address
display.println(")");

Serial.print("Found address: ");
Serial.print(i, DEC);
Serial.print(" (0x");
Serial.print(i, HEX); // PCF8574 7 bit address
Serial.println(")");
count++;
}
}
Serial.print("Found ");
Serial.print(count, DEC); // numbers of devices
Serial.println(" device(s).");

display.display();
}

void loop() {
Scanner();
delay(3000);
}
info

Once you flash you should see the following output on your SSD1306 screen.