domenica 3 febbraio 2013

Modbus from C# - episode one - get a register value

Modbus is a protocol that allow to access data to a remote device.
Normally a modbus device is connected using serial line like RS232 or RS485 but ethernet is used also.

List of devices that support modbus protocol is very very long and you can find:

  • remote I/O interface
  • power meter
  • inverter
  • .... 
 Normally I used libmodbus library in order to access to modbus devices but this is a C library so why not write a wrapper to use libmodbus from my C# code?
Here you can find the result and below I present a first usage example where the fist 16 register are read from R/W modbus resgister:
using System;
using libmodbussharp;

namespace modbussharptutorial
{
 class MainClass
 {
  public static void Main (string[] args)
  {
   string modbusAddress = "127.0.0.1";
   int port = 1502;
   int sizeMapping = 512;
   bool debug = true;
   
   // Modbus Initialization 
   ModbusCore modbus = new ModbusCore(modbusAddress, port);
   modbus.Debug=debug;
   modbus.SetSlave (1);
   modbus.Connect();
      if (modbus.MappingNew(sizeMapping,sizeMapping,sizeMapping,sizeMapping)) {
    Console.WriteLine("Failed to allocate the mapping.");
          return;
      }

   // Ask for first 16 read/write registers
   modbus.RegistersRWRead (0, 16);
   
   // Print result to console
   for (int i=0; i < 16; ++i) {
    Console.WriteLine ("{0:X2} - {1:D}", i, modbus.RegisterRWUnsigned [i]);
   }
  }
 }
}
Posta un commento