#include <avr/interrupt.h>
#include <avr/sleep.h>
volatile unsigned long count1 = 15625; // 1 Hz in a clock cycle
// Edge detection flags for the switches
volatile int edge0 = 0; // Switch 1
volatile int edge1 = 0; // Switch 2
void setup() {
cli(); // Clear global interrupt
DDRD |= B01000000; // Set Pin 6 as output
DDRD &= B01111111; // Set Pin 7 as input
DDRB &= B111110; // Set Pin 8 as input
// Enabling both the PCINT0 (Port B) and PCINT2 (Port D) to activate
PCICR |= B00000101;
// Setting up the switch interrupts
PCMSK0 |= (1 << PCINT0); // Mask for Pin 8
PCMSK2 |= (1 << PCINT23); // Mask for Pin 7
// Setting up Timer1
TCCR1A = B00000000; // Initialize to 0
TCCR1B = B00000101; // Pre-scaling to 1024 (max value)
// Turn on the OVF timer for Ports B and D (1 Hz)
TIMSK1 = B00000101;
// Set the initial clock reading
TCNT1 = 0xFFFF - count1; // 0xC2F6 or (65535-15625 = 49910)
sei(); // Setting up all global interrupts
// Set the appropriate sleep mode for lowest power possible
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
}
// Interrupt for Timer1 in OVF mode
ISR(TIMER1_OVF_vect) {
PORTD ^= B01000000; // Toggle LED on Pin 6
TCNT1 = 0xFFFF - count1; // Reset the timer to most updated clock cycle value
}
// Interrupt Service Request by pressing the switch connected to Pin 8
ISR(PCINT0_vect) {
edge0 = edge0 + 1; // Increments upon pushing Switch 1
if (edge0 == 1) {
// Add the code to decrease the output frequency
count1 = count1 * 2;
// If the following clock cycle number (for 0.5 Hz) is exceeded...
if (count1 > 31250) {
count1 = 31250; //... reset clock cycle to highest possible
}
}
if (edge0 > 1) {
edge0 = 0;
}
}
// Interrupt Service Request by pressing the switch connected to Pin 7
ISR(PCINT2_vect) {
edge1 = edge1 + 1; // Increments upon pushing Switch 2
if (edge1 == 1) {
// Add the code to increase the output frequency
count1 = count1 / 2;
// If the following clock cycle number (for 8 Hz) is lowered...
if (count1 < 1953) {
count1 = 1953; //... reset clock cycle to lowest possible
}
}
if (edge1 > 1) {
edge1 = 0;
}
}
void loop() {
// Serial.println(value); // Used for debugging
sleep_mode();
}