Arduino - C Serial Communication closes after opening the Serial Monitor

Hello, I've been making a project to send orders and read information to and from Arduino using a webpage made in PHP (locally hosted in Apache). Since Serial Port Reading from PHP in Windows is impossible (without paying like 30 dollars) I made 3 C++ programs to open a COM Port (The one that the Arduino is assigned to) send/read and send-read data from it. The problem I have is actually trivial or unimportant, but annoying. If for some reason I decide to open the Serial Monitor and then close it (Let's say, I make a demonstration of how to send and read using the Serial Port without making an external program) If I call any of the aforementioned programs again to write or read (or both) on the Arduino, the board will simply deny itself to either carry out the corresponding orders (powering up a LED for example) or send anything to the Serial Port (The temperature value read by an LM35 as an example). I'm using Arduino UNO R3.

This is what my "WriteSerial" program should print in the command prompt whenever it works:

WriteSerial COM3 0 /*The 0 argument powers up the LED */
GetCommState: OK
SetCommState: OK
SetCommTimeouts: OK
WriteFile: 0

WriteSerial COM3 1 /*The 1 argument powers it down */
GetCommState: OK
SetCommState: OK
SetCommTimeouts: OK
WriteFile: 1
GetCommState: OK

If I open the Serial Monitor and then close it, the program still prints the above, but the Arduino won't turn on or off the LED, however all 3 states are still shown as OK.

It can be ""solved" by unplugging the Arduino (and therefore powering it down) and plugging it again.

<>

This is the WriteSerial code (In C++):

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

HANDLE hSerial;
char serialPort[22];
char szBuff[99];

HANDLE port_open(char serialPort[])
{
	/* Abrir un archivo con los siguientes parametros:
		Nombre: serialPort; 
		Accesso solicitado: Lectura y escritura; 
		Compartir: No compartir; 
		Medidas de seguirdad: Nulas; 
		Disposicion de creacion: Abrir archivo existente;
		Atributos del archivo: Sin atributos / Estándar  */
    hSerial = CreateFile(serialPort, GENERIC_READ | GENERIC_WRITE,
						  0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,0);
	/* Manija al archivo: 'hSerial'  */

    if(hSerial!=INVALID_HANDLE_VALUE)
 	{
 		DCB dcbSerialParams = {0}; /*Crear una estructura de tipo DCB de identificador dcbSerialParams */
 		DCB dcbSerial = {0};

 		dcbSerial.DCBlength=sizeof(dcbSerialParams);
 		if (!GetCommState(hSerial, &dcbSerialParams)) /* Solicitar estado de comunicacion del puerto indicado por hSerial con su configuracion de controles dada por dcbSerialParams */
 			printf("\nError de GetCommState!");
 		else
    		printf("\nFase GetCommState: OK.");

 		dcbSerialParams.BaudRate=CBR_9600;
 		dcbSerialParams.ByteSize=8;
 		dcbSerialParams.StopBits=ONESTOPBIT;
 		dcbSerialParams.Parity=NOPARITY;

 		if(!SetCommState(hSerial, &dcbSerialParams)) /*Asignar la configuracion dada por dcbSerialParams al dispositivo dado por la "manija" hSerial */
 			printf("\nError de SetCommState!");
 		else
 			printf("\nFase SetCommState: OK.");

 		COMMTIMEOUTS timeouts={0};
 		timeouts.ReadIntervalTimeout=50;
 		timeouts.ReadTotalTimeoutConstant=50;
 		timeouts.ReadTotalTimeoutMultiplier=10;
		timeouts.WriteTotalTimeoutConstant=50;
 		timeouts.WriteTotalTimeoutMultiplier=10;
 		if(!SetCommTimeouts(hSerial, &timeouts))
 			printf("\nError de SetCommTimeouts!");
 		else
  			printf("\nFase SetCommTimeouts: OK.");
    }
    return hSerial;
}

int WriteToSerial(char mensaje[]){
	sprintf(szBuff, "%s\n", mensaje);
	DWORD dwBytesRead = 0;
	if(!WriteFile(hSerial, szBuff, strlen(szBuff), &dwBytesRead, NULL)){
	  printf("\nError de WriteFile!");
	  return 1;
	}
	else {
    printf("\nWriteFile: %s", szBuff);
    return 0;
  } 
}

main(int argc, char *argv[]){
	if(argc==1){
		puts("No ha introducido un argumento");
		exit(1);
	}
	if(port_open(argv[1]) != INVALID_HANDLE_VALUE){
		WriteToSerial(argv[2]);
		CloseHandle(hSerial);
	}
	else {
		puts("La comunicacion con el puerto no pudo darse");
		exit(1);
	}
}

This is the code in the Arduino:

int redpin = 7;
int greenpin = 8;
int incomingbyte;
int SensorPin = 0;
float adRead = 0;
float Tmp = 0.0;

void setup(){
  Serial.begin(9600);
  pinMode(redpin, OUTPUT);
  pinMode(greenpin, OUTPUT);
}

void loop(){
  if(Serial.available() > 0){
  incomingbyte = Serial.read();
  switch (incomingbyte){
    case '0':
      Serial.println("Se recibio un 0, LED Rojo ON");
      digitalWrite(redpin, HIGH);
      break;
    case '1':
       Serial.println("Se recibio un 1, LED Rojo OFF");
       digitalWrite(redpin, LOW);
       break;
    case '2':
       Serial.println("Se recibio un 2, LED Verde ON");
       digitalWrite(greenpin, HIGH);
       break;
    case '3':
       Serial.println("Se recibio un 3, LED Verde OFF");
       digitalWrite(greenpin, LOW);
       break;
    case '4':
       adRead = analogRead(SensorPin);
       Tmp = (adRead/1023) * 500;
       Serial.println(Tmp);
       break; 
  }
  }
}

PD: Sorry for my english level.

Only one program on your PC can access the serial port. If you run serial monitor, then your other program cannot access the serial port.

ArticWolfPrD:
Since Serial Port Reading from PHP in Windows is impossible (without paying like 30 dollars)

It's free with Python.

Does your C program allow time for the Arduino to reset when it opens the serial port?

...R

michinyon:
Only one program on your PC can access the serial port. If you run serial monitor, then your other program cannot access the serial port.

I already knew that a single Serial Port can't be used by 2 programs at the same time, however, from what you're saying, it seems the Serial Monitor still holds property over the Port even after I close it. Is that correct?
Also, while I have the Serial Monitor open, my program won't be able to make a handle to the PORT returning this: Can not communicate with the port In the code, that message will only appear if the open_port function returns INVALID_HANDLE_VALUE. However if I close the Monitor and then try to send or read something, my program returns:

GetCommState: OK
SetCommState: OK
SetCommTimeouts: OK

But Arduino won't return anything in case I try to read from the Port nor it will comply the orders I send to it.

Robin2:
It's free with Python.

Does your C program allow time for the Arduino to reset when it opens the serial port?

...R

Didn't place any kind of "pause" routine. How do I make it?

ArticWolfPrD:
from what you're saying, it seems the Serial Monitor still holds property over the Port even after I close it. Is that correct?

Not in my experience. Yesterday I was alternating frequently between the serial monitor and Tera Term. There was no conflict as long as they were not open simultaneously.

ArticWolfPrD:
Didn't place any kind of "pause" routine. How do I make it?

My normal practice is to have the Arduino say "<I'm ready>" (or equivalent) from setup() and have my PC program wait until it receives that message.

See this Python-Arduino demo.

And I agree with @aarg, I have never had any problem alternating between my Python code and the Arduino IDE.

...R