我是个初学者,主要是搞串行通讯的,工业用。手上有一本《C++Builder与RS-232串行通讯控制》清华大学出版社的。里面有一个试验,内容是将COM1COM2用RS232连接,然后些个小程序,将数据由一个口传到另外一个口。很简单的,有4个按钮,开打端口,发送数据,接受数据,结束任务。和2个Memo分别是送发送的数据和接受的数据。我把程序写下来:
#include
#pragma hdrstop
#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
HANDLE hComm;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
char *ComNo;
DCB dcb;
String Temp;
Temp="COM"+IntToStr(rdCOM->ItemIndex +1);
ComNo=Temp.c_str();
hComm=CreateFile(ComNo,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,0);
if(hComm==INVALID_HANDLE_VALUE)
{
MessageBox(0,"打开通讯端口错误!!","Comm ERROR",MB_OK);
return;
}
GetCommState(hComm,&dcb);
dcb.BaudRate=CBR_9600;
dcb.ByteSize=8;
dcb.Parity=NOPARITY;
dcb.StopBits=ONESTOPBIT;
if(!SetCommState(hComm,&dcb)){
MessageBox(0,"通讯端口设置错误!!","Set ERROR",MB_OK);
CloseHandle(hComm);
return;
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button2Click(TObject *Sender)
{
if (hComm!=INVALID_HANDLE_VALUE) CloseHandle(hComm);
exit(EXIT_SUCCESS);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button3Click(TObject *Sender)
{
String Temp;
char *SendData;
int ln;
unsigned long lrc,BS;
if(hComm==0) return;
Temp = mSend->Text;
SendData = Temp.c_str();
BS= Temp.Length();
WriteFile(hComm,SendData,BS,&lrc,NULL);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button4Click(TObject *Sender)
{
String Temp;
char inbuff[1024];
DWORD nBytesRead, dwEvent ,dwError;
COMSTAT cs;
ClearCommError(hComm,&dwError,&cs);
if (cs.cbInQue>sizeof(inbuff))
{
PurgeComm(hComm,PURGE_RXCLEAR);
return;
}
ReadFile(hComm,inbuff,cs.cbInQue,&nBytesRead,NULL);
inbuff[cs.cbInQue]='\0';
mReceive->Text = inbuff;
}
但是当我运行时,并没有出现想象的结果。我查了一下,writefile将数据发送出去,可是我查找状态时,readfile 函数中的inbuff中没有内容。所以就没有数据显示在第2个Memo中,现在我改怎么解决这个问题,谢谢。
帮帮一个才鸟把,跪谢
--------------------next---------------------
阅读(1000) | 评论(0) | 转发(0) |