Blank lines when reading data C++

I followed the guide to interface the arduino in C++ via serial.
I included the files since I think mine have changed a bit to make it work...
The problem is exhibited in Capture.PNG.
The arduino simply writes:

on
off
on
off
.
.
.

But instead skips a line. It doesn't appear to skip writing (no missing on or off - also either line write after 1 sec as expected). It seems to simply add another line!
I'm trying to troubleshoot the problem of having a lot of data coming out from an accelerometer and having this new line spacing which I have no idea why it happens. I wonder if it's due to the line buffer? Any help is welcomed!

main.cpp (569 Bytes)

SerialPort.cpp (2.32 KB)

SerialPort.h (538 Bytes)

testr.ino (235 Bytes)

Have you tried just writing to the serial monitor?

The serial monitor displays what I am expecting, i.e. on,off,on,off etc. without problem.

readSerialPort returns the number of bytes read from the serial port, yet you don't use it. Instead you're printing receivedString as if it's a C string. So what's happening is:

  • You read "on\r\n". Buffer contains "on\r\n\0\0\0...". You print "on\r\n". All's OK in the world.
  • You read "off\r\n". Buffer contains "off\r\n\0\0\0...". You print "off\r\n". All's OK in the world.
  • You read "on\r\n". Buffer contains "on\r\n\n\0\0...". You print "on\r\n\n". All's not OK in the world. There's an extra newline!

The last two steps repeat. You need to print only hasRead bytes from the buffer and not treat the buffer as a null-terminated C string.

christop:
readSerialPort returns the number of bytes read from the serial port, yet you don't use it. Instead you're printing receivedString as if it's a C string. So what's happening is:

  • You read "on\r\n". Buffer contains "on\r\n\0\0\0...". You print "on\r\n". All's OK in the world.
  • You read "off\r\n". Buffer contains "off\r\n\0\0\0...". You print "off\r\n". All's OK in the world.
  • You read "on\r\n". Buffer contains "on\r\n\n\0\0...". You print "on\r\n\n". All's not OK in the world. There's an extra newline!

The last two steps repeat. You need to print only hasRead bytes from the buffer and not treat the buffer as a null-terminated C string.

Thanks a lot! Makes perfect sense.
I checked the bytes reading and it happens to be 4...5...4...5... as expected. If I print two char with the same amount of letter, I get the same amount of bytes read. I'm not sure why there's an extra '\n' and how this would be detected with hasRead?
I guess the only fix is to print until '\n' is found? This sounds like a very archaic fix.

Edit: ugly fix
int main(void){
arduino = new SerialPort(portName);
while (arduino->isConnected()) {
auto hasRead = arduino->readSerialPort(receivedString, MAX_DATA_LENGTH);
char* p = receivedString;
while (*p && (*p != '\n')) {
std::cout << *p;
p++;
}
std::cout << '\n';
//else std::cerr << "Error occured reading data" << "\n";
Sleep(1000);
}
}