button_led.ino

Download
cpp 45 lines 1.1 KB
 1// button_led.ino
 2// 버튼으로 LED 제어하기
 3
 4const int BUTTON_PIN = 2;  // 버튼 핀
 5const int LED_PIN = 13;    // LED 핀
 6
 7bool ledState = false;
 8bool lastButtonState = HIGH;
 9
10void setup() {
11    pinMode(BUTTON_PIN, INPUT_PULLUP);  // 내부 풀업 사용
12    pinMode(LED_PIN, OUTPUT);
13
14    Serial.begin(9600);
15    Serial.println("Button LED Control");
16    Serial.println("Press button to toggle LED");
17}
18
19void loop() {
20    bool currentButtonState = digitalRead(BUTTON_PIN);
21
22    // 버튼이 눌렸을 때 (HIGH → LOW)
23    if (lastButtonState == HIGH && currentButtonState == LOW) {
24        ledState = !ledState;  // LED 상태 토글
25        digitalWrite(LED_PIN, ledState);
26
27        Serial.print("LED ");
28        Serial.println(ledState ? "ON" : "OFF");
29    }
30
31    lastButtonState = currentButtonState;
32    delay(50);  // 간단한 디바운싱
33}
34
35/*
36 * Wokwi 회로 구성:
37 * 1. Arduino Uno 추가
38 * 2. Pushbutton 추가
39 * 3. 연결:
40 *    - 버튼 한쪽 → 핀 2
41 *    - 버튼 다른쪽 → GND
42 *
43 * 버튼을 누를 때마다 LED가 켜지고 꺼집니다.
44 */