Read ambient light with an LDR (photoresistor) and show it as a live percentage and bar graph on the OLED - a standalone light meter.
Wiring:
OLED -> VCC=3V3, GND=GND, SDA=GPIO4, SCL=GPIO5
LDR -> 3V3 to one leg of the LDR; GPIO0 to the LDR/10k junction; GND to the other leg of the 10k resistor
Bright light -> higher reading. Libraries: Adafruit SSD1306, Adafruit GFX.
Copy Download .ino
#include <Wire.h> // I2C for the OLED
#include <Adafruit_GFX.h> // graphics functions
#include <Adafruit_SSD1306.h> // OLED driver
Adafruit_SSD1306 display(128, 64, &Wire, -1); // 128x64 OLED over I2C
#define LDR 0 // LDR/10k junction on GPIO0 (an ADC pin)
void setup() {
Serial.begin(115200); // Serial for debugging
Wire.begin(4, 5); // OLED I2C on GPIO4/GPIO5
display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // start OLED at 0x3C
}
void loop() {
int raw = analogRead(LDR); // 0 (dark) .. 4095 (bright)
int pct = map(raw, 0, 4095, 0, 100); // rescale to 0..100 %
display.clearDisplay(); // erase previous frame
display.setTextColor(SSD1306_WHITE);
display.setTextSize(1); // small label
display.setCursor(0, 0);
display.println("Light Level");
display.setTextSize(3); // big value font
display.setCursor(0, 18);
display.printf("%d%%", pct); // percentage
// progress bar: outline + fill proportional to pct
display.drawRect(0, 52, 128, 10, SSD1306_WHITE);
display.fillRect(0, 52, map(pct, 0, 100, 0, 128), 10, SSD1306_WHITE);
display.display(); // push to screen
Serial.printf("Light: %d%% (raw %d)\n", pct, raw);
delay(250); // 4 updates/sec
}