jack jill
jack jill

Reputation: 3

NodeMCU interrupt code does not execute every time

I want to blink and led for 2 seconds when I press a push button. For that, I wrote this code using interrupts. But it does not execute every time the code is uploaded. Any suggestion is welcome. Even the serial.println("started") is not displayed. No error is shown either.

#define led_pin D1
#define int_pin D8

volatile bool led = false;

void ICACHE_RAM_ATTR ISR_func();

void setup() {
 Serial.begin(9600);
 Serial.println("started");
 pinMode(int_pin, INPUT_PULLUP);
 attachInterrupt(digitalPinToInterrupt(int_pin), ISR_func, RISING);
}

void loop() {
    if(led){
        led_func();
    }
}

void ISR_func(){
    //Serial.println("interrupt detected");
    led = true;
    return;
}

void led_func(){
    Serial.println("led");
    digitalWrite(led_pin, HIGH);
    delay(2000);
    digitalWrite(led_pin, LOW);
    delay(2000);
    led = false;
    return;
}

Hardware: I connected D8 and GND pin using a push button and D1 is connected to led, which is again connected to GND of nodemcu (ESP8266).

~ld

Upvotes: 0

Views: 1366

Answers (2)

mohammed saleh qaid
mohammed saleh qaid

Reputation: 1

pinMode(led_pin, OUTPUT); you have to define the led_pin as an output pin, I have tried your code and it works fine after I add this line of code only.

Upvotes: 0

Masoud Rahimi
Masoud Rahimi

Reputation: 6031

First, you can't use Serial function in an interrupt's ISR because it uses an interrupt. Second, your code seems fine but I think your problem is with the wiring.

In the NodeMCU board, the pins of the microcontroller don’t map to the pins of the board. For example, the GPIO15 will map to the D8 pin of the board. You can see the full pin maps here.

#define led_pin D1
const byte int_pin = 15;

volatile bool led = false;

void ICACHE_RAM_ATTR ISR_func();

void setup()
{
    Serial.begin(9600);
    Serial.println("started");
    pinMode(int_pin, INPUT_PULLUP);
    attachInterrupt(digitalPinToInterrupt(int_pin), ISR_func, RISING);
}

void loop()
{
    if (led)
    {
        led_func();
        led = false;
    }
}

void ISR_func()
{
    led = true;
}

void led_func()
{
    Serial.println("led");
    digitalWrite(led_pin, HIGH);
    delay(2000);
    digitalWrite(led_pin, LOW);
    delay(2000);
}

Upvotes: 1

Related Questions