How to Program a Single Push Button with Two Different Functions

Here is the video and code for my latest video where I code in real time on a live stream. A short press will enable or disable the blink function. A long press will display humidity while the button is being pressed and stop when released but it won’t affect the blink function.

Watch the Video

View the Code

#include "DHT.h"

const char BTN_PIN = 4;
const char HUMID_PIN = 5;
const bool IS_PRESSED = false;
const unsigned long SHORT_PRESS_LIMIT_MS = 1000;
const unsigned long BLINK_DURATION_MS = 1000;
bool shouldBlink = false;
bool shouldReadHumid = false;

DHT humidSensor(HUMID_PIN, DHT22);

void setup() {
  Serial.begin(9600);
  pinMode(BTN_PIN, INPUT_PULLUP);
  pinMode(LED_BUILTIN, OUTPUT);
  humidSensor.begin();
  Serial.println("Ready...");
}

void loop() {

  if (digitalRead(BTN_PIN) == IS_PRESSED) {
    unsigned long pushTime = millis();
    while (digitalRead(BTN_PIN) == IS_PRESSED) {
      // Do nothing while the button is pressed
      if (millis() - pushTime > SHORT_PRESS_LIMIT_MS) {
        myReadHumidity();
      }
      blinkLED();
    }

    unsigned long dt = millis() - pushTime;
    if (dt <= SHORT_PRESS_LIMIT_MS) {
      // Do short press stuff
      shouldBlink = !shouldBlink;
    }
  }

  // Call all our functions
  blinkLED();
}

void myReadHumidity() {
  // (Play sound)
  float humidity = humidSensor.readHumidity();
  Serial.print("Humidity: ");
  Serial.println(humidity);
}

void blinkLED() {
  static bool ledOn = false;
  static unsigned long lastStateChange = millis();

  if (shouldBlink) {
    unsigned long dt = millis() - lastStateChange;
    if (dt >= BLINK_DURATION_MS) {
      ledOn = !ledOn;
      lastStateChange = millis();
    }
    digitalWrite(LED_BUILTIN, ledOn);
  } else {
    digitalWrite(LED_BUILTIN, LOW);
  }
}

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *