Arduino Nano - Sleep/Wake - Same Button

Hi

I want to make Arduino Nano go to deep sleep using interrupt, Pin 2. And then wake up with same pin.

Schematic => A jumper wire connected to pin D2.
Here is the code:

#include <avr/sleep.h>
#define interruptPin 2 

unsigned long wakeUpMillis = 0;
bool IntAttached = true; // Interrupt is attached 

void setup() 
{
  Serial.begin(115200);//Start Serial Comunication
  pinMode(LED_BUILTIN,OUTPUT);
  pinMode(interruptPin,INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), goToSleep, LOW);
}

void loop() 
{
  digitalWrite(LED_BUILTIN,HIGH);
  delay(500);
  digitalWrite(LED_BUILTIN,LOW);
  delay(500);
  
  if (!IntAttached && millis() - wakeUpMillis > 2000)
  {
    noInterrupts();
    attachInterrupt(digitalPinToInterrupt(interruptPin), goToSleep, LOW);
    interrupts();
    IntAttached = true;
  }
}

void goToSleep()
{
  sleep_enable();//Enabling sleep mode
  noInterrupts();
  attachInterrupt(digitalPinToInterrupt(interruptPin), wakeUp, LOW);
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  Serial.println("Going to sleep..... zzzZZZZ");
  delay(2000);
  interrupts();
  sleep_cpu();//activating sleep mode
  // Now the µController is asleep........zzzZZZZZZ
  //
  //
  // will resume from here
  //  
  //
  Serial.println("just woke up!"); 
}

void wakeUp()
{
  noInterrupts();
  detachInterrupt(digitalPinToInterrupt(2));
  interrupts();
  IntAttached = false; // Interrupt is detached.

  Serial.println("Interrupt Fired");
  sleep_disable();
  wakeUpMillis = millis();
}

The problem is that the Nano goes to sleep and wakes up immediately when D2 is LOWered.

" Nano goes to sleep and wakes up immediately when D2 is LoWered." That means the switch attached to pin2 is now working as a momentary switch. But you want it to work as a toggle switch, right? There are many examples for toggle switches. Usually If you apply the same concept in your code, it will give your desired result.

No, it is a momentary switch.
One push ---- Go to sleep
Next push --- Wake up

I have also tried to Attach the interrupt on FALLING but no results.

You may think you're disabling interrupts, but in reality this doesn't happen in your sketch. I think it's actually the internal watchdog on the microcontroller that re-enables them; you'd have to chekc the datasheet on this. Good thing too, because for instance your Serial.println wouldn't work if interrupts were truly disabled.

Also I think you're better off using an interrupt only for wakeup and not to go to sleep, so I'd give the fundamental logic of your code a serious thought.

Finally, consider debouncing. It's a thing!

And the other end of the wire goes to GND, I assume? Even a simple schematic can have bugs in it, it shows :wink:

I have tried digitalRead (with debounce) to Go to Sleep and interrupt for Wake up. But still not working.

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