通过串行方式从Raspberry(Python)向Arduino发送值的快速方法?

2024-09-29 17:23:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我想通过RX/TX串行端口(不是USB)从Raspberry发送一个int值(0-640)。在

目前我在UDP上收到Raspberry的值,因此接收到的类型是“class'bytes'”。我正在将字节转换为int,将其编码为一个字符串并发送给Arduino。在

我的问题是在Arduino端从ASCII转换到int是非常慢的。当然,最好的情况是,有一些简单的东西,比如:

覆盆子(梦境场景):

serial.write(data)

Arduino(梦境场景):

^{pr2}$

有什么建议吗?问题?在

目前我的代码:

覆盆子代码:

import struct
import serial

serial = serial.Serial('/dev/ttyAMA0', 115200)

while True:
    # (This is here to show you where it comes from):
    data, addr = sock.recvfrom(4)

    if len(data)!=4:
        continue
    else:
        # Convert data to int
        msg = struct.unpack('i',data)[0]
        # Send to Arduino
        serial.write(str(msg).encode() + str('\n').encode())

Arduino代码:

void setup()
{
  // Opens serial ports, sets data rate
  Serial1.begin(115200); // Serial1 = reads from Pi
}

void loop()
{
  if (Serial1.available())
  {
    // Resets RPiMsg
    RPiMsg = 0;

    // Read serial one byte at a time and convert ASCII to int
    while(true)
    {
      incomingByte = Serial1.read();

      // Exit while-loop, end of message
      if (incomingByte == '\n') break;

      // If nothing is in the buffer, Serial1.read() = -1
      if (incomingByte == -1) continue;

      // Shift 1 decimal place left
      RPiMsg *= 10;

      // Convert ASCII to int
      RPiMsg = ((incomingByte - 48) + RPiMsg);
    }

    Serial.println(RPiMsg);
  }
}

Tags: to代码data覆盆子ifasciiserialraspberry

热门问题