watterott / ATmega328PB-Testing

Atmel/Microchip ATmega328PB support for Arduino IDE
https://learn.watterott.com
76 stars 61 forks source link

Sleep and wake up on ext. interrupt not working #31

Closed leozulfiu closed 6 years ago

leozulfiu commented 6 years ago

The Problem

I would like to put the atmega328pb to sleep and wake up again when pressing a button which is connected to an external interrupt pin. I tried it with the attached sketch but it doesn't work really stable.

Observations

Example Code

#include <avr/sleep.h>

int wakePin = 2;
int sleepStatus = 0;
int count = 0;

void wakeUpNow() {
  detachInterrupt(0);
}

void setup() {
  pinMode(wakePin, INPUT);
  Serial.begin(9600);
  attachInterrupt(0, wakeUpNow, LOW);
}

void sleepNow() {
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);
    sleep_enable();
    attachInterrupt(0, wakeUpNow, LOW);
    sleep_mode();

    sleep_disable();
}

void loop() {
  Serial.print("Awake for ");
  Serial.print(count);
  Serial.println("sec");
  count++;
  delay(1000);

  if (count >= 5) {
      Serial.println("Timer: Entering Sleep mode");
      Serial.flush();
      delay(100);

      count = 0;
      sleepNow();
  }
}
leozulfiu commented 6 years ago

I added another println statement (Serial.println("In setup method");) in the setup method to debug the issue and found out that the microcontroller is restarting itself after each sleep cycle. Is this a bug or an issue with my sketch?

awatterott commented 6 years ago

I have tested your program with IDE 1.8.5 + AVR Boards 1.6.206 and it is working. I have only activated the pull-up on pin 2.

void setup() {
  pinMode(wakePin, INPUT);
  digitalWrite(wakePin, HIGH);