Demo 21: How to use interrupt in Arduino ESP32

1. Introduction
- When interrupt occurs, micro-controller will stop current task immediately to process the event that cause the interrupt. If we do not use interrupt, we have to use loop control statement to always listen on events that we are interested in. In case our program has many tasks to do, we may miss the interested event because micro-controller is busy to process another task.
- The demo for this tutorial is quite simple. We use a button to connect to an interrupt pin. Every time the user press the button, it will cause an interrupt on ESP32 and ESP32 process this interrupt by toggle a LED.
2. Hardware
Figure: ESP32 attach external interrupt
Here we set interrupt pin as INPUT_PULLUP, it means there is a resister connect the input pin to Vcc so our circuit is more simple.
Figure: ESP32 connect to button (input_pullup) and LED
Connections:
[ESP32 GIO12 - BUTTON - GND]
[ESP32 GIO14 - LED - GND]
3. Software
- In order to use interrupt, we will use the 2 functions: attachInterrupt(digitalPinToInterrupt(pin), ISR, mode)
+ pin: is the pin to attach interrupt.
+ ISR: the function to be invoked when interrupt occurs.
+ mode: which event trigger interrupt (CHANGE: trigger when the pin change value, RISING: when the pin go from LOW to HIGH, ...)
- Create an Arduino project with code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/* LED pin */
byte ledPin = 14;
/* pin that is attached to interrupt */
byte interruptPin = 12;
/* hold the state of LED when toggling */
volatile byte state = LOW;

void setup() {
  pinMode(ledPin, OUTPUT);
  /* set the interrupt pin as input pullup*/
  pinMode(interruptPin, INPUT_PULLUP);
  /* attach interrupt to the pin
  function blink will be invoked when interrupt occurs
  interrupt occurs whenever the pin change value */
  attachInterrupt(digitalPinToInterrupt(interruptPin), blink, CHANGE);
}

void loop() {
}

/* interrupt function toggle the LED */
void blink() {
  state = !state;
  digitalWrite(ledPin, state);
}
4. Result

Post a Comment

3 Comments

Unknown said…
Hi, have you tried using many interrupts in the same code? I'm trying to implement a basic encoder with interrupts but haven't been able to succeed.
Anonymous said…
Can you say which pins can be used for interupts on the esp32?
Anonymous said…
all IO pins can be used in esp32