Справочник функций

Ваш аккаунт

Войти через: 
Забыли пароль?
Регистрация
Информацию о новых материалах можно получать и без регистрации:

Почтовая рассылка

Подписчиков: -1
Последний выпуск: 19.06.2015

Прерывания при поступлении данных на COM порт

2.0K
23 февраля 2003 года
WhiteShadow
6 / / 08.10.2002
Требуется в Builder 5 во время работы программы перехватывать поступление данных на COM порт. Надо сделать всё на С. Нашёл функции для работы с портом, но никак их работу не могу завязать с прерыванием. Как сделать чтобы прога занималась своими делами и лишь при поступлении данных обрабатывала их?
427
24 февраля 2003 года
Glazunov Oleg
79 / / 20.03.2000
Я ниже приведу программку в которой используется приревание от com-порта (точнее в нем задействовано событие (Event) и функция WaitForSingleObject). Приводить конкретные строки не стал, т.к. потеря бы много времени на вылавливания их из кода програмы.

Разбирайтесь :)

//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include <assert.h>
#include <mem.h>
#include "Gps.h"
#include "Main.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "CSPIN"
#pragma resource "*.dfm"
TForm1 *Form1;

DCB dcb;
HANDLE hCom;
OVERLAPPED o;
COMMTIMEOUTS CommTimeouts;
BOOL fSuccess;
DWORD dwEvtMask;
byte Buf[1000];
byte Buf2[300];
DWORD ReadBytes;
RAW_MEASUREMENT_DATA RMD;

//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
hCom = CreateFile("COM1",
GENERIC_READ | GENERIC_WRITE,
0, /* exclusive access */
NULL, /* no security attrs */
OPEN_EXISTING,
0,//FILE_FLAG_OVERLAPPED,
NULL
);

if (hCom == INVALID_HANDLE_VALUE) {
/* Deal with the error. */
MessageBox(NULL,"Error CreateFile!","Message",MB_OK);
}

fSuccess = GetCommState(hCom, &dcb);

if (!fSuccess) {
/* Handle the error. */
MessageBox(NULL,"Error GetCommState!","Message",MB_OK);
}

/* Fill in the DCB: baud=9600, 8 data bits, no parity, 1 stop bit. */

dcb.BaudRate = CBR_115200;
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;

Label2->Caption=dcb.fBinary;
Label4->Caption=dcb.fParity;
Label6->Caption=dcb.EofChar;
Label8->Caption=dcb.fDtrControl;
Label10->Caption=dcb.fDsrSensitivity;

GetCommTimeouts(hCom,&CommTimeouts);
CommTimeouts.ReadIntervalTimeout=10;
// CommTimeouts.ReadTotalTimeoutMultiplier=0;
SetCommTimeouts(hCom,&CommTimeouts);

fSuccess = SetCommState(hCom, &dcb);

if (!fSuccess) {
/* Handle the error. */
MessageBox(NULL,"Error SetCommState!","Message",MB_OK);
}

/* Set the event mask. */

fSuccess = SetCommMask(hCom, EV_CTS | EV_DSR|EV_RXCHAR);

if (!fSuccess) {
/* deal with error */
MessageBox(NULL,"Error SetCommMask!","Message",MB_OK);
}

/* Create an event object for use in WaitCommEvent. */

o.hEvent = CreateEvent(NULL, /* no security attributes */
FALSE, /* auto reset event */
FALSE, /* not signaled */
NULL /* no name */
);

assert(o.hEvent);
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Button1Click(TObject *Sender)
{
char MyTitle[5];
int ReadPos;
for(;;)
{
WaitCommEvent(hCom, &dwEvtMask,NULL);//&o);
// WaitForSingleObject(o.hEvent,NULL);
// GetOverlappedResult(hCom,&o,&ReadBytes,true);
{
if (dwEvtMask & EV_DSR) {
MessageBox(NULL,"Ok EV_DSR!","Message",MB_OK);
/*
* . . .
*/
}
if (dwEvtMask & EV_RXCHAR) {
// MessageBox(NULL,"Ok EV_RXCHAR!","Message",MB_OK);
// Memo1->Lines->Clear();
ReadFile(hCom,Buf,500,&ReadBytes,NULL);
Buf[300]=Buf[8];
Buf[8]=Buf[11];
Buf[11]=Buf[300];
Buf[300]=Buf[9];
Buf[9]=Buf[10];
Buf[10]=Buf[300];
Label12->Caption=ReadBytes;
Label30->Caption=(ReadBytes-40)/42;
ReadPos=4;
// ReadPos=memchr(Buf, 'FAST', strlen(Buf));
if(Buf[ReadPos]=='r')
{
memcpy(&RMD,Buf+5+42*(UpDown1->Position-1),42);
Label14->Caption=RMD.PRN;
Label16->Caption=RMD.Warning;
Label18->Caption=IntToStr(RMD.Carrier_number);
Label20->Caption=RMD.SatX*0.03125;
Label22->Caption=RMD.SatY*0.03125;
Label24->Caption=RMD.SatZ*0.03125;
Label26->Caption=RMD.Channel_Number;
Label28->Caption=RMD.SNR;
Label32->Caption=RMD.SigR;
Label34->Caption=RMD.SigPhi;
Label36->Caption=0;
Label38->Caption=RMD.Pseudorange;
Label40->Caption=RMD.Doppler;
Label42->Caption=RMD.Status;
}
if(Buf[ReadPos]=='x')
{

}
Memo1->Lines->Add(StrPas(Buf));
/*
* . . .
*/
}
if (dwEvtMask & EV_CTS) {
MessageBox(NULL,"Ok EV_CTS!","Message",MB_OK);
/*
* . . .
*/
}
}
ZeroMemory(MyTitle,sizeof(MyTitle));
ZeroMemory(Buf,sizeof(Buf));
ZeroMemory(Buf2,sizeof(Buf2));
Application->ProcessMessages();
}
/*LPVOID lpMsgBuf;

//if(GetLastError()==ERROR_IO_PENDING)
// MessageBox(NULL,"Error Yes!","Message",MB_OK);
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL
);

// Display the string.
MessageBox( NULL,(LPCTSTR) LocalLock(lpMsgBuf),"GetLastError",MB_OK|MB_ICONINFORMATION );

// Free the buffer.
LocalFree( lpMsgBuf );*/
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormDestroy(TObject *Sender)
{
CloseHandle(hCom);
CloseHandle(o.hEvent);
}
//---------------------------------------------------------------------------
Реклама на сайте | Обмен ссылками | Ссылки | Экспорт (RSS) | Контакты
Добавить статью | Добавить исходник | Добавить хостинг-провайдера | Добавить сайт в каталог