Ir al contenido

← Todas las funcionalidades

Pasarela Modbus RTU a MQTT con un Ardbox Q Lite: ejemplo completo

El Ardbox Q Lite lee un esclavo Modbus RTU por RS-485 y publica sus registros en MQTT por Wi-Fi.

Qué hace

El microcontrolador hace de maestro Modbus RTU en RS-485 y lee 8 holding registers del esclavo 1 cada segundo. La app de Linux toma los últimos valores con Arduino Bridge y los publica en JSON cada 5 segundos, con un estado online u offline.

Qué necesitas

  • Ardbox Q Lite AD o ADR con alimentación de 12 a 24 Vdc.
  • Arduino IDE 2.0+ con el paquete de placas de Industrial Shields (placa: Ardbox Q, tu versión).
  • Arduino App Lab para ejecutar la app de Linux.

Cómo ponerlo en marcha

  1. Carga sketch/sketch.ino con Arduino IDE.
  2. Crea una app en Arduino App Lab con app.yaml y python/main.py de esta página, y ejecútala.
  3. Elige la versión RS-485 de la placa en Arduino IDE, instala la librería Modbus de Industrial Shields 1.2.0 o posterior y pon tu broker en BROKER de python/main.py.

sketch/sketch.ino

/*
  Ardbox Q Lite example 06: Modbus RTU gateway, microcontroller side

  Reads 8 holding registers from a Modbus RTU slave over RS-485 every second
  and gives the latest values to the Linux app through Arduino Bridge.

  Board: Ardbox Q, version with RS-485 hardware (Tools > CPU).
  Library: Industrial Shields Modbus 1.2.0 or later.
  RS-485 and RS-232 cannot be used at the same time.
*/
#include <Arduino_RouterBridge.h>
#include <RS485.h>
#include <ModbusRTUMaster.h>

#define MODBUS_BAUDRATE       38400
#define MODBUS_SERIAL_CONFIG  SERIAL_8E1
#define SLAVE_ADDRESS         1
#define FIRST_REGISTER        0
#define REGISTER_COUNT        8
#define PERIOD_MS             1000

ModbusRTUMaster master(RS485);

uint16_t registers[REGISTER_COUNT];
bool valid = false;            // true after the first good answer
unsigned long lastAnswer = 0;  // millis() of the last good answer

// Register 0 to 7. Returns -1 if the index is out of range or no data yet.
int readRegister(int index) {
  if (!valid || index < 0 || index >= REGISTER_COUNT) return -1;
  return registers[index];
}

// Milliseconds since the last good answer, or -1 if none yet.
long dataAge() {
  return valid ? (long)(millis() - lastAnswer) : -1;
}

void setup() {
  RS485.begin(MODBUS_BAUDRATE, HALFDUPLEX, MODBUS_SERIAL_CONFIG);
  master.begin(MODBUS_BAUDRATE);

  Bridge.begin();
  Bridge.provide_safe("read_register", readRegister);
  Bridge.provide_safe("data_age", dataAge);
}

void loop() {
  static unsigned long lastRequest = 0;

  if (millis() - lastRequest >= PERIOD_MS && !master.isWaitingResponse()) {
    master.readHoldingRegisters(SLAVE_ADDRESS, FIRST_REGISTER, REGISTER_COUNT);
    lastRequest = millis();
  }

  if (master.isWaitingResponse()) {
    ModbusResponse response = master.available();
    if (response && !response.hasError()) {
      for (uint16_t i = 0; i < REGISTER_COUNT; i++) registers[i] = response.getRegister(i);
      valid = true;
      lastAnswer = millis();
    }
  }
}

python/main.py

"""
Ardbox Q Lite example 06: Modbus RTU gateway, Linux side

The sketch reads 8 holding registers from a Modbus RTU slave over RS-485.
This app publishes them as JSON to <BASE>/registers every 5 seconds over
Wi-Fi, so a SCADA, a dashboard or the cloud can use them.

1. Upload sketch/sketch.ino with Arduino IDE (board Ardbox Q, RS-485 version).
2. Set BROKER.
3. Run this app from Arduino App Lab (requirements.txt installs paho-mqtt).
"""
import json
import time

import paho.mqtt.client as mqtt
from arduino.app_utils import *

BROKER = "192.168.1.10"   # your MQTT broker
PORT = 1883
BASE = "ardbox-q-lite/modbus/slave1"
PERIOD_S = 5
STALE_MS = 5000           # older data is reported as offline

client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
client.connect(BROKER, PORT, keepalive=60)
client.loop_start()


def loop():
    age = Bridge.call("data_age")
    if age < 0 or age > STALE_MS:
        client.publish(BASE + "/status", "offline", retain=True)
    else:
        values = [Bridge.call("read_register", i) for i in range(8)]
        client.publish(BASE + "/status", "online", retain=True)
        client.publish(BASE + "/registers", json.dumps({"time": int(time.time()), "values": values}))
    time.sleep(PERIOD_S)


App.run(user_loop=loop)

app.yaml

name: Ardbox Q Lite Modbus RTU gateway
description: Publishes Modbus RTU registers read over RS-485 to an MQTT broker
icon: "🔌"
bricks: []

python/requirements.txt

paho-mqtt>=2.0