python - 处理 Arduino-Python 通信中的异常

标签 python arduino

我正在尝试实现一个系统,其中 Arduino 的输出可以传递到 Python 并用 Python 打印。

下面有以下 Arduino 代码片段:

void loop() {
  if (Serial.available()) {
    c = Serial.read();
    if (c == '1') {
      digitalWrite(pinLED1, HIGH);
      digitalWrite(pinLED2, LOW);
      //Serial.print("1 ON, 2 OFF\n");
    }

我的Python代码片段如下:

import serial
import time

arduino = serial.Serial('COM3', 9600, timeout=1)
msg = arduino.readline(arduino.inWaiting())  # read everything in the input buffer

time.sleep(3)

ASCIIdata = '121210'

for i in range(len(ASCIIdata)):

    if ASCIIdata[i] == '1':
        strin = '1'
        arduino.write(strin.encode())
        time.sleep(0.2)
        #print(ASCIIdata[i])
        try:
            print ("Message from arduino: ")
            print arduino.readline()
            raise
        except Exception as e:
            print ("Fail to send!")

在上面的例子中,我尝试通过ASCIIdata向Arduino发送输入,当它与Arduino中的if语句匹配时,将执行if语句中的命令。我故意不在 Arduino 中进行打印,并尝试通过执行以下操作从 Python 读取某些内容:

try:
    print ("Message from arduino: ")
    print arduino.readline()
    raise
except:
    print ("Fail to send!")

我观察到,如果我不在 try 语句中放入 raise ,则 except 语句将不会被执行,但程序会在特定的超时后继续执行。因此,我将 raise 放在 try 语句中。请问这是否是引发异常的正确方法?

我读到我应该做 except Exception as e 而不是做 except 因为我会在程序运行时捕获各种异常。请问这个思路是否正确?

最佳答案

首先,我不太喜欢Python,所以我不太确定,但是拥有其他语言的经验,我认为这个答案是正确的。

你所做的是......错误的。您不想每次都引发异常。

查看the documentation of the readline function ,

readlines() depends on having a timeout and interprets that as EOF (end of file). It raises an exception if the port is not opened correctly.

这意味着超时不会引发异常。您可以测试缓冲区是否为空:

try:
    print ("Message from arduino: ")
    buff = arduino.readline()
    print buff
    if not buff:
        raise
except:
    print ("Fail to send!")

即使您可以跳过异常:

print ("Message from arduino: ")
buff = arduino.readline()
print buff
if not buff:
    print ("Fail to send!")

如果您更喜欢其他行为,请编写自己的函数(例如,这个答案有一些看起来像阅读函数的东西;您只需添加异常引发即可。

对于异常类型,通常最好只使用一种类型的异常,以避免捕获所有异常。例如:

class MyError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)

try:
    raise MyError(2*2)
except MyError as e:
    print 'My exception occurred, value:', e.value

关于python - 处理 Arduino-Python 通信中的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47158220/

相关文章:

c - 带双引号的 sscanf

python - Django+Gunicorn+nginx Internal Server Error,错误在哪里,如何解决?

python - 获取声音文件中给定时间的振幅?

python - Matplotlib:编写从右到左的文本(希伯来语、阿拉伯语等)

assembly - 有关新 AVR 指令 LAC、LAS、LAT 和 XCH 的更多详细信息

arduino - 在处理中压缩一个大的 "} else if { "语句

python - 快速检查 Pandas 系列是否包含负值的方法

python - 根据数组中数据的 if/then 添加列到 numpy 数组

arduino - 如何使用 Arduino + ESP8266 AT 命令发送 HTTP 请求

compilation - 无法编译 Arduino CapSense 示例