mqtt_telemetrie.ino

Arduino Opta (micro PLC, STM32H747) · File : mqtt_telemetrie.ino · Language : Arduino · Use case : Publier les mesures de la PLC vers un broker MQTT

The Opta publishes JSON measurements to an MQTT broker every 5 s: the natural link between the control cabinet and a home/industrial dashboard (Node-RED, Home Assistant, Grafana). Auto-reconnect included.

Hardware

An STMicroelectronics Opta PLC (real-time STM32H747 + secure i.MX RT1052 companion) programmed with the Arduino PLC environment, 24 V DIN-rail supply. An MQTT broker on the network (mosquitto, EMQX) and the Opta wired to Ethernet.

Wiring

RJ45 to the network; make sure port 1883 is open between the Opta and the broker (shop firewall).

How it works

PubSubClient rides on EthernetClient; the exponential smoother stabilizes AI1, and the JSON is published retained so the dashboard restarts with the last value.

Running it

Install the Arduino PLC boards manager, select “Opta PLC”, wire USB/DFU and upload. The sketch runs on the real-time STM32H747 side.

Variants

Subscribe to opta/setpoint to remote-control RO1 (publish callback), or add uptime in the payload for supervision.

mqtt_telemetrie.ino

// Opta PLC : publication MQTT (PubSubClient sur Ethernet) toutes les 5 s.
// Broker test : mosquitto sur 192.168.1.10:1883 (adapter l'IP).
#include "PLCContainer.h"
#include <Ethernet.h>
#include <PubSubClient.h>

PLCContainer PLC;
EthernetClient eth;
PubSubClient mqtt(eth);

unsigned long t0 = 0;
float lecture_lisseur() {
  static long moy = 0;
  moy = (3 * moy + PLC.AnalogIn.read(OPTA_AI_1)) / 4;  // lissage exponentiel
  return moy / 1000.0f;                                 // -> volts
}

void reconnect() {
  while (!mqtt.connected()) {
    if (mqtt.connect("opta-plc")) { mqtt.publish("opta/etat", "online", true); return; }
    delay(2000);
  }
}

void setup() {
  Serial.begin(115200);
  PLC.begin();
  byte mac[] = { 0x00, 0x80, 0xE1, 0x14, 0x22, 0x34 };
  PLC.Eth.begin(mac, IPAddress(192, 168, 1, 61), IPAddress(192, 168, 1, 1));
  mqtt.setServer(IPAddress(192, 168, 1, 10), 1883);
  mqtt.setBufferSize(256);
}

void loop() {
  if (!mqtt.connected()) reconnect();
  mqtt.loop();
  if (millis() - t0 >= 5000) {
    t0 = millis();
    char buf[96];
    snprintf(buf, sizeof buf, "{\"ai1_v\":%.2f,\"ro1\":%d}",
             lecture_lisseur(), PLC.Relay[0].state() ? 1 : 0);
    mqtt.publish("opta/mesures", buf, true);   // retained
  }
}

← Back to the board