# Attachinterrupt & Software timer

**URL:** <https://community.particle.io/t/attachinterrupt-software-timer/59598>\
**Category:** Firmware\
**Created:** [March 8, 2021, 6:33am UTC](https://community.particle.io/t/attachinterrupt-software-timer/59598 "2021-03-08T06:33:31Z")\
**Posts on this page:** 14\
**Page:** 1

<div class="post-metadata">

**Author:** ![Tino52](https://sea2.discourse-cdn.com/flex026/user_avatar/community.particle.io/tino52/32/16619_2.png) [@Tino52](https://community.particle.io/u/Tino52)\
**Post date:** [March 8, 2021, 6:33am UTC](https://community.particle.io/t/attachinterrupt-software-timer/59598/1 "2021-03-08T06:33:31Z")

</div>

Hello  
a few weeks ago I opened a post on volatile variables with interrupts. Starting from there I ran some tests using timer software.  
I need to have a delay of happening in the event. Using an on - off switch connected to the negative pole and to D0 and D1 for the tests. With the skecht attached sometimes the device freeze or the led output D8 does not turn off.  
Unfortunately I can’t find a correct solution, does anyone have any suggestions to solve the problem or some corrections to do in my skecht?  
Thanks Valentino

```cpp
#include "Particle.h"
int Inscent=D0; // CENTR INS.
int DInscent=D1; // CENTR DINS.
int LedInsCent=D8;
int StatoInscent=0;
int StatoDInscent=0;
int StatoC=0;
int Uscita=0;
// **********************
int Zona1 = D3; // Input Zona1
int StatoZ1=0;    
int AStatoZ1= 0;
int LedZona1 = D4;
void CentrOn()
{
    if (StatoInscent=1)
   {
    digitalWrite(LedInsCent,HIGH);
    }
}
void CentrOff()
{   
    if (StatoDInscent=1)
    {
    digitalWrite(LedInsCent,LOW);
    }
}
//declare timer object one shot
Timer TCentrOn(5000, CentrOn, true);
Timer TCentrOff(500, CentrOff, true);
void setup() {
    attachInterrupt(Inscent,CentrIntOn,CHANGE); //RISING
    attachInterrupt(DInscent, CentrIntOff,CHANGE);//FALLING
    Serial.begin(9600);
    pinMode(LedInsCent,OUTPUT);
    pinMode(Inscent,INPUT_PULLUP);
    pinMode(DInscent,INPUT_PULLUP); 
    
    pinMode(Zona1,INPUT_PULLDOWN);    
    pinMode(LedZona1,OUTPUT);
    StatoZ1=0;
    AStatoZ1=1;
    Particle.variable("Z1",AStatoZ1);
}
void loop()
{
    StatoZ1=digitalRead(Zona1);
    StatoInscent=digitalRead(Inscent);
    StatoDInscent=digitalRead(DInscent);
    Uscita=digitalRead(D8);
    Serial.print("StatoC : ");Serial.println(StatoC);
    Serial.print("Uscita ");Serial.println(Uscita);
    Serial.print("Stato on: ");Serial.println(StatoInscent);
    Serial.print("Stato off: ");Serial.println(StatoDInscent);
    delay(1000);
}
    void CentrIntOn()
    {
        TCentrOn.startFromISR();
    }
    void CentrIntOff()
    {
        TCentrOff.startFromISR();        
    }

```

---

<div class="post-metadata">

**Author:** ![ScruffR](https://sea2.discourse-cdn.com/flex026/user_avatar/community.particle.io/scruffr/32/6952_2.png) [@ScruffR](https://community.particle.io/u/ScruffR)\
**Post date:** [March 8, 2021, 7:45am UTC](https://community.particle.io/t/attachinterrupt-software-timer/59598/2 "2021-03-08T07:45:00Z")

</div>

@Tino52, first you are long enough in this community to know how to format code blocks - I know I have reminded you before to use the "Preformatted text" ![image](https://us1.discourse-cdn.com/flex026/uploads/particle/original/3X/1/2/12c1701669ea7ca654d7c6d82d4f189c181ddda6.png) feature - please do.

For the question at hand: Do you really need the exact timing down to a few microseconds?  
If not, you can well use the interrupt to set a flag but then act upon it in your `loop()`.  
Starting a software timer from an ISR should be the exception not the first option.

First kick out that dreaded `delay()` at the end of your `loop()` and wrap the delayed actions in a `millis()` timing block.  
When that is taken care of, you can implement the flag idea rather comfortably

something like this

```cpp
bool startNeeded[2] = { false, false }; // flags for ISR to tell loop() to initiate the timer [0]..off, [1]..on
Timer timer[2] = { Timer( 500, CentrOff, true) // array of timers to wrap similar actions in one loop
                       , Timer(5000, CentrOn , true) };

void loop() {
  static uint32_t ms1Sec = 0;

  for (int i = 0; i < 2; i++) { // traverse timer array
    if (startNeeded[i] && !timer[i].isActive()) { // when a start is needed and not currently running
      startNeeded[i] = false; // reset the start flag
      timer[i].start(); // start the timer
    }
  }

  if (millis() - ms1Sec >= 1000) { // when last execution is at least one second in the past
    ms1Sec = millis();
    StatoZ1 = digitalRead(Zona1);
    StatoInscent = digitalRead(Inscent);
    StatoDInscent = digitalRead(DInscent);
    Uscita = digitalRead(D8);
    Serial.printlnf("StatoC : %5d\r\n"
                    "Uscita : %5d\r\n"
                    "Stato on : %5d\r\n"
                    "Stato off: %5d\r\n"
                   , StatoC
                   , Uscita
                   , StatoInscent
                   , StatoDInscent
                   );
  }
}

void CentrIntOn() {
  startNeede[1] = true;
}
    
void CentrIntOff() {
  startNeeded[0] = true;
}

```

BTW, you'd usually _ **first** _ set the `pinMode()` for the pins _ **before** _ you attach an interrupt to said pin. Otherwise you may be getting erroneous triggers of the floating pins.  
I'd also _not_ use a CHANGE trigger for this. Usually I'd opt for the button release to trigger any action with time component.  
_(for button handling you may have a look at [Rick's brilliant library](https://community.particle.io/t/debounceswitchrk-library-for-switch-debouncing/59559) - debouncing is also something your code should do)_

Also this is wrong

> [@Tino52](#):
>
> ```auto
> if (StatoInscent=1)
> 
> ```

and

> [@Tino52](#):
>
> ```auto
> if (StatoDInscent=1)
> 
> ```

Here you are _ **not** _ checking the state of your flags but _ **setting** _ them.

You may also need to give the re-trigger logic some more thought.  
Your code (and hence my derivative of it too) does not properly address at least two possible states:

- what if the button was pressed _again_ while the timer was running?
- what if the button stays pressed for the duration of the timer running (or while the timer is about to expire)?

You _first_ need to formulate the intent for all cases and _based on that_ develop your code.

---

<div class="post-metadata">

**Author:** ![Tino52](https://sea2.discourse-cdn.com/flex026/user_avatar/community.particle.io/tino52/32/16619_2.png) [@Tino52](https://community.particle.io/u/Tino52)\
**Post date:** [March 8, 2021, 10:13am UTC](https://community.particle.io/t/attachinterrupt-software-timer/59598/3 "2021-03-08T10:13:59Z")

</div>

Hello  
usually I always do a small flowchart to better understand where I want to go, this time too it has been done.  
I edited the sketch as suggested and it works fine with an on and off switch.  
Your question:  
what if the button was pressed again while the timer was running?  
With the switch works, it turns off and does not turn on again, while during the test with the buttons it turns on again after the set time has elapsed (Timer timer [2] = {Timer (1000, CentrOff, true)).  
Attached is the photo of the switch used to better understand us.  
However, I have to thank for the good help you always give me.  
Regards  
Valentino

 ![IMG_4159](https://us1.discourse-cdn.com/flex026/uploads/particle/original/3X/d/a/dae08e6307b58f819e00bddd30d4d9bc23cd2c23.jpeg)

---

<div class="post-metadata">

**Author:** ![Tino52](https://sea2.discourse-cdn.com/flex026/user_avatar/community.particle.io/tino52/32/16619_2.png) [@Tino52](https://community.particle.io/u/Tino52)\
**Post date:** [March 22, 2021, 6:57pm UTC](https://community.particle.io/t/attachinterrupt-software-timer/59598/4 "2021-03-22T18:57:50Z")

</div>

Hello @ScruffR  
After several tests I felt that for my purpose using millis would have been ideal.  
In the tests I found that if I impose for example: 30000 and measuring the time the action occurs before 30000 have elapsed. In my tests I arrived around 14-20 seconds.  
I attach my skecht and I ask you if there is an error in using the millis function.  
Also I wanted to know if I declare ‘static uint32\_t ms1Sec = 0;’ can I also use it for other millis settings?  
(millis () - ms30Sec\> = 30000)  
(millis () - ms1Sec\> = 1000)  
Thanks Valentino

```auto
#include "Particle.h"
// ZONA2
int Zona2 = A1;
int StatoZ2=0;
int AStatoZ2= 0;
int LedZona2 = D5;
int LedZ2=0;
int Inscent=D12; // CENTR INS.
int LedInsCent=D7;
int StatoInscent=0;
int AStatoC=0;

void setup() {
    Serial.begin(9600);
    //ZONA2
    pinMode(Zona2,INPUT_PULLUP);
    pinMode(LedZona2,OUTPUT);
    Particle.variable("Z2",AStatoZ2);
    attachInterrupt(Zona2,Z2Interrupt,RISING); //RISING
    // ************
    pinMode(LedInsCent,OUTPUT);
    pinMode(Inscent,INPUT_PULLDOWN);//INPUT_PULLDOWN);
}

void loop() {
    StatoInscent = digitalRead(Inscent);
    static uint32_t ms1Sec = 0;
    static uint32_t ms30Sec = 0;
    if (StatoInscent == 1) {
        digitalWrite(LedInsCent, HIGH);
        if (StatoZ2 == 1) {
            if (millis() - ms30Sec >= 30000) {
                ms30Sec = millis();
                digitalWrite(LedZona2, HIGH);
            }
        }
    }
    else { // if (StatoInscent != 1)
        digitalWrite(LedZona2,LOW);
        StatoZ2 = 0;
        digitalWrite(LedInsCent, LOW);
        StatoInscent = 0;
    }    
    if (millis() - ms1Sec >= 1000) {
        ms1Sec = millis();
        Serial.print("Stato Z2:");Serial.println(StatoZ2);
        Serial.print("Centr:");Serial.println(StatoInscent);
    }
}

void Z2Interrupt() {
    StatoZ2=1;
}

```

---

<div class="post-metadata">

**Author:** ![ScruffR](https://sea2.discourse-cdn.com/flex026/user_avatar/community.particle.io/scruffr/32/6952_2.png) [@ScruffR](https://community.particle.io/u/ScruffR)\
**Post date:** [March 22, 2021, 9:06pm UTC](https://community.particle.io/t/attachinterrupt-software-timer/59598/5 "2021-03-22T21:06:03Z")

</div>

I'm not entirely sure what your code intends to do, but having `if(millis() - ms30Sec >= 30000)` _ **inside** _ another condition that may already be `false` when the 30sec are over does feel somewhat obscure (to me).

> [@Tino52](#):
>
> Also I wanted to know if I declare ‘static uint32\_t ms1Sec = 0;’ can I also use it for other millis settings?

You can have as many independent time variables as you want.

---

<div class="post-metadata">

**Author:** ![Tino52](https://sea2.discourse-cdn.com/flex026/user_avatar/community.particle.io/tino52/32/16619_2.png) [@Tino52](https://community.particle.io/u/Tino52)\
**Post date:** [March 23, 2021, 6:22am UTC](https://community.particle.io/t/attachinterrupt-software-timer/59598/6 "2021-03-23T06:22:38Z")

</div>

Hello @ScruffR  
I’m replacing part of a burglary center. The radio receiver part for the wireless sensors (infrared) works, in this there are some closed relays that open every x seconds at the time of an infringement and my device (Argon) should trigger an alarm.  
I put this line (if (StatoInscent == 1)) because only if the burglary control unit is active can an alarm be activated.  
Have a nice day  
Valentino

---

<div class="post-metadata">

**Author:** ![Tino52](https://sea2.discourse-cdn.com/flex026/user_avatar/community.particle.io/tino52/32/16619_2.png) [@Tino52](https://community.particle.io/u/Tino52)\
**Post date:** [March 23, 2021, 7:02am UTC](https://community.particle.io/t/attachinterrupt-software-timer/59598/7 "2021-03-23T07:02:12Z")

</div>

Hello  
I add that I want to put a delay on Zone2 so that the alarm only goes on after x seconds.  
Best and Thanks  
Valentino

---

<div class="post-metadata">

**Author:** ![ScruffR](https://sea2.discourse-cdn.com/flex026/user_avatar/community.particle.io/scruffr/32/6952_2.png) [@ScruffR](https://community.particle.io/u/ScruffR)\
**Post date:** [March 23, 2021, 7:32am UTC](https://community.particle.io/t/attachinterrupt-software-timer/59598/8 "2021-03-23T07:32:29Z")

</div>

> [@Tino52](#):
>
> put a delay on Zone2 so that the alarm only goes on after x seconds.

I see.  
This calls for some clarification then.

> [@Tino52](#):
>
> ```auto
> if (millis() - ms30Sec >= 30000) {
> ms30Sec = millis();
> 
> ```

This construct isn't quite giving you what you intend because it does _ **not** _ take into account _ **when** _ your triggering event occured but only _ **when** _ the condition was _ **last checked and rendered true** _.  
If you want to make one thing dependent on something happening somewhere else you'd need slightly different approach.

e.g.

```auto
bool AStatoZ2 = false;
uint32_t msZona2 = 0; // make this global (could be volatile but doesn't have to ;-) @joel
                              // replaces int ZonaZ2 = 0; 
void Z2Interrupt() {
    ms30Sec = millis(); // record when the interrupt happened
}

void loop() {
    static uint32_t ms1Sec = 0;

    if (StatoInscent = digitalRead(Inscent)) { // assginment "=" on purpose (not only a check "==")
        if (msZona2 && millis() - msZona2 >= 30000) {
            AStatoZ0 = true;
        }
    }
    else {
        msZona2 = 
        AStatoZ0 = 0;
    }
    digitalWrite(LedInsCent, StatoInscent);
    digitalWrite(LedZona2, AStatoZ2);

    if (millis() - ms1Sec >= 1000) {
      ms1Sec = millis();
      Serial.printlnf("Centr : %s \r\n"
                      "Stato Z2: %s (%.1f)\r\n"
                      , StatoInscent ? "ON" : "OFF"
                      , AStatoZ2 ? "ON" : "OFF"
                      , msZone2 ? (millis() - msZone2) / 1000.0 : 0.0 // sec since trigger 
                      ); 
    }
}

```

---

<div class="post-metadata">

**Author:** ![Tino52](https://sea2.discourse-cdn.com/flex026/user_avatar/community.particle.io/tino52/32/16619_2.png) [@Tino52](https://community.particle.io/u/Tino52)\
**Post date:** [March 24, 2021, 6:20am UTC](https://community.particle.io/t/attachinterrupt-software-timer/59598/9 "2021-03-24T06:20:31Z")

</div>

Hello @ScruffR  
thanks in the next few days I will do some tests with your suggestions.  
Have a good day for now  
Valentino

---

<div class="post-metadata">

**Author:** ![Tino52](https://sea2.discourse-cdn.com/flex026/user_avatar/community.particle.io/tino52/32/16619_2.png) [@Tino52](https://community.particle.io/u/Tino52)\
**Post date:** [April 13, 2021, 6:36am UTC](https://community.particle.io/t/attachinterrupt-software-timer/59598/10 "2021-04-13T06:36:12Z")

</div>

Hello @ScruffR  
I finally had time to review the program and make the necessary changes. Now it works well, I am attaching the skecht so that those who want to use it have an idea.  
Thanks again for the valuable help.  
Valentino

```auto
#include "Particle.h"
// ZONA2
int Zona2 = A1;
int StatoZ2=0;
//int AStatoZ2= 0;
int LedZona2 = D5;
int LedZ2=0;

int Inscent=D12; // CENTR INS.
int LedInsCent=D8;
int StatoInscent=0;
int AStatoLedC=0;
int AStatoC=0;

bool AStatoZ2 = false;
uint32_t msZona2 = 0; // make this global (could be volatile but doesn't have to ;-) @joel
                              // replaces int ZonaZ2 = 0; 
//static uint32_t ms30Sec = 0;
void Z2Interrupt() {
    msZona2 = millis(); // record when the interrupt happened
}
void setup() {
    Serial.begin(9600);
    //ZONA2
    pinMode(Zona2,INPUT_PULLUP);
    pinMode(LedZona2,OUTPUT);
    Particle.variable("Z2",AStatoZ2);
    attachInterrupt(Zona2,Z2Interrupt,RISING); //RISING
    // ************
    pinMode(LedInsCent,OUTPUT);
    pinMode(Inscent,INPUT_PULLDOWN);//INPUT_PULLDOWN);
}
void loop() {
    static uint32_t ms1Sec = 0;

    if (StatoInscent = digitalRead(Inscent)) { // assgniment "=" on purpose (not only a check "==")
        if (msZona2 && millis() - msZona2 >= 10000) {
            AStatoZ2 = true;
        }
    }
    else {
        msZona2 = 
        AStatoZ2 = 0;
    }
    digitalWrite(LedInsCent, StatoInscent);
    digitalWrite(LedZona2, AStatoZ2);
    
    if (millis() - ms1Sec >= 1000) {
      ms1Sec = millis();
      Serial.printlnf("Centr : %s \r\n"
                      "Stato Z2: %s (%.1f)\r\n"
                      , StatoInscent ? "ON" : "OFF"
                      , AStatoZ2 ? "ON" : "OFF"
                      , msZona2 ? (millis() - msZona2) / 1000.0 : 0.0 // sec since trigger 
                      ); 
    }
}

```

---

<div class="post-metadata">

**Author:** ![Tino52](https://sea2.discourse-cdn.com/flex026/user_avatar/community.particle.io/tino52/32/16619_2.png) [@Tino52](https://community.particle.io/u/Tino52)\
**Post date:** [April 14, 2021, 5:08am UTC](https://community.particle.io/t/attachinterrupt-software-timer/59598/11 "2021-04-14T05:08:17Z")

</div>

Hello @ScruffR  
one last thing about this project that I have not found on the internet in the Printlnf specifications

```auto
Serial.printlnf ("Centr:% s \ r \ n"
                       "Z2 state:% s (% .1f) \ r \ n"
                       , StatusInscent? "ON": "OFF"

```

The question mark has what function (if?)  
Regards  
Valentino

---

<div class="post-metadata">

**Author:** ![ScruffR](https://sea2.discourse-cdn.com/flex026/user_avatar/community.particle.io/scruffr/32/6952_2.png) [@ScruffR](https://community.particle.io/u/ScruffR)\
**Post date:** [April 14, 2021, 5:44am UTC](https://community.particle.io/t/attachinterrupt-software-timer/59598/12 "2021-04-14T05:44:10Z")

</div>

For one, there should be a blank between the variable name and the question mark and _ **no** _ blanks after `%` or `\`.  
And this hasn’t got anything to do with `snprintf()` but is a standard C construct called [_“ternary operator”_](http://www.cplusplus.com/articles/1AUq5Di1/) - in a nutshell it’s a one-line if…else statement that returns a specific value for either of the two branches.

---

<div class="post-metadata">

**Author:** ![Tino52](https://sea2.discourse-cdn.com/flex026/user_avatar/community.particle.io/tino52/32/16619_2.png) [@Tino52](https://community.particle.io/u/Tino52)\
**Post date:** [April 15, 2021, 12:38pm UTC](https://community.particle.io/t/attachinterrupt-software-timer/59598/13 "2021-04-15T12:38:49Z")

</div>

Thanks I don’t know because maybe with the cut & paste it has been modified, it is still in the sketch as indicated by you.  
Good day & Grazie!  
Valentino

```auto
[quote="Tino52, post:10, topic:59598"]
`, StatoInscent ? "ON" : "OFF"`
[/quote]

```

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/flex026/uploads/particle/original/3X/3/2/3291e3c9351789fe8620ae5bcec8d3fec67ff221.png) [@system](https://community.particle.io/u/system)\
**Post date:** [October 15, 2021, 12:39am UTC](https://community.particle.io/t/attachinterrupt-software-timer/59598/14 "2021-10-15T00:39:36Z")

</div>

Closed on October 15, 2021, 12:39am UTC

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