16 Sample C code for RS-232 Win32 send & receive
#include <windows.h>
HANDLE hCom;
void ExitOnError(char*message)
{
printf("%s error", message);
exit(1);
}
void OpenCom(char* COM_name)
{
DCB dcb;
COMMTIMEOUTS ct;
hCom = CreateFile(COM_name, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if(hCom==INVALID_HANDLE_VALUE) ExitOnError(COM_name); // can't open COM port
if(!SetupComm(hCom, 4096, 4096)) ExitOnError("SetupComm");
if(!GetCommState(hCom, &dcb)) ExitOnError("GetCommState");
dcb.BaudRate = 115200;
((DWORD*)(&dcb))[2] = 0x1001; // set port properties for TXDI + no flow-control
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = 2;
if(!SetCommState(hCom, &dcb)) ExitOnError("SetCommState");
// set the timeouts to 0
ct.ReadIntervalTimeout = MAXDWORD;
ct.ReadTotalTimeoutMultiplier = 0;
ct.ReadTotalTimeoutConstant = 0;
ct.WriteTotalTimeoutMultiplier = 0;
ct.WriteTotalTimeoutConstant = 0;
if(!SetCommTimeouts(hCom, &ct)) ExitOnError("SetCommTimeouts");
}
void CloseCom()
{
CloseHandle(hCom);
}
DWORD WriteCom(char* buf, int len)
{
DWORD nSend;
if(!WriteFile(hCom, buf, len, &nSend, NULL)) exit(1);
return nSend;
}
void WriteComChar(char b)
{
WriteCom(&b, 1);
}
int ReadCom(char *buf, int len)
{
DWORD nRec;
if(!ReadFile(hCom, buf, len, &nRec, NULL)) exit(1);
return (int)nRec;
}
char ReadComChar()
{
DWORD nRec;
char c;
if(!ReadFile(hCom, &c, 1, &nRec, NULL)) exit(1);
return nRec ? c : 0;
}
void main()
{
OpenCom("COM1:"); // change that to use a different COM port
WriteComChar(0x41);
CloseCom();
}
FPGA RS-232 development boards Page 21