"Digital input" บน Arduino คือการรับสัญญาณดิจิทัลจากอุปกรณ์ภายนอกเข้ามายังบอร์ด Arduino โดยสัญญาณดิจิทัลมีแค่สองสถานะ คือ:
HIGH (1): มักหมายถึงแรงดันไฟฟ้า 5V (หรือ 3.3V แล้วแต่บอร์ด)
LOW (0): หมายถึงแรงดันไฟฟ้า 0V หรือ ground
ตัวอย่างการใช้งาน:
กดปุ่ม (push button)
สัญญาณจากสวิตช์
เซนเซอร์ที่ให้ output เป็นดิจิทัล เช่น PIR motion sensor
อุปกรณ์อื่น ๆ ที่ส่งข้อมูลเป็น on/off
วิธีใช้งาน digital input บน Arduino:
การต่อวงจร (ตัวอย่าง: ปุ่มกด) ขาปุ่มฝั่งหนึ่งต่อไปยังขา digital input (เช่น D2) อีกฝั่งของปุ่มต่อกับ GND ใส่ pull-up resistor (ใช้ภายใน Arduino ก็ได้)
โค้ดตัวอย่าง:
const int buttonPin = 2; // ใช้ขา digital 2
int buttonState = 0;
void setup() {
pinMode(buttonPin, INPUT_PULLUP); // ใช้ pull-up ภายใน
Serial.begin(9600);
}
void loop() {
buttonState = digitalRead(buttonPin);
if (buttonState == LOW) { // ปุ่มถูกกด
Serial.println("Button pressed");
} else {
Serial.println("Button released");
}
delay(200);
}
หมายเหตุ: ถ้าใช้ INPUT_PULLUP สัญญาณจะกลับกัน (LOW = กด, HIGH = ไม่กด)