gpt4 book ai didi

python - 从 Arduino 串行发送信号到 Python 程序

转载 作者:行者123 更新时间:2023-11-28 18:59:09 24 4
gpt4 key购买 nike

我是 Python 和 Raspberry Pi 的新手,希望将它们用于 Arduino 的项目。基本上,我想按下连接到 Arduino 的按钮,然后让该输入在树莓派上播放视频文件。

我在通过串行数据这样做时遇到了一些困难。我可以在 Arduino 和 Pi 之间连接串行消息,即:“Hello World”,但不太清楚如何打开视频文件。现在,当我运行 Python 代码时,什么也没有出现,按钮按下也没有反应。我有正确的 USB 端口,因为它可以与其他仅打印串行数据的程序一起使用。我该如何解决这个问题?

简而言之,最终目标是“按下按钮-->播放视频。”

Arduino 代码:

int pushButton=2;
int buttonState=0;

void setup()
{
serial.Begin(9600);
pinMode(pushButton, INPUT);
}

void loop()
{
int buttonState=digitalRead(pushButton);
if (buttonState==HIGH)
{
Serial.println("a");
delay(100);
}
if (buttonState==LOW)
{
//do nothing
}
}

Python 代码:

import sys
import os
from subprocess import Popen
import serial

movie1=("/home/pi/Videos/test.mp4")

ser = serial.Serial('/dev/ttyUSB0',9600)

while True:
data = ser.read()

if data=="a":
os.system('killall omxplayer.bin')
print("a")
omxc = Popen(['omxplayer','-b', movie1])

最佳答案

首先我认为串口通信不需要发送字符串,发送字节即可。问题是当您使用 Serial.println("Something") 时,您正在发送 Something\r\n 所以在另一台设备上您应该使用 Something 检查它\r\n,正如评论中所说,您可以打印调试信息以确保您的数据处于事件状态并且连接正常。您还可以在 python 代码上添加确认以响应命令以确保数据已发送并且不发送另一个。Arduino代码:

int pushButton=2;
int buttonState=0;

void setup()
{
serial.Begin(9600);
pinMode(pushButton, INPUT);
}

void loop()
{
int buttonState=digitalRead(pushButton);
if (buttonState==HIGH)
{
Serial.print('1');
delay(100);
}
if (buttonState==LOW)
{
//do nothing
}
}

Python代码:

from subprocess import Popen
import serial

movie1 = "/home/pi/Videos/test.mp4"

ser = serial.Serial('/dev/ttyUSB0',9600)

while True:
command = ser.read()
if command:
# flush serial for unprocessed data
ser.flushInput()
print("new command:", command)
if str(command) == '1':
print("Playing movie")
Popen('killall omxplayer.bin')
Popen(['omxplayer','-b', movie1])
else:
print("Not a valid command")

关于python - 从 Arduino 串行发送信号到 Python 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54662362/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com