/* Grade 9: campus light-alert MODEL - classic ESP32 only. Teacher must confirm the exact development board and labelled GPIOs. LDR divider: 3V3 -> LDR -> junction -> 10 kohm resistor -> GND. Connect that junction to GPIO34. Darker -> higher LDR resistance -> lower ADC. GPIO25 -> 330 ohm resistor -> LED anode (+); LED cathode (-) -> GND. USB powers the development board. Never put 5 V or mains on any GPIO. If no LDR is available: REMOVE the complete LDR/resistor divider and use a 10 kohm potentiometer: outside terminals to 3V3/GND, wiper to GPIO34. Set SIMULATED_INPUT=true and label all resulting evidence SIMULATED INPUT. A potentiometer demonstrates the algorithm; it does not measure light. Serial Monitor: 115200 baud. Copy the CSV header and rows into a spreadsheet. Values are uncalibrated ADC counts, NOT lux. No Wi-Fi or extra library needed. */ #include constexpr uint8_t LED_PIN = 25; constexpr uint8_t SENSOR_PIN = 34; // ADC1_CH6; input only, no internal pull-up. constexpr bool SIMULATED_INPUT = false; // EXAMPLES ONLY. Measure your own "dark" and "bright" readings first. // Choose two thresholds between those readings; ON must be lower than OFF. constexpr int ALERT_ON_BELOW = 1400; constexpr int ALERT_OFF_ABOVE = 1800; static_assert(0 <= ALERT_ON_BELOW && ALERT_ON_BELOW < ALERT_OFF_ABOVE && ALERT_OFF_ABOVE <= 4095, "Use 0 <= ON threshold < OFF threshold <= 4095"); constexpr uint32_t SAMPLE_INTERVAL_MS = 100; constexpr uint8_t SAMPLES_PER_READING = 8; bool alertOn = false; // If startup is inside the hysteresis band, start OFF. uint32_t lastSampleAt = 0; int readAverage() { uint32_t total = 0; for (uint8_t i = 0; i < SAMPLES_PER_READING; ++i) { total += analogRead(SENSOR_PIN); } return int(total / SAMPLES_PER_READING); } void setup() { pinMode(LED_PIN, OUTPUT); digitalWrite(LED_PIN, LOW); pinMode(SENSOR_PIN, INPUT); analogReadResolution(12); // Raw counts 0..4095. analogSetPinAttenuation(SENSOR_PIN, ADC_11db); // Classic ESP32's specified measurement range at this attenuation is // approximately 0.15..3.10 V. Near 0 or 3.3 V readings may saturate. Serial.begin(115200); Serial.println("time_ms,input_mode,adc_avg,on_threshold,off_threshold,led_on"); lastSampleAt = millis(); } void loop() { const uint32_t now = millis(); if (uint32_t(now - lastSampleAt) < SAMPLE_INTERVAL_MS) { return; } lastSampleAt = now; const int reading = readAverage(); // Hysteresis: keep the previous state between OR exactly on the thresholds. if (!alertOn && reading < ALERT_ON_BELOW) { alertOn = true; } else if (alertOn && reading > ALERT_OFF_ABOVE) { alertOn = false; } digitalWrite(LED_PIN, alertOn ? HIGH : LOW); Serial.print(now); Serial.print(','); Serial.print(SIMULATED_INPUT ? "SIMULATED_INPUT" : "LDR"); Serial.print(','); Serial.print(reading); Serial.print(','); Serial.print(ALERT_ON_BELOW); Serial.print(','); Serial.print(ALERT_OFF_ABOVE); Serial.print(','); Serial.println(alertOn ? 1 : 0); }