Skip to main content
edited tags
Link
VE7JRO
  • 2.5k
  • 19
  • 28
  • 31
Tweeted twitter.com/#!/StackArduino/status/505858545666228225
Source Link
xcdemon05
  • 173
  • 1
  • 1
  • 6

Why can't this C++ program read my arduino's Serial.write()?

I made a super simple arduino uno sketch to send a serial byte once every second:

void setup(){
  Serial.begin(9600);
}

void loop(){
   Serial.write(12); // send a byte with the value 12
   delay(1000);
}

My arduino is hooked up to com 3.

On the other end of the line, I have a C++ program with the following read function:

int Serial::ReadData(char *buffer, unsigned int nbChar)
{
    //Number of bytes we'll have read
    DWORD bytesRead;
    //Number of bytes we'll really ask to read
    unsigned int toRead;

    //Use the ClearCommError function to get status info on the Serial port
    ClearCommError(this->hSerial, &this->errors, &this->status);

    //Check if there is something to read
    if(this->status.cbInQue>0)
    {
        //If there is we check if there is enough data to read the required number
        //of characters, if not we'll read only the available characters to prevent
        //locking of the application.
        if(this->status.cbInQue>nbChar)
        {
            toRead = nbChar;
        }
        else
        {
            toRead = this->status.cbInQue;
        }

        //Try to read the require number of chars, and return the number of read bytes on success
        if(ReadFile(this->hSerial, buffer, toRead, &bytesRead, NULL) && bytesRead != 0)
        {
            return bytesRead;
        }

    }

    //If nothing has been read, or that an error was detected return -1
    return -1;

}

This seems to check only one time if data is available, so obviously I have to loop through it until data comes in. I did that in my main program:

#include "Serial.h"
#include <iostream>

using namespace std;

int main(void)
{
    Serial serial("COM3");

    char* c = "";
    int len = strlen(c);
    while(c == "")
    {
        serial.ReadData(c, len);
    }

    cout << "\n\n";
    system("PAUSE");
}

When I do this, my C++ program gets stuck in an infinite loop waiting for data from the arduino, and I cannot figure out why this is happening. My program never sees the data the arduino is sending.

This Serial class works and is configured properly because I can SEND all the data I want to the arduino without any problems. My issues are only with reading back from the arduino.

Can someone please help me figure out why this is not working?