#include <windows.h> #include <stdio.h>
#define CRC_PRESET 0xFFFF #define CRC_POLYNOM 0x8408
unsigned short CRC16(void * , unsigned int );
int main() { u_char caString[255] = {0x0D, 0x00, 0x71, 0x00, 0x3F, 0x00, 0x35, 0x00, 0x14, 0x00, 0x00}; //u_char caCmd[255] = {0x05, 0x00, 0x02, 0x00, 0x30, 0x00, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x46, 0x41}; unsigned int uiCnt; DWORD dwCnt; DCB sPState; HANDLE hComm = CreateFile("Com4" , GENERIC_READ | GENERIC_WRITE , 0 , NULL , OPEN_EXISTING , FILE_ATTRIBUTE_NORMAL , 0); if(INVALID_HANDLE_VALUE == hComm) { printf("포트를 열 수 없음 \n"); return 0; } if(0 == SetupComm(hComm, 4096, 4096)) { printf("버퍼 설정 에러 \n"); CloseHandle(hComm); return 0; }
if(0 == PurgeComm(hComm, PURGE_TXABORT | PURGE_TXCLEAR)) { printf("버퍼 초기화 에러 \n"); return 0; }
sPState.DCBlength = sizeof(sPState); if(0 == GetCommState(hComm, &sPState)) { printf("시리얼 상태 읽기 에러 \n"); CloseHandle(hComm); return 0; } sPState.BaudRate = CBR_38400; sPState.ByteSize = 8; sPState.Parity = EVENPARITY; sPState.StopBits = ONESTOPBIT;
if(0 == SetCommState(hComm, &sPState)) { printf("시리얼 상태 설정 에러 \n"); CloseHandle(hComm); return 0; }
*((unsigned short*)(caString+caString[0]-2)) = CRC16(caString, caString[0]-2); WriteFile(hComm, caString, caString[0], & dwCnt, 0); ReadFile(hComm, caString, 1, & dwCnt, 0); ReadFile(hComm, caString+1, caString[0]-1, & dwCnt, 0);
return 0; }
unsigned short CRC16(void * vpData, unsigned int uiLen) {
unsigned short crc = CRC_PRESET; unsigned int i; unsigned int j; unsigned char * DATA = vpData;
for(i = 0; i <uiLen; ++i) { crc^=DATA[i]; for (j = 0; j < 8; j++) { if (crc & 0x0001) { crc = (crc >> 1) ^ CRC_POLYNOM; } else { crc = (crc >> 1); } } } return crc;
}
|