新闻中心

EEPW首页>嵌入式系统>设计应用> C++builder串口通信设计(一)-串口接收数据

C++builder串口通信设计(一)-串口接收数据

作者: 时间:2016-11-28 来源:网络 收藏

3、unit1.cpp代码


void __fastcall TForm1::Button1Click(TObject *Sender) // 打开
{
static st=0;
AnsiString s;
if(st==0)
{
try
{
Form1->MSComm1->_CommPort=3;//COM3
Form1->MSComm1->Settings="9600,n,8,1"; //初始化串口
Form1->MSComm1->InputMode=type; ////设置传入数据的格式,0表示文本形式 ,1表示二进制格式
Form1->MSComm1->RThreshold=1;
Form1->MSComm1->PortOpen=true; //打开串口
Application->MessageBoxA("串口初始化成功","串口初始化",0);
}
catch(...)
//catch(EOleException&e)
{
Application->MessageBoxA("串口未连接好或已经打开","故障提示");
}

Button1->Caption="关闭";
st=1;
}
else
{
Form1->MSComm1->PortOpen=false;
Button1->Caption="打开";
st=0;
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::MSComm1Comm(TObject *Sender) //串口接收事件
{
AnsiString str; //声明一个AnsiString类型的变量
OleVariant rec; //声明一个用于接收数据的OleVariant变量。
int count;
int j;
unsigned char buf[128];

switch(MSComm1->CommEvent)
{
case comEvReceive: //接收事件
if(type==0) //字符型接收
{
str=MSComm1->Input;//收到字符串;
Memo1->Text=Memo1->Text+str+" "; //显示收到的字符串
}
else //type=1 为二进制接收
{
count=MSComm1->InBufferCount; //字节数
rec=MSComm1->Input; //取出接收缓冲器内容
for(j=0;j小于count;j++)
{
buf[j]=rec.GetElement(j); //转换成字节类型
}
Memo1->Text=Memo1->Text+"";
for(j=0;j小于count;j++)
{
Memo1->Text=Memo1->Text+IntToHex(buf[j],2)+" "; //显示接收的字节(以十六进制显示)
}
}
break;
default: break;
} //switch(MSComm1->CommEvent)
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button2Click(TObject *Sender)
{
Application->Terminate();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormCreate(TObject *Sender) //初始化
{
RadioButton1->Checked=false;
RadioButton2->Checked=true;
type=1; //0--字符,1---二进制
}
//---------------------------------------------------------------------------
void __fastcall TForm1::RadioButton1Click(TObject *Sender) //字符型
{
RadioButton2->Checked=false;
RadioButton1->Checked=true;
type=0; //字符型
Form1->MSComm1->InputMode=type;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::RadioButton2Click(TObject *Sender) //二进制
{
RadioButton1->Checked=false;
RadioButton2->Checked=true;
type=1;//二进制
Form1->MSComm1->InputMode=type;
}
//---------------------------------------------------------------------------

四、运行结果





可见,选择二进制模式或字符模式都可以完成串口接收通信。


上一页 1 2 下一页

评论


相关推荐

技术专区

关闭