Last active
August 6, 2020 11:02
-
-
Save mpentler/a04f4a7a22eb417fbb1c18c4576c49a6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <avr/sleep.h> | |
#include <avr/interrupt.h> | |
int LEDpin = PB0; // start on green LED | |
void setup() { | |
// Configure our input and output pins | |
DDRB = 0b00000111; // PB0-2 as inputs, leave PB3 (4th bit) as output (0) | |
PORTB |= (1<<PB3); // enable the pull-up resistor on PB3 | |
sei(); // Enable interrupts | |
GIMSK |= _BV(PCIE); // Enable Pin Change Interrupts | |
PCMSK |= _BV(PCINT3); // Use PB3 as interrupt pin | |
// Flash quick sequence so we know setup has finished | |
for (int k = 0; k < 10; k = k + 1) { | |
if (k % 2 == 0) { | |
PORTB = 0b00001111; // Notice PB3 is still 1 (so we don't lose the pullup) | |
} | |
else { | |
PORTB = 0b00001000; // And here too | |
} | |
delay(250); | |
} | |
PORTB |= (1 << LEDpin); | |
} | |
void sleep() { | |
set_sleep_mode(SLEEP_MODE_PWR_DOWN); // set the correct mode | |
sleep_enable(); // Sets the Sleep Enable bit in the MCUCR Register (SE BIT) | |
sleep_cpu(); // sleep | |
// =========================================== sleeps here | |
sleep_disable(); // Clear SE bit | |
} | |
ISR(PCINT0_vect) { // Runs when the button is pushed | |
if (PINB & (1 << PB3) ) { | |
PORTB &= ~(1 << LEDpin); // turn off the current LED | |
if (LEDpin < PB2) { // if we're not currently on red... | |
LEDpin++; // ...we iterate the pin by one | |
} | |
else { | |
LEDpin = PB0; // otherwise we cycle back to green again | |
} | |
PORTB |= (1 << LEDpin); // Light the new LED | |
} | |
} | |
void loop() { | |
sleep(); // call our sleep routine | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Changed the interrupt code entirely thanks to help from Reddit, also changed to direct pin I/O instead.