按键消抖 — Esp32 C6 simulation

An interactive Esp32 C6 circuit simulation you can run free in your browser on Velxio, by yaxin.

Components

Sketch code

// ESP32-C6-DevKitC-1 - blink GPIO8 + serial log.
// GPIO8 also drives the board's WS2812 RGB LED; a plain external LED (through
// a 220R resistor to GND) on the same header pin is what this blinks.
#define LED_PIN 8
const int LED1_PIN=5;
const int LED2_PIN=6;
const int LED3_PIN=7;
const int KEY1_PIN=22;
const int KEY2_PIN=21;
const int KEY3_PIN=20;

bool key1jicun=1;  //key1动作翻转

const unsigned long key2fangdoushijian =50;
int key2zhongzhuan=0;
int key2fanzhuan=0;
int led2fanzhuan=1;
unsigned long key2fangdouyanshikaishi=0;

void setup() {
  Serial.begin(115200);
  pinMode(LED_PIN, OUTPUT);
  Serial.println("ESP32-C6 ready");
  pinMode(LED1_PIN, OUTPUT);
  pinMode(LED2_PIN, OUTPUT);
  pinMode(LED3_PIN, OUTPUT);
  pinMode(KEY1_PIN, INPUT_PULLUP);
  pinMode(KEY2_PIN, INPUT_PULLUP);
  pinMode(KEY3_PIN, INPUT_PULLUP);


}

void loop() {
//delay函数按键消抖
  if (digitalRead(KEY1_PIN)==0) {
    delay(1000);
    key1jicun=!key1jicun;
    if (digitalRead(KEY1_PIN)==0) {
      digitalWrite(LED1_PIN,key1jicun);
      Serial.println("shuchu");
    }
    //等待按键松开,直到按键松开,继续往下执行
    while (digitalRead(KEY1_PIN)==0) {
      delay(1);
      //Serial.println("weisongkai");
    }
    Serial.println("songkai");
  }


//millis函数消抖
  int key2jicun=digitalRead(KEY2_PIN);
  if (key2jicun!=key2zhongzhuan) 
  {
    key2fangdouyanshikaishi=millis();
    Serial.println(key2fangdouyanshikaishi);
  }
    if ((millis()-key2fangdouyanshikaishi)>key2fangdoushijian) {
    //Serial.println("kaishixiaodoujishi");
      if (key2jicun!=key2fanzhuan) {
        Serial.println("anjiananxia");
      key2fanzhuan=key2jicun;
        if(key2fanzhuan==0)
        {
          Serial.println("diandeng");
          digitalWrite(LED2_PIN, led2fanzhuan);
          led2fanzhuan=(!led2fanzhuan);
        }
      }
    }
  key2zhongzhuan=key2jicun;


  digitalWrite(LED_PIN, HIGH); delay(250);
  digitalWrite(LED_PIN, LOW);  delay(250);
  Serial.println("tick tick");
}

More projects by yaxin