HOME  - -  Many other Arduino "How Tos", etc, at my older site

Arduino: How an interrupt can give you a counter

Monitor a digital signal without polling in software
rising or falling edges

(filename: aht3inter_count.htm)

(Q: What is an "edge"? A: Something important that you need to know about. I've done a hasty explanation for you, if you don't already know 'all about' edges.)

yyy

This is a stub for a tutorial on using an interrupt to implement a counter in an ESP8266 Arduino.

There is almost no "explanation" here, but you may find the following code and references helpful... I hope they are, anyway!

/*ar_counter23517

vers 17 May 2023


====  "1st" ref.... =============================================
https://techtutorialsx.com/2016/12/11/esp8266-external-interrupts/

(Basis of most of what follows)
Other code makes the Adafruit Feather Huzzah 8266's on-bard blue LED
  wink. Eventually, the line driving the
  LED (output) will be connected to the pin by which interrupts are
  triggered, and then the counter will be counting the flashes of
  the blue LED. All lines added for that are remmed "//bf" for
  "Blue Flash".

====  "2nd" ref.... ================================================
https://randomnerdtutorials.com/interrupts-timers-esp8266-arduino-ide-nodemcu/

The ESP8266 supports interrupts in any GPIO, except GPIO16

The second argument of the attachInterrupt() function is the name of the function, [the ISR],
   that will be called...
   ISRs need to have ICACHE_RAM_ATTR before the function definition to run the interrupt code in RAM.

The third argument is the mode and there are 3 different modes:

    CHANGE: to trigger the interrupt whenever the pin changes value - for
           example from HIGH to LOW or LOW to HIGH;
    FALLING: for when the pin goes from HIGH to LOW;
    RISING: to trigger when the pin goes from LOW to HIGH.

---
//in setup()
   // Set motionSensor pin as interrupt, assign interrupt function and set RISING mode
   attachInterrupt(digitalPinToInterrupt(motionSensor), detectsMovement, RISING);

//Available SR...
   // Checks if motion was detected, sets LED HIGH and starts a timer
  ICACHE_RAM_ATTR void detectsMovement() {
  Serial.println("MOTION DETECTED!!!");
  digitalWrite(led, HIGH);
  startTimer = true;
  lastTrigger = millis();
}

---
delay() vs millis()

The delay() function accepts a single int number as an argument. This number represents the time in milliseconds the program has to wait until moving on to the next line of code.

delay(time in milliseconds);

When you call delay(1000) your program stops on that line for 1 second. delay() is a blocking function. Blocking functions prevent a program from doing anything else until that particular task is completed. If you need multiple tasks to occur at the same time, you cannot use delay(). For most projects you should avoid using delays and use timers instead.

Using a function called millis() you can return the number of milliseconds that have passed since the program first started.

  // check to see if it's time to blink the LED; that is, if the
  // difference between the current time and last time you blinked
  // the LED is bigger than the interval at which you want to
  // blink the LED.
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }

=================================================================
https://learn.adafruit.com/adafruit-feather-huzzah-esp8266/pinouts

GPIO #2, is used to detect boot-mode. It is also connected to the blue LED that is near the WiFi
    antenna. It has a pullup resistor connected to it, and you can use it as any output (like #0)
    and blink the blue LED.

You can use SPI on any pins but if you end up using 'hardware SPI' you will want to use the following:
    SPI MOSI = GPIO #13 (default)

I(Adafruit says...
    GPIO #16 can be used to wake up out of deep-sleep mode, you'll need to connect it to the RESET pin
 (But RandomeNerds says...
    The ESP8266 supports interrupts in any GPIO, except GPIO16

(So if you don't want to use pin 13 to be the place to trigger the interrupt, you can use 16, I think.)

 */

const byte pinInterrupt = 13;
const byte pinBlueLED = 2;//bf
volatile byte bInterruptCounter = 0;
unsigned int unintNumberOfInterrupts = 0;
unsigned int unintLoopsCompleted = 0;//bf

unsigned long unlongCurrentMillis,unlongPreviousMillis;//bf- from "2nd ref", to avoid need for
  //  "blocking" delay()
unsigned long unlongInterval = 1000;//bf- set to 1000 to make LED on 1 second,
  // off one second. Connect pinBlueLED to pinInterrupt and unintNumberOfInterrupts will
  // go up by one each time the LED goes from on to off, i.e. once every two seconds if
  // unlongInterval is set to 1000.
boolean boLedState = LOW;//bf


void setup() {

  Serial.begin(115200);
  delay(250);
  Serial.println("Number 8622 is alive");//bf
  pinMode(pinInterrupt, INPUT_PULLUP);
  pinMode(pinBlueLED, OUTPUT);//bf
  attachInterrupt(digitalPinToInterrupt(pinInterrupt), handleInterrupt, FALLING);//Mostly from 1st

}//end of setup()


ICACHE_RAM_ATTR void handleInterrupt() { //version from 2nd
//void handleInterrupt() { //version from 1st
  bInterruptCounter++;
}

void loop() {

  unintLoopsCompleted++;//bf

  if ((unintLoopsCompleted % 1000)==1){Serial.print("+");};//bf
  if ((unintLoopsCompleted % 20000)==1){Serial.println();};//bf

  /*Discarded "answer" to slowing loop begins...
  if ((unintLoopsCompleted % 100)>50) {digitalWrite(pinBlueLED,HIGH);}
   else {digitalWrite(pinBlueLED,LOW);};//bf
  delay(20);//bf
  ... END of discarded "answer to slowing loop.*/

//Better, non-blocking answer begins. From 2nd reference...
    unlongCurrentMillis = millis();//bf
    if ((unlongCurrentMillis - unlongPreviousMillis) >= unlongInterval) {
    // save the last time you blinked the LED
    unlongPreviousMillis = unlongCurrentMillis;
    //Hmmm... what happens when millis() rolls over??

    // if the LED is off turn it on and vice-versa:
    if (boLedState == LOW) {
      boLedState = HIGH;
    } else {
      boLedState = LOW;
    }
    // set the LED with the ledState of the variable:
    digitalWrite(pinBlueLED, boLedState);}
//... END of "Better, non-blocking answer

  if(bInterruptCounter>0){

      bInterruptCounter--;
      unintNumberOfInterrupts++;

      Serial.println();
      Serial.print("An interrupt has occurred. Total: ");
      Serial.println(unintNumberOfInterrupts);
  }//loop()

}//end of sketch

A few words from the sponsors...

Please get in touch if you discover flaws in this page. Please cite the page's URL. (http://wywtk.com/ardu/aht3inter_count.htm).

If you found this of interest, please mention in forums, give it a Facebook "like", Google "Plus", or whatever. If you want more of this stuff, help!? There's not much point in me writing these things, if no one feels they are of any use.



index sitemap
What's New at the Site Advanced search
Search tool (free) provided by FreeFind... whom I've used since 2002. Happy with it, obviously!

Unlike the clever Google search engine, this one merely looks for the words you type, so....
*    Spell them properly.
*    Don't bother with "How do I get rich?" That will merely return pages with "how", "do", "I"....

Please also note that I have three other sites, and that this search will not include them. They have their own search buttons.

My SheepdogSoftware.co.uk site, where you'll find my main homepage. It has links for other areas, such as education, programming, investing.

My SheepdogGuides.com site.

My site at Arunet.




How to email or write this page's editor, Tom Boyd. Please cite page's URL (http://wywtk.com/ardu/aht3inter_count.htm) if you write.


Valid HTML Page has been tested for compliance with INDUSTRY (not MS-only) standards, using the free, publicly accessible validator at validator.w3.org. Mostly passes.

AND passes... Valid CSS!


Why does this page cause a script to run? Because of the Google panels, and the code for the search button. Also, I have my web-traffic monitored for me by eXTReMe tracker. They offer a free tracker. If you want to try one, check out their site. Why do I mention the script? Be sure you know all you need to about spyware.

....... P a g e . . . E n d s .....