Push button as input
Push button as input LED as output
Push button as input LED as output
In words:
Expectations: When the button is pushed, the serial screen shows a message. Pin 13 LED lights up, waits for 2 seconds and turns off.
Output: As expected.
int lastButtonState = LOW; // state of the button last time you checked
void setup() {
// initialize serial communication:
Serial.begin(9600);
// make pin 2 an input:
pinMode(2, INPUT);
// make pin 13 output
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
// read the pushbutton:
int buttonState = digitalRead(2);
digitalWrite(LED_BUILTIN, LOW); // turn the LED off
// if it's changed and it's high, toggle the mouse state:
if (buttonState != lastButtonState) {
if (buttonState == HIGH) {
Serial.println("Button was just pressed.");
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(2000);
}
}
// save button state for next comparison:
lastButtonState = buttonState;
}
Code related Question:
Code Reference: https://itp.nyu.edu/physcomp/labs/labs-arduino-digital-and-analog/digital-input-and-output-with-an-arduino/