const int btn_pin = 2;
const int led_pin = 5;
/*
void setup() {
pinMode(btn_pin, INPUT_PULLUP);
pinMode(led_pin, OUTPUT);
}
void loop() {
int btn = digitalRead(btn_pin);
if(btn == LOW){
digitalWrite(led_pin, HIGH);
}
else{
digitalWrite(led_pin, LOW);
}
}
*/
void setup() {
/* NOTE: Although we did BXXXXXXXX for visual simplicity here
it is best to use AND and OR type operation together with
left shift to prevent altering other bits we do not want.
*/
DDRD = B00100000; // Set Pins to Be either Input or Output
PORTD = B00000100; // If Input, (1 or 0 Enables or Disables Pull-UP)
// If Output (1 or 0 Sets to 5V or 0V)
}
void loop() {
// int btn = digitalRead(btn_pin);
int btn = (PIND & (1 << btn_pin)) >> 2;
/*
In order to read the states of A (Single) Pin in Port D, specifically the
state of Pin 2, I can first shift a 1 bit left two times, where we have "1" for position
of Pin 2, and a 0 for eveything else.
I then can AND this with the state of all the Pins using PIND.
Since 0 ANDED with either 1 or 0, is 0, we know all other bits other than bit for Pin 2 is 0.
This leaves is only worrying about the 2 bits that correspond with Pin 2.
If PIN 2 was previously 1, 1 AND 1 = 1.
IF PIN 2 was previously 0, 1 AND 0 = 0.
We then shift back to the right by 2 to represent the value correct by either
HIGH 1 which is B00000001 which 1 Decimal or LOW 0 which is B00000000 which is 0 decimal.
*/
if(btn == LOW){
// PORTD = B00100000;
/* Preferably do the below to prevent messing with pins
other than the one we want to. Like accidently changing a input pin pull-up resistor.
*/
//NOTE: led_pin = pin #5, We are shfting 1 left 5 times.
PORTD = (1<< led_pin | PORTD);
}
else{
//PORTD = B00000100;
/* Using the way above we have to pay atttention to not mess with
other pins, like here we had to keep pin bit 2 high to keep tpin 2 pull-up
resistor on.
*/
PORTD = ~(1 << led_pin) & PORTD;
}
}