ข้ามไปยังเนื้อหา

Lesson 5: Buttons

English

Reading a pin

  • A pin can also read: digitalRead(2) gives HIGH or LOW.
  • The button on this board connects pin 2 to GND (0 volts) when you press it.
  • INPUT_PULLUP keeps the pin HIGH when nobody presses. So: pressed = LOW.
void setup() {
  pinMode(2, INPUT_PULLUP);
  pinMode(13, OUTPUT);
}

void loop() {
  if (digitalRead(2) == LOW) {     // pressed
    digitalWrite(13, HIGH);
  } else {
    digitalWrite(13, LOW);
  }
}
  • Press Run, then hold the red button. The LED is on only while you press.
  • == asks "is it equal?". One = puts a value into a variable.

เข้าสู่ระบบหรือสร้างบัญชี

IGCSE, A-Level & AP