1 // Elementary functions for for serial communication for Visual C / MFC
2 // Bela Torok / bela.torok@kssg.ch, March 2001
4 // This version is using the CTS/RTS protocol only, with 8 databits + no parity.
5 // This file was tested with ser_ir_cts_rts.c (in device/lib)
7 // Todo: Imporve the function SerialInit to support communication with no_protocol & XON/XOFF protocol,
8 // 7 databits, even & odd parity, 1, 1.5 & 2 stopbits, etc...
13 //#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers
15 #include <afxwin.h> // serial.cpp : Defines the entry point for the console application.
24 #define FC_DTRDSR 0x01
25 #define FC_RTSCTS 0x02
26 #define FC_XONXOFF 0x04
30 #define ASCII_BEL 0x07
34 #define ASCII_XON 0x11
35 #define ASCII_XOFF 0x13
37 // variables used with the com port
40 COMMTIMEOUTS CommTimeouts;
46 HANDLE SerialInit(char *ComPortName, int BaudRate)
50 hCom = CreateFile(ComPortName,
51 GENERIC_READ | GENERIC_WRITE,
52 0, // exclusive access
55 0, // no overlapped I/O
56 NULL); // null template
58 bPortReady = SetupComm(hCom, 2, 128); // set buffer sizes
61 bPortReady = GetCommState(hCom, &dcb);
62 dcb.BaudRate = BaudRate;
64 dcb.Parity = NOPARITY;
65 // dcb.Parity = EVENPARITY;
66 dcb.StopBits = ONESTOPBIT;
67 dcb.fAbortOnError = TRUE;
70 dcb.fOutX = FALSE; // XON/XOFF off for transmit
71 dcb.fInX = FALSE; // XON/XOFF off for receive
73 dcb.fOutxCtsFlow = TRUE; // turn on CTS flow control
74 dcb.fRtsControl = RTS_CONTROL_HANDSHAKE; //
76 dcb.fOutxDsrFlow = FALSE; // turn on DSR flow control
77 dcb.fDtrControl = DTR_CONTROL_ENABLE; //
78 // dcb.fDtrControl = DTR_CONTROL_DISABLE; //
79 // dcb.fDtrControl = DTR_CONTROL_HANDSHAKE; //
81 bPortReady = SetCommState(hCom, &dcb);
83 // Communication timeouts are optional
85 bPortReady = GetCommTimeouts (hCom, &CommTimeouts);
87 CommTimeouts.ReadIntervalTimeout = 5000;
88 CommTimeouts.ReadTotalTimeoutConstant = 5000;
89 CommTimeouts.ReadTotalTimeoutMultiplier = 1000;
90 CommTimeouts.WriteTotalTimeoutConstant = 5000;
91 CommTimeouts.WriteTotalTimeoutMultiplier = 1000;
93 bPortReady = SetCommTimeouts (hCom, &CommTimeouts);
98 char SerialGetc(HANDLE *hCom)
102 static DWORD iBytesRead;
104 bReadRC = ReadFile(*hCom, &rxchar, 1, &iBytesRead, NULL);
109 void SerialPutc(HANDLE *hCom, char txchar)
112 static DWORD iBytesWritten;
114 bWriteRC = WriteFile(*hCom, &txchar, 1, &iBytesWritten,NULL);
117 char* SerialGets(HANDLE *hCom)
119 static char rxstring[256];
124 c = SerialGetc(hCom);
125 if(c == '\r') continue; // discard carriage return
134 void SerialPuts(HANDLE *hCom, char *txstring)
137 static DWORD iBytesWritten;
139 bWriteRC = WriteFile(*hCom, txstring, strlen(txstring), &iBytesWritten,NULL);
143 void sleep( int _wait)
146 goal = clock() + _wait;
147 while( goal > clock() );