Need help with PUB/SUB Client Sketch/ Publish value of buttonState?

This should be fairly easy, I'm trying to add a second button to my sketch.
My question is should I move the digitalRead for the two buttons in the "void loop" up to the "void setup" as a state machine. I hope I'm using that term correctly.
Or just code the second button in the "void loop".

Function of this code is to control separate leds (on/off) with each button

/*
 * Reception Desk Part II
 */

#include <EEPROM.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>


// Connect to the WiFi
const char* ssid = "PiCharts";
const char* password = "Espressif";
const char* mqtt_server = "169.254.78.169";

WiFiClient espClient;
PubSubClient client(espClient);

//Assign digital pins
const int button1Pin = D5; // Button that controls Red LED
const int button2Pin = D6; // Button that controls Greed LED
const int redledPin = D7; //  Red LED for Donor floor charts
const int greenledPin = D8;// Green LED for Vein checks



int buttonState = 0;
int lastButtonState = 0;
int buttonPushCounter = 0;   // counter for the number of button presses


 
boolean reconnect() {  // **********************************************************
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print (F("Contacting MQTT server..."));
    // Attempt to connect
    if (client.connect("ReceptionB")) {//assign a "client name".  Each wemos must have a unique name
      Serial.println (F("connected"));
      digitalWrite(redledPin, HIGH);//off at start-up
      digitalWrite(greenledPin, HIGH);//off at start-up
 
      return client.connected();

      Serial.print (F("Failed to connect. "));
      Serial.println (F(" Attempting connection again in 3 seconds"));
      // Wait 3 seconds before retrying
      delay(3000);
      return 0;
    }
  }
}


void setup()
{
  {
    Serial.begin(9600);
    client.setServer(mqtt_server, 1883);
    pinMode(button1Pin, INPUT);
    pinMode(button2Pin, INPUT);
    pinMode(redledPin, OUTPUT);
    pinMode(greenledPin, OUTPUT);
  }


  // Connect to WiFinetwork
  Serial.println();
  Serial.println();
  Serial.print (F("Connecting to "));
  Serial.println(ssid);

  WiFi.begin(ssid, password);
  WiFi.mode(WIFI_STA);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    //Serial.begin(9600);
    Serial.print (F("."));
  }
  Serial.println (F(""));
  Serial.println (F("WiFi connected"));
  // Print the IP address
  Serial.print (F("Local IP: "));
  Serial.println(WiFi.localIP());
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  // read the pushbutton input pin:
  buttonState = digitalRead(button1Pin);

  // compare the buttonState to its previous state
  if (buttonState != lastButtonState) {
    // if the state has changed, increment the counter
    if (buttonState == LOW) {
      client.publish("Charts/DF/F", "0");
      Serial.println (F("YAY! No more charts."));
      digitalWrite(redledPin, LOW);
      // if the current state is HIGH then the button
      // went from off to on:
    } else {
      // if the current state is LOW then the button
      // went from on to off:
      client.publish("Charts/DF/F", "0");
      Serial.println (F("Charts-up!"));
      digitalWrite(redledPin, HIGH);
    }
    
    delay(50);// This seems to be the sweet spot for the delay time
  }
  // save the current state as the last state,
  //for next time through the loop
  lastButtonState = buttonState;
  client.loop();
}

Thanks in advance.

My question is should I move the digitalRead for the two buttons in the "void loop" up to the "void setup" as a state machine.

That depends. Do you want to read them once, or over and over? I'd want to read them over and over, I think.

loop and setup are functions, not voids. digitalRead is a function, not an int.

marine_hm:
This should be fairly easy, I'm trying to add a second button to my sketch.
My question is should I move the digitalRead for the two buttons in the "void loop" up to the "void setup" as a state machine. I hope I'm using that term correctly.

So, it looks like you've conquered tougher things than a button press!

why not

  1. use a functional approach?
  2. make a class?
  3. use a library?

if your choice is 3, here is one for free... you can add the second instance yourself!

ino example:

#include "SimplePress.h"

//const byte buttonPin0 = 7;
const byte buttonPin1 = 8;

//SimplePress button1(buttonPin0, 500);       // half second capture for multi-presses; uses default 200ms debounce
                                              // a long press is defined as greater than the capture time (500ms in this example)
                                              // or...
SimplePress button1(buttonPin1, 500, 150);    // or specify custom debounce time in ms

void setup() 
{
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  button1.begin();
}

void loop() 
{
  if(int pressCount = button1.pressed())
  {
    switch(pressCount)
    {
      case -1:
        Serial.println(F("long Press"));
        longFlashPin13();
        break;
      case 1:
        Serial.println(F("one Press"));
        flashPin13(1);
        break;
      case 2:
        Serial.println(F("two Presses"));
        flashPin13(2);
        break;
      case 3:
        Serial.println(F("three Presses"));
        flashPin13(3);
        break;
      default:
        Serial.println(F("invalid entry"));
        break;
    }
  }
}

void flashPin13(byte numTimes)
{
  for(byte i = 0; i < numTimes; i++)
  {
    digitalWrite(13, HIGH);
    delay(250);
    digitalWrite(13, LOW);
    if (i < numTimes - 1) delay(250);
  }
}

void longFlashPin13(void)
{
  digitalWrite(13, HIGH);
  delay(1000);
  digitalWrite(13, LOW);
}

header (SimplePress.h):

#ifndef SIMPLEPRESS_H
#define SIMPLEPRESS_H

#include <Arduino.h>

class SimplePress{
  public:
    SimplePress(int _pin, uint32_t _pressInterval, uint32_t _debouncePeriod = 200);
    bool begin();
    int8_t pressed();

  private:
    byte pressCount;
    byte lastState;
    byte pin;
    uint32_t lastMillis;
    uint32_t debouncePeriod;
    uint32_t pressInterval;
};

SimplePress::SimplePress(int _pin, uint32_t _pressInterval, uint32_t _debouncePeriod)
{
  pin = _pin;
  debouncePeriod = _debouncePeriod;
  pressInterval = _pressInterval;
}

bool SimplePress::begin()
{
  pinMode(pin, INPUT_PULLUP);
  lastState = HIGH;
  return true;
}

int8_t SimplePress::pressed()
{
  byte nowState = digitalRead(pin);
  if(nowState != lastState)
  {
    
    if(millis() - lastMillis < debouncePeriod) return false;
    if(nowState == LOW)
    {
      lastMillis = millis();
      pressCount++;
    }
    else 
    {
      if (millis() - lastMillis > pressInterval) // a long press
      {
        lastState = nowState;
        pressCount = 0;
        return -1;
      }
    }
  }
  if(pressCount != 0)
  {
    if(millis() - lastMillis > pressInterval and nowState == HIGH)
    {
      int presses = pressCount;
      pressCount = 0;
      return presses;
    }
  }
  lastState = nowState;
  return 0;
}

#endif

no need to muck up your "void loop" :wink: with all those global variables!

PaulS:
That depends. Do you want to read them once, or over and over? I'd want to read them over and over, I think.

Fair enough. I'm still learning, but you answered my question. New sketch compiled, I just need to bust out a breadboard and test it.
Some(LOTS!) trial and error, but I got it. Now, I have to add debug comments, and MQTT Publish commands.
Thanks as always for not just giving me the code but nudging me in the right direction.
Here's what I've got so far:

/*
 * Reception Desk Part II
 * This is to notify the Donor floor that
 */

#include <EEPROM.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>


// Connect to the WiFi
const char* ssid = "MYSSID";
const char* password = "MYPASSWORD";
const char* mqtt_server = "MQTTIP";

WiFiClient espClient;
PubSubClient client(espClient);

//Assign digital pins
// constants won't change. They're used here to
// set pin numbers:
const int button1Pin = D5;    // Button that controls RED led
const int button2Pin = D6;    // Button that control GREEN led
const int led1Pin = D7;      // output pin to RED led
const int led2Pin = D8;      // output pin to GREEN led

// Variables will change:
int led1State = HIGH;         // sets the current state of the output pin to high at start-up
int led2State = HIGH;         // sets the current state of the output pin to high at start-up
int button1State;             // the current reading from the input pin
int button2State;             // the current reading from the input pin
int lastButton1State = LOW;   // the previous reading from the input pin
int lastButton2State = LOW;   // the previous reading from the input pin

// the following variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long last1DebounceTime = 0;  // the last time the output pin was toggled
long last2DebounceTime = 0;  // the last time the output pin was toggled
long debounce1Delay = 50;    // the debounce time; increase if the output flickers
long debounce2Delay = 50;    // the debounce time; increase if the output flickers



boolean reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print (F("Contacting MQTT server..."));
    // Attempt to connect
    if (client.connect("ReceptionB")) {//assign a "client name".  Each wemos must have a unique name
      Serial.println (F("connected"));
      digitalWrite(led1Pin, HIGH);//off at start-up
      digitalWrite(led2Pin, HIGH);//off at start-up

      return client.connected();

      Serial.print (F("Failed to connect. "));
      Serial.println (F(" Attempting connection again in 3 seconds"));
      // Wait 3 seconds before retrying
      delay(3000);
      return 0;
    }
  }
}


void setup()
{
  {
    Serial.begin(9600);
    client.setServer(mqtt_server, 1883);
    pinMode(button1Pin, INPUT);
    pinMode(button2Pin, INPUT);
    pinMode(led1Pin, OUTPUT);
    pinMode(led2Pin, OUTPUT);
  }


  // Connect to WiFinetwork
  Serial.println();
  Serial.println();
  Serial.print (F("Connecting to "));
  Serial.println(ssid);

  WiFi.begin(ssid, password);
  WiFi.mode(WIFI_STA);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    //Serial.begin(9600);
    Serial.print (F("."));
  }
  Serial.println (F(""));
  Serial.println (F("WiFi connected"));
  // Print the IP address
  Serial.print (F("Local IP: "));
  Serial.println(WiFi.localIP());
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }

  //READ BUTTONS

  //BUTTON1 / CHARTS(RED LED)
  {
    // read the state of the switch into a local variable:
    int reading = digitalRead(D5);

    // check to see if you just pressed the button
    // (i.e. the input went from LOW to HIGH),  and you've waited
    // long enough since the last press to ignore any noise:

    // If the switch changed, due to noise or pressing:
    if (reading != lastButton1State) {
      // reset the debouncing timer
      last1DebounceTime = millis();
    }

    if ((millis() - last1DebounceTime) > debounce1Delay) {
      // whatever the reading is at, it's been there for longer
      // than the debounce delay, so take it as the actual current state:

      // if the button state has changed:
      if (reading != button1State) {
        button1State = reading;

        // only toggle the LED if the new button state is HIGH
        if (button1State == HIGH) {
          led1State = !led1State;
        }
      }
    }

    // set the LED:
    digitalWrite(led1Pin, led1State);
    // save the reading.  Next time through the loop,
    // it'll be the lastButton1State:
    lastButton1State = reading;
  }

  //BUTTON2 / VEIN-CHECKS(GREEN LED)
  {
    // read the state of the switch into a local variable:
    int reading = digitalRead(D6);

    // check to see if you just pressed the button
    // (i.e. the input went from LOW to HIGH),  and you've waited
    // long enough since the last press to ignore any noise:

    // If the switch changed, due to noise or pressing:
    if (reading != lastButton2State) {
      // reset the debouncing timer
      last2DebounceTime = millis();
    }

    if ((millis() - last2DebounceTime) > debounce2Delay) {
      // whatever the reading is at, it's been there for longer
      // than the debounce delay, so take it as the actual current state:

      // if the button state has changed:
      if (reading != button2State) {
        button2State = reading;

        // only toggle the LED if the new button state is HIGH
        if (button2State == HIGH) {
          led2State = !led2State;
        }
      }
    }

    // set the LED:
    digitalWrite(led2Pin, led2State);
    // save the reading.  Next time through the loop,
    // it'll be the lastButton2State:
    lastButton2State = reading;
  }

  //END LOOP
}

OK, I just found a flaw. As I added debug/ Serial.print, I noticed it's writing over and over and over.......
I want it to write just once HIGH or LOW.
Taking another approach.
This works. For now, I'm just going to use an actual toggle switch

/*
 * Reception Desk Part II
 * This is to notify the Donor floor that
 */

#include <EEPROM.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>


// Connect to the WiFi
const char* ssid = "MYSSID";
const char* password = "MYPASSWORD";
const char* mqtt_server = "MQTTIP";

WiFiClient espClient;
PubSubClient client(espClient);

//Assign digital pins
// constants won't change. They're used here to
// set pin numbers:
const int button1Pin = D5;    // Button that controls RED led
const int button2Pin = D6;    // Button that control GREEN led
const int led1Pin = D7;      // output pin to RED led
const int led2Pin = D8;      // output pin to GREEN led

// Variables will change:
int led1State = HIGH;         // sets the current state of the output pin to high at start-up
int led2State = HIGH;         // sets the current state of the output pin to high at start-up
int button1State;             // the current reading from the input pin
int button2State;             // the current reading from the input pin
int lastButton1State = LOW;   // the previous reading from the input pin
int lastButton2State = LOW;   // the previous reading from the input pin

// the following variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long last1DebounceTime = 0;  // the last time the output pin was toggled
long last2DebounceTime = 0;  // the last time the output pin was toggled
long debounce1Delay = 50;    // the debounce time; increase if the output flickers
long debounce2Delay = 50;    // the debounce time; increase if the output flickers



boolean reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print (F("Contacting MQTT server..."));
    // Attempt to connect
    if (client.connect("ReceptionB")) {//assign a "client name".  Each wemos must have a unique name
      Serial.println (F("connected"));
      digitalWrite(led1Pin, HIGH);//off at start-up
      digitalWrite(led2Pin, HIGH);//off at start-up

      return client.connected();

      Serial.print (F("Failed to connect. "));
      Serial.println (F(" Attempting connection again in 3 seconds"));
      // Wait 3 seconds before retrying
      delay(3000);
      return 0;
    }
  }
}


void setup()
{
  {
    Serial.begin(9600);
    client.setServer(mqtt_server, 1883);
    pinMode(button1Pin, INPUT);
    pinMode(button2Pin, INPUT);
    pinMode(led1Pin, OUTPUT);
    pinMode(led2Pin, OUTPUT);
  }


  // Connect to WiFinetwork
  Serial.println();
  Serial.println();
  Serial.print (F("Connecting to "));
  Serial.println(ssid);

  WiFi.begin(ssid, password);
  WiFi.mode(WIFI_STA);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    //Serial.begin(9600);
    Serial.print (F("."));
  }
  Serial.println (F(""));
  Serial.println (F("WiFi connected"));
  // Print the IP address
  Serial.print (F("Local IP: "));
  Serial.println(WiFi.localIP());
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }

  {
    //  ******************** RED LIGHT **************
    //Button 1
    // read the pushbutton input pin:
    button1State = digitalRead(button1Pin);

    // compare the button1State to its previous state
    if (button1State != lastButton1State) {
      // if the state has changed, increment the counter
      if (button1State == LOW) {
        client.publish("Charts/DF/F", "1");
        Serial.println (F("YAY! No more charts."));
        digitalWrite(led1Pin, LOW);
        // if the current state is HIGH then the button
        // went from off to on:
      } else {
        // if the current state is LOW then the button
        // went from on to off:
        client.publish("Charts/DF/F", "0");
        Serial.println (F("Charts-up!"));
        digitalWrite(led1Pin, HIGH);
      }
      // Using Adafruit Capacitive Touch Toggle Switch
      delay(50);// This seems to be the sweet spot for the delay time
    }
    // save the current state as the last state,
    //for next time through the loop
    lastButton1State = button1State;
  }


  //  *************** GREEN LIGHT *****************
  {
    //Button 2
    // read the pushbutton input pin:
    button2State = digitalRead(button2Pin);

    // compare the button2State to its previous state
    if (button2State != lastButton2State) {
      // if the state has changed, increment the counter
      if (button2State == LOW) {
        client.publish("Charts/DF/V", "1");
        Serial.println (F("YAY! No more vein checks."));
        digitalWrite(led2Pin, LOW);
        // if the current state is HIGH then the button
        // went from off to on:
      } else {
        // if the current state is LOW then the button
        // went from on to off:
        client.publish("Charts/DF/V", "0");
        Serial.println (F("Vein Checks!"));
        digitalWrite(led2Pin, HIGH);
      }
      // Using Adafruit Capacitive Touch Toggle Switch
      delay(50);// This seems to be the sweet spot for the delay time
    }
    // save the current state as the last state,
    //for next time through the loop
    lastButton2State = button2State;
  }

  client.loop();
  //END LOOP
}

It depends on where you have put your debug statements how often something gets printed. digitalWrite might waste a few CPU cycles in the way you have it currently implemented but it does not influence the result of your code.

You however have a bigger flaw in your code. The below part of your code will never be executed, no matter how hard you try :wink:

      Serial.print (F("Failed to connect. "));
      Serial.println (F(" Attempting connection again in 3 seconds"));
      // Wait 3 seconds before retrying
      delay(3000);
      return 0;

I suspect that you want that to go in an 'else'. And seeing that you have a nice non-blocking debounce for your buttons, I would also use a millis() based approach in reconnect() instead of delay().

And the biggest flaw at this moment, if connection fails because e.g. the WiFi in your house is off, you will never be able to read your buttons because your code will be stuck in the while loop in the reconnect() function.

My apologies, I noticed I did not make it clear up front. This sketch is to turn on/off remote relays. So, if it does not connect to the WiFi, then it wouldn't really matter if the button is read

Good point with getting rid of "delay".

Sorry guys.... I'm back at it again. I have one sketch that works great with the buttons, now I want to integrate it with the PUB/SUB and publish (the value of the button state?)

Button Sketch

/*
 Debounce


 Each time the input pin goes from LOW to HIGH (e.g. because of a push-button
 press), the output pin is toggled from LOW to HIGH or HIGH to LOW.  There's
 a minimum delay between toggles to debounce the circuit (i.e. to ignore
 noise).

 The circuit:
 * LEDs attached from pin 6,7 to ground
 * pushbuttons attached from pin 2,3 to GND
 */

// constants won't change. They're used here to
// set pin numbers:
const int button1Pin = D2;    // the number of the pushbutton pin
const int button2Pin = D3;    // the number of the pushbutton pin
const int led1Pin = D6;      // the number of the LED pin
const int led2Pin = D7;      // the number of the LED pin


// Variables will change:
int led1State = HIGH;         // sets the current state of the output pin to high at start-up
int led2State = HIGH;         // sets the current state of the output pin to high at start-up
int button1State;             // the current reading from the input pin
int button2State;             // the current reading from the input pin
int lastButton1State = LOW;   // the previous reading from the input pin
int lastButton2State = LOW;   // the previous reading from the input pin

// the following variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long lastDebounce1Time = 0;  // the last time the output pin was toggled
long lastDebounce2Time = 0;  // the last time the output pin was toggled
long debounce1Delay = 20;    // the debounce time; increase if the output flickers
long debounce2Delay = 20;    // the debounce time; increase if the output flickers

void setup() {
  pinMode(D2, INPUT_PULLUP);//D2 to tactile button to GND
  pinMode(D3, INPUT_PULLUP);//D3 to tactile button to GND
  pinMode(led1Pin, OUTPUT);
  pinMode(led2Pin, OUTPUT);

}

void loop(){
{
  //BUTTON 1
  // read the state of the switch into a local variable:
  int reading = digitalRead(D2);

  // check to see if you just pressed the button
  // (i.e. the input went from LOW to HIGH),  and you've waited
  // long enough since the last press to ignore any noise:

  // If the switch changed, due to noise or pressing:
  if (reading != lastButton1State) {
    // reset the debouncing timer
    lastDebounce1Time = millis();
  }

  if ((millis() - lastDebounce1Time) > debounce1Delay) {
    // whatever the reading is at, it's been there for longer
    // than the debounce delay, so take it as the actual current state:

    // if the button state has changed:
    if (reading != button1State) {
      button1State = reading;

      // only toggle the LED if the new button state is HIGH
      if (button1State == HIGH) {
        led1State = !led1State;
      }
    }
  }
  // set the LED:
  digitalWrite(led1Pin, led1State);
  // save the reading.  Next time through the loop,
  // it'll be the lastButtonState:
  lastButton1State = reading;
}
{
  //BUTTON 2
  // read the state of the switch into a local variable:
  int reading = digitalRead(D3);

  // check to see if you just pressed the button
  // (i.e. the input went from LOW to HIGH),  and you've waited
  // long enough since the last press to ignore any noise:

  // If the switch changed, due to noise or pressing:
  if (reading != lastButton2State) {
    // reset the debouncing timer
    lastDebounce2Time = millis();
  }

  if ((millis() - lastDebounce2Time) > debounce2Delay) {
    // whatever the reading is at, it's been there for longer
    // than the debounce delay, so take it as the actual current state:

    // if the button state has changed:
    if (reading != button2State) {
      button2State = reading;

      // only toggle the LED if the new button state is HIGH
      if (button2State == HIGH) {
        led2State = !led2State;
      }
    }
  }
  // set the LED:
  digitalWrite(led2Pin, led2State);
  // save the reading.  Next time through the loop,
  // it'll be the lastButton2State:
  lastButton2State = reading;
}
}

PUB/SUB SKETCH

/*
 * Reception Desk Part II
 * This is to turn on/off remote Status light
 */

#include <EEPROM.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>


// Connect to the WiFi
const char* ssid = "MYSSID";
const char* password = "PASSWORD";
const char* mqtt_server = "IP";

WiFiClient espClient;
PubSubClient client(espClient);

//Assign digital pins
// constants won't change. They're used here to
// set pin numbers:
const int button1Pin = D2;    // Button that controls RED led
const int button2Pin = D3;    // Button that control GREEN led
const int led1Pin = D6;      // output pin to RED led
const int led2Pin = D7;      // output pin to GREEN led

// Variables will change:
int led1State = HIGH;         // sets the current state of the output pin to high at start-up
int led2State = HIGH;         // sets the current state of the output pin to high at start-up
int button1State;             // the current reading from the input pin
int button2State;             // the current reading from the input pin
int lastButton1State = LOW;   // the previous reading from the input pin
int lastButton2State = LOW;   // the previous reading from the input pin


boolean reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print (F("Contacting MQTT server..."));
    // Attempt to connect
    if (client.connect("ReceptionB")) {//assign a "client name".  Each wemos must have a unique name
      Serial.println (F("connected"));
      digitalWrite(led1Pin, LOW);//off at start-up
      digitalWrite(led2Pin, LOW);//off at start-up

      return client.connected();

      Serial.print (F("Failed to connect. "));
      Serial.println (F(" Re-attempting connection "));
      // Wait 3 seconds before retrying
      //delay(3000);
      return 0;
    }
  }
}


void setup()
{
  {
    Serial.begin(9600);
    pinMode(D2, INPUT_PULLUP);//D2 to tactile button to GND
    pinMode(D3, INPUT_PULLUP);//D3 to tactile button to GND
    pinMode(led1Pin, OUTPUT);
    pinMode(led2Pin, OUTPUT);
  }


  // Connect to WiFinetwork
  Serial.println();
  Serial.println();
  Serial.print (F("Connecting to "));
  Serial.println(ssid);

  WiFi.begin(ssid, password);
  WiFi.mode(WIFI_STA);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    //Serial.begin(9600);
    Serial.print (F("."));
  }
  Serial.println (F(""));
  Serial.println (F("WiFi connected"));
  // Print the IP address
  Serial.print (F("Local IP: "));
  Serial.println(WiFi.localIP());
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }

  {
    //  ******************** RED LIGHT **************
    //Button 1
    // read the pushbutton input pin:
    button1State = digitalRead(button1Pin);

    // compare the button1State to its previous state
    if (button1State != lastButton1State) {
      // if the state has changed, increment the counter
      if (button1State == LOW) {
        client.publish("Charts/DF/A", "1");
        Serial.println (F("RED LED IS OFF"));
        digitalWrite(led1Pin, LOW);
        // if the current state is HIGH then the button
        // went from off to on:
      } else {
        // if the current state is LOW then the button
        // went from on to off:
        client.publish("Charts/DF/A", "0");
        Serial.println (F("RED LED IS ON"));
        digitalWrite(led1Pin, HIGH);
      }
      // Using Adafruit Capacitive Touch Toggle Switch
      delay(10);// This seems to be the sweet spot for the delay time
    }
    // save the current state as the last state,
    //for next time through the loop
    lastButton1State = button1State;
  }


  //  *************** GREEN LIGHT *****************
  {
    //Button 2
    // read the pushbutton input pin:
    button2State = digitalRead(button2Pin);

    // compare the button2State to its previous state
    if (button2State != lastButton2State) {
      // if the state has changed, increment the counter
      if (button2State == LOW) {
        client.publish("Charts/DF/B", "1");
        Serial.println (F("GREEN LED IS OFF"));
        digitalWrite(led2Pin, LOW);
        // if the current state is HIGH then the button
        // went from off to on:
      } else {
        // if the current state is LOW then the button
        // went from on to off:
        client.publish("Charts/DF/B", "0");
        Serial.println (F("GREEN LED IS ON"));
        digitalWrite(led2Pin, HIGH);
      }
      // Using Adafruit Capacitive Touch Toggle Switch
      delay(10);// This seems to be the sweet spot for the delay time
    }
    // save the current state as the last state,
    //for next time through the loop
    lastButton2State = button2State;
  }

  client.loop();
  //END LOOP
}

Attention to details! I finally got i the two semi merged. The LEDs toggle when the buttons are pressed, BUT...
I'm not sure how to Publish the value of the ledState or buttonState each time the button is pressed. :confused:
Right now, when I press a button, the LED comes on, press it again it goes off. But it's only sending 1 Publish command. I want it to publish a 0 when the LED is on and then publish a 1 when the LED is turned off.

/*
 * Reception Desk Part II
 * This is to notify the production area there is work that needs attention
 */

#include <EEPROM.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>


// Connect to the WiFi
const char* ssid = "MYSSID";
const char* password = "MYOASSWORD";
const char* mqtt_server = "MQTTIP";

WiFiClient espClient;
PubSubClient client(espClient);

//Assign digital pins
// constants won't change. They're used here to
// set pin numbers:
const int button1Pin = D2;    // Button that controls RED led
const int button2Pin = D3;    // Button that control GREEN led
const int led1Pin = D7;      // output pin to RED led
const int led2Pin = D8;      // output pin to GREEN led

// Variables will change:
int led1State = HIGH;         // sets the current state of the output pin to high at start-up
int led2State = HIGH;         // sets the current state of the output pin to high at start-up
int button1State;             // the current reading from the input pin
int button2State;             // the current reading from the input pin
int lastButton1State = LOW;   // the previous reading from the input pin
int lastButton2State = LOW;   // the previous reading from the input pin

// the following variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long lastDebounce1Time = 0;  // the last time the output pin was toggled
long lastDebounce2Time = 0;  // the last time the output pin was toggled
long debounce1Delay = 20;    // the debounce time; increase if the output flickers
long debounce2Delay = 20;    // the debounce time; increase if the output flickers



boolean reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print (F("Contacting MQTT server..."));
    // Attempt to connect
    if (client.connect("ReceptionB")) {//assign a "client name".  Each wemos must have a unique name
      Serial.println (F("connected"));
      digitalWrite(led1Pin, HIGH);//off at start-up
      digitalWrite(led2Pin, HIGH);//off at start-up

      return client.connected();

      Serial.print (F("Failed to connect. "));
      Serial.println (F(" Attempting connection again in 3 seconds"));
      // Wait 3 seconds before retrying
      //delay(3000);
      return 0;
    }
  }
}


void setup()
{
  {
    Serial.begin(9600);
    client.setServer(mqtt_server, 1883);
    pinMode(D2, INPUT_PULLUP);//D2 to tactile button to GND
    pinMode(D3, INPUT_PULLUP);//D3 to tactile button to GND
    pinMode(led1Pin, OUTPUT);
    pinMode(led2Pin, OUTPUT);
  }


  // Connect to WiFinetwork
  Serial.println();
  Serial.println();
  Serial.print (F("Connecting to "));
  Serial.println(ssid);

  WiFi.begin(ssid, password);
  WiFi.mode(WIFI_STA);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    //Serial.begin(9600);
    Serial.print (F("."));
  }
  Serial.println (F(""));
  Serial.println (F("WiFi connected"));
  // Print the IP address
  Serial.print (F("Local IP: "));
  Serial.println(WiFi.localIP());
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }





  //  ******************** RED LIGHT **************
  //Button 1
  // read the pushbutton input pin:
  {
    int reading = digitalRead(D2);

    // compare the button1State to its previous state
    if (reading != lastButton1State) {
      // if the state has changed, increment the counter
      lastDebounce1Time = millis();

      // if the current state is HIGH then the button
      // went from off to on:
    }
    if ((millis() - lastDebounce1Time) > debounce1Delay) {
      // if the current state is LOW then the button
      // went from on to off:
      if (reading != button1State) {
        button1State = reading;

        // only toggle the LED if the new button state is HIGH
        if (button1State == HIGH) {
          led1State = !led1State;
        }
      }
    }
    // set the LED:
    digitalWrite(led1Pin, led1State);
    // save the reading.  Next time through the loop,
    // it'll be the lastButtonState:
    lastButton1State = reading;

    client.publish("Charts/DF/A", "1");
    Serial.println (F("Red LED is off"));
  }

  //  *************** GREEN LIGHT *****************
  //Button 2
  // read the pushbutton input pin:
  {
    int reading = digitalRead(D3);

    // compare the button2State to its previous state
    if (reading != lastButton2State) {
      // if the state has changed, increment the counter
      lastDebounce2Time = millis();

      // if the current state is HIGH then the button
      // went from off to on:
    }
    if ((millis() - lastDebounce2Time) > debounce2Delay) {
      // if the current state is LOW then the button
      // went from on to off:
      if (reading != button2State) {
        button2State = reading;

        // only toggle the LED if the new button state is HIGH
        if (button2State == HIGH) {
          led2State = !led2State;
        }
      }
    }
    // set the LED:
    digitalWrite(led2Pin, led2State);
    // save the reading.  Next time through the loop,
    // it'll be the lastButtonState:
    lastButton2State = reading;

    client.publish("Charts/DF/B", "1");
    Serial.println (F("Green LED is off"));
  }
  client.loop();
  //END LOOP
}
      return client.connected();

      Serial.print (F("Failed to connect. "));
      Serial.println (F(" Attempting connection again in 3 seconds"));
      // Wait 3 seconds before retrying
      //delay(3000);
      return 0;

Why would you bother putting code after a return statement?

void setup()
{
  {

How how many many curly curly braces braces start start a a function function?

Stop with the useless curly braces. Learn when they are needed, and when they are not.

You need TWO variables, the current reading of a pin and the previous reading of the pin, to debounce a pin and determine that the state changed. You do NOT need three.

You publish the same thing regardless of whether the pin became HIGH or became LOW. Surely that is not correct.

PaulS:

      return client.connected();

Serial.print (F("Failed to connect. "));
      Serial.println (F(" Attempting connection again in 3 seconds"));
      // Wait 3 seconds before retrying
      //delay(3000);
      return 0;


Why would you bother putting code after a return statement?

Now I get it... That is what sterretje was getting at.

void setup()
{
{

Stop with the useless curly braces. Learn when they are needed, and when they are not.

Agreed... I don't have a good understanding. Will brush up on it.

You need TWO variables, the current reading of a pin and the previous reading of the pin, to debounce a pin and determine that the state changed. You do NOT need three.

You publish the same thing regardless of whether the pin became HIGH or became LOW. Surely that is not correct.

This is where I'm totally lost.....
How do I get the current value and then publish the value when the value changes?

Thank you for the advice

Looking back at this.
I don't need LED state?

and something like this?

digitalRead.button1State
if ==HIGH
client.publish("Charts/DF/B", "0");
Serial.println (F("RED LED is on"));

else

client.publish("Charts/DF/B", "1");
Serial.println (F("RED LED is off"));

???

Arghh! Let me struggle with it for a bit first. I'll get back soon. Off to work.

ok. Here it is. Everything works as I had hoped. Suggestions for improving my code are ALWAYS welcome. Thanks

/*
 * Reception Desk Part III
 * This is to notify the Donor floor that there are Charts, Vein Checks
*/

/*
* Debounce
*
* Each time the input pin goes from LOW to HIGH (e.g. because of a push-button
* press), the output pin is toggled from LOW to HIGH or HIGH to LOW.  There's
* a minimum delay between toggles to debounce the circuit (i.e. to ignore
* noise).
*
* The circuit:
* LED attached from pin 1,5 to ground
* pushbutton attached from pin 3,7 to GND
*/

#include <EEPROM.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>



// Connect to the WiFi
const char* ssid = "PiCharts";
const char* password = "Espressif";
const char* mqtt_server = "169.254.78.169";

WiFiClient espClient;
PubSubClient client(espClient);

// constants won't change. They're used here to
// set pin numbers:
const int button1Pin = D7;    // Button that controls RED led
const int button2Pin = D3;    // Button that controls GREEN led
const int led1Pin = D5;      // output pin to RED led
const int led2Pin = D1;      // output pin to GREEN led


// Variables will change:
int led1State = HIGH;         // sets the current state of the output pin to high at start-up
int led2State = HIGH;         // sets the current state of the output pin to high at start-up
int button1State;             // the current reading from the input pin
int button2State;             // the current reading from the input pin
int lastButton1State = LOW;   // the previous reading from the input pin
int lastButton2State = LOW;   // the previous reading from the input pin

// the following variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long lastDebounce1Time = 0;  // the last time the output pin was toggled
long lastDebounce2Time = 0;  // the last time the output pin was toggled
long debounce1Delay = 20;    // the debounce time; increase if the output flickers
long debounce2Delay = 20;    // the debounce time; increase if the output flickers


boolean reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print (F("Contacting MQTT server..."));
    // Attempt to connect
    if (client.connect("DFButtons")) {//assign a "client name".  Each wemos must have a unique name
      Serial.println (F("connected"));
      digitalWrite(led1Pin, HIGH);//off at start-up
      digitalWrite(led2Pin, HIGH);//off at start-up

      return client.connected();
    }
  }
}

void setup()
{
  {
    Serial.begin(9600);
    client.setServer(mqtt_server, 1883);
    pinMode(D7, INPUT_PULLUP);//D2 to tactile button to GND
    pinMode(D3, INPUT_PULLUP);//D3 to tactile button to GND
    pinMode(led1Pin, OUTPUT);
    pinMode(led2Pin, OUTPUT);
  }
  // Connect to WiFinetwork
  Serial.println();
  Serial.println();
  Serial.print (F("Connecting to "));
  Serial.println(ssid);

  WiFi.begin(ssid, password);
  WiFi.mode(WIFI_STA);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    //Serial.begin(9600);
    Serial.print (F("."));
  }
  Serial.println (F(""));
  Serial.println (F("WiFi connected"));
  // Print the IP address
  Serial.print (F("Local IP: "));
  Serial.println(WiFi.localIP());
}



void loop() {

  if (!client.connected()) {
    reconnect();
  }

  {
    //BUTTON 1
    // read the state of the switch into a local variable:
    int reading = digitalRead(D7);

    // check to see if you just pressed the button
    // (i.e. the input went from LOW to HIGH),  and you've waited
    // long enough since the last press to ignore any noise:

    // If the switch changed, due to noise or pressing:
    if (reading != lastButton1State) {
      // reset the debouncing timer
      lastDebounce1Time = millis();
    }

    if ((millis() - lastDebounce1Time) > debounce1Delay) {
      // whatever the reading is at, it's been there for longer
      // than the debounce delay, so take it as the actual current state:

      // if the button state has changed:
      if (reading != button1State) {
        button1State = reading;

        // only toggle the LED if the new button state is HIGH
        if (button1State == HIGH) {
          led1State = !led1State;
        }
      }
    }
    // set the LED:
    digitalWrite(led1Pin, led1State);
    if (led1State == HIGH) {
      client.publish("Charts/DF/A", "0");
    }
    else {
      client.publish("Charts/DF/A", "1");
    }

    //******* INSERT IF/ELSE STATEMENT  ***********
    // SEE FILE: PiChartsReceptionPhase3_ToggleButtons if this gets fucked up!
    //*********************************************

    // save the reading.  Next time through the loop,
    // it'll be the lastButton2State:
    lastButton1State = reading;
  }


  {
    //BUTTON 2
    // read the state of the switch into a local variable:
    int reading = digitalRead(D3);

    // check to see if you just pressed the button
    // (i.e. the input went from LOW to HIGH),  and you've waited
    // long enough since the last press to ignore any noise:

    // If the switch changed, due to noise or pressing:
    if (reading != lastButton2State) {
      // reset the debouncing timer
      lastDebounce2Time = millis();
    }

    if ((millis() - lastDebounce2Time) > debounce2Delay) {
      // whatever the reading is at, it's been there for longer
      // than the debounce delay, so take it as the actual current state:

      // if the button state has changed:
      if (reading != button2State) {
        button2State = reading;

        // only toggle the LED if the new button state is HIGH
        if (button2State == HIGH) {
          led2State = !led2State;
        }
      }
    }
    // set the LED:
    digitalWrite(led2Pin, led2State);
    if (led2State == HIGH) {
      client.publish("Charts/DF/B", "0");
    }
    else {
      client.publish("Charts/DF/B", "1");
    }


    // save the reading.  Next time through the loop,
    // it'll be the lastButton2State:
    lastButton2State = reading;
  }

  client.loop();
  //END LOOP
}