同步Arduino和Python

2024-05-08 21:36:06 发布

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

我有一些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.read公司(2) 并检查命令是否为“ok”。在

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

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


Tags: 命令sizeparameterbufferstepdirpinserial
1条回答
网友
1楼 · 发布于 2024-05-08 21:36:06

与其一次只读取97个字节(BUFFER_SIZE - 3),不如尝试从Python代码中发送一个“命令结束”字符(或字符序列)。在

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

相关问题 更多 >