【问题标题】:Sync Arduino and Python同步 Arduino 和 Python
【发布时间】:2013-05-10 01:05:49
【问题描述】:

我有一些 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。我试图“冲洗”它,但它是一样的。

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

【问题讨论】:

    标签: python serial-port arduino


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2017-11-17
      • 1970-01-01
      • 2016-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-23
      • 1970-01-01
      相关资源
      最近更新 更多