narduino利用传感器获取环境数据传输到Python创建的窗口上显示出来的代码
时间: 2024-02-25 21:59:16 浏览: 11
这里是一个简单的示例代码,实现了通过Arduino读取温度传感器数据,并将数据传输到Python程序中,最终在Pygame创建的窗口中显示出来。
Arduino代码:
```c++
const int sensorPin = A0;
void setup() {
Serial.begin(9600);
}
void loop() {
int sensorValue = analogRead(sensorPin);
float temperature = (sensorValue * 5.0 / 1024.0 - 0.5) * 100.0;
Serial.println(temperature);
delay(1000);
}
```
Python代码:
```python
import serial
import pygame
# 初始化pygame
pygame.init()
# 创建窗口
screen = pygame.display.set_mode((400, 300))
# 设置字体
font = pygame.font.SysFont(None, 24)
# 打开串口
ser = serial.Serial('COM3', 9600)
while True:
# 读取串口数据
data = ser.readline().decode().strip()
# 将数据转换为浮点数
temperature = float(data)
# 清空窗口
screen.fill((255, 255, 255))
# 绘制文本
text = font.render('Temperature: %.2f ℃' % temperature, True, (0, 0, 0))
screen.blit(text, (50, 50))
# 更新窗口
pygame.display.flip()
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
# 关闭窗口和串口
ser.close()
pygame.quit()
exit()
```
在代码中,我们使用了Pygame库创建了一个窗口,并在其中绘制了温度传感器读取到的数据。我们通过Serial库打开了Arduino的串口,并在每次循环中读取传感器数据。然后,我们将数据转换为浮点数,并使用Pygame绘制到窗口中。最后,我们处理了Pygame的QUIT事件,以便在关闭窗口时安全地关闭串口。