| ||
In almost all cases, when interfacing to the serial port of a PC, the tools that come with the PC are adequate. There are cases, however, when HyperTerminal isnt sufficient. For example, if you need to observe binary data on a serial line or if you need to implement a custom serial protocol on the target, you will find it quite handy to be able to manipulate the UART on the PC directly. Listing A.3 is a base for a home-grown serial port interface that you can use in place of the default Windows tools when necessary.
HANDLE comOpen(int portnum, int baud) { DCB dcb; HANDLE hCom; char portname[16]; sprintf(portname,"COM%d",portnum); hCom = CreateFile(portname, GENERIC_READ GENERIC_WRITE, // Open for read/write. 0, // Sharing flags. NULL, // Security attributes. OPEN_EXISTING, // Required for serial port. 0, // File attributes (NA). NULL); // Required for serial port. if (hCom == INVALID_HANDLE_VALUE) { ShowLastError("comOpen() CreatFile()"); return(INVALID_HANDLE_VALUE); } // Fill in the DCB... if (!GetCommState(hCom,&dcb)) { ShowLastError("comOpen() GetCommState()"); return(INVALID_HANDLE_VALUE); } dcb.BaudRate = baud; dcb.ByteSize = 8; dcb.Parity = NOPARITY; dcb.StopBits = ONESTOPBIT; dcb.fDtrControl = DTR_CONTROL_ENABLE; dcb.fDsrSensitivity = FALSE; dcb.fOutX = FALSE; dcb.fInX = FALSE; dcb.fNull = FALSE; if (!SetCommState(hCom,&dcb)) { ShowLastError("comOpen() SetCommState()"); return(INVALID_HANDLE_VALUE); } return(hCom); } void comClose(HANDLE hCom) { CloseHandle(hCom); } int comRead(HANDLE hCom,char *buf,int count) { DWORD bytesread; DWORD tot; tot = (DWORD)count; while(tot) { if (ReadFile(hCom,buf,(DWORD)tot, &bytesread,NULL) != TRUE) { ShowClearCommError(hCom); ShowLastError("comread ReadFile()"); return(-1); } tot -= bytesread; buf += bytesread; } return(count); } int comWrite(HANDLE hCom, char *buffer,int count) { DWORD byteswritten; if (WriteFile(hCom,buffer,(DWORD)count, &byteswritten,NULL) != TRUE) return(-1); return((int)byteswritten); }
The code in Listing A.3 depends on the Windows services: CreateFile() , GetCommState() , SetCommState() , ReadFile() , and WriteFile() . For details on these system calls, refer to the Visual C++ CD documentation. The comOpen() function is a wrapper for CreateFile() , GetCommState() , and SetCommState() to open a com port that creates a convenient hook to configure baud, parity, and other serial-port parameters. The comRead() and comWrite() functions create convenient wrappers for the ReadFile() and WriteFile() system calls, which are used to transmit to and receive from the serial port.
| ||