0

I am using the TComPort library, to send a request to the device I need to send the command in Hexadecimal data like the example below

procedure TForm1.Button3Click(Sender: TObject);
begin
  ComPort1.WriteStr(#$D5#$D5);
end;  

But that is a hardcoded example.

How can I convert S into a valid value for ComPort1.WriteStr

procedure TForm1.Button3Click(Sender: TObject);
var
  S:String;
begin
  Edit1.Text:='D5 D5';
  ComPort1.WriteStr(Edit1.Text);
end;  
0

1 Answer 1

2

You don't send actual hex strings over the port. That is just a way to encode binary data in source code at compile-time. #$D5#$D5 is encoding 2 string characters with numeric values of 213 (depending on {$HIGHCHARUNICODE}, which is OFF by default).

TComPort.WriteStr() expects actual bytes to send, not hex strings. If you want the user to enter hex strings that you then send as binary data, look at Delphi's HexToBin() functions for that conversion.

That being said, note that string in Delphi 2009+ is 16-bit Unicode, not 8-bit ANSI. You should use TComPort.Write() to send binary data instead of TComPort.WriteStr(), eg:

procedure TForm1.Button3Click(Sender: TObject);
var
  buf: array[0..1] of Byte;
begin
  buf[0] := $D5;
  buf[1] := $D5;
  ComPort1.Write(buf, 2);
end;  

However, TComPort.WriteStr() will accept a 16-bit Unicode string and transmit it as an 8-bit binary string by simply stripping off the upper 8 bits of each Char. So, if you send a string containing two Char($D5) values in it, it will be sent as 2 bytes $D5 $D5.

Sign up to request clarification or add additional context in comments.

3 Comments

Hello, sorry for delay, I don't get it very clear yet, I am trying to use HexToBin(PWideChar(HexStr),bytes,Length(bytes)); then ComPort1.Write(bytes,Length(bytes)); but is not converting as expected
Make sure that the length of HexStr is an even multiple of 2, and contains only hex digits (0..9, a..f, A..F), no other characters including spaces. And that bytes is preallocated to at least Length(HexStr) div 2 bytes in size.
I found a way to achieve what I was looking: for i:=0 to (Length(Hexstr) div 2 - 1) do a:=a+Chr(Byte(StrToInt('$'+Copy(hexStr, (i * 2) + 1, 2))));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.