Forum > Beginners

Use ttyS0, exsample code? For Linux

(1/3) > >>

coradi:
Hallo,
is tehre any exsample code for using Serial ports with USb Converter (ttyS0)?
A simple open Port, and read port, or send and read back from same RX/TX?

MarkMLl:
https://github.com/MarkMLl/serialcomms plus several others in the same repo.

MarkMLl

coradi:
Great, I will try

MarkMLl:
That's obviously based on the standard serial.pp, which hasn't had any attention for many years /but/ was tested on Linux, Windows (2Kish?) and SunOS/Solaris (which should be fairly similar to MacOS or whatever it's called).

It extended work that somebody else had done, but I was specifically focusing on low-level access and the calls will typically be in their own thread. At the time I was working on a serial comms analyzer (to capture the protocol between two commercial comms analyzers) and I very much wanted each captured byte to have a timestamp and a snapshot of the control line states.

On Windows it gets sole-access to the port, on unix it doesn't (which is something I'd be inclined to change). Also it doesn't have a SerAvailable(), but in Linux that has a gotcha: the result is truncated at 4K. More details in that repo, which also has stuff to detect various USB devices (which in practice are often built into e.g. a multimeter, Arduino etc.).

MarkMLl

coradi:
This example is from chatgpt,but why it doesn't work?
With hterm the LED from CH UART is working, but with this code, nothing happends


--- Code: ---program uart19200;

{$mode objfpc}{$H+}

uses
  cthreads, SysUtils, synaser;

var
  Serial: TBlockSerial;
  ReceivedData: string;
begin
 // WriteLn('Empfangene Daten: ');
  // Serielle Schnittstelle initialisieren
  Serial := TBlockSerial.Create;
  try
    // Serielle Schnittstelle öffnen
    Serial.Connect('/dev/ttyUSB0'); // Passe den Pfad hier an
    Serial.Config(19200, 8, 'N', SB1, False, False);

    // Empfangen von Daten
    WriteLn('Warte auf Daten...');

    while True do
    begin


      if Serial.WaitingData > 0 then
      begin
        ReceivedData := Serial.Recvstring(1000); // 1 Sekunde Timeout
        if ReceivedData <> '' then
        begin
          WriteLn('Empfangene Daten: ', ReceivedData);
        end;
      end
      else
        Sleep(100); // Warte kurz, um CPU-Last zu reduzieren
    end;

  except
    on E: Exception do
      WriteLn('Fehler: ', E.Message);
  end;

  Serial.Free;
end.             
--- End code ---

Navigation

[0] Message Index

[#] Next page

Go to full version