Arduino - Digital input/output

UpdatedUpdatedJune 12 - 2017June 12 - 2017

Digital I/O (INPUT/OUTPUT) functions



pinMode( x, y );
x = pin name or pin number that we want to define as INPUT or OUTPUT
Return: NONE

By default, all analog and digital pins are configured as INPUT. So when we want to read value, it is not necessary to configure the pin as INPUT, but there is no harm if we do that.
When we want to write a value to a pin, we have to configure the pin as OUTPUT.


digitalWrite( x, y );
x = pin name or pin number to where we want to write a HIGH (1) or LOW (0) value
y = HIGH / LOW
Return: NONE

With pinMode(); if the pin is configured as OUTPUT, with digitalWrite(); we can set corresponding values (either HIGH or LOW).


pinMode( x );
x = pin name or pin number from where we want to read a digital (1/0) value
Return: HIGH / LOW

With pinMode(); first the pin is configured as INPUT. Then with digitalRead(); function we can read values (HIGH or LOW) from a specified pin.
If a pin is configured as INPUT but there is no input to that pin, then digitalRead(); can give us wrong result (either HIGH or LOW). So by default we should connect it to a known voltage (+5V for HIGH or GND for LOW) to avoid any confusion.

Now we will combine all 3 functions to write a complete Arduino sketch.
Digital pin 2 (configured as INPUT) is connected to a pushbutton .
Digital pin 3 (configured as OUTPUT) is connected to the anode of an LED.
When we press the pushbutton, LED is activated (ON).
When we release the pushbutton, LED is deactivated (OFF).

For better understanding, I used a breadboard power-supply. I connected its +5V to Arduino digital pin 2. And LED (anode) is connected to digital pin 3.
When the power-supply is OFF, digital pin 2 receives LOW or 0 volt and digital pin 3 sends LOW or 0 volt to LED (anode). So LED is OFF.
When the power-supply is ON, digital pin 2 receives HIGH or +5 volt and digital pin 3 sends HIGH or +5 volt to LED (anode). So LED is ON.

External link

Hint: Click on Start Simulation, then activate LED by pressing the pushbutton. When you release the pushbutton, LED will be deactivated.