【Delphi】Utils.SerialPort

unit Utils.SerialPort;

interface

uses
    SysUtils, SPComm;

type
    TSerialPort = class(TObject)
    private
        comm: TComm;
    public
        constructor Create(name: string; baud: cardinal); overload;
        constructor Create(name: string; baud: cardinal; data: TByteSize; stop: TStopBits; parity: TParity); overload;
        procedure AttchDataEvent(event: TReceiveDataEvent);
        procedure AttchErrorEvent(event: TReceiveErrorEvent);
        procedure Open;
        procedure Close;
        procedure Send(data: string);
        destructor Destroy; override;
    end;

implementation

constructor TSerialPort.Create(name: string; baud: cardinal);
begin
    comm := TComm.Create(nil);
    comm.CommName := Trim(name);
    if Length(comm.CommName) > 4 then begin
        comm.CommName := '\\.\' + comm.CommName;
    end;
    comm.BaudRate := baud;
    comm.ByteSize := _8;
    comm.StopBits := _1;
    comm.Parity := None;
end;

constructor TSerialPort.Create(name: string; baud: cardinal; data: TByteSize; stop: TStopBits; parity: TParity);
begin
    comm := TComm.Create(nil);
    comm.CommName := Trim(name);
    if Length(comm.CommName) > 4 then begin
        comm.CommName := '\\.\' + comm.CommName;
    end;
    comm.BaudRate := baud;
    comm.ByteSize := data;
    comm.StopBits := stop;
    comm.Parity := parity;
end;

procedure TSerialPort.AttchDataEvent(event: TReceiveDataEvent);
begin
    comm.OnReceiveData := event;
end;

procedure TSerialPort.AttchErrorEvent(event: TReceiveErrorEvent);
begin
    comm.OnReceiveError := event;
end;

procedure TSerialPort.Open;
begin
    comm.StopComm;
    Sleep(200);
    comm.StartComm;
end;

procedure TSerialPort.Close;
begin
    comm.StopComm;
end;

procedure TSerialPort.Send(data: string);
begin
    comm.WriteCommData(PChar(data), Length(data));
end;

destructor TSerialPort.Destroy;
begin
    comm.Free;
    comm := nil;
    inherited Destroy;
end;

end.

上一篇:Axios封装和跨域问题-02


下一篇:下拉刷新 shang 拉刷新