How to increase time in-between interrupts in ESP32

so I need to use interrupts in my code this is a code I found online

volatile int interruptCounter;
int totalInterruptCounter;
 
hw_timer_t * timer = NULL;
portMUX_TYPE timerMux = portMUX_INITIALIZER_UNLOCKED;
 
void IRAM_ATTR onTimer() {
  portENTER_CRITICAL_ISR(&timerMux);
  interruptCounter++;
  portEXIT_CRITICAL_ISR(&timerMux);
 
}
 
void setup() {
 
  Serial.begin(115200);
 
  timer = timerBegin(0, 80, true);
  timerAttachInterrupt(timer, &onTimer, true);
  timerAlarmWrite(timer, 1000000, true);
  timerAlarmEnable(timer);
 
}
 
void loop() {
 
  if (interruptCounter > 0) {
 
    portENTER_CRITICAL(&timerMux);
    interruptCounter--;
    portEXIT_CRITICAL(&timerMux);
 
    totalInterruptCounter++;
 
    Serial.print("An interrupt as occurred. Total number: ");
    Serial.println(totalInterruptCounter);
 
  }
}

Currently, the time in between each delay is 1 second. I want to change it to either 30 seconds, 1 minute or the maximum possible. How do I do it?
Do I change it like this?

timer = timerBegin(0, 1, true);
  timerAttachInterrupt(timer, &onTimer, true);
  timerAlarmWrite(timer, 80000000, true);
  timerAlarmEnable(timer);

Hello
Why do you think you need an interrupt?
Well, I think you need a timer to simulatively manage different tasks at different times.

How to write Timers and Delays in Arduino
and
Multi-tasking in Arduino
covers non-blocking timers that work on ESP32 (and other micros)
multitaskingDiagramSmall

so my project is a battery management system and it has 5 sensors measuring data.
My void loop has calculations to get other data. After I get the data I publish it to google sheet.
I was using a delay to slow down the publishing of data until my teacher told me about the interupt.
So I want to use interrupt to slow down the publishing of data to google sheets while not slowing down the measuring of data in the sensors

Thank you ill look into the websites

Just sayin':


As a beginner, it is [b]incredibly unlikely[/b] that interrupts will be useful to you.

A common "newbie" misunderstanding is that an interrupt is a mechanism for altering the flow of a program - to execute an alternate function. Nothing could be further from the truth! :astonished:

An interrupt is a mechanism for performing an action which can be executed in "no time at all" with an urgency that it must be performed immediately or else data - information - will be lost or some harm will occur. It then returns to the main task without disturbing that task in any way though the main task may well check at the appropriate point for a "flag" set by the interrupt.

Now these criteria are in a microprocessor time scale - microseconds. This must not be confused with a human time scale of tens or hundreds of milliseconds or indeed, a couple of seconds. A switch operation is in this latter category and even a mechanical operation perhaps several milliseconds; the period of a 6000 RPM shaft rotation is ten milliseconds. Sending messages to a video terminal is clearly in no way urgent,

Unless it is a very complex procedure, you would expect the loop() to cycle many times per millisecond. If it does not, there is most likely an error in code planning; while the delay() function is provided for testing purposes, its action goes strictly against effective programming methods. The loop() will be successively testing a number of contingencies as to whether each requires action, only one of which may be whether a particular timing criteria has expired. Unless an action must be executed in the order of mere microseconds, it will be handled in the loop().

So what sort of actions do require such immediate attention? Well, generally those which result from the computer hardware itself, such as high speed transfer of data in UARTs(, USARTs) or disk controllers.

An alternate use of interrupts, for context switching in RTOSs, is rarely relevant to this category of microprocessors as it is more efficient to write cooperative code as described above.

Well I would need my sensors to constantly measure the data while only wanting to send data to be printed on Google sheets every 30 secs.
So for this do you suggest I don't use interrupt ( quit new to interrupt) or just use delay ?

Don't use delay! Use millis() instead to time the publishing of the data. It can be as simple as this:

const unsigned long publishMs = 30000;

void setup()
{
}

void loop()
{
  static unsigned long prevMs = millis();
  unsigned long currMs = millis();

  if (curMs - prevMs >= publishMs)
  {
    // PUBLISH DATA HERE!!!
    prevMs = currMs;
  }

  // do all of your other stuff
}

Well I gave you the tutorial on interrupts. :grin:

The simple story on "delay()" is that it is not usable in serious applications. (Why? Because it does nothing! :roll_eyes:)

You have posted some random code about interrupts. You later gave a vague description of what you actually wanted to do. Have you actually generated any code so far? If so, we can perhaps discuss it.

What you need to do is to organise your project. You need to define a number of short "chunks" that will each take very little time and code each, then you can determine how to string them together with a simple scheduling system. In particular, you need to break up your "calculations" and "publishing" into workable sections so that they can be interspersed with things that you need to do on time. Then you can use timing with the clock (millis()) to get those time-critical parts done when needed and get the other things done in between.

All a matter of organisation, not a matter of trying to stick interrupts in to make up for disorganisation. :face_with_raised_eyebrow:

if I'm already using millis to time my current sensor i can't use it again right?

So this is my code

#include <EEPROM.h>
#define EEPROM_SIZE 12
#include <WiFi.h>
#include <time.h>
#include <Wire.h>
#include "cactus_io_HIH6130.h"

//volatile int interruptCounter;
//int totalInterruptCounter;

//hw_timer_t * timer = NULL;
//portMUX_TYPE timerMux = portMUX_INITIALIZER_UNLOCKED;

//void IRAM_ATTR onTimer() {
// portENTER_CRITICAL_ISR(&timerMux);
//interruptCounter++;
//portEXIT_CRITICAL_ISR(&timerMux);
}

const char* ssid = "ssid";
const char* password =  "password";

const char* resource1 = "/trigger/BMS_hih6130/with/key/df1-S5UmTDro6K4V";
const char* server1 = "maker.ifttt.com";

const char* resource2 = "/trigger/BMS_Sensors/with/key/df1-S5UmTDro6K4V";
const char* server2 = "maker.ifttt.com";

const char* resource3 = "/trigger/BMS_health/with/key/df1-S5UmTDro6K4V";
const char* server3 = "maker.ifttt.com";

const char* ntpServer = "pool.ntp.org";
const long  gmtOffset_sec = 28800;
const int   daylightOffset_sec = 0;

#define PIN_SDA 21
#define PIN_SCL 22
byte address = 0x27;
HIH6130 hih6130(address);

float ADC = 34;
float ADCvalue;
float VoltageValue;


const int CurrentSensor = 12;
float CurrentValue;

int smokesensor = 27;
int MQ2Sensor;

int buzzer = 33;
int led = 32;

float SOC;
int SOH;
int count;

unsigned long startMillis;
unsigned long currentMillis;
const int period = 1000;
float totalCoulumbs = 0.0;

void setup() {

  Serial.begin(115200);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.println("Connecting to WiFi..");
  }
  Serial.println("Connected to the WiFi network");

  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);

  startMillis = millis();

  Wire.begin();

  EEPROM.begin(EEPROM_SIZE);

  count = EEPROM.read(0);

  pinMode(smokesensor, INPUT);

  pinMode(led, OUTPUT);

  pinMode(buzzer, OUTPUT);

  //timer = timerBegin(0, 1, true);
  //timerAttachInterrupt(timer, &onTimer, true);
  //timerAlarmWrite(timer, 80000000, true);
  //timerAlarmEnable(timer);

}

void loop() {
  ADCvalue = analogRead(ADC);
  VoltageValue = ADCvalue / 4096 * 14.6 * (29203.54 / 30000);

  unsigned int x = 0;
  float AcsValue = 0.0, Samples = 0.0, AvgAcs = 0.0, CurrentValue = 0.0;
  for (int x = 0; x < 150; x++) {
    AcsValue = analogRead(CurrentSensor);
    Samples = Samples + AcsValue;
    delay (3);
  }
  AvgAcs = Samples / 150.0;
  CurrentValue = (2.5 - (AvgAcs * (5.0 / 1024.0)) ) / 0.185;

  MQ2Sensor = analogRead(smokesensor);

  hih6130.readSensor();


  if (hih6130.temperature_C > 60 || hih6130.temperature_C < -20 || MQ2Sensor > 400 || hih6130.humidity > 75) {
    digitalWrite(buzzer, HIGH);
    digitalWrite(led, HIGH);
  }
  else {
    digitalWrite(buzzer, LOW);
    digitalWrite(led, LOW);
  }

  currentMillis = millis();
  if (currentMillis - startMillis >= period) {
    totalCoulumbs = totalCoulumbs + CurrentValue;
    float TotalAh = totalCoulumbs / 3600.0;
    SOC = ((50 - TotalAh) / 50) * 100;
    startMillis = currentMillis;
  }

  if ( SOC > 99.9) {
    count = count + 1;
    EEPROM.write(0, count);
  }

  float percentage = count;
  SOH = ((2000 - percentage) / 2000) * 100;

  printLocalTime();

  if (interruptCounter > 0) {

    portENTER_CRITICAL(&timerMux);
    interruptCounter--;
    portEXIT_CRITICAL(&timerMux);

    totalInterruptCounter++;

    senddata();
  }
}

void printLocalTime()
{
  struct tm timeinfo;
  if (!getLocalTime(&timeinfo)) {
    Serial.println("Failed to obtain time");
    return;
  }
  Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
}

void senddata()
{
  Serial.println("Battery percentage: ");
  Serial.print(SOC);

  Serial.println("Battery capacity: ");
  Serial.print(SOH);
  Serial.println("Count");
  Serial.print(count);

  Serial.println("Volatge Input: ");
  Serial.print(VoltageValue);

  Serial.print("Current Input: ");
  Serial.print(CurrentValue);

  Serial.println("Smoke Value: ");
  Serial.print(MQ2Sensor);

  Serial.println("RH\tTemp (C)\tTemp (C)\tHeat Index (F)");
  Serial.print(hih6130.humidity); Serial.print("\t");
  Serial.print(hih6130.temperature_C); Serial.print("\t\t");
  Serial.print(hih6130.computeHeatIndex_C()); Serial.print("\t\t");

  makeIFTTTRequest1();
  makeIFTTTRequest2();
  makeIFTTTRequest3();
}

void makeIFTTTRequest1() {
  Serial.print("Connecting to ");
  Serial.print(server1);
  WiFiClient client;
  int retries = 5;
  while (!!!client.connect(server1, 80) && (retries-- > 0)) {
    Serial.print(".");
  }
  Serial.println();
  if (!!!client.connected()) {
    Serial.println("Failed to connect...");
  }
  Serial.print("Request resource: ");
  Serial.println(resource1);
  String jsonObject1 = String("{\"value1\":\"") + hih6130.humidity + "\",\"value2\":\"" + hih6130.temperature_C
                       + "\",\"value3\":\"" + hih6130.computeHeatIndex_C() + "\"}";
  client.println(String("POST ") + resource1 + " HTTP/1.1");
  client.println(String("Host: ") + server1);
  client.println("Connection: close\r\nContent-Type: application/json");
  client.print("Content-Length: ");
  client.println(jsonObject1.length());
  client.println();
  client.println(jsonObject1);
  int timeout = 5 * 10; // 5 seconds
  while (!!!client.available() && (timeout-- > 0)) {
    delay(100);
  }
  if (!!!client.available()) {
    Serial.println("No response...");
  }
  while (client.available()) {
    Serial.write(client.read());
  }
  Serial.println("\nclosing connection");
  client.stop();
}

void makeIFTTTRequest2() {
  Serial.print("Connecting to ");
  Serial.print(server2);
  WiFiClient client;
  int retries = 5;
  while (!!!client.connect(server2, 80) && (retries-- > 0)) {
    Serial.print(".");
  }
  Serial.println();
  if (!!!client.connected()) {
    Serial.println("Failed to connect...");
  }
  Serial.print("Request resource: ");
  Serial.println(resource2);
  String jsonObject2 = String("{\"value1\":\"") + MQ2Sensor + "\",\"value2\":\"" + CurrentValue
                       + "\",\"value3\":\"" + VoltageValue + "\"}";
  client.println(String("POST ") + resource2 + " HTTP/1.1");
  client.println(String("Host: ") + server2);
  client.println("Connection: close\r\nContent-Type: application/json");
  client.print("Content-Length: ");
  client.println(jsonObject2.length());
  client.println();
  client.println(jsonObject2);
  int timeout = 5 * 10; // 5 seconds
  while (!!!client.available() && (timeout-- > 0)) {
    delay(100);
  }
  if (!!!client.available()) {
    Serial.println("No response...");
  }
  while (client.available()) {
    Serial.write(client.read());
  }
  Serial.println("\nclosing connection");
  client.stop();
}

void makeIFTTTRequest3() {
  Serial.print("Connecting to ");
  Serial.print(server3);
  WiFiClient client;
  int retries = 5;
  while (!!!client.connect(server3, 80) && (retries-- > 0)) {
    Serial.print(".");
  }
  Serial.println();
  if (!!!client.connected()) {
    Serial.println("Failed to connect...");
  }
  Serial.print("Request resource: ");
  Serial.println(resource3);
  String jsonObject3 = String("{\"value1\":\"") + SOC + "\",\"value2\":\"" + SOH + "\",\"value3\":\"" + count + "\"}";
  client.println(String("POST ") + resource3 + " HTTP/1.1");
  client.println(String("Host: ") + server3);
  client.println("Connection: close\r\nContent-Type: application/json");
  client.print("Content-Length: ");
  client.println(jsonObject3.length());
  client.println();
  client.println(jsonObject3);
  int timeout = 5 * 10; // 5 seconds
  while (!!!client.available() && (timeout-- > 0)) {
    delay(100);
  }
  if (!!!client.available()) {
    Serial.println("No response...");
  }
  while (client.available()) {
    Serial.write(client.read());
  }
  Serial.println("\nclosing connection");
  client.stop();
}

See the void senddata() loop that's the part where I want to try interrupt with.
( I have commented the interrupt part)

The calculation is in the void loop part