簡體   English   中英

與arduino的C ++通信

[英]C++ communication with arduino

使用C ++在arduino和PC(Win 7)之間進行通信。 創建通信沒有問題,或者只是使用WriteFile和ReadFile簡單地發送或接收數據。 但是當我想以某種方式“協調”交流時,我會遇到問題。 目標是為了周期(簡單):

for (int i=0; i < 310; i++)
{
    com->send(micro[i]);
}

調用過程,該過程應該將數據發送到arduino,現在只需接收回該數據即可。

int send(string input)
{
    DWORD written, read;
    char buffer[7] = {' ',' ',' ',' ',' ',' ',' '};
    input.append("$");


    if(!WriteFile(this->comMotor, input.c_str(), input.size(), &written, NULL))
        qDebug() << "WriteFile failed"

    if(written != input.c_str())
        qDebug() << "write problem";


    do
    {
        if(!ReadFile(this->comMotor, buffer, sizeof(buffer), &read, NULL))
            qDebug() << "ReadFile failed";
        if (read)
            qDebug() << "buffer: " << buffer;
    }while(!read);

我期望它將輸入發送到arduino,然后接收類似$的輸入字符串,而無需$ back。 但這是行不通的..有時它顯示“無”或真正延遲,這是我不期望使用主動等待響應的結果。 我認為下一個發送的字符串應該等待響應,但顯然不是。

為了完成,這是arduino中的代碼:

void loop() 
{ 
    if (Serial.available())  
    {
        char c = Serial.read();
        if (c == '$') 
        {
            if (readString.length() >0) 
            {
                Serial.println(readString); //prints string to serial port out
                int n = readString.toInt();  //convert readString into a number
            }

            readString=""; //clears variable for new input
        } 
        else 
        {     
            readString += c; //makes the string readString
        }
    }
}

關於如何解決這個問題的任何建議,或者知道我在做什么錯? 非常感謝。

編輯:編輯后的代碼

已解決-Ulrich是正確的,但可悲的是,我只編輯了一個功能。 我的錯。 所以問題實際上出在sizeof(input.c_str())上,在所有地方都將其更改為input.size()后,它才起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM