/*
//Pins
const uint8_t btn_pin = 2;
const uint8_t led_pin = 5;
// Global state
uint8_t led_state = LOW; // Initializing state
void setup() {
pinMode(btn_pin, INPUT_PULLUP);
pinMode(led_pin, OUTPUT);
// Pin to interrupt, Function to jump to when inturrupt, Triggered when Falling Edge on Pin 2 (btn_pin)
attachInterrupt(digitalPinToInterrupt(btn_pin), toggle, FALLING);
}
void loop() {
//pretend doing other stuff
delay(500);
}
void toggle(){
led_state = !led_state;
digitalWrite(led_pin, led_state);
}
*/
//Pins
const uint8_t btn_pin = 2;
const uint8_t led_pin = 5;
// Global state
uint8_t led_state = LOW; // Initializing state
void setup() {
/* NOTE: Please not the importance of using AND and OR operation with left shift operation
Rather than just doing B00000100. Remember, by using the operations like so, we are just
manipulating the single bit we want without messing with any of the other bits.
If we just do BXXXXXXXXX, we run into the problem where we will likely manipulate or change other bits!
*/
DDRD &= ~(1 << btn_pin); // Clearing or Setting only Bit 2 to 0. Since we want to need to be input for Pull Up
PORTD |= (1 << btn_pin); // Enabling PULL UP Onlt for Pin 2.
//Set LED pin to be Output
DDRD |= (1 << led_pin);
// Pin to interrupt, Function to jump to when inturrupt, Triggered when Falling Edge on Pin 2 (btn_pin)
//attachInterrupt(digitalPinToInterrupt(btn_pin), toggle, FALLING);
// Falling edge of INT0 generares interrupt (External Inrerrupt Control Register A (EICRA))
// NOTE: "EICRA" is the Register Name address..."ISC01" is bit 1 and "ISC00" is bit 0.
EICRA |= (1 << ISC01); // Set bit 1
EICRA &= ~(1 << ISC00); // Clear bit 0
/* Above bits were dont this way since from the data sheet, last or lowest
two bits in EICRA need to 10*/
//Enable Interrupts for INT0
EIMSK |= (1 << INT0); // Allow External Interrupts to trigger for INT0
//Enable global Interrupts
//NOTE: Arduino already turns them on by default
/*NOTE: Although arduino AVR library provides the function sei(); to enable global interrupts
using registers, SREG |= (1 << I) I think */
sei();
}
void loop() {
//pretend doing other stuff
delay(500);
}
// void toggle()
ISR(INT0_vect){
PORTD ^= (1 << led_pin);
/*
NOTE: ^ is XOR operation
In XOR, It is 0 if the two bits are the same
It is 1 if the two bits are different.
In doing so we can Flip an individual bit.
And yes it does work, just think about the logic.
Above code is doing same as this
led_state = !led_state;
digitalWrite(led_pin, led_state);
*/
}