作业:电脑和板子串口交互,从电脑输入字符串1,然后板子灯就亮,同时板子向电脑发送“亮”;输入字符串2板子灯就灭,同时板子向电脑发送“灭”;输入字符串3板子灯就闪烁,同时板子向电脑发送“闪
时间: 2024-06-12 12:07:26 浏览: 8
烁”。
解题思路:
1. 在电脑上安装串口助手软件,用于向串口发送数据和接收串口返回数据。
2. 在板子上编写程序,初始化串口,读取串口接收到的数据,并根据不同的字符串控制板子的LED灯的状态。
3. 在板子上编写程序,根据不同的状态向电脑发送返回数据。
4. 在串口助手软件上输入字符串,观察板子LED灯的状态和串口返回数据。
代码实现:
1. 电脑端代码:
```python
import serial
ser = serial.Serial('COM3', 9600)
while True:
data = input("请输入要发送的字符串:")
ser.write(data.encode())
res = ser.readline().decode().strip()
print(res)
```
2. 板子端代码:
```c++
#include <Arduino.h>
#define LED_PIN 13
void setup() {
Serial.begin(9600);
pinMode(LED_PIN, OUTPUT);
}
void loop() {
if (Serial.available()) {
String data = Serial.readStringUntil('\n');
data.trim();
if (data == "1") {
digitalWrite(LED_PIN, HIGH);
Serial.println("亮");
} else if (data == "2") {
digitalWrite(LED_PIN, LOW);
Serial.println("灭");
} else if (data == "3") {
for (int i = 0; i < 3; i++) {
digitalWrite(LED_PIN, HIGH);
delay(500);
digitalWrite(LED_PIN, LOW);
delay(500);
}
Serial.println("闪烁");
}
}
}
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)