从 Python 到 Arduino Teensy 的通信

问题描述 投票:0回答:0

我对 arduino 有点陌生,还没有发现任何以前的问题能够解决我的问题,所以我们开始吧。

我正在从事一个高级设计项目,在该项目中我使用 openCV 进行一些图像处理以识别特定颜色并跟踪它在框架中出现的位置。使用我从中收集的像素距离数据,我想使用 arduino 移动伺服系统。 但是数据似乎不会在 arduino 上发送,直到 python 和 arduino 之间的串行连接关闭之后(即当我取消 python 代码时)。这真的行不通,因为我正在尝试实时跟踪东西。

我已经确认 arduino 代码可以通过串行监视器手动发送东西并从 python 手动发送东西,但是自动发送失败了。

这是我用来向 arduino 发送数据的 python 代码部分。所以数据是一个结构化的字符串,所以 x 距离首先是一个空格,然后是 y 距离 - 例如“100 100”。我用它来分离 arduino 端的数据。 *注意我在一个类中有这个,这就是为什么串行被定义为 arduinoData,但称为 Test.arduinoData - 如果这很重要

# This is defined out of the function -
   arduinoData = serial.Serial('COM3', 115200) 

# Send pixel data to arduino
# these calculate the difference between the center of the object and the frame. Always less than a 1000 in both x and y
   px_dist = f"{Nframe_centerX - center[0]} {Nframe_centerY - center[1]}" 
   print(px_dist)
   Test.arduinoData.write(px_dist.encode())

我的arduino代码如下。前面提到的主要问题是串行端口不会停止接收数据并实际处理它,直到我停止 python 代码之后。所以数据被合并成一大行,如“100 100320 213523 463”等等。 我读过一些关于缓冲的内容,但我认为这不是问题所在?虽然它通常以 30 FPS 的速度运行,但我放慢了我的 python 代码,每秒只处理大约 5-8 帧,从而为 readString 的 Serial.setTimeout 提供了足够的时间来关闭。但这似乎从来没有奏效。

我还尝试了 Serial.readStringUntil() 在发送的数据中使用定界符,但也没有用。

// Includes
//#include <Servo.h>

// constant values
// Variables for pixel readings
String myCmd=""; 
bool reset = false;
int len; int X_val; int Y_val;
// Variables for Encoder readings
int d_x_rad=0; int d_y_rad=0; int d_x=0; int d_y=0;


void setup() {
  // put your setup code here, to run once:
  // Pin modes
  //Servo Servo1;
  //Servo1.attach(9);
  Serial.begin(115200);
  Serial.setTimeout(25);
  //Servo1.write(0);
  //delay(5);
  //Servo1.write(45);

}


void loop() {
  // put your main code here, to run repeatedly:

  if (Serial.available() > 0){ // if there is a msg
    myCmd = Serial.readString();
    Serial.println(myCmd);
    len = myCmd.length();
    
    // Split the string by the half mark
    String x = myCmd.substring(0,len/2);
    String y = myCmd.substring(len/2,len);
  
    // convert to int
    X_val = x.toInt();
    Y_val = y.toInt();
    Serial.println(X_val);

    String y_check = "";
    // if the half mark of the original string ISNT a space, then we need to split the y by 
    // the value before the half
    if (y.substring(len/2,len/2 + 1) != " ");{
      String y_check = myCmd.substring(len/2 -1,len);
      Y_val = y_check.toInt();
    }
    Serial.println(Y_val);

   }

... Servo things done here...

}

任何帮助表示赞赏!谢谢!

python arduino serial-port communication
© www.soinside.com 2019 - 2024. All rights reserved.