2013-05-09 53 views
1

我有一些Arduino代碼,移動電機,我想與一個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.readline()或ser.read(2)這樣的東西,並檢查命令是否「OK」。

奇怪的是,每個命令都應該有一個「ok」,但是並不是所有的命令都到達Python。我試圖「沖洗」它,但它是一樣的。

我創建了一個線程,不斷地從串口監聽,並檢查命令是否「OK」,但它不是,也許如果我發送4個命令,我收到2「OK」,有時爲0,有時爲1.

回答

0

而不是簡單地一次讀取多達97個字節(BUFFER_SIZE - 3),請嘗試發送Python代碼中的'結束命令'字符(或字符序列)。

在Arduino草圖中讀取,直到收到此命令結束序列,然後運行該命令。