Code Analysis
Define variables
const int buttonPin = 12; //the button connect to pin 12
const int ledPin = 13; //the led connect to pin13
int buttonState = 0; // variable for reading the pushbutton status
Connect the button to pin 12. LED has been connected to pin 13. Define a
variable buttonState to restore the state of the button.
Set the input and output status of the pins
pinMode(buttonPin, INPUT); //initialize thebuttonPin as input
pinMode(ledPin, OUTPUT); //initialize the led pin as output
We need to know the status of the button in this experiment, so here set
the buttonPin as INPUT; to set HIGH/LOW of the LED, we set LedPin as
OUTPUT.
Read the status of the button
buttonState = digitalRead(buttonPin);
buttonPin(Pin12) is a digital pin; here is to read the value of the
button and store it in buttonState.
digitalRead (Pin): Reads the value from a specified digital pin,
either HIGH or LOW.
Press the button to make the buzzer sound
if (buttonState == HIGH )
{
digitalWrite(ledPin, HIGH); //turn the led on
}
else
{
digitalWrite(ledPin, LOW); //turn the led off
}
In this part, when the buttonState is High level, write ledPin as
High and the LED will be turned on. As one end of the button has been
connected to 5V and the other end to pin 12, when the button is pressed,
pin 12 is 5V (HIGH). And then determine with the if (conditional); if
the conditional is true, then the LED will light up.
else means that when the if(conditional) is determined as false, run
the code in else.