delphi 7中的串行通信未完全接收

时间:2014-09-17 00:19:05

标签: delphi serial-port arduino

我有一个Delphi代码,可以从arduino接收传感器值。 Delphi收到的值是4个字符的长字符串。例如0.04; 0,32; 0,28等但有时价值没有完全收到。只显示4个字符,如4; 33; 2等,应为0.04; 0,32; 0.28。 这是我在Delphi 7中编写的代码:

procedure TForm1.ComPort1RxChar(Sender: TObject; Count: Integer);
var
  Str: String;
  tegangan: real;
begin
  DecimalSeparator:='.';
  sleep(25);
  ComPort1.ReadStr(Str, 4);
if Str <> '' then
begin
  Edit1.Text:=Str;
  tegangan:=strtofloat(Edit1.Text);
  x := x + 1;
  with chart1 do
    with series1 do
      addxy(x,tegangan);
      Adotable1.Open;
      AdoTable1.Append;
      AdoTable1.FieldByName('Arus').AsString:=Edit1.Text;
      AdoTable1.FieldByName('Waktu').AsString:=formatdatetime('dd/mm/yyyy'+'hh:nn:ss',now);
      AdoTable1.Post;
    end;
  end;
end;

1 个答案:

答案 0 :(得分:2)

您假设ReadStr()会返回您要求的所有内容。 Count事件的OnRxChar参数告诉您实际可用的字节数。如果数字总是4个字符,请尝试更类似的内容(类似于您评论过的other discussion中提供的答案):

var
  Buffer: AnsiString;

procedure TForm1.ComPort1RxChar(Sender: TObject; Count: Integer);
var
  Str: AnsiString;
  tegangan : Real;
begin
  ComPort1.ReadStr(Str, Count);
  Buffer := Buffer + Str;

  while Length(Buffer) >= 4 do
  begin
    Str := Copy(Buffer, 1, 4);
    Delete(Buffer, 1, 4);

    Edit1.Text := Str;

    DecimalSeparator := '.';
    tegangan := StrToFloat(Str);
    Inc(x);

    chart1.series1.addxy(x, tegangan);

    AdoTable1.Open;
    AdoTable1.Append;
    AdoTable1.FieldByName('Arus').AsString := Str;
    AdoTable1.FieldByName('Waktu').AsString := FormatDateTime('dd/mm/yyyyhh:nn:ss', Now);
    AdoTable1.Post;
  end;
end;