Question

Working on communication between arduino and PC (Win 7) in c++. No problem creating communication or just simple sending or receiving data with WriteFile and ReadFile. But when I want to somehow "coordinate" communication, I have problem. The goal is in for cycle (simplistic):

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

call procedure, that should send data to arduino, and now just receive back that data.

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);

I expected it will send input to arduino and then receive string like input without $ back. But it doesn't work.. it's sometimes reading "nothing" or really delayed, what I didn't expecting using active waiting for response. I think next sended string should wait for response, but apparently it doesn't.

for completion, here is code in 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
        }
    }
}

Any advice how to solve this, or idea what I'm doing wrong? Thank you a lot.

EDIT: edited code

Was it helpful?

Solution

Solved - Ulrich was right, but sadly, I edited only one function. My fault. So problem was really in sizeof(input.c_str()), after changed it everywhere to input.size() it works.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top