⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 unit1.~pas

📁 需要安装“MSCOMM”组件,串口通信实例
💻 ~PAS
字号:
unit Unit1;

interface

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

type
  TForm1 = class(TForm)
    MSComm1: TMSComm;
    Button1: TButton;
    Memo1: TMemo;
    Button2: TButton;
    ComboBox1: TComboBox;
    ComboBox2: TComboBox;
    Label1: TLabel;
    Label2: TLabel;
    procedure MSComm1Comm(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.MSComm1Comm(Sender: TObject);
var
  recstr : OleVariant;
begin
  if Mscomm1.CommEvent = 2 then
  begin
    recstr := Mscomm1.Input ;
    Memo1.text := Memo1.Text+recstr;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  Mscomm1.Settings :=ComboBox1.Text;
  if ComboBox2.Text ='com1' then // 串口只有com1和com2两种情况
    Mscomm1.CommPort :=1
  else
    Mscomm1.CommPort :=2;
  Mscomm1.PortOpen :=true; // 打开串口
  Mscomm1.DTREnable :=true; // 数据终端准备好
  Mscomm1.RTSEnable :=true; // 请求发送
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  Mscomm1.InBufferCount :=0; // 清空接收缓冲区
  Mscomm1.InputLen :=0; // Input读取整个缓冲区内容
  Mscomm1.RThreshold :=1; // 每次接收到字符即产生OnComm事件
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  Mscomm1.PortOpen :=false; // 关闭串口
  Mscomm1.DTREnable :=false;
  Mscomm1.RTSEnable :=false;
end;

end.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -