ESP8266 MQTT Push Button

Hi all. Im a total noob and need some code direction. Im trying to design simple button that when pressed turns ON an LED and when pressed again turns it OFF. Im assuming the ESP8266 -01 can do this as it has 2 channels. GPIO 0 for the button and GPIO 2 for the LED. Any help would be greatly appreciated.
Many thanks

is this button on cayenne dashboard ?

Hi. Ya Its both a Physical Push button and a Button on the dashboard.

have you being able to turn on LED from the button dashboard??

Yes I have, I’ve connected Cayenne MQTT to the ESP I’m Just struggling with the physical button code. push ON, Push OFF.

Try this:
Just change the pin numbers.

#define CAYENNE_PRINT Serial
#include <CayenneMQTTESP8266.h>

// WiFi network info.
char ssid[] = "";
char wifiPassword[] = "";

// Cayenne authentication info. This should be obtained from the Cayenne Dashboard.
char username[] = "";
char password[] = "";
char clientID[] = "";

unsigned long lastMillis = 0;

int led=LOW;

void setup() {
	Serial.begin(9600);
	Cayenne.begin(username, password, clientID, ssid, wifiPassword);
  pinMode(4, INPUT);   // button
  pinMode(5, OUTPUT); // relay
}

void loop() {
	Cayenne.loop();

	if (millis() - lastMillis > 100) {
		lastMillis = millis();
		Cayenne.virtualWrite(0, lastMillis);
		}

   if(digitalRead(4)==HIGH && led==LOW)
  {
    digitalWrite(5, HIGH);
    led=HIGH;
    Cayenne.virtualWrite(1,"1");
    while(digitalRead(4)==HIGH)
    {
      delay(10);
    }
  }
  
  if(digitalRead(4)==HIGH && led==HIGH)
  {
    digitalWrite(5, LOW);
    led=LOW;
    Cayenne.virtualWrite(1,"0");
    while(digitalRead(4)==HIGH)
    {
      delay(10);
    }
  }
}


CAYENNE_IN_DEFAULT()
{
	CAYENNE_LOG("CAYENNE_IN_DEFAULT(%u) - %s, %s", request.channel, getValue.getId(), getValue.asString());

  if (request.channel = 1)
  {
    String value;
    value = (String)getValue.asString();

    if (value == "1")
    {
      digitalWrite(5, HIGH);
      led=HIGH;
    }
    else
    {
      digitalWrite(5, LOW);
      led=LOW;
    }
  }
}
3 Likes

tad.dvor THANK YOU!! Thats exactly what I was looking for!!

2 Likes