I made up a hacked up code that attempts to detect what port the board is connected to using VC++.
THe problem is that it only works sometimes, or not at all. I'm thinking it's a synch issue, or Windows doesn't buffer the serial port the way I'm using it.
This is the VC++ code I made: Error handling will be implemented later:
bool board_detected = 0;
char ports[] = {'1','2','3','4','5','6','7'};
int currentport = 0;
int maxports = 7;
HANDLE hSerial;
char portname[5];
strcpy(portname, "COM");
for(; currentport < maxports; currentport++)
{
portname[3] = ports[currentport];
portname[4] = '\0';
hSerial = CreateFile( portname, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
printf("\n\nTrying PORT: %s\n\n", portname);
printf("\n\n%s\n\n", (LPCWSTR)portname);
if(hSerial == INVALID_HANDLE_VALUE)
continue;
else
{
//FlushFileBuffers(hSerial);
DCB dcbSerialParams = {0};
dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
if(!GetCommState(hSerial, &dcbSerialParams)) {
printf("\nError Getting Com Port State!\n\n");
// Error handling
}
dcbSerialParams.BaudRate = CBR_9600;
dcbSerialParams.ByteSize = 8;
dcbSerialParams.StopBits = ONESTOPBIT;
dcbSerialParams.Parity = NOPARITY;
if(!SetCommState(hSerial, &dcbSerialParams)) {
printf("\n\nError Setting Serial Port STATE!\n\n");
//Error Handling
}
// To Prevent Timing out the serial port Tell Windows not to wait up for us
COMMTIMEOUTS timeouts = {0};
timeouts.ReadIntervalTimeout = 50;
timeouts.ReadTotalTimeoutConstant = 50;
timeouts.ReadTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 50;
timeouts.WriteTotalTimeoutMultiplier = 10;
if(!SetCommTimeouts(hSerial, &timeouts)){
printf("\n\n Serious Timeout error occured!!\n\n");
}
char readystatus[8] = {0};
DWORD testWrote = 0;
WriteFile(hSerial, "~READY~", 8, &testWrote, NULL);
Sleep(150);
ReadFile(hSerial, readystatus, 8, &testWrote, NULL);
readystatus[7] = '\0';
printf("\n\nREADY STATUS: %s\n\n", readystatus);
if(strstr(readystatus, "~READ1~") != NULL){
board_detected = 1;
break;
}
else
continue;
}
Now the Ardunio parses for ~ and ~ characters and whatever is between them is a string. If it parses ~READY~ it responds with ~READ1~ using Serial.Print.
Can anyone see how I can do this better? As I said it works sometimes, but it seems like hit or miss.