Чтение из Com - порта
#include <vcl.h>
#pragma hdrstop
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
char lpInBuffer;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
hcom = CreateFile("\\\\.\\COM1",GENERIC_READ,0,NULL,OPEN_EXISTING,FILE_FLAG_OVERLAPPED,NULL);
if (hcom != INVALID_HANDLE_VALUE)
Memo1->Lines ->Add("Handle create successeful");
else
Memo1->Lines ->Add("Handle create error");
int i;
i = PurgeComm(hcom, PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|PURGE_RXCLEAR);
if (i == Null())
Memo1->Lines->Add("Purge error");
if ((i=ClearCommBreak(hcom))==Null())
Memo1->Lines->Add("ClearComm Break error");
DCB dcb;
if ((GetCommState (hcom, &dcb))==Null())
Memo1->Lines->Add("GetCommState error");
dcb.BaudRate=CBR_9600;
dcb.ByteSize=8;
dcb.Parity=NOPARITY;
dcb.StopBits=ONESTOPBIT;
//dcb.fOutxCtsFlow=false;
//dcb.fOutxDsrFlow=false;
if ((i=SetCommState(hcom, &dcb))==Null())
Memo1->Lines->Add("SetCommState error");
DWORD CommEventMask = EV_BREAK | EV_CTS | EV_DSR | EV_ERR | EV_RING |
EV_RLSD | EV_RXCHAR | EV_RXFLAG | EV_TXEMPTY;
if ((i = SetCommMask(hcom, CommEventMask))==Null())
Memo1->Lines->Add("SetCommNask error");
OVERLAPPED OL;
OL.hEvent=CreateEvent(NULL,TRUE,FALSE,NULL);
DWORD EventMask = 0;
do {
i = WaitCommEvent(hcom, &EventMask, &OL);
if ( ( !i ) && (GetLastError()==ERROR_IO_PENDING) ){
Memo1->Lines->Add("Waiting for event");
WaitForSingleObject(OL.hEvent, INFINITE);
}
if(EventMask & EV_RXCHAR)
Memo1->Lines->Add("Event RXCHAR");
DWORD ErrorMask = 0;
COMSTAT CStat;
ClearCommError(hcom, &ErrorMask, &CStat);
DWORD quelen = CStat.cbInQue;
DWORD dwReaded = 0;
i = ReadFile(hcom, lpInBuffer, quelen, &dwReaded, &OL);
if( dwReaded == 0 && GetLastError() == ERROR_IO_PENDING ) {
i = GetOverlappedResult(hcom, &OL, &dwReaded, FALSE) ;
}else
{
if (dwReaded>0) //если прочитали данные
Memo1->Lines->Add(lpInBuffer);
else
Memo1->Lines->Add("error reciving");
}
PurgeComm(hcom, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR);
EventMask=0;
ResetEvent(OL.hEvent);
}while(1);
}