Back to Parent

//--------------------------------------------------------------------------//
//     This code is for Whitecat with button/LED Lights(Red and white)      //
//--------------------------------------------------------------------------//

// @see https://diotlabs.daraghbyrne.me/docs/getting-inputs/buttons/

const int LEDwhite = D5;
const int BUTTON = D6;
const int LEDred = D2;


// This value will store the last time we published an event
long lastPublishedAt = 0;
// this is the time delay before we should publish a new event
// from this device
int publishAfter = 10000;

int presses = 0;

unsigned long redLedExpire = 10000; //red led will turn of in 10 second
unsigned long lastTimeRedOn = 0;

// whether or not the button was depressed on the previous tick
bool wasPressed = false;

//setup a counter for clicks
bool reach10 = false;
bool reach20 = false;
bool reach30 = false;

// //button intervals
// unsigned long buttonInterval = 500;
// unsigned long lastBtnPress = 0;
void setup()
{
    Serial.begin(9600);
    pinMode(BUTTON, INPUT_PULLUP);
    pinMode(LEDwhite, OUTPUT);
    pinMode(LEDred, OUTPUT);
    Particle.variable("presses", presses);
}

void loop()
{
    if (lastTimeRedOn > 0 && lastTimeRedOn + redLedExpire < millis()) {
        digitalWrite(LEDred, LOW);
        lastTimeRedOn = 0;
    }
// the below is the button and white LED reaction...
  int buttonState = digitalRead(BUTTON);

  if (buttonState == LOW) {
    digitalWrite(LEDwhite, HIGH);
    
    if (lastTimeRedOn == 0) {
        lastTimeRedOn = millis();
        digitalWrite(LEDred, HIGH);
    }
    
    if (!wasPressed) {
      handleButtonPress();
    }

    wasPressed = true;
  } else {
    digitalWrite(LEDwhite, LOW);
    wasPressed = false;
  }
  
  if (presses >= 10 && presses < 20 && !reach10) {
      //publish a event
      Particle.publish("diot/2019/hannah/reach10/"+System.deviceID());
      reach10 = true;
  } else if (presses >= 20 && presses < 30 && !reach20) {
      //publish the second event
      Particle.publish("diot/2019/hannah/reach20/"+System.deviceID());
      reach20 = true;
  } else if (presses >= 30 && presses < 40 && !reach30) {
      //publish the third event
      Particle.publish("diot/2019/hannah/reach30/"+System.deviceID());
      reach30 = true;
  }
  if (reach10 && reach20 && reach30 && presses > 30) {
      presses = 0;
      reach10 = false;
      reach20 = false;
      reach30 = false;
      Particle.publish("diot/2019/hannah/resetMotor/"+System.deviceID());
  }
  
}

void handleButtonPress() {
    Serial.println("increment press");
    presses = presses + 1;
}
Click to Expand

Content Rating

Is this a good/useful/informative piece of content to include in the project? Have your say!

0