用Python脚本从Arduino数据发出播放mp3文件



我正在尝试使用Arduino Uno和Python脚本执行以下操作:如果Arduino的超声波传感器计算的长度低于36,则播放我硬盘上的音乐。

我的Python代码如下:
import serial, webbrowser
arduino = serial.Serial('/dev/ttyACM0', 9600)
data = arduino.readline()
while (1==1):
    if (arduino.inWaiting()>0) and data < 36:
        webbrowser.open("/home/path/my-music.mp3")

但是当我启动它时什么都没有发生,脚本一直在我的shell中运行。如果我执行打印数据,我注意到数据的值与Arduino控制台不同,并且当Python脚本同时运行时,Arduino控制台似乎不能正常工作(超声波传感器的长度值似乎被截断)。

运行以下Python脚本:

import serial, webbrowser
webbrowser.open("/home/path/my-music.mp3")
我的mp3播放正常。什么好主意吗?

我修改了你的脚本来告诉你发生了什么。我不能测试出来。

# import the modules
import serial
import webbrowser
# open a serial connection to the Arduino to read data from
arduino = serial.Serial('/dev/ttyACM0', 9600)
# we want to read everything the Arduino tells us
while True:
    # read one line (a str) that the Arduino wrote with Serial.println()
    line = arduino.readline()
    # convert the line into a string that contains only the numbers
    # by stripping away the line break characters and spaces
    string_with_number_in_it = line.strip()
    # convert the string into a number that can be compared
    number = float(string_with_number_in_it)
    if number < 36:
        webbrowser.open("/home/path/my-music.mp3")

另外,我建议你安装mplayer并使用它而不是浏览器。

import subprocess
def play_music_file(filename):
    subprocess.call(('mplayer', filename))

最新更新