We use pinMode function
But this time to set the pin as INPUT
To achieve this, we use digitalRead function
Reads the value from a specified digital pin,
either HIGH or LOW.
int v = digitalRead(4);
The most intuitive way:
But what is the voltage when the button is not pressed?
The voltage measured by a non connected (floating) pin is highly variable in time
Every tiny change in charge can determine a big change in voltage
by using a...
or, as an alternative...
void setup() {
pinMode(8, OUTPUT); // initializes LED pin as output
pinMode(4, INPUT); // initializes button pin as input
}
void loop() {
if (digitalRead(4) == HIGH) { // checks for button pressing
digitalWrite(8, HIGH); // turns the LED on
} else { // if button is released
digitalWrite(8, LOW); // turns the LED off
}
delay(100); // waits a moment
}
At the beginning, the LED stays off,
when we hold the button the LED turns on,
when we release it the LED turns back off
The MCU "listens" to the environment
and when something changes it does something