comport4操作很简单
ComPort1.Open;//打开串口
ComPort1.close;//关闭串口
comport1.WriteStr('a');//发送字符a
ComPort1.ReadStr(Str,Count);//读取字符
使用comport4做串口调试程序
comport4的安装见:comport4.11 delphi2010安装教程_乌拉大喵喵-CSDN博客
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, CPort, CPortCtl, StdCtrls;
type
TForm1 = class(TForm)
ComPort1: TComPort;
btnFs: TButton;
Edit2: TEdit;
Memo1: TMemo;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Memo2: TMemo;
procedure FormCreate(Sender: TObject);
procedure btnFsClick(Sender: TObject);
procedure ComPRxChar(Sender: TObject; Count: Integer);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{16进制字符串转换成字符串}
function HexStrToStr(const S:string):string;
//16进制字符串转换成字符串
var
t:Integer;
ts:string;
M,Code:Integer;
begin
t:=1;
Result:='';
while t<=Length(S) do
begin
while not (S[t] in ['0'..'9','A'..'F','a'..'f']) do
inc(t);
if (t+1>Length(S))or(not (S[t+1] in ['0'..'9','A'..'F','a'..'f'])) then
ts:='$'+S[t]
else
ts:='$'+S[t]+S[t+1];
Val(ts,M,Code);
if Code=0 then
Result:=Result+Chr(M);
inc(t,2);
end;
end;
{字符串转换成16进制字符串}
function StrToHexStr(const S:string):string;
//字符串转换成16进制字符串
var
I:Integer;
begin
for I:=1 to Length(S) do
begin
if I=1 then
Result:=IntToHex(Ord(S[1]),2)
else Result:=Result+' '+IntToHex(Ord(S[I]),2);
end;
end;
//点击发送按钮
procedure TForm1.btnFsClick(Sender: TObject);
var
Str: String;
begin
comport1.WriteStr(Hexstrtostr(edit2.Text));//调用Hexstrtostr函数
end;
//初始化窗口
procedure TForm1.FormCreate(Sender: TObject);
begin
ComPort1.Open;
end;
//相当于串口中断 (要与comport1的OnRxChar进行连接)
procedure TForm1.ComPRxChar(Sender: TObject; Count: Integer);
var
Str: String;
begin
ComPort1.ReadStr(Str, Count);
memo1.Text:=StrToHexStr(Str);//显示成16进制形式
memo2.Text:={StrToHexStr}(Str);//显示成字符串形式
end;
end.
注意:ComPort1.ComPRxChar要与comport1的OnRxChar进行连接
源文件下载地址:百度网盘-链接不存在
其中35-72行的程序是为了
将输入的16进制的字符型数据转换成真实的16进制数
和
将16进制数,转成字符串进行显示用的程序
{16进制字符串转换成字符串}
function HexStrToStr(const S:string):string;
//16进制字符串转换成字符串
var
t:Integer;
ts:string;
M,Code:Integer;
begin
t:=1;
Result:='';
while t<=Length(S) do
begin
while not (S[t] in ['0'..'9','A'..'F','a'..'f']) do
inc(t);
if (t+1>Length(S))or(not (S[t+1] in ['0'..'9','A'..'F','a'..'f'])) then
ts:='$'+S[t]
else
ts:='$'+S[t]+S[t+1];
Val(ts,M,Code);
if Code=0 then
Result:=Result+Chr(M);
inc(t,2);
end;
end;
{字符串转换成16进制字符串}
function StrToHexStr(const S:string):string;
//字符串转换成16进制字符串
var
I:Integer;
begin
for I:=1 to Length(S) do
begin
if I=1 then
Result:=IntToHex(Ord(S[1]),2)
else Result:=Result+' '+IntToHex(Ord(S[I]),2);
end;
end;