#include #include void dump(const unsigned char *data_buffer, const unsigned int length) { unsigned char byte; unsigned int i, j; for (i = 0; i < length; i++) { byte = data_buffer[i]; printf("%02x ", data_buffer[i]); // display byte in hex if (((i % 16) == 15) || (i == length - 1)) { for (j = 0; j < 15 - (i % 16); j++) printf(" "); printf("| "); for (j = (i - (i % 16)); j <= i; j++) { // display printable bytes from line byte = data_buffer[j]; if ((byte > 31) && (byte < 127)) // outside printable char range printf("%c", byte); else printf("."); } printf("\n"); // end of the dump line (each line 16 bytes) } // end if } // end for } void PrintAPIError(const char *msg, DWORD err) { if (msg) fprintf(stderr, "%s%d\n", msg, err); LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR)&lpMsgBuf, 0, NULL); fprintf(stderr, "Win API Last Error: %s", (char *)lpMsgBuf); LocalFree(lpMsgBuf); } int ReadByte(char *Port, int BaudRate, int ByteSize,int Parity,int StopBits) { DCB dcb; int retVal; BYTE Byte; DWORD dwBytesTransferred; DWORD dwCommModemStatus=0; const char* DRV_PATH = "\\\\.\\"; char portName[32]; strcpy(portName, DRV_PATH); strncat(portName, Port, 6); HANDLE hPort = CreateFile(portName,GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL ); if (INVALID_HANDLE_VALUE == hPort) { PrintAPIError("Error on CreateFile()!!!\n", GetLastError()); return 0; } if (!GetCommState(hPort,&dcb)) { PrintAPIError("Error on GetCommState()!!!\n", GetLastError()); return 0; } dcb.BaudRate = BaudRate; //9600 Baud dcb.ByteSize = ByteSize; //8 data bits dcb.Parity = Parity; //no parity dcb.StopBits = StopBits; //1 stop if (!SetCommState(hPort,&dcb)) { fprintf(stderr,"Error on SetCommState()!!!\n"); return 0; } SetCommMask (hPort, EV_RXCHAR | EV_ERR); //receive character event WaitCommEvent (hPort, &dwCommModemStatus, 0); //wait for character while (dwCommModemStatus & EV_RXCHAR) { ReadFile (hPort, &Byte, 1, &dwBytesTransferred, 0); //read 1 printf("%c",Byte); //dump(&Byte,sizeof(Byte)); } retVal = Byte; CloseHandle(hPort); return retVal; } int main(int argc, char *argv[]) { char *port="COM17"; ReadByte(port, CBR_9600, 8, NOPARITY, ONESTOPBIT); return 0; }