代码分析
本帖最后由 长大的幸福 于 2012-12-25 08:52 编辑求大虾指点一下下面的代码,我的Memo接收到的数据怎么全是乱码呢?我用COM3发送的16进制的数据。COM1用于接收数据。波特率是:9600奇偶校验是:无校验位:8停止位:1我估计是红色代码这段出问题了,求指点。
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, OleCtrls, MSCommLib_TLB, StdCtrls;
type
TForm1 = class(TForm)
Memo1: TMemo;
Button1: TButton;
Button2: TButton;
ComboBox1: TComboBox;
ComboBox2: TComboBox;
MSComm1: TMSComm;
Label1: TLabel;
Button3: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure MSComm1Comm(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
Mscomm1.InBufferCount :=0; // 清空接收缓冲区
Mscomm1.InputLen :=0; // Input读取整个缓冲区内容
Mscomm1.RThreshold :=1; // 每次接收到字符即产生OnComm事件
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
Mscomm1.Settings :=ComboBox1.Text;
Mscomm1.CommPort :=1;
Mscomm1.PortOpen :=true; // 打开串口
Mscomm1.DTREnable :=true; // 数据终端准备好
Mscomm1.RTSEnable :=true; // 请求发送
Label1.Caption :='串口已打开';
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
Mscomm1.PortOpen :=false; // 关闭串口
Mscomm1.DTREnable :=false;
Mscomm1.RTSEnable :=false;
Label1.Caption :='串口已关闭';
end;
procedure TForm1.MSComm1Comm(Sender: TObject);
varrecstr:Olevariant;
begin
if
Mscomm1.CommEvent = 2 then
begin
recstr :=Mscomm1.Input;
Memo1.text :=Memo1.Text+recstr;
end;
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
Memo1.Lines.Clear;
end;
end.
void __fastcall TForm1::MSComm1Comm(TObject *Sender)
{
// COM1:接收事件,格式与InputMode一致,
// 当无新来字符时,即使有未取字符,不会再次发生接收事件
// 接收的字符边界是乱的
String ss="接收<-:";
OleVariant buf;
int bl;
while (buf=MSComm1->Input,
bl=buf.ArrayHighBound()+1,bl!=0) // 要反复取字符串,直至空
{
for (int i=0;i<bl;i++)
{
int c=(unsigned char)buf.GetElement(i);
ss=ss+IntToHex(c,2)+" ";
}
}
Memo1->Lines->Add(ss);
}
这是什么?? 小甲鱼 发表于 2012-12-26 15:47 static/image/common/back.gif
谢谢。{:5_109:} 强烈支持楼主ing……
页:
[1]