You just cannot control the port so precisely that you can switch a pin on or off as you like.
If you want to use your computer as a switch, you should had some additional electronics behind
the port.
The problem is that any information sent to the port appears during a short period of time.
This windows program just switches the TX pin of the port during a short period
(enough to be detected by a circuit anyway).
#include <windows.h>
#include <iostream>
#include <string>
using namespace std;
void set_com_pin(bool value);
int main(int argc, char *argv)
{
if(argc != 2)
{
cerr<<"bad usage !"<endl;
return -1;
}
bool onoff;
if(string(argv[1])==string("-on"))onoff=true;
else if(string(argv[1])==string("-off"))onoff=false;
else
{
cerr<<"bad parameters !"<<endl;
return -1;
}
set_com_pin(onoff);
return 0;
}
void set_com_pin(bool value)
{
HANDLE hPort=CreateFile("COM1", GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
if(hPort==INVALID_HANDLE_VALUE)
{
cerr<<"there is a problem"<<endl;
return;
}
DCB dcb;
GetCommState(hPort, &dcb);
dcb.BaudRate=CBR_110; //we slow down the port
SetCommState(hPort, &dcb);
//we send the data;
char data=value?0xFF:0x00;
DWORD written=0;
WriteFile(hPort, &data, 1, &written, NULL);
CloseHandle(hPort);
if(written!=1)
{
cerr<<"there is a problem"<<endl;
}
}
another solution could be the use of two programs : a daemon, in a separate process, that repeatedely writes on the serial port, an a controller, that would
communicate with the daemon to turn it on/off (your program.exe), using named mutexes.
If I have some more time...