0% found this document useful (0 votes)
4 views1 page

Arduino Code

This Arduino code controls an LED based on button presses and serial commands. It implements a debounce mechanism to ensure stable button readings and toggles the LED state accordingly. The LED state can also be set via serial input, responding to '1' for ON and '0' for OFF.

Uploaded by

Hoàng Lương
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views1 page

Arduino Code

This Arduino code controls an LED based on button presses and serial commands. It implements a debounce mechanism to ensure stable button readings and toggles the LED state accordingly. The LED state can also be set via serial input, responding to '1' for ON and '0' for OFF.

Uploaded by

Hoàng Lương
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

const int buttonPin = A0;

const int ledPin = 13;

bool ledState = false;


bool lastButtonState = HIGH;

unsigned long lastDebounceTime = 0;


const unsigned long debounceDelay = 50;

void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
[Link](9600);
}

void loop() {
bool buttonState = digitalRead(buttonPin);

if (buttonState != lastButtonState) {
lastDebounceTime = millis();
}

if ((millis() - lastDebounceTime) > debounceDelay) {


if (buttonState == LOW && ledState == false && lastButtonState == HIGH) {
ledState = true;
digitalWrite(ledPin, HIGH);
[Link]("1");
} else if (buttonState == LOW && ledState == true && lastButtonState == HIGH) {
ledState = false;
digitalWrite(ledPin, LOW);
[Link]("0");
}
}
lastButtonState = buttonState;

if ([Link]()) {
char cmd = [Link]();
if (cmd == '1' || cmd == '0') {
ledState = (cmd == '1');
digitalWrite(ledPin, ledState ? HIGH : LOW);
[Link](cmd);
}
}
}

You might also like