在 C++ Builder中利用串行通信控件编程
http://tech.ddvip.com 2006年12月03日 社区交流
本文详细介绍在 C++ Builder中利用串行通信控件编程
(6)CommEvent=6时:检测到振铃信号。
另外十种情况是通信错误时产生,即错误代码。
三、程序的实现
1.注册MSComm控件
众所周知,C++Builder本身并不提供串行通讯控件MSComm,但我们却可以通过注册后直接使用它。启动C++Builder5.0后,然后选择C++Builder主菜单中的Component菜单项,单击Import Active Control命令,弹出Import Active窗口,选择Microsoft Comm Control6.0,再选择Install按钮执行安装命令,系统将自动进行编译,编译完成后即完成MSComm控件在C++Builder中的注册,系统默认安装在控件板的Active页,接下来我们就可以像使用C++Builder本身提供的控件那样使用新注册的MSComm控件了。(前提条件是你的机子上安装了Visual Basic,或者有它的库)
2.具体实现
新建一个工程Project1,把注册好的MSComm控件加入到窗体中,然后再加入5个ComboBox用来设置串口的属性,4个Button分别用来"打开串口" "关闭串口""发送数据""保存数据" ,2个Memo控件分别用来显示接收到的数据和发送的数据。再加入一个Shape控件用来标明串口是否打开。
ComboBox1用来设置串口号,通过它的Items属性设置1,2,3,4四个列表项分别表示COM1,COM2,COM3,COM4口。ComboBox2用来设置波特率,ComboBox3用来设置奇偶校验位,ComboBox4用来设置数据位,ComboBox5用来设置停止位。他们的缺省值分别是9600,n,8,1。
Button1用来打开串口,Button2用来关闭串口,Button3用来发送数据,Button4用来保存数据。Memo1用来显示发送的数据,Memo2显示接收的数据。Shape1的Shape属性设置为stCircle。
下面给出部分源码:
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
if(MSComm1->PortOpen==true)
{
Button1->Enabled=false;
Button2->Enabled=true;
Button3->Enabled=true;
Button4->Enabled=true;
Shape1->Brush->Color=clGreen;
}
else
{
Button2->Enabled=true;
Button2->Enabled=false;
Button3->Enabled=false;
Button4->Enabled=false;
Shape1->Brush->Color=clRed;
}
}
void __fastcall TForm1::Button1Click(TObject *Sender) / /打开串口
{
if(MSComm1->PortOpen!=true)
{
MSComm1->CommPort=StrToInt(ComboBox1->Text);//选择串口号
MSComm1->Settings=
ComboBox2->Text+","+
ComboBox3->Text+","+
ComboBox4->Text+","+
ComboBox5->Text; file://设置串口的属性波特率、奇偶校验、数据位和、//停止位。
MSComm1->InputMode=0;//设置传入数据的格式,0表示文本形式
MSComm1->PortOpen=true;//打开串口
Button1->Enabled=false;
Button2->Enabled=true;
Button3->Enabled=true;
Button4->Enabled=true;
Shape1->Brush->Color=clGreen;
}
}
void __fastcall TForm1::Button2Click(TObject *Sender) / /关闭串口
{
if(MSComm1->PortOpen!=false)
{
MSComm1->PortOpen=false;
Button1->Enabled=true;
Button2->Enabled=false;
Button3->Enabled=false;
Button4->Enabled=false;
Shape1->Brush->Color=clRed;
}
else
{
Button1->Enabled=false;
Button2->Enabled=true;
Shape1->Brush->Color=clRed;
}
}MSComm控件的Input和Output属性在Object Inspector中是看不到的,而且在C++Builder环境下这两个属性已不在是VB、VC中的原类型,而是OleVariant类型,也就是Ole万能变量,这就需要我们在发送接收数据时要把数据转换成Ole类型。
来源:yesky 作者:陆晓洁 责编:豆豆技术应用