Donde poner attachInterrupt

Quiero hacer un proyecto con baterías en el que arduino esta todo el rato en sleep, excepto cuando un sensor magnético cambie de alto a bajo y viceversa, que despierte el arduino y ejecuta unas acciones una sola vez.
La cuestion es que no se muy bien donde poner el attachInterrupt, si en el setup o en el loop

Esta es mi idea:

#include <LowPower.h>
#include <Serial.h>

const int sensor = 1;

void setup() {
    pinMode(sensor, INPUT);
    Serial.begin(9600);
    attachInterrupt(digitalPinToInterrupt(sensor), wakeUp, CHANGE);
    LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);
}

void loop() {
}

void wakeUp() {
    serial.println("Hola mundo!");
    LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);
}

En los ejemplos de LowPower tienes el que que dice WakeUp with External Interrupt que es tu caso.

Supongamos que uses esta librería

Este ejemplo powerDownWakeExternalInterrupt

// **** INCLUDES *****
#include "LowPower.h"

// Use pin 2 as wake up pin
const int wakeUpPin = 2;

void wakeUp()
{
    // Just a handler for the pin interrupt.
}

void setup()
{
    // Configure wake up pin as input.
    // This will consumes few uA of current.
    pinMode(wakeUpPin, INPUT);   
}

void loop() 
{
    // Allow wake up pin to trigger interrupt on low.
    attachInterrupt(0, wakeUp, LOW);
    
    // Enter power down state with ADC and BOD module disabled.
    // Wake up when wake up pin is low.
    LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF); 
    
    // Disable external pin interrupt on wake up pin.
    detachInterrupt(0); 
    
    // Do something here
    // Example: Read sensor, data logging, data transmission.
}

Tienes como usarlo.

 // Allow wake up pin to trigger interrupt on low.
    attachInterrupt(0, wakeUp, LOW);  
    // Enter power down state with ADC and BOD module disabled.
    // Wake up when wake up pin is low.
    LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF); 
 // Disable external pin interrupt on wake up pin.
    detachInterrupt(0); 

Estas 3 lineas comandan todo, le dicen que rutina debe despertarlo o sea wakeup y que lo hará por LOW asi que veo que tu pusiste CHANGE pero change anda tanto de 0a a 1 como de 1 a 0, ojo. Tienes RISING y FALLING. Si quieres ir de 0 a 1 es RISING
como se pone a dormir apagando todo.
Finalmente el de detachInterrupt(0); que lo pone en normal y haces lo que quieres hacer cuando este despierto.

1 Like

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