🖲️ دکمه‌ی بی‌لرزش

دکمه روی D2، LED روی D13 — هر فشار یک شمارش.

سطح: متوسط ⭐⭐ · مود: آردوینو (سه‌بعدی + کد)

قطعات لازم

کد کامل پروژه

const int BUTTON = 2, LED = 13;
const unsigned long DEBOUNCE_MS = 50;   // bounce is over after ~5-20 ms

int lastReading = HIGH;     // what the pin said last loop
int stableState = HIGH;     // the state we believe
unsigned long lastChange = 0;
int presses = 0;
bool ledOn = false;

void setup() {
  pinMode(BUTTON, INPUT_PULLUP);
  pinMode(LED, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  int reading = digitalRead(BUTTON);

  // the pin moved: restart the quiet-time clock
  if (reading != lastReading) {
    lastChange = millis();
    lastReading = reading;
  }

  // quiet for 50 ms AND different from what we believed = a real change
  if (millis() - lastChange > DEBOUNCE_MS && reading != stableState) {
    stableState = reading;
    if (stableState == LOW) {          // pressed (pull-up: LOW = pressed)
      presses++;
      ledOn = !ledOn;
      digitalWrite(LED, ledOn);
      Serial.print("presses: ");
      Serial.println(presses);
    }
  }
}

چطور اجرایش کنم؟

  1. شبیه‌ساز تینکرکد فارسی را باز کن و «مود آردوینو» را انتخاب کن.
  2. از پنل «نمونه‌ها»، «دکمه‌ی بی‌لرزش» را بارگذاری کن — مدار و کد با هم می‌آیند.
  3. دکمه‌ی اجرا ▶ را بزن و خروجی Serial و رفتار قطعات را تماشا کن.
  4. حالا کد را تغییر بده — عددها، پین‌ها، ترتیب — و دوباره اجرا کن!
این پروژه را رایگان در شبیه‌ساز اجرا کن 🤖