串口通信甲机四个按钮控制乙机,按钮1被按下时乙机8个流水灯全亮,按钮2被按下时乙机8个流水灯以流水形式点亮,按钮3被按下时乙机4个4个流水灯亮,按钮4被按下时流水灯全灭代码
时间: 2023-09-30 13:12:15 浏览: 75
以下是串口通信控制乙机流水灯的代码,需要在甲机和乙机之间进行串口通信:
甲机代码:
```c
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
void setup() {
mySerial.begin(9600);
pinMode(2, INPUT_PULLUP); // 按钮1
pinMode(3, INPUT_PULLUP); // 按钮2
pinMode(4, INPUT_PULLUP); // 按钮3
pinMode(5, INPUT_PULLUP); // 按钮4
}
void loop() {
if (digitalRead(2) == LOW) {
// 按钮1被按下
mySerial.write(0x01); // 发送字节码 0x01
} else if (digitalRead(3) == LOW) {
// 按钮2被按下
mySerial.write(0x02); // 发送字节码 0x02
} else if (digitalRead(4) == LOW) {
// 按钮3被按下
mySerial.write(0x03); // 发送字节码 0x03
} else if (digitalRead(5) == LOW) {
// 按钮4被按下
mySerial.write(0x04); // 发送字节码 0x04
}
delay(100); // 延迟一段时间,避免连续检测到按钮按下
}
```
乙机代码:
```c
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
#define LED_PIN_1 2
#define LED_PIN_2 3
#define LED_PIN_3 4
#define LED_PIN_4 5
#define LED_PIN_5 6
#define LED_PIN_6 7
#define LED_PIN_7 8
#define LED_PIN_8 9
void setup() {
mySerial.begin(9600);
pinMode(LED_PIN_1, OUTPUT);
pinMode(LED_PIN_2, OUTPUT);
pinMode(LED_PIN_3, OUTPUT);
pinMode(LED_PIN_4, OUTPUT);
pinMode(LED_PIN_5, OUTPUT);
pinMode(LED_PIN_6, OUTPUT);
pinMode(LED_PIN_7, OUTPUT);
pinMode(LED_PIN_8, OUTPUT);
}
void loop() {
if (mySerial.available() > 0) {
int command = mySerial.read(); // 读取甲机发送的字节码
switch (command) {
case 0x01: // 按钮1被按下
digitalWrite(LED_PIN_1, HIGH);
digitalWrite(LED_PIN_2, HIGH);
digitalWrite(LED_PIN_3, HIGH);
digitalWrite(LED_PIN_4, HIGH);
digitalWrite(LED_PIN_5, HIGH);
digitalWrite(LED_PIN_6, HIGH);
digitalWrite(LED_PIN_7, HIGH);
digitalWrite(LED_PIN_8, HIGH);
break;
case 0x02: // 按钮2被按下
for (int i = 2; i <= 9; i++) {
digitalWrite(i, HIGH);
delay(100);
digitalWrite(i, LOW);
}
break;
case 0x03: // 按钮3被按下
for (int i = 2; i <= 8; i+=4) {
digitalWrite(i, HIGH);
digitalWrite(i+1, HIGH);
digitalWrite(i+2, HIGH);
digitalWrite(i+3, HIGH);
delay(100);
digitalWrite(i, LOW);
digitalWrite(i+1, LOW);
digitalWrite(i+2, LOW);
digitalWrite(i+3, LOW);
}
break;
case 0x04: // 按钮4被按下
digitalWrite(LED_PIN_1, LOW);
digitalWrite(LED_PIN_2, LOW);
digitalWrite(LED_PIN_3, LOW);
digitalWrite(LED_PIN_4, LOW);
digitalWrite(LED_PIN_5, LOW);
digitalWrite(LED_PIN_6, LOW);
digitalWrite(LED_PIN_7, LOW);
digitalWrite(LED_PIN_8, LOW);
break;
}
}
}
```
以上代码中,乙机根据甲机发送的字节码来控制流水灯的亮灭,具体控制逻辑如下:
- 按钮1被按下时,乙机的8个流水灯全亮。
- 按钮2被按下时,乙机的8个流水灯以流水形式点亮。
- 按钮3被按下时,乙机的4个4个流水灯亮。
- 按钮4被按下时,乙机的8个流水灯全灭。
阅读全文