使用Arduino数据中的Python脚本播放mp3文件的问题

时间:2015-10-04 16:58:10

标签: python arduino pyserial

我正在尝试使用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播放正常。 有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我修改了你的脚本,告诉你发生了什么。我无法测试它。

# 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并使用它而不是webbrowser。

import subprocess
def play_music_file(filename):
    subprocess.call(('mplayer', filename))
相关问题