Digital input

The goal

We want to get the value of a digital signal

First step (as usual), init the pin

We use pinMode function

But this time to set the pin as INPUT

Read the value of the pin

To achieve this, we use digitalRead function

digitalRead(pin)

Reads the value from a specified digital pin,
either HIGH or LOW.
int v = digitalRead(4);

The task

We want to turn on an LED
as long as a button is held pressed

How can I wire a button to Arduino?

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

Can we set a known state when the button is not pressed?

by using a...

Pulldown resistor

n.b. We want a big resistance (why?)

or, as an alternative...

Pullup resistor

The circuit

The sketch

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
}

What (is supposed to) happen?

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

We created a (very simple) control system

(An open loop control system)

The MCU "listens" to the environment
and when something changes it does something

Well done!