반응형

// 시리얼 포트 (COM1) 입출력 예제 

// 2015.10.02  by osm

 

#include "stdafx.h"

#include <windows.h>

#include <stdio.h>

using namespace std;

 

#define COMPORT "COM1"

 

u_char SendStr[255] = "안녕하세요!";

u_char RcvStr[255] = "";

LPCWSTR Port = _T(COMPORT);

 

int _tmain(int argc, _TCHAR* argv[])

{

DWORD dwWritten;

WORD    Error = 0;

DCB sPState;

HANDLE hComm = CreateFile(Port, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

 

if(INVALID_HANDLE_VALUE == hComm)

{

printf("%s: 포트를 열 수 없음!\n", COMPORT); Error = 1;

} else if(0 == SetupComm(hComm, 4096, 3096))

{

printf("버퍼 설정 에러!\n"); Error = 2;

CloseHandle(hComm);

 

} else if(0 == PurgeComm(hComm, PURGE_TXABORT | PURGE_TXCLEAR))

{

printf("버퍼 초기화 에러!\n"); Error = 4; 

CloseHandle(hComm);

}

 

if(Error) 

return 1;

 

sPState.DCBlength = sizeof(sPState);

 

if(0 == GetCommState(hComm, &sPState))

{

printf("%s: 시리얼 상태 읽기 에러\n", COMPORT);

CloseHandle(hComm);

return 1;

}

 

sPState.BaudRate = CBR_38400;

sPState.ByteSize = 8;

sPState.Parity = EVENPARITY;

sPState.StopBits = onESTOPBIT;

 

if(0 == SetCommState(hComm, &sPState))

{

printf("%s: 시리얼 상태 설정 에러\n", COMPORT);

CloseHandle(hComm);

return 0;

}

 

if(0 == WriteFile(hComm, SendStr, sizeof(SendStr), &dwWritten, 0))

printf("%s: 쓰기 에러!\n", COMPORT);

else

printf("%s: 쓰기 성공!\n[%s]\n", COMPORT, SendStr);

 

    if(0 == ReadFile(hComm, RcvStr, sizeof(RcvStr), &dwWritten, 0))  

printf("%s: 읽기 에러!\n", COMPORT);

else

printf("%s: 읽기 성공!\n[%s]\n", COMPORT, RcvStr);

 

CloseHandle(hComm);

return 0;

}

반응형

+ Recent posts