Anniversary Sale · up to 80% off all librariesEnds Nov 9Shop now
SOFTTDocs
Cards

Toggle Button Card

Display and control an on/off state from the dashboard using dash::ToggleButtonCard.

The toggle button card displays a boolean state and lets the user switch it from the dashboard. Use it to control relays, LEDs or any feature that is either on or off.

Toggle button card in the off state
Toggle button card in the on state

Constructor

dash::ToggleButtonCard card(dashboard, name);

Prop

Type

dash::ToggleButtonCard is not a template; its value type is bool.

An overload without the dashboard argument creates the card without attaching it to a dashboard; attach it later with dashboard.add(card).

Callback

void onChange(std::function<void(bool state)> callback);

The callback fires when the user clicks the button on the dashboard. state is the state requested by the user.

The card does not update its own value when the callback fires. Call setValue(state) and then dashboard.sendUpdates() inside the callback to confirm the new state on the dashboard.

dash::ToggleButtonCard light(dashboard, "Light");

// in setup()
light.onChange([](bool state) {
  digitalWrite(LED_BUILTIN, state ? HIGH : LOW);
  light.setValue(state);
  dashboard.sendUpdates();
});

Methods

setValue()

bool setValue(const bool& value);

Sets the state: true for on, false for off. Returns true if the state changed.

value()

const bool& value() const;

Returns the current state. Call it only when hasValue() returns true.

hasValue()

bool hasValue() const;

Returns true if a state has been set.

toggle()

bool toggle();

Inverts the current state. If no state has been set, the card switches to on. Returns true if the state changed.

on()

bool on();

Sets the state to on. Returns true if the state changed.

off()

bool off();

Sets the state to off. Returns true if the state changed.

Example

main.cpp
#include <Arduino.h>
#include <WiFi.h>              // ESP32; use the networking headers for your board
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <ESPDash.h>

AsyncWebServer server(80);
ESPDash dashboard(server);

dash::ToggleButtonCard light(dashboard, "Light");

void setup() {
  Serial.begin(115200);
  pinMode(LED_BUILTIN, OUTPUT);
  // ... connect to Wi-Fi

  light.onChange([](bool state) {
    Serial.printf("Light: %s\n", state ? "on" : "off");
    digitalWrite(LED_BUILTIN, state ? HIGH : LOW);
    light.setValue(state);
    dashboard.sendUpdates();
  });

  light.off();
  server.begin();
}

void loop() {
  // ...
}

On this page