No. 5 – Push button and LED

Task: After pushing the button an LED is supposed to light up for 5 seconds.

Required equipment: Arduino / one LED (blue) / one resistor with 100Ohm / one resistor with 1K Ohm (1000 Ohm) / Breadboard / Cables / Push button

The digital pins of the microcontroller are not only able to put out voltage, they are also able to read out voltage. We are going to try this with the following program. This time there is something special in the setup. If we would simply connect the push button with the microcontroller and push the button, there would be voltage on the pin. You can imagine it like many electrons floating around the pin. When you now release the button, there wouldn’t get any more electrons to the pin. Now the difficulty: The electrons that are already floating around the pin are only escaping extremely slow. So the microcontroller thinks that the button has been pushed longer than it actually has been. The microcontroller thinks that the button has been pushed until the electrons have escaped completely from the pin. This problem can be fixed by grounding the pin with a 1000 Ohm (1K Ohm) resistor. Now the electrons are able to escape from the pin faster and the microcontroller recognizes that the button only has been pushed briefly. The resistor is called “PULLDOWN”- resistor, because the resistors is always “pulling down” the voltage to 0V. ATTENTION: If you are using a smaller valued resistor, you can get an electrical short on the microcontroller while pushing the button.

Setup:

PL1

Code:


int LEDblue=6; //The word “LEDblue” stands for the value 6.

int button=7; //The word “button” stands for the value 7.

int buttonstatus=0; //The word “buttonstatus” stands for the value 0. Later on there will be safed wheter //the button is pushed or not.

void setup()

{ //The setup starts here

pinMode(LEDblue, OUTPUT); //The pin connected to the LED (pin 6) is an output

pinMode(button, INPUT); //The pin connected to the button (pin 7) is an input.

}

void loop()

{ //with this bracket the loop part starts

buttonstatus=digitalRead(button); //The value on pin 7 is read out (command: digitalRead). The result will //be safed under “buttonstatus”. (HIGH means 5V and LOW means 0V)

if (buttonstatus == HIGH) //If the button gets pushed (high voltage value)…

{ //open program part of the IF-command

digitalWrite(LEDblue, HIGH); //…the LED should light up

delay(5000); //5000 miliseconds (5 seconds) long

digitalWrite(LEDblue, LOW); //after 5seconds the LED should turn off

} //close the program part of the IF-command

else

{ //open the program part of the else-command

digitalWrite(LEDblue, LOW); //the LED shouldn’t light up

} //close the program part of the else-command

} //with this bracket the whole loop parts gets closed