如题

解决方案 »

  1.   

    procedure SendHex(S: String);
    var
    s2:string;
    buf1:array[0..50000] of char;
    i:integer;
    begin
    s2:='';
    for i:=1 to length(s) do
    begin
        if ((copy(s,i,1)>='0') and (copy(s,i,1)<='9'))or((copy(s,i,1)>='a') and (copy(s,i,1)<='f'))
            or((copy(s,i,1)>='A') and (copy(s,i,1)<='F')) then
        begin
            s2:=s2+copy(s,i,1);
        end;
    end;
    for i:=0 to (length(s2) div 2-1) do
        buf1[i]:=char(strtoint('$'+copy(s2,i*2+1,2)));
        frmBatCapRecord.Comm1.WriteCommData(buf1,(length(s2) div 2));
    end;
      

  2.   


    function  tform1.hextostring(s:string):string;
    var
      j,i:integer;
      s2:string;
      begin
      s2:='';
      j:=trunc((Length(s)/2))-1;
      for i:=0 to j do
      s2:=s2+chr(strtoint('$'+(copy(s,2*i+1,2))));
      result:=s2;
    end;procedure TForm1.Button1Click(Sender: TObject);
    begin
      self.Comm1.CommName:=edit1.Text;
      self.Comm1.BaudRate:=strtoint(edit2.Text);
      self.Comm1.ByteSize:=Tbytesize(3);
      self.Comm1.StopBits:=Tstopbits(0);
      self.Comm1.Parity:=tparity(0);
      try
        self.Comm1.StartComm;
      except
        raise exception.Create('打开串口失败!');
      end;  self.StatusBar1.Panels[0].Text:=edit1.text+'已打开';
      self.StatusBar1.Refresh;
    end;procedure TForm1.Button3Click(Sender: TObject);
    begin
      self.Comm1.StopComm;
      self.StatusBar1.Panels[0].Text:=edit1.text+'已关闭';
      self.StatusBar1.Refresh;
    end;procedure TForm1.Button2Click(Sender: TObject);
    var
      str:Pchar;
      count:integer;
    begin
      str:=pchar(edit3.Text);
      str := hextostring(str); //将字符串转为十六进制
      count:=length(str);
      if self.Comm1.WriteCommData(str,count) then
        self.Memo1.Lines.Add('已发送'+inttostr(count)+'个字符')
      else
        raise  exception.Create('发送错误');
    end;procedure TForm1.Button4Click(Sender: TObject);
    begin
       close;
    end;procedure TForm1.Comm1ReceiveData(Sender: TObject; Buffer: Pointer;
      BufferLength: Word);
    var
      str:string;
      strrecv:string;
    begin
      setlength(strrecv,bufferlength);
      move(buffer^,Pchar(strrecv)^,bufferLength);
      self.Memo2.Lines.Add('已收到:'+inttostr(bufferlength)+'字节的数据');
      self.Memo2.Lines.Add(strrecv);
    end;