Skip to content

Instantly share code, notes, and snippets.

@Tech500
Last active April 26, 2023 14:05
Show Gist options
  • Save Tech500/95f9d0d96d2320a40fd1d13272665418 to your computer and use it in GitHub Desktop.
Save Tech500/95f9d0d96d2320a40fd1d13272665418 to your computer and use it in GitHub Desktop.
/*
Developed by William Lucid with assist from OpenAI's, ChatGPT
04/26/2023
*/
#include "esp_sleep.h"
int switchPin = 27; // Use GPIO27 for the switch pin
int switchState = HIGH; // Current state of the switch
int lastSwitchState = HIGH; // Last state of the switch
unsigned long lastDebounceTime = 0; // Time since last switch debounce
unsigned long debounceDelay = 50; // Delay for switch debouncing
bool switchDetected = false; // Flag for switch detection
RTC_DATA_ATTR unsigned long currentSleepTime = 0;
RTC_DATA_ATTR unsigned long lastSleepTime = 0;
RTC_DATA_ATTR unsigned long elapsed = 0;
void IRAM_ATTR gotSwitch() {
switchDetected = true;
}
void setup() {
Serial.begin(9600);
while(! Serial){}
Serial.println("Ready");
// Configure external wakeup source
pinMode(switchPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(switchPin), gotSwitch, FALLING);
// Configure sleep mode
esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_ON);
esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_SLOW_MEM, ESP_PD_OPTION_ON);
esp_sleep_enable_ext1_wakeup(1ULL << switchPin, ESP_EXT1_WAKEUP_ANY_HIGH);
}
void loop() {
// Read the current state of the switch and debounce it
int reading = digitalRead(switchPin);
if (reading != lastSwitchState) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading != switchState) {
switchState = reading;
if (switchState == LOW) {
switchDetected = true;
}
}
}
lastSwitchState = reading;
// If the switch has been detected, print the elapsed sleep time
if (switchDetected) {
switchDetected = false;
Serial.println("Wakeup enabled");
currentSleepTime = micros();
float elapsed = (currentSleepTime - lastSleepTime) / 1000000.0;
Serial.println("Sleep time: " + String(elapsed) + " Seconds");
lastSleepTime = currentSleepTime;
Serial.println("Going to Deep Sleep...");
esp_deep_sleep_start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment