Comport4 CPort for delphi2010串列埠應用程式
阿新 • • 發佈:2019-01-09
comport4操作很簡單
ComPort1.Open;//開啟串列埠
ComPort1.close;//關閉串列埠
comport1.WriteStr('a');//傳送字元a
ComPort1.ReadStr(Str,Count);//讀取字元
使用comport4做串列埠除錯程式
注意:ComPort1.ComPRxChar要與comport1的OnRxChar進行連線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.
其中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;