1 // UART wrapper implementation for the Win32 platform
2 // make a new version of this file for different systems, e.g. Linux
5 #include "scalar_types.h" // (U)INT8/16/32
8 // COMx for windows, returns NULL on error
9 tUartHandle
UartOpen(char* szPortName
)
13 COMMTIMEOUTS cto
= { 0, 0, 0, 0, 0 };
15 memset(&dcb
,0,sizeof(dcb
));
17 /* -------------------------------------------------------------------- */
18 // set DCB to configure the serial port
19 dcb
.DCBlength
= sizeof(dcb
);
23 dcb
.fDtrControl
= DTR_CONTROL_ENABLE
; // enable for power
24 dcb
.fDsrSensitivity
= 0;
25 dcb
.fRtsControl
= RTS_CONTROL_ENABLE
; // enable for power
29 /* ----------------- misc parameters ----- */
33 dcb
.fAbortOnError
= 0;
41 /* ----------------- defaults ----- */
43 dcb
.Parity
= NOPARITY
;
45 dcb
.StopBits
= ONESTOPBIT
;
49 /* -------------------------------------------------------------------- */
50 // opening serial port
51 serial_handle
= CreateFile(szPortName
, GENERIC_READ
| GENERIC_WRITE
,
52 0, NULL
, OPEN_EXISTING
, FILE_FLAG_WRITE_THROUGH
, NULL
);
54 if (serial_handle
== INVALID_HANDLE_VALUE
)
56 //printf("Cannot open port \n");
60 SetCommMask(serial_handle
, 0);
61 SetCommTimeouts(serial_handle
, &cto
);
63 if(!SetCommState(serial_handle
, &dcb
))
65 //printf("Error setting up COM params\n");
66 CloseHandle(serial_handle
);
73 // returns true on success, false on error
74 bool UartConfig(tUartHandle handle
, long lBaudRate
, tParity nParity
, tStopBits nStopBits
, int nByteSize
)
78 if (!GetCommState (handle
, &dcb
))
83 dcb
.BaudRate
= lBaudRate
;
85 dcb
.StopBits
= nStopBits
;
86 dcb
.ByteSize
= nByteSize
;
88 if(!SetCommState(handle
, &dcb
))
90 //DWORD dwErr = GetLastError();
91 //printf("Error %d setting up COM params for baudrate byte\n", dwErr);
98 // returns how much data was actually transmitted
99 long UartWrite(tUartHandle handle
, unsigned char* pData
, long lSize
)
104 success
= WriteFile(handle
, pData
, lSize
, &result_nbr
, NULL
);
114 // returns how much data was actually received
115 long UartRead(tUartHandle handle
, unsigned char* pBuffer
, long lSize
)
120 success
= ReadFile(handle
, pBuffer
, lSize
, &read_nbr
, NULL
);
130 void UartClose(tUartHandle handle
)