Delphi 调用WIN32 API操作串口


本文整理自网络,侵删。

 一段用API操作串口的代码,还是API好,一目了然,呵呵。
unit main;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;

type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Memo1: TMemo;
Memo2: TMemo;
Label1: TLabel;
Label2: TLabel;
RadioGroup1: TRadioGroup;
Button3: TButton;
Button4: TButton;
procedure Button1Click(Sender: TObject);
procedure OpenSerialPort;
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;
hSerialPort:Cardinal;
implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
OpenSerialPort;
end;
procedure tform1.OpenSerialPort;
var
cc:TCommConfig;
Temp:string;

begin
Temp:='Com'+inttostr(RadioGroup1.ItemIndex+1);
hSerialPort:=CreateFile(PChar(Temp),GENERIC_READ or GENERIC_WRITE,0,nil,OPEN_EXISTING,0,0);
if (hSerialPort=invalid_handle_value) then
begin
MessageBox(0,'打开串口失败','',MB_OK);
Exit;
end;
GetCommState(hSerialPort,cc.dcb);
cc.dcb.BaudRate:=CBR_9600;
cc.dcb.ByteSize:=8;
cc.dcb.Parity:=NOPARITY;
cc.dcb.StopBits:=ONESTOPBIT;
if not SetCommState(hSerialPort,cc.dcb) then
begin
ShowMessage('不能设置串口');
CloseHandle(hSerialPort);
Exit;
end
else
ShowMessage('打开,并设置成功!');
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
if hSerialPort<>0 then CloseHandle(hSerialPort);
Exit;
end;

procedure TForm1.Button3Click(Sender: TObject);
var
temp:string;
lw:LongWord;
begin
if hSerialPort=0 then Exit;
temp:=Memo1.Text;
WriteFile(hSerialPort,PChar(temp)^,Length(temp),lw,nil);
end;

procedure TForm1.Button4Click(Sender: TObject);
var
tempString:string;
inBuff:array[0..2047]of Char;
bytesRead,dwError:LongWord;
cs:TComStat;
begin
ClearCommError(hSerialPort,dwError,@cs);
if cs.cbInQue>SizeOf(inBuff)then
begin
PurgeComm(hSerialPort,PURGE_RXCLEAR);
Exit;
end;
ReadFile(hSerialPort,inBuff,cs.cbInQue,bytesRead,nil);
tempString:=Copy(inBuff,1,cs.cbInQue);
Memo2.Text:=tempString;
end;

end.

相关阅读 >>

Delphi 打开android应用信息

Delphi关于延迟时间的一点智慧

Delphi 打开win8及以上操作系统的系统已安装程序目录

Delphi 批量日期格式化

incsecond:将一个tdatetime变量加减一定数量的秒数

Delphi mac地址转换字符串

Delphi xe5实现随机大小写字幕或者数字

Delphi中三种延时方法

Delphi根据输入日期按年月周日输出日期段

Delphi xe7 rest获取天气实例

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...