Delphi7串口通訊實例(含Spcomm控件)

最近在用Delphi7做串口通信,但在網上找了很多代碼,都是沒有一個完整的實例,複製粘貼網上的代碼運行就沒有能通過的,可能是現在Delphi7在市場上用得不是很多,又或者說我是井底之蛙。因此,爲了解決大部分初學者對串口通訊不怎麼了解的鬱悶,現將我做好的實例分享給大家參考參考,希望能給初學者予以幫助,如有不對的地方還請多多指教。本實例用到的控件是Spcomm,也包含在這個文件夾裏面了,下面是部份截圖和部份代碼展示:





部分代碼展示:

//打開、關閉串口
procedure TCommixForm.btnPortClick(Sender: TObject);
begin
  if btnPort.Caption = 'Open Port' then
  begin
    if ComPortAvailable(pchar(cbbPort.Text)) then
    begin
      cmPort.StopComm;
      cmPort.CommName := cbbPort.Text;
      cmPort.BaudRate := StrToInt(cbbBaudRate.Text);
      Commsize;
      cmPort.StartComm;
      btnPort.Caption := 'Close Port';
      cbbPort.Enabled := False;
      btnSend.Enabled := True;
    end
    else
    begin
      ShowMessage(cbbPort.Text + ' 打開失敗,請檢查串口!');
      cbbPort.Enabled := True;
      btnPort.Caption := 'Open Port';
      btnSend.Enabled := False;
    end;
  end
  else
  begin
    cmPort.StopComm;
    cbbPort.Enabled := True;
    btnPort.Caption := 'Open Port';
    btnSend.Enabled := False;
  end;
end;

//處理接收的數據
procedure TCommixForm.cmPortReceiveData(Sender: TObject; Buffer: Pointer; BufferLength: Word);
var
  str, rbuf: string;
  i: Integer;
begin
  SetLength(rbuf, BufferLength);
  Move(Buffer^, PChar(rbuf)^, BufferLength);
  if rbShowHEX.Checked then
  begin
    rbuf := StrToHex(rbuf);
    str := '';
    for i := 0 to Length(rbuf) div 2 do
    begin
      //加個空格相對美觀點  clBlue
      if i < 1 then
        str := str + Copy(rbuf, i * 2, 2);
      if i > 0 then
        str := str + ' ' + Copy(rbuf, i * 2 + 1, 2);
    end;
    rbuf := str;
  end;
  mmoShow.Font.Color := clBlue;
  mmoShow.Lines.Add(rbuf);
end;

// 發送數據
procedure TCommixForm.btnSendClick(Sender: TObject);
var
  sendInput, result: string;
  i: Integer;
begin
  sendInput := mmoInput.Text;
  if rbInputHEX.Checked then
  begin
    sendInput := StringReplace(mmoInput.Text, ' ', '', [rfReplaceAll, rfIgnoreCase]);
    for i := 1 to Length(sendInput) do
    begin
      if System.Odd(i) then
      begin
        result := result + Char(StrToIntDef('$' + Copy(sendInput, i, 2), 0))
      end;
    end;
    cmPort.WriteCommData(PChar(result), Length(sendInput) div 2);
  end
  else
  begin
    cmPort.WriteCommData(PChar(sendInput), Length(sendInput));
  end;
end;

 本實例我將上傳至CSDN,有需要的朋友請自行下載!
下載地址:https://download.csdn.net/download/weixin_42148410/12251892

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章