代码
#define KEY 7 int KEY_NUM = 0; int count = 0; #define LED_R 11 #define LED_G 10 #define LED_B 9 #define LED_ON HIGH #define LED_OFF LOW int state = 0; void setup() { pinMode(LED_R, OUTPUT); pinMode(LED_G, OUTPUT); pinMode(LED_B, OUTPUT); pinMode(KEY, INPUT_PULLUP); // 将7号引脚 设置为输入并且内部上拉模式 Serial.begin(9600); // setup serial } void loop() { scanKey(); if (KEY_NUM == 1) { KEY_NUM = 0; switch (state++) { case 0: digitalWrite(LED_R, LED_ON); digitalWrite(LED_G, LED_OFF); digitalWrite(LED_B, LED_OFF); break; case 1: digitalWrite(LED_R, LED_OFF); digitalWrite(LED_G, LED_ON); digitalWrite(LED_B, LED_OFF); break; case 2: digitalWrite(LED_R, LED_OFF); digitalWrite(LED_G, LED_OFF); digitalWrite(LED_B, LED_ON); break; } if (state == 3) state = 0; Serial.println("KEY DOWN"); } } // 读取按键状态 void scanKey() { if (digitalRead(KEY) == LOW) { delay(10); if (digitalRead(KEY) == LOW) { while (digitalRead(KEY) == LOW); KEY_NUM = 1; } } }