1

我有一些 Arduino 代码可以移动我想与 python 脚本同步的电机,以使用串行控制它。

这是Arduino代码:

#define BUFFER_SIZE 100

#define P1_STEP_PIN         31
#define P1_DIR_PIN          33
#define P1_ENABLE_PIN       29

#define V1_STEP_PIN         25
#define V1_DIR_PIN          27
#define V1_ENABLE_PIN       23

char buffer[BUFFER_SIZE];

int pins[1][2][2] = { 
    { {P1_STEP_PIN, P1_DIR_PIN}, {V1_STEP_PIN, V1_DIR_PIN} }
};

void setup()
{
  Serial.begin(115200);
  Serial.flush();

  // pins setup
}

void loop()
{
  get_command();
}


void get_command()
{
  if (Serial.available() > 0) {

    int index = 0;
    delay(100); // let the buffer fill up
    int numChar = Serial.available();

    if ( numChar > ( BUFFER_SIZE - 3 ) ) { //avoid overflow
      numChar = ( BUFFER_SIZE - 3 );
    }

    while (numChar--) {
      buffer[index++] = Serial.read();
    }

    process_command(buffer);
  }
}

void process_command(char* data)
{
  char* parameter;
  parameter = strtok (data, " "); // strtok splits char* in " "

  while (parameter != NULL) {
    long dir, pump, motor, sp, steps;

    switch ( parameter[0] ) {
      // moves the motor around
    }

    parameter = strtok(NULL, " ");
  }

  for ( int x=0; x < BUFFER_SIZE; x++) {
    buffer[x] = '\0';
  }
  Serial.flush();
  Serial.write("ok");
}

Python部分是我遇到问题的地方。当我从 Python 发送命令来移动电机时,Arduino 代码运行良好,但是当我连续发送多个命令时它会失败,因为我怀疑 Python 会同时发送所有内容,而不是等待 Arduino 完成每个动作。

所以基本上在 Python 中我尝试了所有的东西,主要是 ser.readline() 或 ser.read(2) 之类的东西,并检查命令是否“正常”。

奇怪的是,每个命令应该有一个“ok”,但没有,并不是所有的命令都到达 Python。我试图“冲洗”它,但它是一样的。

我创建了一个线程,不断地从串口监听,并检查命令是否“正常”,但不是,也许如果我发送 4 个命令,我会收到 2 个“正常”,有时是 0,有时是 1。

4

1 回答 1

0

BUFFER_SIZE - 3尝试从 Python 代码发送一个“命令结束”字符(或字符序列),而不是一次简单地读取最多 97 个字节 ( )。

在 Arduino 草图中阅读,直到您收到此“命令结束”序列,然后运行命令。

于 2013-05-09T09:43:37.407 回答