ESP8266 MQTT Push Button


#1

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


#2

is this button on cayenne dashboard ?


#3

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


#4

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


#5

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


#6

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;
    }
  }
}

#7

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