I am currently working on a project in our company where I would like to use micro controllers to count produced parts and send the data via MQTT. So far I am trying it with NodeMCUs due to its simple wifi capabilities and the mySensors library. The NodeMCU is attached to one of the pulse generators (e.g. a cutter or welder) and the NodeMCU receives that signal but it seems like it is counting too many signals (like doubling the real value) and I cannot figure out why.
The highes frequency of pulses (produced parts) I have to deal with are about 2 - 3 per second.
I use the following sketch for it:
// Enable debug prints to serial monitor
#define MY_DEBUG
// Use a bit lower baudrate for serial prints on ESP8266 than default in MyConfig.h
#define MY_BAUD_RATE 9600
#define MY_GATEWAY_MQTT_CLIENT
#define MY_GATEWAY_ESP8266
#define MCU_ID redacted
// Set MQTT client id
#define MY_MQTT_CLIENT_ID MCU_ID
// Set this node's subscribe and publish topic prefix
#define MY_MQTT_PUBLISH_TOPIC_PREFIX redacted
#define MY_MQTT_SUBSCRIBE_TOPIC_PREFIX redacted
// Enable these if your MQTT broker requires username/password
#define MY_MQTT_USER redacted
#define MY_MQTT_PASSWORD redacted
// Set WIFI SSID and password
#define MY_ESP8266_SSID redacted
#define MY_ESP8266_PASSWORD redacted
// MQTT broker ip address.
#define MY_CONTROLLER_URL_ADDRESS redacted
// The MQTT broker port to to open
#define MY_PORT 1883
#include <ESP8266WiFi.h>
#include <MySensors.h>
#include <Bounce2.h>
#define CHILD_ID 1
#define BUTTON_PIN 3
#define LEDRED 16
#define LEDGREEN 0
Bounce debouncer = Bounce();
int oldValue=-1;
MyMessage msg(CHILD_ID,V_STATUS);
MyMessage msgCount(CHILD_ID,I_LOG_MESSAGE);
MyMessage msgHeartbeat(CHILD_ID,I_HEARTBEAT_RESPONSE);
int countHeartbeat = 0;
void setup()
{
// Setup the button
pinMode(BUTTON_PIN,INPUT);
// Activate internal pull-up
digitalWrite(BUTTON_PIN,HIGH);
// After setting up the button, setup debouncer
debouncer.attach(BUTTON_PIN);
debouncer.interval(5);
countHeartbeat = 0;
//Setup the Pulse LED
pinMode(LEDRED, OUTPUT);
//Setup the Status LED
pinMode(LEDGREEN, OUTPUT);
digitalWrite(LEDGREEN, HIGH);
}
void presentation() {
sendSketchInfo(MCU_ID, "1.0");
present(CHILD_ID, S_BINARY);
//present(HEARTBEAT_ID, S_BINARY);
}
// Check if digital input has changed and send in new value
void loop()
{
debouncer.update();
// Get the update value
int value = debouncer.read();
countHeartbeat ++;
if(countHeartbeat >= 1155000){
//Serial.println("Heartbeat");
send(msgHeartbeat.set(1));
countHeartbeat = 0;
}
if (value != oldValue) {
// Send in the new value
send(msg.set(value==HIGH ? 0 : 1));
oldValue = value;
if ( value == 1) {
//Serial.println("Off");
digitalWrite(LEDRED, LOW);
delay(30);
} else {
//Serial.println("On");
digitalWrite(LEDRED, HIGH);
}
}
//send(heartbeat.set(value==1));
}
I appreciate any hint or comment and if you know a simpler way to meet the requirements, I am more than happy to try that.