Q&A

  • serial 통신 예제
간단히 만들어 봤습니다.

1, 우선 var 및에 전역번수를 잡어 놓구

// variables for serial communication.

lpszCommName : PChar; {Serial Port Name}

hCommPort : THandle; {Port handle.}

iAccess : Integer; {Type of access needed.}

dwCreation : DWORD; {Creation flags.}

DeviceControlBlock : TDCB; {Serial Port Control Stucture}

ts : TCommTimeouts;



2. 그밑에다 DCB 상수(?)를 적어놓습니다.

const

{Serial port flag values.}

DCB_BINARY = $0001;

DCB_PARITY = $0002;

DCB_OUTXCTSFLOW = $0004;

DCB_OUTXDSRFLOW = $0008;

DCB_DTRENABLE = $0010;

DCB_DTRFLOW = $0020;

DCB_DSRSENSE = $0040;

DCB_TXCONTONXOFF = $0080;

DCB_OUTX = $0100;

DCB_INX = $0200;

DCB_PECHAR = $0400;

DCB_NULL = $0800;

DCB_RTSENABLE = $1000;

DCB_RTSFLOW = $2000;

DCB_RTSTOGGLE = $3000;

DCB_ABORT = $4000;



3. 물론 앞에 선언이 되어야 하고 implementation 아래 다음을 타이핑.



procedure TForm1.ComPortStart;

begin

lpszCommName := 'COM1';

iAccess := GENERIC_READ or GENERIC_WRITE;

dwCreation := OPEN_EXISTING;



hCommPort := CreateFile(lpszCommName, iAccess, 0, NIL, dwCreation,0,0);

SetupComm( hCommPort, 1024, 1024); // Buffer Size



///////////////////////////////////////////////////////////////////////

// 통신할때 포트에 쌓인 값이 몇바이트가 되던지 무조건 다읽고

// 기다리지 않고 다음것을 읽을 수 있도록 초기화 한다.

///////////////////////////////////////////////////////////////////////

ts.ReadIntervalTimeout := 5;

ts.ReadTotalTimeoutMultiplier := 5;

ts.ReadTotalTimeoutConstant := 50;

SetCommTimeouts(hCommPort, ts);



GetCommState( hCommPort, DeviceControlBlock ) ; //dcb의 기본값을 받는다.

DeviceControlBlock.BaudRate := 9600 ; //BAUD_9600 -- 전송속도

DeviceControlBlock.ByteSize := DATABITS_8 ; //데이타비트

DeviceControlBlock.Parity := NOPARITY ; //패리티 체크

DeviceControlBlock.StopBits := ONESTOPBIT ; //스톱비튼

SetCommState( hCommPort, DeviceControlBlock ) ; //변경된 Dcb 설정

end;



4. 불러쓸때는 간단히 'CommPortStart;'라고만 적으면 되겠죠?



5. 마지막으로 가장(?) 중요한건 나가기전에 반드시 close를 해줘야겠죠?

'CloseHandle(hCommPort);' 이렇게요.



-- 전에 시리얼 통신을 잘 몰라서 질문도 하구 컴포넌트도 구해봤지만,

이렇게 api를 이용하는게 가장 안정적이더라구요.

자세한 내용은 통신에 관한 책들을 참조하시고 도움됐으면 좋겠네요

그럼 수고하십시오.



0  COMMENTS