Lesson 13 Button Switch

Share for us

Introduction

Most SunFounder boards already have an LED attached to pin 13 itself. So we will use a button module and this LED to build a simple circuit and make an LED brighten.

Components

– 1 * SunFounder Uno board

– 1 * USB data cable

– 1 * Button module

–  Several jumper wires

Experimental Principle

With the LED attached to pin 13, connect the button module to digital pin 8. When the button module inducts button-pressing signals, the LED will be on. Otherwise, it will be off.

Experimental Procedures

Step 1: Build the circuit

                                    Button Module          SunFounder Uno

                                            S ————————————- Digital 8

                                            –  ————————————– GND

                                            + ————————————— 5V

Step 2: Program (Please refer to the example code in LEARN -> Get Tutorial on our website)

Step 3: Compile

Step 4: Upload the sketch to SunFounder Uno

Now, press the button and the LED attached to pin 13 on the SunFounder Uno board will light up.

Code

/*********************************************/
const int ledPin = 13;//the number of the led pin
const int buttonPin = 8; //the button pin attach to
int val = 0;//variable to store the value read from button
/*********************************************/
void setup()
{
pinMode(ledPin,OUTPUT);//initialize the ledPin as an output
pinMode(buttonPin,INPUT);//initialize the buttonPin as an intput
}
/*********************************************/
void loop()
{
val = digitalRead(buttonPin);//read the value from button
if(val == HIGH)
{
digitalWrite(ledPin,LOW);//turn the led off
}
else //when pressed
{
digitalWrite(ledPin,HIGH);//turn the led on
}
}
/***********************************************/