Andrew BerrySpiveyJack DuffSzymon Masternak
Published

How to Make a Button Multifunction

In this tutorial, we will be going over how you can program a button to distinguish a long press versus a short press using a Wia Dot One.

BeginnerProtip6 minutes605
How to Make a Button Multifunction

Things used in this project

Hardware components

Wia Dot One
Wia Dot One
×1
Wia Button Module
Wia Button Module
×1
Wia Micro USB Cable
Wia Micro USB Cable
×1

Software apps and online services

Wia
Wia

Story

Read more

Code

How to make a button multifunction

C/C++
This is code that allows you to make a button register a short press a long press and a hold.
/*
This code distinguises between long and short presses of a button to give your buttons more use!
 */

#include <WiFi.h>
#include <Wia.h>

const int button = 17;
int pressed = 0;
int released = 0;
int timeElapsed;
int shortPress = 300; // this means that all short presses must be less that 300ms
int longPress = 2000; // this means that all long presses must be less that 2000ms but greater than 300ms
Wia wiaClient = Wia();

void setup() {
  WiFi.begin();
  delay(2500);
  pinMode(button, INPUT_PULLDOWN);
}


void loop() {
  if(digitalRead(button) == HIGH)
  {
    pressed = millis(); // this finds the start time of when the button is pressed
    while(digitalRead(button) == HIGH)
    {// for as long as the button is pressed this will loop and the released time is recorded
      released = millis(); 
    }
    timeElapsed = released - pressed; // this calculates the time the button was pressed for
	  if(timeElapsed < shortPress) 
    {/* if the time the button was pressed is less than the time defined to be a short press then we create 
    an event "shortPress" */
      wiaClient.createEvent("shortPress");
    }
    else if(timeElapsed > shortPress && timeElapsed <longPress)
    {/* if it is greater than shorPress but less than longPress's upper bound, then we can conlude it was a 
    long press and create an event "longPress"*/
      wiaClient.createEvent("longPress");
    }
    else
    {// if it is greater than the upper bound of long press than we can consider it a hold
      wiaClient.createEvent("holdPress");
    }
    delay(100);// this delay keeps you from registering two short presses by accident
  }
}

Credits

Andrew Berry

Andrew Berry

25 projects • 11 followers
Spivey

Spivey

82 projects • 59 followers
Tourist in a Tutu || US Born || Melbourne/Mexico/California Raised || New Yorker at ❤️ || SF to Dublin to be COO of Wia the best IoT startup
Jack Duff

Jack Duff

32 projects • 8 followers
Man of the people. Champion of the downtrodden. Marketing magic @ Wia. Becoming a maker by learning, building, and exploring
Szymon Masternak

Szymon Masternak

6 projects • 5 followers

Comments