Skip to content

Instantly share code, notes, and snippets.

@ashish1405
Last active March 21, 2023 09:21
Show Gist options
  • Save ashish1405/b8f81af3aadb0f9ecd5b0befea672033 to your computer and use it in GitHub Desktop.
Save ashish1405/b8f81af3aadb0f9ecd5b0befea672033 to your computer and use it in GitHub Desktop.
nodemcu esp8266 on off timer switch script
#define RTCMEMORYSTART 65
#define MAXHOUR 11 // number of hours to deep sleep for
extern "C" {
#include "user_interface.h"
}
typedef struct {
int count;
} rtcStore;
rtcStore rtcMem;
const long onInterval = 2*60*1000;
const long offInterval = 60*60;
unsigned long cm = 0;
void setup() {
// put your setup code here, to run once:
cm = millis();
Serial.begin(115200);
Serial.setTimeout(2000);
while(!Serial) { }
delay(1000);
Serial.println("");
Serial.print("Waking up...");
Serial.println(millis()-cm);
Serial.print("Reading ");
readFromRTCMemory();
Serial.print("Writing ");
writeToRTCMemory();
Serial.print("Current Count ");
Serial.println(rtcMem.count);
if (rtcMem.count == 0) {
pinMode(D4,OUTPUT);
Serial.println("Start!");
delay(100);
Serial.println(millis()-cm);
digitalWrite(D4, LOW);
delay(onInterval);
Serial.println(millis()-cm);
}
delay(100);
Serial.println("Sleep!");
ESP.deepSleep(offInterval*1000000UL, WAKE_RF_DEFAULT);
}
void readFromRTCMemory() {
system_rtc_mem_read(RTCMEMORYSTART, &rtcMem, sizeof(rtcMem));
if (rtcMem.count < 0){
rtcMem.count = 0;
system_rtc_mem_write(RTCMEMORYSTART, &rtcMem, 4);
pinMode(D4,OUTPUT);
Serial.println("Start!");
delay(100);
digitalWrite(D4, LOW);
delay(onInterval);
}
Serial.print("read count = ");
Serial.println(rtcMem.count);
yield();
}
void writeToRTCMemory() {
if (rtcMem.count <= MAXHOUR) {
rtcMem.count++;
} else {
rtcMem.count = 0;
}
system_rtc_mem_write(RTCMEMORYSTART, &rtcMem, 4);
Serial.print("write count = ");
Serial.println(rtcMem.count);
yield();
}
void loop() {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment