// กำหนดพิน
/*const int buttonPin = 2; // พินของปุ่มสวิตช์
const int ledPin = 13; // พินของ LED
// ตัวแปรสถานะ
bool ledState = false; // สถานะ LED (เริ่มต้นปิด)
bool lastButtonState = LOW; // สถานะปุ่มสวิตช์ครั้งก่อน
bool currentButtonState = LOW;
void setup() {
pinMode(buttonPin, INPUT_PULLUP); // ตั้งค่าปุ่มสวิตช์ให้ใช้ Pull-up Resistor
pinMode(ledPin, OUTPUT); // ตั้งค่าพิน LED เป็น Output
}
void loop() {
// อ่านสถานะปุ่มสวิตช์
currentButtonState = digitalRead(buttonPin);
// ตรวจจับการเปลี่ยนแปลงของสถานะปุ่ม (จาก LOW ไป HIGH)
if (currentButtonState == HIGH && lastButtonState == LOW) {
delay(50); // หน่วงเวลาเพื่อลดการเด้งของปุ่ม (Debouncing)
ledState = !ledState; // สลับสถานะ LED
digitalWrite(ledPin, ledState ? HIGH : LOW); // ตั้งสถานะ LED
}
// บันทึกสถานะปุ่มครั้งก่อน
lastButtonState = currentButtonState;
}*/
const int BUTTON_PIN = 13; // Connect the Button to pin 7 or change here
const int LED_PIN = 8; // Connect the LED to pin 3 or change here
// variables will change:
int ledState = LOW; // tracks the current state of LED
int lastButtonState; // the previous state of button
int currentButtonState; // the current state of button
void setup() {
Serial.begin(9600); // initialize serial
pinMode(BUTTON_PIN, INPUT); // set arduino pin to input mode
pinMode(LED_PIN, OUTPUT); // set arduino pin to output mode
currentButtonState = digitalRead(BUTTON_PIN);
}
void loop() {
lastButtonState = currentButtonState; // save the last state
currentButtonState = digitalRead(BUTTON_PIN); // read new state
if(lastButtonState == HIGH && currentButtonState == LOW) {
Serial.print("The button is pressed: ");
// toggle state of LED
if(ledState == LOW) {
ledState = HIGH;
Serial.println("Turning LED on");
delay(500);
}
else {
ledState = LOW;
Serial.println("Turning LED off");
delay(500);
}
// control LED arccoding to the toggled state
digitalWrite(LED_PIN, ledState); //turns the LED on or off based on the variable
}
}