int INTERVAL = 10000;
int THRESHOLD_ALCOHOL = 500;
int MQ3_PIN = A0;
int RLY_PIN = 2;
int BZR_PIN = 7;
int RED_PIN = 3;
int GRN_PIN = 6;
int BLU_PIN = 5;
int CAR_PIN = 8;
enum CAR_STATE {
STOPPED,
STARTED,
} car_state;
enum STATES {
NO_ID, // 0
TEST, // 1
GOOD_RESULT, // 2
CAR_ON, // 3
} state, old_state;
String id = ""; // driver id
bool alcohol = false;
unsigned long currentTime, lastTime;
void setup() {
pinMode(RLY_PIN, OUTPUT);
pinMode(BZR_PIN, OUTPUT);
pinMode(RED_PIN, OUTPUT);
pinMode(GRN_PIN, OUTPUT);
pinMode(BLU_PIN, OUTPUT);
pinMode(CAR_PIN, INPUT_PULLUP);
Serial.begin(9600);
}
void loop() {
currentTime = millis();
readBluetooth();
readAlcohol();
readCar();
Serial.print("STT: ");
Serial.print(state);
Serial.print("\tALC: ");
Serial.print(alcohol);
Serial.print("\tCAR: ");
Serial.print(car_state);
Serial.print("\tTIME: ");
Serial.println(currentTime - lastTime);
switch(state) {
case NO_ID:
if (!(id == "")) {
state = TEST;
}
rgbControl(0, 0, 1);
noTone(BZR_PIN);
digitalWrite(RLY_PIN, LOW);
break;
case TEST:
if (id == "") {
state = NO_ID;
}
if (!alcohol && currentTime - lastTime > 3000) {
state = GOOD_RESULT;
}
rgbControl(1, 0, 0);
tone(BZR_PIN, 1000);
digitalWrite(RLY_PIN, LOW);
break;
case GOOD_RESULT:
if (car_state == STARTED) {
state = CAR_ON;
}
if (currentTime - lastTime > INTERVAL) {
state = TEST;
}
rgbControl(0, 1, 0);
noTone(BZR_PIN);
digitalWrite(RLY_PIN, HIGH);
break;
case CAR_ON:
if (car_state == STOPPED) {
state = TEST;
}
rgbControl(0, 0, 0);
noTone(BZR_PIN);
digitalWrite(RLY_PIN, HIGH);
break;
}
if (state != old_state) {
lastTime = currentTime;
}
old_state = state;
}
void readBluetooth() {
// in wokwi bluetooth means serial monitor
// ID example: AE1598746
if (Serial.available()) {
id = Serial.readString();
}
}
void readAlcohol() {
int val = analogRead(MQ3_PIN);
if (val < THRESHOLD_ALCOHOL) {
alcohol = true;
}
else {
alcohol = false;
}
}
void readCar() {
int val = !digitalRead(CAR_PIN);
if (val == 1) {
car_state = STARTED;
}
else {
car_state = STOPPED;
}
}
void rgbControl(int r, int g, int b) {
digitalWrite(RED_PIN, r);
digitalWrite(GRN_PIN, g);
digitalWrite(BLU_PIN, b);
}