I am writing a program to control a relay switch connected thru the serial (RS-232) COM1 port. The device I am using has contains two relay switches. These are either ‘open’ or ‘closed’.
By default, both relays are open. The number 1 relay is closed by setting bit 1 in the modem control register. Number 2 relay is closed by setting bit 0 in the modem control register.
In C, this can be achieved as follows:
x = inportb(0x3FC);
x=x & ~2; //Set bit 1 to zero
x=x | 2; //Set bit 1 to one
x=x & ~1; //Set bit 0 to zero
x=x | 1; //Set bit 0 to one
C++ however, does not make COM port access so easy (or so I am led to believe). I currently have the following code, which successfully opens and closes the COM port so that it can be communicated with in C++ and Windows:
#include <windows.h>
//Initialise Windows module
int WINAPI WinMain (HINSTANCE hThisInstance, HINSTANCE hPrevInstance,
LPSTR lpszArgument, int nFunsterStil)
{
//Define the serial port precedure
HANDLE hSerial;
//Initialise relay
hSerial = CreateFile("COM1",GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
//SOME CODE MUST GO HERE
//Deactivate relay
CloseHandle(hSerial);
return 0;
}
However, I am at a loss as to how to ‘set bits’. I’m still very new to C++. Any help would be gratefully appreciated.
You need to understand how your device works. You cannot “set bits” directly in hSerial. Having COM port opened, you can send/receive bytes. Possibly you need to send something to device using WriteFile(hSerial, …). Maybe you need to read information from device using ReadFile(hSerial, …). COM port is not port as it was called in DOS, this is not address or register. This is input/output stream. You work with COM port like C program works with STDIN and STDOUT – read and wrire information from/to port.
Once you understand what your device needs (this means, define communication protocol), implement it in the program. Read this article: Serial Communications http://msdn.microsoft.com/en-us/library/ff802693.aspx – everything Win32 programmer needs to know about serial communications.