#include <SPI.h>
#include <LiquidCrystal_I2C.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Wire.h>
#define LCD_COLUMNS 16
#define LCD_LINES 2
#define I2C_ADDR 0x27
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_LINES);
byte error, address;
int nDevices;
void setup()
{
Wire.begin();
Serial.begin(9600);
lcd.init();
lcd.backlight();
if (!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;); // Don't proceed, loop forever
}
display.clearDisplay();
display.display();
ssdDisplay("I2C Scanner");
lcdDisplay("I2C Scanner");
delay(2000);
}
void loop()
{
byte error, address;
int nDevices;
ssdDisplay("Scanning...");
lcdDisplay("Scanning...");
nDevices = 0;
for (address = 1; address < 127; address++ )
{
// The i2c_scanner uses the return value of
// the Write.endTransmisstion to see if
// a device did acknowledge to the address.
Wire.beginTransmission(address);
error = Wire.endTransmission();
if (error == 0)
{
delay(5000);
ssdDevFound(address);
lcdDevFound(address);
nDevices++;
}
else if (error == 4)
{
}
}
delay(5000); // wait 5 seconds for next scan
}
void ssdDisplay(String msg) {
display.clearDisplay();
display.setFont();
display.setTextSize(1); // Normal 1:1 pixel scale
display.setTextColor(WHITE); // Draw white text
display.setCursor(0, 20); // Start at top-left corner
display.cp437(true); // Use full 256 char 'Code Page 437' font
display.println(msg);
display.display();
}
void lcdDisplay(String msg) {
lcd.clear();
lcd.println(msg);
}
void ssdDevFound(byte address) {
display.clearDisplay();
display.setFont();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0, 10);
display.cp437(true);
display.print("I2C Device Found");
display.setCursor(0, 20);
display.print("Address ");
display.print(address, HEX);
display.display();
}
void lcdDevFound(byte address) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("I2C Device Found!");
lcd.setCursor(0, 1);
lcd.print("Address ");
lcd.print(address, HEX);
}