Deepsleep after 1min with void.loop

Is it possible to use deepsleep after several "void.loop" loops but not at the end of the one loop?
I don't know how to explain it.

I would like to do something like this

*I turn on the power

-Esp works for 1 minute (connects to wifi and sends data from sensors several times etc etc)
-Deep sleep 29 minutes

-Esp works for 1 minute (connects to wifi and sends data from sensors several times etc etc) -
Deep sleep 29 minutes

And again and again.

This is a sketch of my test code, it works not fully ready yet :upside_down_face:




// Fill-in information from your Blynk Template here
#define BLYNK_TEMPLATE_ID           "TMPL4HAPTt4l7"
#define BLYNK_TEMPLATE_NAME         "Battery Monitor"
#define USE_ESP32_DEV_MODULE


#define BLYNK_FIRMWARE_VERSION        "0.1.0"
#define TerminalPin V0
#define BLYNK_PRINT Serial
//#define BLYNK_DEBUG

#define APP_DEBUG

#include <WiFi.h>
#include <WiFiClient.h>
#include "BlynkEdgent.h"
#include <DHT.h>


char ssid[] = "*********";  // type your wifi name
char pass[] = "************";  // type your wifi password



#define DHTTYPE DHT22     // DHT 22
#define DHTPIN 4 //DHT22 Pin D4(GPIO 2)


DHT dht(DHTPIN, DHTTYPE);


float voltage;
int bat_percentage;
int analogInPin  = 35;    // Analog input pin
int sensorValue;
float calibration = 0.00; // Check Battery voltage using multimeter & add/subtract the value

WidgetTerminal terminal(TerminalPin);


void setup()
{
  Serial.begin(115200);
  delay(100);

  BlynkEdgent.begin();
  delay(1000);
  Serial.println("Connected");
  terminal.println("Connected");
  terminal.print("Sensors");
  terminal.print(".");
  terminal.print(".");
  terminal.print(".");
  terminal.print(".");
  terminal.println("Sensors ON");
  
  
  dht.begin();


  delay(3000);

}

void loop() {
  BlynkEdgent.run();
  float t = dht.readTemperature();
  float h = dht.readHumidity();

  sensorValue = analogRead(analogInPin);
  voltage = (((sensorValue) / 4096.0) * 7.445 + calibration); 

  bat_percentage = mapfloat(voltage, 3.3, 4.2, 0, 100); //2.8V as Battery Cut off Voltage & 4.2V as Maximum Voltage

  if (bat_percentage >= 100)
  {
    bat_percentage = 100;
  }
  if (bat_percentage <= 0)
  {
    bat_percentage = 1;
  }
  
      //send data to blynk
    Blynk.virtualWrite(V1, t); //for Temperature
    Blynk.virtualWrite(V2, h); //for Humidity
    Blynk.virtualWrite(V3, voltage);  // for battery voltage
    Blynk.virtualWrite(V4, bat_percentage);  // for battery percentage
  
    //Print data on serial monitor
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.println(" *C");

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.println(" %");

  Serial.print("Analog Value = ");
  Serial.println(sensorValue);
  Serial.print("Output Voltage = ");
  Serial.println(voltage);
  Serial.print("Battery Percentage = ");
  Serial.println(bat_percentage);

  Serial.println();
  Serial.println("****************************");
  Serial.println();

  terminal.print("Analog Value = ");
  terminal.println(sensorValue);
  terminal.print("Voltage = ");
  terminal.print(voltage);
  terminal.println(" V");
  delay(500);
  terminal.print("Battery Percentage = ");
  terminal.print(bat_percentage);
  terminal.println(" %");

  
  delay(3000);
 


  delay(1500);
}
float mapfloat(float x, float in_min, float in_max, float out_min, float out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

My device Lolin D32
Can you help me?

That's the common way of using deep sleep. Read sensors etc, post them somewhere and go to sleep.
Do you want it to be time related (1min)?

Don't use delay, use a millis() approach, see the tutorial at https://forum.arduino.cc/t/using-millis-for-timing-a-beginners-guide/483573
You might want to check the time 3 times, the first being is it time to collect sensor data, second is it time to send sensor data, and the third is is it time to goto sleep. This is very standard code for more experienced programmers.

Yes, but most of the codes I've seen are without "void.loop()" or deepsleep is at the end of the first loop. And I want the loop and the countdown to deepsleep to run in parallel. So that the loop runs for a minute and after a minute deepsleep is activated. Or after a few loops -> deepsleep

Both are possible, either a for-loop x times or millis counter for time. Personally I see for-loop more logical, but it totally depends on your approach.
If you want to do something let's say 10 times and then go to sleep or you want do something for one minute and then go to sleep.

Maybe this will help you

I saw this article before, and there is the code without the "void.loop" only void.setup and all the code there. If I understood it correctly

Serial.println("Going to sleep now");
  delay(1000);
  Serial.flush(); 
  esp_deep_sleep_start();
  Serial.println("This will never be printed");
}

void loop(){
  //This is not going to be called
}

Loop x times will be more easier, right?
These millis is something new for me :grin:

loop() has no statements because all the code is developed in setup().
Remember that when exit deep sleep the micro is restarted (with some exceptions) so loop() is rarely executed.

Maybe take the short time it would to understand how to make a timer with millis(). It will be worth knowing for all kindsa reasons.

You can use a timer to make something happen every so often, just count up to how many times you want to do that and then reset the counter for next time and sleep.

Or just have another timer that is of longer duration so

  if it is time to do that thing again, do it and reschedule

  if this has been going on for one minute
    go to sleep
    reschedule this (and thinking about it, reschedule the frequent tasks timer too) 

A timer in this context is nothing more than an unsigned long integer. Setting a timer is nothing more than making it equal to the value of millis() and checking a timer for expiry is just seeing if millis() has advanced enough to mean the time is up.

google and read seven explanations taking 7 minutes with each. Try a few on for size. In one hour or less any ignorance or fear will be dealt with. Forever.

a7

It's simply question if you prefer to do something for x time or x times.
Millis is too useful to ignore even if you haven't experimented with it, independently from approach you choose for this setup..

For-loop at the end of setup would be simple like this:

for (j = 0; j < 10; j++)
    {
      all your code to be repeated here
    }
esp_deep_sleep_start();

Thank you for this code. I'll try to use it to start with. But I'll read about millis too.

I don't normally post solutions. But I did have fun with chatGPT, and it was not too hard to get it to write a full demonstartion of a millis() based approach.

"We" decided to put all the sleep related functionality into a function. Presumably this would be the only place where those pesky details would need to be handled.

To simulate what I guess will be some kind of wake up signal, we used a pushbutton wired between pin 2 and GND; pressing it simulates waking up.

unsigned long previousMillis = 0;    // Store the last time "frequent" was printed
unsigned long sleepMillis = 0;       // Store the last time we went to sleep

const unsigned long interval = 777;  // every 777 milliseconds (for testing)
const unsigned long sleepDuration = 13000; // after 13 seconds in milliseconds (for testing)

const int buttonPin = 2;  // Button connected to pin 2

void setup() {
  Serial.begin(9600); // Initialize serial communication
  pinMode(buttonPin, INPUT_PULLUP); // Set button pin as input with internal pull-up resistor
}

void loop() {
  // Print "frequent" every so often
  if (millis() - previousMillis >= interval) {
    Serial.println("frequent");
    previousMillis = millis(); // Update the timer after the activity
  }

  //  go to sleep after a longer period of doing the frequent thing
  if (millis() - sleepMillis >= sleepDuration) {
    goToSleep();
    sleepMillis = millis(); // Update sleepMillis after returning from sleep
  }
}

// Placeholder for the goToSleep() function
void goToSleep() {
  Serial.println("I am going to sleep now");

  // ---- Start of Sleep Mode ----
  // Entering an infinite loop to simulate sleep.
  // The program will stay here until the button is pressed (wake-up).
  while (1) {
    if (digitalRead(buttonPin) == LOW) {
      // Wake-up condition: Button pressed, exit sleep loop.
      break;
    }
  }
  // ---- End of Sleep Mode ----

  // ---- Wake-up processing ----
  // Execution continues here once the button is pressed.
  Serial.println("Something woke me up!");
  Serial.println("Resuming activity after waking up.");
}

HTH

a7

This is just an example, the same sleep could be in the loop.

I tried it, onelce but when I wanted chatgpt to write me a code it said more nonsense than me :rofl::rofl::rofl::rofl:

I'll read about it.
But if I understand correctly, I determine the time the sensor will work. Like non-stop?
I read that dth22 needs a break between readings...

Aaaaaaa now I understand.

Everything will happen simultaneously. Not like with "delay" one sensor after another. So for example dth22 sensor will work for 30 seconds And at the same time the countdown for Deepsleep will start and these times will flow simultaneously So I will be able to add an independent delay for the sensor in these 30 seconds because I read that dth22 needs a break between readings.

So I will be able to do everything in a much shorter time
I will try to read more about it.

Edid:
I forgot to ask. Did I understand this correctly? :upside_down_face:

No doubt. chatGPT really isn't terribly useful if you aren't yourself able to write the code you are asking it to write. In fact, it can be detrimental. I would not recommend, and did not mean to suggest, that you waste any time with it on matters like this. Not even for fun.

In the right hands it might be a timesaver, in the right hands and within a narrow scope.

I just felt more like taking 40 minutes to get it to write what I wanted than the seven minutes it might have taken me to do it myself.

I have found chatGPT to be especially bad at anything the least bit out of the ordinary. When I tried doing something I have never seen (not that it hasn't been done) it tried valiantly but no matter the prompts, could not produce working code.

In this case it got fairly close pretty early on. And the sketch I posted illustrates everything I said in #10 above - what a timer is, and what the structure of a sketch that is timing two things might be.

In the few times I've tried anything challengin, again only to experiment, it goes off the rails at some point, and there is no way to recover. I remain of the opinion that there will always be work for humans...

a7

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.