Communication ports


Communication ports are the way used by the protocol drivers to send and receive data. One communication port can be used by one or more protocol drivers, simultaneously.

Communication ports aren’t implemented together with protocol drivers to allow more flexibility to the system. An real application that can be done using this architecture, is the association of a TTCP_UDPPort with a COMServer (devices that acts as a gateway of RS-232/485/422 to TCP/IP), to by example, communicate with a Modbus RTU device that is far, over the Internet. Another advantage of this design is to put two or more different protocols using the same communication port simultaneously, both on the same application. This is possible because all PascalSCADA ports comes with mechanism that only allows one protocol to use communication port. That is, an application can communicate with multiple devices, these devices with different communication protocols and all connected to the same RS-485 network. It is possible, though not recommended.

All port classes that exists on PascalSCADA descend from TCommPort class, that implements the methods to open and close the port, read and write data, and clean the buffers when a communication error occurs. But if a new port is being written, these methods should be specialized to handle the new port being implemented.


The TSerialPort class, descendant of TCommPort class, has been created to allow the protocol drivers to exchange data over serial ports, regardless of the physical layer used by serial port.

On Windows, this class need of a serial port with name between COM1 and COM255.

Running over Linux, any device where the name starts with tty<number>, ttyUSB<number> or ttyACM<number> is valid.

On FreeBSD, any device where the name starts with cuad<number> is accepted by the class.

Both Linux and FreeBSD (or another Unix) should be added the user that will run the application on the group owner of the serial port and the group must have permission of read/write on the desired serial port. The name of this group can vary depending of the operating system.

Independent of operating system, the TSerialPort class has the following properties that configure the operation of the serial port:

  • COMPort: defines the name of serial port to be used. If the application has been configured with one serial port and it is disconnected of the system (by example, a USB <-> serial converter) and the application is started, a exception will be raised. If this exception occurs on the application load (initialization), your application will be not loaded, even if Active=false.
  • Baudrate: communication speed in bits per second that will be used on the configured serial port while it’s in use. Baud rates between 110 bps and 115200 bps are accepted.
  • DataBits: Defines the word length in bits that will be used when communicating with the serial port. Only the size of 7 or 8 bits are accepted, the default is 8 bits. Some protocols requires the value of this property set to 7 bits, like Modbus ASCII. Others requires the word size of 8 bits, like Mobus RTU.
  •  StopBits: Configure how many bits will be used to mark start and the end of each word transmitted or received in the serial communication. Valid values are 1 or 2 stop bits. The default is 1 stop bit.
  • Paridade: configures if each word received word will have a parity error check, and if error check exists, this defines if it will be even or odd.
  • Timeout: defines the maximum time that the serial port will wait for reading a certain amount of data. This time is set in milliseconds. In cases of timeout overflow, a clean up of the read and write buffers is performed.
  • AcceptAnyPortName: if this property is enabled on a Unix system (Linux, FreeBSD, etc), makes the TSerialPort accept any device name on the COMPort property. Very useful when some some drivers create devices with names that don’t matches the patterns described above.
  • WriteReadDelay: Delay in milliseconds between write and read commands.
  • Active: This property controls when the port will be opened or closed. The serial port should not be open by another process when this property goes to true, otherwise the value of this property come back to false. In the development time, Active = true only checks if everything is OK to open the serial port, but don’t open it.

The class TTCP_UDPPort, descendant of TCommport, has been created to allow the protocol drivers exchange data over TCP (tested) or UPD (not tested) over IPv4, independent of physical and link layer being used by the port.

This class has no operating system dependent properties, and the following properties configures its operation:

  • Host: The IPv4 address of the host to connect. Host names are not accepted, only IPv4 address.
  • Port: Port number on the destination host to connect. Only port numbers between 1 and 65535 are accepted.
  • PortType: Sets the socket type that will created when connected with the host. It can be a TCP or UDP.
  • ExclusiveDevice: If true, don’t opens the socket when in the development time. Useful when the destination host has a few numbers of available connections.
  • EnableAutoReconnect: If true and if the socket is disconnected (problem on the physical layer or on the host) enables the timer that tries to reconnect the socket. In this case the invalid socket is closed while Active property remains true.
  • ReconnectRetryInterval: This property defines the interval in milliseconds to attempt to reconnect lost connections. This property is only valid if both EnableAutoReconnect and Active are true.
  • Timeout: Sets the maximum time to wait to complete a reading or writing of a certain amount of data. This time is set in milliseconds. If any operation exceeds this time limit, the buffers are cleaned up, the socket is verified and if some trouble is detected, the current socket will be closed and if EnableAutoReconnect is true, a attempt to connect a new socket will be made.

Bellow is listed a example of how exchange data using the PascalSCADA communication ports directly on the source code, in other words, without use a protocol driver. As all the communication ports are descendants of TCommPort class, the example below also applies if you want to implement something using TTCP_UDPPort.

27 thoughts on “Communication ports”

  1. I did not find any examples, but I figured out the system’s work. But still, I did not have a definite mistake. When I add a few tags and connect to the HMI component, it displays some kind of nonsense if I do not use the built-in method of auto-reading, and I use the timer then it works.

  2. hi sir good afternoon, am ajay kumar from india. i started learning of HMI’s . my question is ” HMI having two ports COM0, COM1. while COM0 in connected with PLC to pass Modbus commands over TCP . While that is happening I want to read HMI registers from another COM port on the same HMI. How can we do that?

  3. hi , my name is AJAY from INDIA. i need some answer regarding below question. please review on this question
    basically HMI having 2 ports vise COM0 & COM1. now am connected COM0 to passed Modbus commands over TCP to PLC while HMI was master.
    While that is happening I want to read HMI registers from another COM port on the same HMI. How can we do that? Can you implement and show?

    1. Hi Mr. Ajay!

      Why not read and write using the same port (COM0)?

      I don’t understand if your slave is Modbus RTU or TCP. If your slave is Modbus RTU you can’t put your application using COM0 and COM1 communicating with the same PLC port, because Modbus RTU don’t alloos two masters on the same bus.

      But if:
      you are using Modbus RTU AND have two ports on your PLC


      you are using Modbus TCP

      You should put two:

      ** Two serial ports and two Modbus RTU protocolo driver, one for read other writing operations

      ** Two TCP_Udpport and two Modbus TCP driver, one for read other writing operations.

      For both cases:

      ** tags linked with with port dedicated for read, should autowrite set to false

      ** tags linked with port dedicated to write should autoread set to false

      ** Modbus driver linked with the port dedicated for read should have ReadOnly property set to true.

      I don’t what you want to do, but I hope this helps.

      The best regards from Brazil,


      1. thnaks Fabio for valuable information . may i use this information to solve my problem , but still i confused.
        if any issues made during my working process i will ask questions , please give some guidance for me. i want to learn good HMI knowledge. i needed this . thank you sir.
        best regards AJAY KUMAR

  4. Hello from Turkey. First of all thank you for this perfect project.
    I would like some update about baudrate list. As you know nowadays it is common to use upper baudrates. Could you add the following rates to TSerialPort.
    128000, 153600, 230400, 256000, 460800, 921600.

    P.S. : I am not sure if this is a right place for such kind of request.

    Thanks in advance.


    1. Hi Fatih!

      I’ll find the baudrates common to all supported OSes and keep you updated. If I’m right, these low baudrates are a Windows limitations. I will keep you updated.

      1. Hi Fabio,

        I have already tested in lab for modbus rtu protocol by adding extra baudrates above. Of course mentioned limits depend on the capability of hardware, our adapter works up to 2 Mbits.
        As I said I can make the modifications on code but in order to use up-to-date code without editing, it would be better, it also helps other people as well. I have just test it in Windows, but in next week, I can test in Linux .


        1. Hi Fatih!

          Can you check if these baud rates are available on Windows, installing your hardware on that? I’m reading into docs, and Windows appears to support only 128kbps baud rate… sad!

          Can you send me your modifications to merge into current code base?

  5. Bom dia!
    Estou montando uma rede de PLCs via ethernet TcpIP e gostaria de saber se o PascalScada pode se comunicar com mais de um equipamento com uma unica porta.

    1. Bom dia Rafael!

      Não. E não é uma limitação do PascalSCADA e sim do design das conexões (UDP,TCP)/IP que são 1:1, ou seja, em qualquer sistema de supervisão vc terá esta limitação. A única excessão é se na outra ponta, você tem um equipamento que desempenha a função de gateway, como um gateway ModbusTCP => Modbus RTU. Ai neste caso sim, um unica conexão TCP pode ser usada para “conectar-se” com vários equipamentos Modbus RTU, mantendo a conexão TCP 1:1.

      Para solucionar seu problema no PascalSCADA, será necessário uma porta TCP/IP para cada equipamento que vc precisa comunicar.

      1. Certo… Quando você fala uma porta para cada equipamento você esta se referindo a uma porta física ou uma porta componente do Pascalscada, se for a componente, você teria algum exemplo de como gerenciar essa portas? Sei que a pergunta é simples, mas acontece que só havia tido experiencias com portas seriais.
        Ahhh… outra coisa, eu gostaria também de parabeniza-lo Fabio, com certeza sei q não se lembra de mim, mas a uns 7 ou 8 anos eu fiz meu primeiro contato contigo, eu ainda morava em Vitória ES, agora estou em Petrolina PE e fico muito feliz de ver que seu trabalho permanece em desenvolvimento e ajudando dessa maneira. Desenvolvi algumas soluções usando o PascalScada, como prensas, sistemas de pesagem e o maior foi desenvolvido a uns 3 anos, um sistema de gerenciamento de 60 medidores de grandezas elétricas da Schneider Electric, PM1200, usando a serial RS232->RS485 direto nos equipamentos de shopping aqui da região.

        1. Boa tarde Rafael!

          Lembro de ti sim, você me enviou screenshots de algumas de suas aplicações a alguns anos (que estão publicados na pagina de screenshots). Se quiser mandar mais alguns screenshots das suas aplicações, me ajuda bastante.

          Bom respondendo sua pergunta, são necessário vários componentes TCP_UDPPort do PascalSCADA inseridos na sua aplicação. Este componente representa um socket tcp/ip (que é uma das várias conexões lógicas que um equipamento pode ter) que correm sobre uma porta física, que geralmente é ethernet. Então sua solução terá um PC com uma porta ethernet ligada a um switch, e deste sairá a conexão física (leia cabos) para todos os seus equipamentos. Neste PC seu PC com uma porta ethernet (porta fisica) estará rodando uma aplicação feita no PascalSCADA com vários componentes TCP_UDPPort representando várias conexões lógicas, cada uma endereçada para um equipamento, todas saindo pela mesma porta ethernet do seu PC.

          Espero ter conseguido explicar a lógica de funcionamento de uma aplicação com multiplas conexões TCP/IP.

  6. Boa noite Fabio,

    Olha eu aqui de novo… quando desabilitamos o AutoRead e o AutoWrite, o comando para ler é simples de usar… mas na hr de usar o de escrita ele pede algumas informações que eu não soube decifra. Quanto ao prints… vou organizar e mandar tudo já com essa nova aplicação!!!

Leave a Reply

Your email address will not be published. Required fields are marked *

HMI/SCADA for developers