【问题标题】:Arduino Uno to Raspberry Pi output required as a float but get b'VALUE\r\n'Arduino Uno 到 Raspberry Pi 输出需要作为浮点数但得到 b'VALUE\r\n'
【发布时间】:2018-07-24 11:49:47
【问题描述】:

我已经解决了一些与我的问题相似的问题,但我看不到一个可以为我提供可靠解决方案的问题(我对所有这些问题也很陌生)。我已经使用 USB 电缆将 Arduino Uno 与 Raspberry Pi 连接,这样我就可以使用串行连接从 Arduino 读取值。一切似乎都连接正常,但我似乎无法从通过串行连接读取的值中获得浮点值。 python中的输出格式为:

b'VALUE\r\n'(其中 VALUE 是我需要的数字)

我认为这是一个字节值?我从一个在线示例中检索了 Arduino 草图,所以我很确定这很好,它会在 Arduino 程序中将正确的值输出到串行监视器。我使用的python代码是:

    import serial
    ser = serial.Serial("/dev/tty/ACM0",9600)
    ser.baudrate = 9600

    while True:
        read_ser = ser.readline().strip.decode("utf-8")
        #read_ser = float(ser.readline().strip())
        #read_ser = ser.readline().strip()
        #read_ser = ser_readline()
        print(read_ser)

第一次尝试使用解码进行读取会出现错误: UnicodeDecodeError:“utf-8”编解码器无法解码位置 0 的字节 0xfe:无效的起始字节

第二个: 读取一些值,然后说: ValueError:无法将字符串转换为浮点数:b'0.0\xfd05025' (我确实在某处读到过,这可能是由于 arduino 草图中的延迟时间造成的?我目前有 1 毫秒,这是否太低了?)

第三个和第四个确实会产生值,但将多余的字符 / 作为字符串。

非常感谢! 附言Arduino 代码:

#define trigPin 11
#define echoPin 12

float duration, distance;

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {

  // Write a pulse to the HC-SR04 Trigger Pin

  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Measure the response from the HC-SR04 Echo Pin

  duration = pulseIn(echoPin, HIGH);

  // Determine distance from duration
  // Use 343 metres per second as speed of sound

  distance = ((duration / 2) * 0.0343)/100;

  // Send results to Serial Monitor
  Serial.println(distance,5);
  delay(1);
}

【问题讨论】:

    标签: python-3.x raspberry-pi3 arduino-uno


    【解决方案1】:

    我用于 Raspberry 和 Arduino 之间的串行通信的代码是:

    import serial
    ser = serial.Serial('/dev/ttyUSB0', 9600)
    
    while True:
        readSerial = ser.readline()
        print readSerial
    

    请注意,此代码在 Python 2.7 中,您必须稍作更改才能在 Python 3.x 中使用它。还要确保您在 Raspberry 中拥有正确的串行端口,因为我的始终是 USB0(我认为 ACM 是保留的,但我可能在这里错了)。

    此外,如果 Arduino 草图中存在延迟,最好将其添加到 Raspberry 代码中(尝试稍微大于 Arduino 中的延迟)。

    更新:我使用的Arduino代码如下:

    float duration = 10;
    
    void setup(){
      Serial.begin(9600);
    }
    
    void loop(){
      duration = duration + 1;
      float distance = ((duration / 2) * 0.0343)/100;
      Serial.println(distance,5);
      delay(1);
    }
    

    我使用此代码是因为我没有可供我使用的超声波传感器,但它的工作原理相同。

    这是 RaspberryPi 中的输出:

    我认为你应该检查一下你的串口格式,看看端口是否正确。

    【讨论】:

    • 您好,感谢您的回答,但我想我可能一直不清楚我的问题是什么?我可以从 Raspberry Pi 上的 Arduino 获得串行输出,(所以我认为这意味着我有正确的串行端口?)。我的问题是我无法从输出中获取浮点值或任何可用值,因为它是字节格式的?
    • 您介意分享您的 Arduino 部分代码,以便我了解我们正在处理的代码类型吗?
    • 当然,我已将其添加到问题中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-25
    • 2018-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多