写一段2乘3矩阵键盘控制不同花样的流水灯
时间: 2023-05-23 20:02:25 浏览: 107
非常感谢您的提问,以下是一段基于Arduino平台的代码,可以实现2乘3矩阵键盘控制不同花样的流水灯:
```c
//引用Keypad库
#include <Keypad.h>
//设置矩阵键盘的行和列数
const byte ROWS = 2;
const byte COLS = 3;
//定义矩阵键盘的键值和布局
char keys[ROWS][COLS] = {
{'1','2','3'},
{'4','5','6'}
};
//定义LED灯连接的引脚
const int LEDPins[] = {2, 3, 4, 5, 6, 7};
//初始化矩阵键盘和LED灯
Keypad keypad = Keypad(makeKeymap(keys), ROWS, COLS);
int LEDCount = sizeof(LEDPins) / sizeof(int);
void setup() {
//将LED灯连接的引脚设置为输出模式
for (int i = 0; i < LEDCount; i++) {
pinMode(LEDPins[i], OUTPUT);
}
}
void loop() {
//从矩阵键盘获取按键值
char key = keypad.getKey();
if (key != NO_KEY) {
//根据不同的按键值控制LED灯的亮灭
switch (key) {
case '1':
//流水灯模式1
for (int i = 0; i < LEDCount; i++) {
digitalWrite(LEDPins[i], HIGH);
delay(100);
digitalWrite(LEDPins[i], LOW);
}
break;
case '2':
//流水灯模式2
for (int i = LEDCount - 1; i >= 0; i--) {
digitalWrite(LEDPins[i], HIGH);
delay(100);
digitalWrite(LEDPins[i], LOW);
}
break;
case '3':
//流水灯模式3
for (int i = 0; i < LEDCount; i += 2) {
digitalWrite(LEDPins[i], HIGH);
delay(100);
digitalWrite(LEDPins[i], LOW);
}
break;
case '4':
//流水灯模式4
for (int i = 0; i < LEDCount; i += 2) {
digitalWrite(LEDPins[i], HIGH);
digitalWrite(LEDPins[i + 1], HIGH);
delay(100);
digitalWrite(LEDPins[i], LOW);
digitalWrite(LEDPins[i + 1], LOW);
}
break;
case '5':
//流水灯模式5
for (int i = 0; i < LEDCount; i += 3) {
digitalWrite(LEDPins[i], HIGH);
digitalWrite(LEDPins[i + 1], HIGH);
digitalWrite(LEDPins[i + 2], HIGH);
delay(100);
digitalWrite(LEDPins[i], LOW);
digitalWrite(LEDPins[i + 1], LOW);
digitalWrite(LEDPins[i + 2], LOW);
}
break;
case '6':
//流水灯模式6
for (int i = 0; i < LEDCount; i++) {
digitalWrite(LEDPins[i], HIGH);
}
delay(500);
for (int i = 0; i < LEDCount; i++) {
digitalWrite(LEDPins[i], LOW);
}
delay(500);
break;
}
}
}
```
希望这段代码能够满足您的需求。
阅读全文