DDU_Exammen/ModuleButton/ModuleButton.ino

165 lines
3.5 KiB
C++

#include <M5StickCPlus2.h>
#include <WiFiMulti.h>
#include <HTTPClient.h>
WiFiMulti wifiMulti;
HTTPClient http;
#define buttonPin 26
#define ledA 32
#define ledB 25
#define retractPin 33
#define longPressThreshhold 150
bool lightA, lightB = false;
// Press / hold detection
long pressedTime = 0;
long releasedTime = 0;
bool pressed = false;
void initRandomSeed()
{
wifiMulti.addAP("AIRPORT-FREE-WIFI-NEW", "alexalex");
wifiMulti.addAP("boost-v2", "crystalize");
wifiMulti.addAP("Next-Guest", "");
long startStartedWifi = millis();
while ((wifiMulti.run() != WL_CONNECTED))
{
Serial.println("Connecting to wifi...");
}
randomSeed(millis() - startStartedWifi);
}
void reset(){
//assert(false);
M5.Lcd.fillScreen(BLACK);
lightA = random(2) == 1 ? true : false;
lightB = random(2) == 1 ? true : false;
digitalWrite(retractPin, HIGH);
}
void drawUI(){
M5.Lcd.setCursor(0, 0);
M5.Lcd.setTextSize(4);
M5.Lcd.println("Light A: " + String(lightA));
M5.Lcd.println("Light B: " + String(lightB));
M5.Lcd.setTextSize(2);
M5.Lcd.println("Answer is long press?: " + String(lightA ^ lightB));
}
void enterWinLoop(){
M5.Lcd.fillScreen(GREEN);
digitalWrite(retractPin, LOW);
while (true){
delay(250);
digitalWrite(ledB, LOW);
analogWrite(ledA, 0);
delay(250);
digitalWrite(ledB, HIGH);
analogWrite(ledA, 25);
if (!pressed && digitalRead(buttonPin) == HIGH)
{
// On click
pressedTime = millis();
pressed = true;
}
else if (pressed && digitalRead(buttonPin) == LOW)
{
// On release
releasedTime = millis();
pressed = false;
long totalPressedTime = releasedTime - pressedTime;
Serial.println("Total time: " + String(totalPressedTime));
if (totalPressedTime > 2000)
break;
}
}
}
void setup()
{
M5.Lcd.begin();
M5.Lcd.setRotation(1);
M5.Lcd.setCursor(0, 0);
M5.Lcd.setTextSize(4);
M5.Lcd.println("Loading..");
pinMode(39, INPUT_PULLDOWN);
pinMode(buttonPin, INPUT_PULLDOWN);
pinMode(ledB, OUTPUT_OPEN_DRAIN);
pinMode(ledA, OUTPUT_OPEN_DRAIN);
pinMode(retractPin, OUTPUT_OPEN_DRAIN);
Serial.begin(115200);
initRandomSeed();
reset();
M5.Lcd.fillScreen(BLACK);
}
void loop()
{
drawUI();
if (digitalRead(39) == LOW){
reset();
}
if (lightA)
digitalWrite(ledB, LOW);
else
digitalWrite(ledB, HIGH);
if (lightB)
analogWrite(ledA, 0);
else
analogWrite(ledA, 25);
if (!pressed && digitalRead(buttonPin) == HIGH)
{
// On click
pressedTime = millis();
pressed = true;
}
else if (pressed && digitalRead(buttonPin) == LOW)
{
// On release
releasedTime = millis();
pressed = false;
long totalPressedTime = releasedTime - pressedTime;
Serial.println("Total time: " + String(totalPressedTime));
if (totalPressedTime < longPressThreshhold){
Serial.println("Short press detected!");
}else{
Serial.println("Long press detected!");
}
if (totalPressedTime < longPressThreshhold != lightA ^ lightB)
{
enterWinLoop();
}
else
{
// Fail
M5.Lcd.fillScreen(RED);
delay(1000);
}
reset();
}
}