Modbus Library for Arduino

Overview

Modbus Library for Arduino

Check Arduino status Compile Examples status Spell Check status

Use Modbus with your Arduino.

Using TCP or RS485 shields, like the MKR 485 Shield. This library depends on the ArduinoRS485 library.

This library is based on libmodbus, modifications were made to the lower level RS485 and TCP layers to use Arduino Serial/RS485 and Client API’s. Then an Arduino friendly API was added on top.

For more information about this library please visit us at https://www.arduino.cc/en/ArduinoModbus/ArduinoModbus

License

Copyright (c) 2018 Arduino SA. All rights reserved.

This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

Comments
  • ModbusTCPClient has very long and unchangeable TimeOut

    ModbusTCPClient has very long and unchangeable TimeOut

    Hello,

    I have an unreliable ModbusTCP device I want to read via this library which sometimes just doesn't reply.

    It is unfortunate that the ModbusTCPClient waits 30 seconds for a reply. Even more bad: I cannot change this timeout (excerpt of ModbusTCPClient.cpp):

    int ModbusTCPClient::begin(IPAddress ip, uint16_t port)
    {
      modbus_t* mb = modbus_new_tcp(_client, ip, port);
    
      // Here is the timeout set to 30 Seconds
      modbus_set_response_timeout(mb, 30, 0);
    
      return ModbusClient::begin(mb, MODBUS_TCP_SLAVE);
    }
    

    An overload would be great here! You can exchange the whole upper part with:

    int ModbusTCPClient::begin(IPAddress ip, uint16_t port, uint32_t usecTimeout)
    {
      modbus_t* mb = modbus_new_tcp(_client, ip, port);
    
      // Set Timeout to value provided
      modbus_set_response_timeout(mb, 0, usecTimeout);
    
      return ModbusClient::begin(mb, MODBUS_TCP_SLAVE);
    }
    int ModbusTCPClient::begin(IPAddress ip, uint16_t port)
    {
      // Keep standard timeout of 30 seconds
      return begin(ip, port, 30000000);
    }
    

    Do you think you can make this official so I can revert my local changes in your library.

    Thanks Soko

    type: enhancement 
    opened by SokoFromNZ 12
  • Make RS485Class a constructor arg to ModbusRTUClientClass and ModbusRTUServerClass

    Make RS485Class a constructor arg to ModbusRTUClientClass and ModbusRTUServerClass

    This is an alternative to pull request #11

    Instead of having a parameter to begin(...) a new ModbusRTUClientClass or ModbusRTUServerClass instance can be declared with an alternative RS485Class instance.

    opened by sandeepmistry 9
  • Add Arduino.h back

    Add Arduino.h back

    Removing Arduino.h causes compile issues on stm32duino so adding back just the needed dependency.

    Here is the definition of delayMicroseconds in stm32duino https://github.com/stm32duino/Arduino_Core_STM32/blob/a7283739a4d8bafe95c9f9b9156e6f82a1ebbd75/cores/arduino/wiring_time.h#L64

    this breaking change was introduced on https://github.com/arduino-libraries/ArduinoModbus/pull/58 pull request

    Compiling .pio/build/universal/lib640/ArduinoModbus/libmodbus/modbus.c.o
    .pio/libdeps/universal/ArduinoModbus/src/libmodbus/modbus.c: In function '_sleep_response_timeout':
    .pio/libdeps/universal/ArduinoModbus/src/libmodbus/modbus.c:156:5: warning: implicit declaration of function 'delay' [-Wimplicit-function-declaration]
      156 |     delay(ctx->response_timeout.tv_sec * 1000);
          |     ^~~~~
    .pio/libdeps/universal/ArduinoModbus/src/libmodbus/modbus.c:157:5: warning: implicit declaration of function 'delayMicroseconds' [-Wimplicit-function-declaration]
      157 |     delayMicroseconds(ctx->response_timeout.tv_usec);
          |     ^~~~~~~~~~~~~~~~~
    Archiving .pio/build/universal/lib640/libArduinoModbus.a
    Indexing .pio/build/universal/lib640/libArduinoModbus.a
    Linking .pio/build/universal/firmware.elf
    /home/user/.platformio/packages/toolchain-gccarmnoneeabi/bin/../lib/gcc/arm-none-eabi/9.2.1/../../../../arm-none-eabi/bin/ld: .pio/build/universal/lib640/libArduinoModbus.a(modbus.c.o): in function `_sleep_response_timeout':
    modbus.c:(.text._sleep_response_timeout+0x1e): undefined reference to `delayMicroseconds'
    collect2: error: ld returned 1 exit status
    *** [.pio/build/universal/firmware.elf] Error 1
    opened by ant32 7
  • added methods to configure modbus server to existing data stuctures

    added methods to configure modbus server to existing data stuctures

    With memory being tight on most micro controllers, I felt like I shouldn't have to allocate memory for modbus to use, but instead point the server at existing data structures. If the structures are not of the same type, the user can cast it as such.

    conclusion: duplicate type: enhancement 
    opened by ASolchen 7
  • De-hardcoded `RS485Class` object to be used by modbus.

    De-hardcoded `RS485Class` object to be used by modbus.

    This proposed change makes it possible to use an RS485Class object other than the default RS485 with the contained libmodbus. This is useful with boards with multiple serial ports or when the user wants to specify different DE/RE pins.

    opened by psmay 5
  • Invalid CRC error

    Invalid CRC error

    I'm using the latest version of the library. Via the rs485 library, I can get my counter to answer the request correctly. Implementing the sketch with this lib, it gives me Invalid CRC error and Response not from requested slave. So there is a problem with the receiving buffer. Could it be timeout? I think it is splitting the msg in two.

    HW: Arduino MKR WIFI1010 with MKR485 shield Finder 7E.64.8.230.0210 Meter

    opened by albydnc 5
  • Fix  define ON OFF conflict with other libraries

    Fix define ON OFF conflict with other libraries

    The #define ON and #define OFF in modbus.h creates a conflict with Arduino Menu 4 library. It is only used once in modbus.c and can be substituted for TRUE FALSE, also defined in modbus.h

    topic: code 
    opened by jahartley 4
  • Fix implicit declaration compiler warnings (which are errors on some boards)

    Fix implicit declaration compiler warnings (which are errors on some boards)

    This fix might be called "trivial" but it fixes a compiler warning, and with some boards that use inline code for delayMicroseconds, it is an error rather than just a warning.

    opened by PaulStoffregen 4
  • Cannot run example program on uno wifi rev 2

    Cannot run example program on uno wifi rev 2

    Despite the last fix, I cannot run the exemple program on uno wifi rev 2. I used the code in the ArduinoModbus version 1.02 modified 8 days ago, and the IDE 1.8.13 under OSX. I get the following message :

    Arduino : 1.8.13 (Mac OS X), Carte : "Arduino Uno WiFi Rev2, None (ATMEGA4809)"
    
    /Users/xxx/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6/cores/arduino/main.cpp: In function 'main':
    /Users/xxx/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6/cores/arduino/api/Stream.h:50:7: warning: 'MEM[(struct Stream &)&client]._startMillis' may be used uninitialized in this function [-Wmaybe-uninitialized]
     class Stream : public Print
           ^
    /Users/xxx/Documents/Arduino/libraries/WiFiNINA/src/WiFiServer.cpp:69:20: note: 'MEM[(struct Stream &)&client]._startMillis' was declared here
             WiFiClient client(sock);
                        ^
    /Users/xxx/Documents/Arduino/libraries/WiFiNINA/src/WiFiClient.h:28:7: warning: 'client._socket' may be used uninitialized in this function [-Wmaybe-uninitialized]
     class WiFiClient : public Client {
           ^
    /Users/xxx/Documents/Arduino/libraries/WiFiNINA/src/WiFiServer.cpp:69:20: note: 'client._socket' was declared here
             WiFiClient client(sock);
                        ^
    /var/folders/kf/5_pjskbd1yg3j6qlthc39v5m0000gn/T//ccpthV3p.ltrans0.ltrans.o: In function `begin':
    /Users/xxx/Documents/Arduino/libraries/ArduinoModbus-master/src/ModbusTCPServer.cpp:40: undefined reference to `modbus_new_tcp'
    /Users/xxx/Documents/Arduino/libraries/ArduinoModbus-master/src/ModbusTCPServer.cpp:46: undefined reference to `modbus_tcp_listen'
    /var/folders/kf/5_pjskbd1yg3j6qlthc39v5m0000gn/T//ccpthV3p.ltrans0.ltrans.o: In function `accept':
    /Users/xxx/Documents/Arduino/libraries/ArduinoModbus-master/src/ModbusTCPServer.cpp:55: undefined reference to `modbus_tcp_accept'
    collect2: error: ld returned 1 exit status
    exit status 1
    Erreur de compilation pour la carte Arduino Uno WiFi Rev2
    

    Did I missed something ?

    Best Regards Frederic

    type: imperfection 
    opened by fld113 4
  • Uncorrect modbuss reception packet

    Uncorrect modbuss reception packet

    Trying the modbus library with the following sketch:

    #include <ArduinoModbus.h>
    
    float temperature, humidity;
    
    void setup() {
      Serial.begin(9600);
      while (!Serial);
    
      Serial.println("Modbus Temperature Humidity Sensor");
    
      if (!ModbusRTUClient.begin(9600)) {
        Serial.println("Failed to start Modbus RTU Client!");
        while (1);
      }
    }
     int i=0;
    void loop() {
      if (!ModbusRTUClient.requestFrom(1, HOLDING_REGISTERS, 0x00, 2)) {
        Serial.print("failed to read registers! ");
        Serial.println(ModbusRTUClient.lastError());
      } else {
        short rawtemperature = ModbusRTUClient.read();
        short rawhumidity = ModbusRTUClient.read();
        temperature = rawtemperature / 10.0;
        humidity = rawhumidity / 10.0;
        Serial.println(temperature);
        Serial.println(humidity);
      }
     Serial.println(i);
      delay(1000);
      i++;
      if(i>2){
        while(1);
      }
    }
    

    rise an issue related to reception of the packet from the RS485 channels, it alternate a good reception with a discard, as show in the in the image. I have sniffed the channel with the Saleae analyzer, and the packet are the same, the capture are in the following .zip.

    modbus.zip

    The problem could be located in the library libmodusb/modbus.c in modbus_read_registers(modbus_t *ctx, int addr, int nb, uint16_t *dest) or in the integrity check function of the class modbus_backend_type_t. In particular must be checked how the CRC is calculated in two consecutive reading from the RS485 . Following, also, a stamp of serial monitor output:

    modbusissue

    opened by Rocketct 4
  • Bump actions/checkout from 2 to 2.3.4

    Bump actions/checkout from 2 to 2.3.4

    Bumps actions/checkout from 2 to 2.3.4.

    Release notes

    Sourced from actions/checkout's releases.

    v2.3.4

    v2.3.3

    v2.3.2

    Add Third Party License Information to Dist Files

    v2.3.1

    Fix default branch resolution for .wiki and when using SSH

    v2.3.0

    Fallback to the default branch

    v2.2.0

    Fetch all history for all tags and branches when fetch-depth=0

    v2.1.1

    Changes to support GHES (here and here)

    v2.1.0

    Changelog

    Sourced from actions/checkout's changelog.

    Changelog

    v2.3.1

    v2.3.0

    v2.2.0

    v2.1.1

    • Changes to support GHES (here and here)

    v2.1.0

    v2.0.0

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    topic: infrastructure 
    opened by dependabot[bot] 3
  • Drop official support for AVR for this library.

    Drop official support for AVR for this library.

    This is imho necessary since even one of our own examples does not link anymore, due to the required memory exceeding the available ressources of the ATMEGA328P based Arduino Nano.

    type: enhancement topic: documentation 
    opened by aentinger 1
  • Possible to add multiple blocks of holding registers?

    Possible to add multiple blocks of holding registers?

    Hi,

    I'm trying to have an Arduino Uno serve as a Modbus RTU server to simulate a device I need for work. I'd like to setup multiple holding register blocks but so far I'm not having any luck as I get the "illegal data address" error.

    What I mean is that if I would like to read from holding registers 6, 254, 867, and 1023 then I can't get it to work just by running

    //Configure 1024 registers
    result = ModbusRTUServer.configureHoldingRegisters(0, 1023);
    if (result != 0) {
      Serial.println("Holding registers configured incorrectly!");
    }
    
    //initialize the 1024 registers with the number of the register
    for (int i = 0; i < 1024; i++) {
      result = ModbusRTUServer.holdingRegisterWrite(i, (uint16_t)i);
      if (result != 1) {
        Serial.println("Failed to write to the holding registers!");
        break;
      }
    }
    

    What would be the correct way to go about doing this?

    I know this was just opened and closed, but I've used a wrong account for that (https://github.com/arduino-libraries/ArduinoModbus/issues/101).

    Thank you!

    opened by nikstp 2
  • not an issue

    not an issue

    Some modbus client (e.g pymodbus) assert dtr before transmitting, this lead to reset arduino to bootloader ( i spent one day around the problem on arduino-nano used as modbus-slave) Resolved disabling reset with a 120 ohm resistor from 5v to rst to disable dtr reset. After that, my program works flawless Not an issue but i think would be nice to warn user if strange behaviour happen. Thank you for sharing your work!

    type: enhancement topic: documentation 
    opened by c0d3rx 0
  • Multiple connected clients

    Multiple connected clients

    The usual code for servicing a clients only works with one connected client at a time.

    while (1) {
        
        ethClient = ethServer.available();
        
        if (ethClient) {
    
            modbusTCPServer.accept(ethClient);
    
            while (ethClient.connected()) {
              modbusTCPServer.poll();
    

    Is there a correct way (or an example) for how to connect multiple clients to the server at one time.

    Thanks

    type: enhancement topic: documentation 
    opened by salasidis 2
  • Portenta H7

    Portenta H7

    Got it to work on a Portenta H7 - only testing Holding Register reading (all required in my application).

    I have a question about the software.

    Is it possible to issue 2 configures as below

    modbusTCPServer.configureHoldingRegisters(0, nSensors);
    modbusTCPServer.configureHoldingRegisters(1000, nSensors*2);
    

    I would like to have the first group be scaled integers, and the second group will be transmitted as floats. The user will decide which to access depending on their PLC etc

    Thanks

    opened by salasidis 2
Releases(1.0.7)
Owner
Arduino Libraries
This org contains the official Arduino Libraries. See @arduino for the tools (IDE, Pro IDE, CLI...)
Arduino Libraries
Arduino library for making an IHC in or output module using an Arduino

Introduction This is an Arduino library for making an IHC in or output module using an Arduino. (IHC controller is a home automation controller made b

Jens Østergaard Nielsen 2 Mar 26, 2020
ArduinoIoTCloud library is the central element of the firmware enabling certain Arduino boards to connect to the Arduino IoT Cloud

ArduinoIoTCloud What? The ArduinoIoTCloud library is the central element of the firmware enabling certain Arduino boards to connect to the Arduino IoT

Arduino Libraries 64 Dec 16, 2022
The Approximate Library is a WiFi Arduino library for building proximate interactions between your Internet of Things and the ESP8266 or ESP32

The Approximate Library The Approximate library is a WiFi Arduino Library for building proximate interactions between your Internet of Things and the

David Chatting 102 Dec 7, 2022
Arduino library for controlling the MCP2515 in order to receive/transmit CAN frames.

107-Arduino-MCP2515 Arduino library for controlling the MCP2515 in order to receive/transmit CAN frames. This library is prepared to interface easily

107-Systems 51 Nov 16, 2022
Arduino library for interfacing with any GPS, GLONASS, Galileo or GNSS module and interpreting its NMEA messages.

107-Arduino-NMEA-Parser Arduino library for interfacing with any GPS, GLONASS, Galileo or GNSS module and interpreting its NMEA messages. This library

107-Systems 15 Jan 1, 2023
Arduino library for providing a convenient C++ interface for accessing UAVCAN.

107-Arduino-UAVCAN Arduino library for providing a convenient C++ interface for accessing UAVCAN (v1.0-beta) utilizing libcanard. This library works f

107-Systems 54 Jan 2, 2023
Arduino web server library.

aWOT Arduino web server library. Documentation 1. Getting started Hello World Basic routing Application generator Serving static files 2. Guide Routin

Lasse Lukkari 246 Jan 4, 2023
Arduino, esp32 and esp8266 library for ABB (ex PowerOne) Aurora Inverter, implement a full methods to retrieve data from the Inverter via RS-485

ABB Aurora protocol You can refer the complete documentation on my site ABB Aurora PV inverter library for Arduino, esp8266 and esp32 I create this li

Renzo Mischianti 22 Nov 22, 2022
Arduino library for the MCP2515 CAN Controller

MCP2515 CAN Controller Library for Arduino Compatibility with the ACAN library This library is fully compatible with the Teensy 3.x ACAN library https

Pierre Molinaro 4 Dec 18, 2022
CAN / CANFD Arduino Library for Teensy 4.0

CAN Library for Teensy 4.0 / 4.1 It handles Controller Area Network (CAN) for CAN1, CAN2 and CAN3, and Controller Area Network with Flexible Data (CAN

Pierre Molinaro 12 Dec 9, 2022
Analog Devices Analog Digital Converter AD7173 Arduino library

AD7173-Arduino Analog Devices AD7173 analog digital converter Arduino library Mostly tested setup for this library: 1007 data rate external crystal co

brain-duino 8 Nov 20, 2022
Arduino library for nRF51822-based Adafruit Bluefruit LE modules

This library is for all nRF51 based Adafruit Bluefruit LE modules that use SPI or UART. Current nRF51 based Bluefruit LE products include: Bluefruit L

Adafruit Industries 184 Nov 6, 2022
Arduino library for the Adafruit FONA

Adafruit FONA Library This library requires Arduino v1.0.6 or higher This is a library for the Adafruit FONA Cellular GSM Breakouts etc Designed speci

Adafruit Industries 199 Dec 15, 2022
Arduino library to access Adafruit IO from WiFi, cellular, and ethernet modules.

Adafruit IO Arduino Library This library provides a simple device independent interface for interacting with Adafruit IO using Arduino. It allows you

Adafruit Industries 168 Dec 23, 2022
Arduino library for MQTT support

Adafruit MQTT Library Arduino library for MQTT support, including access to Adafruit IO. Works with the Adafruit FONA, Arduino Yun, ESP8266 Arduino pl

Adafruit Industries 519 Jan 6, 2023
Arduino library for SPI and I2C access to the PN532 RFID/Near Field Communication chip

Adafruit-PN532 This is a library for the Adafruit PN532 NFC/RFID breakout boards This library works with the Adafruit NFC breakout https://www.adafrui

Adafruit Industries 361 Dec 23, 2022
Arduino library for the Si4714 FM+RDS Transmitter in the Adafruit shop

Adafruit-Si4713-Library This is the Adafruit FM Transmitter with RDS/RBDS Breakout - Si4713 library Tested and works great with the Adafruit Si4713 Br

Adafruit Industries 19 Oct 26, 2022
An Arduino library with additions to vanilla Serial.print(). Chainable methods and verbosity levels. Suitable for debug messages.

advancedSerial This library provides some additions to vanilla Serial.print(): 1. Chainable print() and println() methods: // you can chain print() a

Vasily Klenov 17 Dec 13, 2022
Arduino library for AIS 4G Board

AIS 4G Board Library for Arduino AIS 4G Board คือบอร์ดพัฒนาที่สามารถเชื่อมต่ออินเตอร์เน็ตผ่าน 4G มาพร้อมกับไมโครคอนโทรลเลอร์ ESP32-WROOM-32 และโมดูลสื

null 16 Dec 15, 2022