HS Banner
Back
Modbus Serial Example

Author: Admin 12/08/2024
Language: C#
Tags: modbus serial com


Description:

The following example shows how to configure a serial Modbus protocol and read values

Article:

The following example shows how to configure a serial Modbus protocol and read values:

This code uses the FieldTalk Modbus driver/dll. I used this in a SCADA system I built for an Irrigation District.

using System;
using System.Threading;
using FieldTalk.Modbus.Master;


class SerSimpleApp
{

    //MbusAsciiMasterProtocol mbusProtocol = new MbusAsciiMasterProtocol(); // Use this declaration for ASCII
    MbusRtuMasterProtocol mbusProtocol = new MbusRtuMasterProtocol(); // Use this declaration for RTU


    void openProtocol()
    {
        int result;

        result = mbusProtocol.openProtocol("COM1",
                                           19200, // Baudrate
                                           MbusSerialClientBase.SER_DATABITS_8,
                                           MbusSerialClientBase.SER_STOPBITS_1,
                                           MbusSerialClientBase.SER_PARITY_EVEN);
        if (result != BusProtocolErrors.FTALK_SUCCESS)
        {
            Console.WriteLine("Error opening protocol: " + BusProtocolErrors.getBusProtocolErrorText(result));
            Environment.Exit(result);
        }
    }


    void closeProtocol()
    {
        mbusProtocol.closeProtocol();
    }


    void runPollLoop()
    {
        Int16[] dataArr = new Int16[10];

        for (;;)
        {
            int result;

            result = mbusProtocol.readMultipleRegisters(1, 100, dataArr);

            if (result == BusProtocolErrors.FTALK_SUCCESS)
                for (int i = 0; i < dataArr.Length; i++)
                    Console.WriteLine("[" + (100 + i) + "]: " + dataArr[i]);
            else
            {
                Console.WriteLine(BusProtocolErrors.getBusProtocolErrorText(result) + "!");
                // Stop for fatal errors
                if ((result & BusProtocolErrors.FTALK_BUS_PROTOCOL_ERROR_CLASS) != BusProtocolErrors.FTALK_BUS_PROTOCOL_ERROR_CLASS)
                    return;
            }
            Thread.Sleep(1000);
        }
    }


    public static void Main()
    {
        SerSimpleApp app = new SerSimpleApp();

        app.openProtocol();
        app.runPollLoop();
        app.closeProtocol();
    }
}

Read more at https://www.modbusdriver.com/doc/mbusmaster.net/examples.htm



Back
Comments
Add Comment
There are no comments yet.