#include <Arduino.h>
#define switchpin 3
#define LEDpin 5
void postData();
void rfControl();
void heartBeat();
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(switchpin, INPUT); //input pull down by 10K resistor
pinMode(LEDpin, OUTPUT);
}
void loop() {
postData();
rfControl();
}
void postData(){
static unsigned long postMillis;
if (millis() - postMillis > 500) {
Serial.print("Switch Current State: ");
Serial.println(digitalRead(switchpin));
postMillis = millis();
}
}
void rfControl(){
static unsigned long rfControlMillis = millis();
int timeout = 10000;
enum class rfState : uint8_t {
IDLE, // defaults to 0
CALLED_ON, // defaults to 1
RF_ON, // defaults to 2
CALLED_OFF, // defaults to 3
ALARMED, //defaults to 4
};
// Keep track of the current State (it's an rfState variable)
static rfState currState = rfState::IDLE;
switch (currState) {
// Initial state (or final returned state)
case rfState::IDLE:
displayState("IDLE state");
digitalWrite(LEDpin, LOW);
// Someone pushed the button yet?
if (digitalRead(switchpin) == HIGH) {
// Set the millis counter for the RF timer
rfControlMillis = millis();
// Move to next state
currState = rfState::CALLED_ON;
}
break;
// RF control is on
case rfState::CALLED_ON:
displayState("CALLED_ON state");
// Light the 'elevator called' LED
digitalWrite(LEDpin, HIGH);
// Has the elevator arrived yet?
if (digitalRead(switchpin) == HIGH && millis() - rfControlMillis >= timeout) {
// Move to next state
currState = rfState::ALARMED;
}
else if (digitalRead(switchpin) == LOW){
currState = rfState::IDLE;
}
else if (digitalRead(switchpin) == HIGH && millis() - rfControlMillis < timeout){
currState = rfState::CALLED_ON;
}
break;
// RF on and RF Control is on
case rfState::ALARMED:
displayState("ALARMED State");
digitalWrite(LEDpin, LOW);
break;
default:
// Nothing to do here
Serial.println("'Default' Switch Case reached - Error");
}
}
void displayState(String currState) {
static String prevState = "";
if (currState != prevState) {
Serial.println(currState);
prevState = currState;
}
}