C++ communication with Arduino using SerialClass.h

Hi,
I'm using the library which you can see here to communicate with my arduino using serial.
I think, that IsConnected() method doesn't work fine for me.
After connecting to my Arduino to receive some data and then unplugging the USB, IsConnected() is still returning true.
Is there any way to fix it?

IsConnected() is still returning true.

The PC is still connected to the serial port, isn't it? It should continue to return true when you unplug the Arduino.

PaulS:
The PC is still connected to the serial port, isn't it? It should continue to return true when you unplug the Arduino.

So how can I detect then if user unplugs the usb?

mikson:
So how can I detect then if user unplugs the usb?

Send a command to the Arduino. If you get a response, it's still connected. If you don't, it isn't (or it crashed).

PaulS:
Send a command to the Arduino. If you get a response, it's still connected. If you don't, it isn't (or it crashed).

I'll do so. Thank you for help.

I'm an experienced C++ programmer on UN*X and Windows, but totally new to Arduino, and also don't often get into the nitty gritty of serial port communication.

I've been provided with an Arduino Leonardo and a sketch that gets input from a sensor device and sends it to the Serial Monitor running on Windows 10. The numbers stream by, so the essential physical setup and the Arduino sketch seem functional. Now I'm trying to access that data stream from my own C++ code, but hitting a brick wall. I've looked at the example SerialClass, but I suspect that I'm missing some "secret sauce" for the setting of Windows DCB fields. I'm currently using this:

	// Any fields not explicitly set are carried over from GetCommState() immediately after CreateFile()

	dcb.BaudRate      = CBR_9600;
	dcb.fBinary       = TRUE;
	dcb.fParity       = FALSE;

	// We don't care about the output flow control; only input -- I guess?
	//
	// dcb.fOutxCtsFlow
	// dcb.fOutxDsrFlow

	dcb.fDtrControl   = DTR_CONTROL_ENABLE;  // suggested by example Serial.cpp

	// dcb.fDsrSensitivity
	// dcb.fTXContinueOnXoff
	// dcb.fOutX

	dcb.fInX          = FALSE;
	dcb.fErrorChar    = FALSE;
	dcb.fNull         = FALSE;
	dcb.fRtsControl   = RTS_CONTROL_DISABLE;
	dcb.fAbortOnError = FALSE;
	dcb.XonLim        = 0;
	dcb.XoffLim       = 0;
	dcb.ByteSize      = 8;
	dcb.StopBits      = ONESTOPBIT;
	dcb.Parity        = NOPARITY;
	dcb.XonChar       = 0x3b;  // from GetCommState() immediately after CreateFile()
	dcb.XoffChar      = 0x38;  // from GetCommState() immediately after CreateFile()
	dcb.ErrorChar     = 0;

	// dcb.EofChar
	// dcb.EvtChar

The behavior I'm getting is that ClearCommError() virtually always returns COMSTAT cbInQue < 1. On rare attempts, I sometimes get a few bytes of input in the first frame, but then there's just nothing there, apparently. ReadFile() either hangs or returns with NumberOfBytesRead = 0, depending on how I set the COMMTIMEOUTS fields in SetCommTimeouts().

This is the Arduino sketch that I was given -- by someone who is also fairly new to the endeavor:

void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}


void loop() {
  //set digital pin 2 as a switch to run the system only when NOT grounded
  pinMode(2,INPUT);
  digitalWrite(2,HIGH);

  while (digitalRead(2))
  {
    // read the input on analog pin 0:
    int EMGinput = analogRead(A0);
    int voltage = EMGinput * (5.0 / 1023.0);
    // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
    // int will send data rounded up or down
    // float will send data with decimals
    // print out the value you read:
  
    //if you want 0-1023 then COMMENT OUT int voltage = EMGinput * (5.0 / 1023.0);
    Serial.println(EMGinput,DEC);
  }
}

Any insights, or maybe a pointer to the Arduino PC Serial Monitor source code, would be greatly appreciated.

It is so much simpler to do Serial input and output using C#. Unless there is an undefined need to use C++, don't.

PaulS:
It is so much simpler to do Serial input and output using C#. Unless there is an undefined need to use C++, don't.

Well, I suppose that depends at least partly on one's particular experience with and knowledge of each language. In any case, my task is to integrate this into a large VR program written in C++. Adding C# to the mix is not desirable.

Also, problem solved. As I suspected, it was a couple of stoopid mistakes that were blocking me: (1) Leaving the Arduino IDE running and connected to the COM port blocks the VR program from reading data from that same COM port. Once the sketch is uploaded to the board, the Arduino IDE should be closed. Not just the Serial Monitor; the whole IDE. (2) A capitalization typo resulted in DTR_CONTROL_ENABLE not being set as intended.

Sounds like you are getting there. It took me ages to get good reliable serial data. Sounds easy reading through the example code but that is just a starting point. Multiple buffers, semaphores, threads... you know the stuff.

Anyhow, I think you may not quite be there. I am pretty certain you do not have to close the IDE down to get serial comms going on the port you just used to upload.

Consequently I suspect you still have some sort of hiccup in your implementation.

PaulS:
Send a command to the Arduino. If you get a response, it's still connected. If you don't, it isn't (or it crashed).

Is it possible to operate a specific program with Arduino. Can Arduino run as input device to give command like distance to move and angle of rotation to the software which controls hardware like robotic arm CNC machine etc.

Is it possible to operate a specific program with Arduino.

The Arduino can run the specific program you uploaded to it. It can't run any other program.

Can Arduino run as input device to give command like distance to move and angle of rotation to the software which controls hardware like robotic arm CNC machine etc.

The Arduino can collect input data, and it can send data, via the serial port. Whether that is of any use to "the software which controls hardware like robotic arm CNC machine etc.", or not, depends on whether that software can read from the serial port that the Arduino is connected to.

Your PC program will have to be capable of either of these two options if you are going to do this via the serial port:-

a) Send and receive serial data with the Arduino. This will depend on whether the program developers have thought to do such a thing. If they have then there will be a protocol documented somewhere.

b) Communicate via serial with something (perhaps something you write) that in turn communicates with your PC program via an IPC (Interprocess Communications Protocol) IF ANY that has been provided within the PC program. This could be the old DDE interface, pipes or named pipes, spooled file system, shared memory or something else.

I have also added a script/sample sketch to the ESM4 that will do the checking of whether an Arduino is connected to an open com port. Enhanced Serial Monitor - ESM4 new error reporting system - Interfacing w/ Software on the Computer - Arduino Forum