【问题标题】:Python Serial Writing but seemingly not reading. Raspberry Pi 0 to ArduinoPython Serial Writing 但貌似不会读。树莓派 0 到 Arduino
【发布时间】:2021-05-17 09:58:25
【问题描述】:

我在 RPI0 上运行的 python 脚本从 Arduino 读取串行输入时遇到问题。我知道 Arduino 的代码是正确的,因为一切都按预期通过 Arduino 软件中的内置串行监视器与 Arduino 交互(发送代码 a10(驱动继电器高电平的代码),Arduino 发回 11(基本上询问多长时间) ,发送代码 b5,Arduino 将保持引脚高电平 5 秒(b5))。

但是,当我尝试使用 pyserial 模块读取 python 中的任何串行输入时,什么也没有发生。我知道它确实成功地将代码发送到了 arduino,因为当我用 ser.write("a10b5") 重写 python 脚本时,它将在指定的秒内保持引脚高电平。

串行连接不是 USB。我使用的是跨接线,它们之间有一个电压转换器,使用 Arduino 和 Pi 的 GPIO TX 和 RX 引脚。

  • 在终端中使用 python -V 告诉我我正在运行 3.8 版
  • 我尝试了多种波特率(300、1200、9600、57600),但行为没有改变
  • 我还尝试将 if x == 11: 更改为 if x == "11": 以防由于某种原因它接收的是字符串而不是整数,但也无济于事。

代码如下:

import time
import serial

ser = serial.Serial(
        port='/dev/ttyAMA0',
        baudrate = 9600,
        parity=serial.PARITY_NONE,
        stopbits=serial.STOPBITS_ONE,
        bytesize=serial.EIGHTBITS,
        timeout=None
)


print("sending data over serial now")
ser.write("a10") #a10 is relay HIGH code

while True:
        x = ser.read()
        if  x == 11:    ##arduino code 11(asking for how long)
                print("recieved code 11")
                print("arduino recieved relay HIGH code and is waiting for time to hold relay for")
                print("sending time now")
                ser.write('a5') # 5 seconds
                time.sleep(1)
        if x == 13:     #arduino code 13(water success)
                print("recieved code 13")
                print("arduino reports watering complete")
        x = 0    ##this is to clear the variable every loop. Not sure if it's needed

这是我从网上下载的一个简单的串行阅读器。在第二个终端中打开它并使用我自己的脚本同时运行它,它实际上会像往常一样从 arduino 业务中读取代码。

#!/usr/bin/env python
import time
import serial
ser = serial.Serial(
 port='/dev/ttyAMA0',
 baudrate = 57600,
parity=serial.PARITY_NONE,
 stopbits=serial.STOPBITS_ONE,
 bytesize=serial.EIGHTBITS,
 timeout=1
)
while True:
 x=ser.readline()
 print x

什么给了?

【问题讨论】:

    标签: python serialization arduino pyserial raspberry-pi-zero


    【解决方案1】:

    回答我自己的问题。在我使用的 arduino 代码中

    Serial.println(whatevergoeshere)
    

    而不是

    Serial.print(whatevergoeshere)
    

    因此,arduino 在每条串行线的末尾都发送了“\n”,而这些串行线没有被 arduino 串行控制台和 python 脚本打印。将我在 python 中的 IF 语句更新为

    if x == "11\n":
    

    解决了问题,一切都按预期工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-29
      • 2013-02-08
      • 2017-05-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多