COM port

I would like to send some binary bytes ('FFEEDDCCBBAA99887766554433221100' in HEX) to COM1 to control another device.
However, the following code cannot work properly. So, what is the problem here ?


  hndFile:= CreateFile(PChar('COM1'),
                       GENERIC_WRITE,
                       0,
                       nil,
                       OPEN_EXISTING,
                       FILE_ATTRIBUTE_NORMAL,
                       0);

  strSource:= 'FFEEDDCCBBAA99887766554433221100';
  intLength:= Length(strSource);
  pchSource:= StrAlloc(intLength);
  StrPCopy(pchSource, strSource);
  intLength:= Round(StrLen(pchSource) / 2);
  pchTarget:= StrAlloc(intLength);
  HexToBin(pchSource, pchTarget, intLength);
  WriteFile(hndFile,
            pchTarget,
            intLength,
            dwdNumberWritten,
            nil);
  StrDispose(pchSource);
  StrDispose(pchTarget);

  CloseHandle(hndFile);
andrewyuAsked:
Who is Participating?
 
mokuleConnect With a Mentor Commented:
You've missed setting Com state. Something like

    if  hndFile <> INVALID_HANDLE_VALUE then
      begin
      if GetCommState( hndFile, dcbPort) then
        begin
        dcbPort.BaudRate := 9600;
        dcbPort.ByteSize := 8;
        dcbPort.Parity := 0;
        dcbPort.StopBits := 0;
        dcbPort.Flags := 0;
        SetCommState( hndFile, dcbPort);
        end;
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.