求串口通讯程序
我想请问你们有没有用C++ BUILDER 写过PC和单片机之间用串口通讯的上位机程序。如果有或有类似的能不能发给我做参考 问题点数:100、回复次数:1Top
1 楼hdaq(一生何求)回复于 2002-11-15 17:22:56 得分 100
__fastcall TForm1::TSpectrumForm(TComponent* Owner)
: TForm(Owner)
{
//串口初始化
if(COMPort==2)
{
//打开COM2
hComServer = CreateFile("COM2",GENERIC_READ | GENERIC_WRITE,0,NULL,OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED,NULL);
BuildCommDCB("COM2: baud=9600 parity=N data=8 stop=1",&dcbServer);
}
else
{
//打开COM1
hComServer = CreateFile("COM1",GENERIC_READ | GENERIC_WRITE,0,NULL,OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED,NULL);
BuildCommDCB("COM1: baud=9600 parity=N data=8 stop=1",&dcbServer);
}
fSuccess = SetCommState(hComServer,&dcbServer);
if(fSuccess)
{
StatusBar1->Panels->Items[9]->Text = "COM" + AnsiString(COMPort)+ ",9600,8,1,0";
SetupComm(hComServer,32,32); //设置发送/接收缓冲
}
else
StatusBar1->Panels->Items[9]->Text = "COM"+ AnsiString(COMPort) + "工作不正常";
}
//---------------------------------------------------------------------------
void __fastcall TForm1::TimerCOMTimer(TObject *Sender)
{
//读串口数据
unsigned char buf[50]; //
unsigned long aa = 1;
unsigned char bufch = '0';
int manyint = 0; //多少位数据
int tmpint;
AnsiString ansitemp="";
ClearCommError(hComServer,&dwErrorMask,&comstate);
tmpint = comstate.cbInQue; //bytes in input buffer n个(4+1个0xff)
if(tmpint > 4)
{
tmpint = (int)floor((double)tmpint / 5.0);
for(int j = 0 ; j < tmpint;j++)
{
manyint = 0;
bufch = '0';
while((bufch != 0xff)&&(manyint<5)&&(aa==1))
{
ReadFile(hComServer,&bufch,1,&aa,&oServer);
buf[manyint] = bufch;
manyint++;
delayforloop(40); //延时40次
}
for(int i=0; i < manyint; i++)
{
ansitemp = ansitemp + IntToHex(buf[i],2) + " ";
}
RxDataProcess(buf,manyint - 1);
//PurgeComm(hComServer,PURGE_RXCLEAR);
//StatusBar1->Panels->Items[9]->Text = "R6:" + ansitemp + "," + IntToStr(manyint);
}
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::sendcomdata(AnsiString ansisenddata)
{
//发送串口数据
PurgeComm(hComServer,PURGE_TXCLEAR);
SetEvent(oServer.hEvent);
char* buf = new char[ ansisenddata.Length() + 1 ];
strcpy( buf, ansisenddata.c_str() );
unsigned long aa = 10;
char ccc;
for(int i=0;i<ansisenddata.Length();i++)
{
ccc = buf[i];
WriteFile(hComServer,&ccc,1,&aa,&oServer);
delayforloop(80);
}
//ccc = 13; //加发回车
//WriteFile(hComServer,&ccc,1,&aa,&oServer);
ResetEvent(oServer.hEvent);
PurgeComm(hComServer,PURGE_TXCLEAR);
//StatusBar1->Panels->Items[9]->Text = "Tx:" + ansisenddata
// + "," + AnsiString(ansisenddata.Length());
}
//---------------------------------------------------------------------------
本例中PC机与单片机通讯的数据均以“回车”结束。
单片机发往PC机的数据为4个字符+回车格式。
你可以在此基础上灵活改动。
还可以使用MsComm控件。Top




