|
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); }
|