Search code examples
delphidelphi-2010

How can I send Unicode characters (16 bit) with Serial port in Delphi 2010?


I have a problem in Delphi 2010. I would like to send from my PC some Unicode (16 bits) characters to the printer with serial port (COM port). I use the TCiaComPort component in D2010.

For example:

CiaComPort1.Open := True; \\I open the port
Data := #$0002 + UnicodeString(Ж) + #$0003;
CiaComPort1.SendStr(Parancs); //I send the data to the device

If the printer characterset is ASCII then the characters arrive, but the ciril character is '?' on the Printer screen. But if the printer characterset is Unicode then the characters do not arrive to the printer.

An Unicode character represented in 2 bytes. How can I decompose an Unicode character to byte for byte? For example #$0002? And how can I send this strings byte for byte with the comport? Which function?


Solution

  • Under Windows (check your OS how to open and write to comm ports), I use the following function to write a UnicodeString to a COMM Port: Bear in mind that the port have to be setup correctly, baud rate, number of bits, etc. See Device Manager => Comm Ports

    function WriteToCommPort(const sPort:String; const sOutput:UnicodeString):Boolean;
    var
       RetW:DWORD;
       buff: PByte;
       lenBuff:Integer;
       FH:THandle;
    begin
       Result:=False;
       lenBuff:=Length(sOutput)*2;
       if lenBuff = 0 then Exit; // Nothing to write, empty string
    
       FH:= Windows.CreateFile(PChar(sPort), GENERIC_READ or GENERIC_WRITE, 0, Nil, OPEN_EXISTING, 0, 0);
       if (FH <> Windows.INVALID_HANDLE_VALUE) then
       try
          Buff:=PByte(@sOutput[1]);
          Windows.WriteFile(FH, buff^, lenBuff, RetW, Nil);
          Result:= Integer(RetW) = lenBuff;
       finally
          Windows.CloseHandle(FH);
       end;
    end;