Note

Hello, welcome to the SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts Community on Facebook! Dive deeper into Raspberry Pi, Arduino, and ESP32 with fellow enthusiasts.

Why Join?

  • Expert Support: Solve post-sale issues and technical challenges with help from our community and team.

  • Learn & Share: Exchange tips and tutorials to enhance your skills.

  • Exclusive Previews: Get early access to new product announcements and sneak peeks.

  • Special Discounts: Enjoy exclusive discounts on our newest products.

  • Festive Promotions and Giveaways: Take part in giveaways and holiday promotions.

👉 Ready to explore and create with us? Click [here] and join today!

1.6 Digital Input Control Output

Overview

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

../_images/list_1.6.png

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.

../_images/image48.png

Schematic Diagram

../_images/image407.png

Code

Note

  • 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

../_images/image49.jpeg