Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade

How to Create a Script to Flash a Light When a Button is Pressed

Script:


const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin

int buttonState = 0; // variable for reading the pushbutton status

void setup() {
pinMode(ledPin, OUTPUT); // initialize the LED pin as an output
pinMode(buttonPin, INPUT); // initialize the pushbutton pin as an input
}

void loop() {
buttonState = digitalRead(buttonPin); // read the state of the pushbutton value

if (buttonState == HIGH) { // check if the pushbutton is pressed
digitalWrite(ledPin, HIGH); // turn LED on
delay(500); // wait for half a second
digitalWrite(ledPin, LOW); // turn LED off
delay(500); // wait for half a second
} else {
digitalWrite(ledPin, LOW); // turn LED off
}
}

Como Executar o Script:


1. Components Required:



  • Arduino board (e.g., Arduino Uno)

  • LED

  • Pushbutton

  • Resistors (220 ohm for LED, 10k ohm for button)

  • Breadboard and jumper wires


2. Circuit Setup:



  • Connect the LED anode (longer leg) to pin 13 on the Arduino and the cathode (shorter leg) to ground through a 220-ohm resistor.

  • Connect one terminal of the pushbutton to pin 2 on the Arduino.

  • Connect the other terminal of the pushbutton to 5V.

  • Connect a 10k-ohm resistor from pin 2 to ground to act as a pull-down resistor.


3. Upload the Script:



  • Open the Arduino IDE on your computer.

  • Copy the provided script into a new sketch.

  • Connect your Arduino board to your computer using a USB cable.

  • Select the correct board and port from the 'Tools' menu in the Arduino IDE.

  • Click on the 'Upload' button to upload the script to the Arduino board.


4. Test the Setup:



  • Once the script is uploaded, press the button.

  • The LED should flash on and off while the button is pressed.


To share Download PDF

Gostou do artigo? Deixe sua avaliação!
Sua opinião é muito importante para nós. Clique em um dos botões abaixo para nos dizer o que achou deste conteúdo.