Raspberry和Arduino python之间的串行通信

时间:2018-03-16 20:23:33

标签: web pyserial uart serial-communication

我有问题,希望你们中的一些人可以帮助我。 我目前的情况: 我在我的Raspberry Pi 3上安装了一个网络服务器,然后在其上运行一个网站。微控制器(Arduino ATMega 2560)与Raspberry串行连接。我在我的Raspberry上存储了一个Send-Char文件和一个用Python编写的Receive-Char文件。当我点击我网站上的一个按钮时,我运行发送文件,文件应该通过UART发送一个字母到微控制器。在Raspberry发送信件之前,程序应该检查是否给出了与控制器的连接。程序还应该在给出连接时将“X”写入文件“callback.txt”,或者在没有连接时写入“Y”。 来我的问题: 当有连接时,一切正常,但是当没有连接时,终端给我写了一个错误(查看附图)。 请帮我解决这个问题。 谢谢!

import serial
from time import sleep

print("SEND CHARACTER")

filestream = -1

filestream = serial.Serial('/dev/ttyACM0', 9600)

if filestream != (-1):
     data = 'X'
else:
     data = 'Y'

text_file = open("callback.txt", "w")
text_file.write(data)
text_file.close()

sleep(0.1)
filestream.write("A")

filestream.close()

顺便说一句:对不起我的英语技能,但我的母语是德语;) error in the terminal

1 个答案:

答案 0 :(得分:0)

使用try exception语句检查连接,如下所示。

try:
    filestream = serial.Serial('/dev/ttyACM0', 9600)
    data = 'X'
except SerialException:
    data = 'Y'
相关问题