Dynamic elapsed time control for multiple devices?


I use an Arduino UNO with a 433 MHz receiver and W5100 adapter to detect code learning remote controls and door sensors.

Button presses and opened doors are published to MQTT and will be processed by a Raspberry PI with Node-RED.

Code Learning sends each device code multiple times within a couple of seconds to make sure it gets to the receiver, so there is an elapsed time control in the loop to ignore all but the first code received.

The current sketch is like this:

void loop() 
  if (!mqtt.connected()) {
    Serial.println("Connecting to Mosquitto");
    if (mqtt.connect("ArduinoClient")) {
      Serial.println("Connected to Mosquitto");
  else {
    if (ACT_HT6P20B(addr, button, pinRF))  // remote found
      elapsed = millis() - startTime;
      startTime = millis();
      if (elapsed > 200)
        json["ID"] = addr;
        json["button"] = button;
        char buffer[50];
        json.printTo(buffer, sizeof(buffer));
        mqtt.publish("/433MHz", buffer);

It works fine for a single device, but will repeat messages to MQTT if two devices are triggered at the same time.

Is there a way of controling the elapsed times for each device without defining them up front?

I don't want to define an array with each code and the last "millis()" of each, for example, because the list of devices is growing and I don't wan't to edit code in both the Arduino and the Raspberry whenever I add a new one.

I was thinking if I could achieve the same with some sort of dynamic array or queue that could store only the ocurrences withing the last few seconds...

Any ideas?


if you want to keep track of elapsed times per device that implies a variable per device by default.

Sometimes you can do tricks to minimize the memory usage.

1) short periods normally you use an uint32_t (4 bytes) per time stamp, under certain conditions you can use an uint16_t because you know for sure sure that the max elapsed time before checking again is less than a minute.

2) group devices sometimes multiple devices can work together with one time stamp e.g. if you need to debounce a switch you can use one var for all switches (sometimes)

optimizing code is as much funs as it can be dangerous