Skip to content

Instantly share code, notes, and snippets.

@sixtyfive
Last active November 12, 2018 23:45
Show Gist options
  • Save sixtyfive/102347005f740ff16594b466ce9bff81 to your computer and use it in GitHub Desktop.
Save sixtyfive/102347005f740ff16594b466ce9bff81 to your computer and use it in GitHub Desktop.
Measure brightness with an ESP32 for fun but not for profit
#include <limits.h> // allow use of ranges in switch-case statements (1 ... 2, etc.)
#include "RunningAverage.h"
#define POWER_SUPPLY 3.3 // volts
#define ADC_MAX_VAL 4095 // 12 bits of resolution
#define ADC_MAX_V POWER_SUPPLY // some docs say not to go higher than 1V, some say 3V3 is fine
#define LED0 2
#define LED1 19
#define LED2 21
#define LED3 22
#define PHOTO_RESISTOR A14
RunningAverage voltage_ra(10);
int samples = 0;
int led_state = 0;
unsigned long interval = 250; // milliseconds
unsigned long current_interval = 0;
void printDebuggingInfo() {
unsigned long current_milliseconds = millis();
if ((current_milliseconds - current_interval) >= interval)
{ Serial.println(voltage_ra.getAverage()); current_interval = millis(); }
}
void setup() {
pinMode(LED0, OUTPUT);
digitalWrite(LED0, LOW);
pinMode(PHOTO_RESISTOR, INPUT);
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
pinMode(LED3, OUTPUT);
Serial.begin(115200);
Serial.println("ADC-Test / Fancy 'Hello World' for Shri");
}
void getBrightness() {
int adcValue = analogRead(PHOTO_RESISTOR);
float V = adcValue * POWER_SUPPLY / ADC_MAX_VAL;
voltage_ra.addValue(V);
samples++;
int state = led_state;
if (samples >= 10) {
int mV = (int)(voltage_ra.getAverage() * 1000); // switch only works with integers
switch(mV) {
case 0 ... 890: state = 0; break;
case 891 ... 1990: state = 1; break;
case 1991 ... 3000: state = 2; break;
case 3001 ... (int)(ADC_MAX_V * 1000): state = 3; break;
}
}
led_state = state;
}
void setLEDCascadeState() {
switch (led_state) {
case 0:
digitalWrite(LED1, LOW);
digitalWrite(LED2, LOW);
digitalWrite(LED3, LOW);
break;
case 1:
digitalWrite(LED1, HIGH);
digitalWrite(LED2, LOW);
digitalWrite(LED3, LOW);
break;
case 2:
digitalWrite(LED1, HIGH);
digitalWrite(LED2, HIGH);
digitalWrite(LED3, LOW);
break;
case 3:
digitalWrite(LED1, HIGH);
digitalWrite(LED2, HIGH);
digitalWrite(LED3, HIGH);
break;
}
}
void loop() {
getBrightness();
setLEDCascadeState();
printDebuggingInfo();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment