1.6 Digital Input Control Output


With the understanding of digitalWrite() and digitalRead(), we can build a complete I / O system to control the output device by obtaining the data from the input device. We can use this method to enable digital input components such as Button, Touch sensor, Infrared motion sensor to control digital output devices such as LED, active buzzer. This lesson will take Button and LED as examples to realize button control LED with the condition (if-else).

Components Required


Fritzing Circuit

In this example, we use pin 9 to drive LED. Use digital pin 2 to read the signal of Button. When the button is pressed, the LED lights up.


Schematic Diagram




  • You can open the file 1.6_digitalInputControlOutput.ino under the path of sunfounder_vincent_kit_for_arduino\code\1.6_digitalInputControlOutput directly.

  • Or copy this code into Arduino IDE.

After uploading the code to the Mega2560 board, you can hold down Button to lighten the LED.

Code Analysis

Declare the pins of LED and Button and declare a variable to store the state of button.

const int buttonPin = 2;
const int ledPin =  9;
int buttonState = 0;

Initialize the pin mode in setup().

pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);

Read the status of the Button in loop() and assign it to the variable buttonState.

buttonState = digitalRead(buttonPin);

Use if condition to judge: if you get high level from a button, light up the LED.

if (buttonState == HIGH) {
    digitalWrite(ledPin, HIGH);

Otherwise, turn off the LED.

else {
digitalWrite(ledPin, LOW);

Phenomenon Picture