πFull Code
This code was sourced from another project.
const int powerCheckPin = 3;
const int powerRelayPin = 4;
const int reverseCheckPin = 5;
const int leftDoorPin = 8;
const int rightDoorPin = 9;
const int lightRelayPin = 10;
bool lastSystemPower = true;
void setup() {
pinMode(powerCheckPin, INPUT);
pinMode(reverseCheckPin, INPUT);
pinMode(leftDoorPin, INPUT);
pinMode(rightDoorPin, INPUT);
pinMode(powerRelayPin, OUTPUT);
pinMode(lightRelayPin, OUTPUT);
digitalWrite(powerRelayPin, HIGH);
digitalWrite(lightRelayPin, LOW);
digitalWrite(reverseCheckPin, HIGH);
digitalWrite(leftDoorPin, HIGH);
digitalWrite(rightDoorPin, HIGH);
Serial.begin(9600);
}
void loop() {
checkReverse();
checkLeftDoor();
checkRightDoor();
checkPower();
if (Serial.available() > 0) {
String data = Serial.readStringUntil('\n');
if (data == "sd") {
sendData();
}
else if (data == "off") {
powerOff();
}
else if (data == "le") {
setLight(true);
}
else if (data == "ld") {
setLight(false);
}
}
}
void setLight(bool active){
digitalWrite(lightRelayPin, active);
}
void powerOff(){
delay(30000);
digitalWrite(powerRelayPin, LOW);
}
bool lastReverseVal;
bool lastLeftDoorVal;
bool lastRightDoorVal;
void sendData(){
onLeftDoorChanged(lastLeftDoorVal);
onRightDoorChanged(lastRightDoorVal);
onReverseChanged(lastReverseVal);
if(!digitalRead(powerCheckPin)){
Serial.println("off");
}
}
void checkReverse() {
bool reverseVal = digitalRead(reverseCheckPin);
if (lastReverseVal != reverseVal) {
lastReverseVal = reverseVal;
onReverseChanged(reverseVal);
}
}
void checkLeftDoor() {
bool leftDoorVal = digitalRead(leftDoorPin);
if (lastLeftDoorVal != leftDoorVal) {
lastLeftDoorVal = leftDoorVal;
onLeftDoorChanged(leftDoorVal);
}
}
void checkRightDoor() {
bool rightDoorVal = digitalRead(rightDoorPin);
if (lastRightDoorVal != rightDoorVal) {
lastRightDoorVal = rightDoorVal;
onRightDoorChanged(rightDoorVal);
}
}
void checkPower() {
bool powerVal = digitalRead(powerCheckPin);
if (lastSystemPower != powerVal) {
lastSystemPower = powerVal;
onPowerChanged(powerVal);
}
}
void onPowerChanged(bool val) {
if (val) {
Serial.println("p");
} else {
Serial.println("po");
}
}
void onReverseChanged(bool val) {
if (val) {
Serial.println("re");
} else {
Serial.println("rd");
}
}
void onLeftDoorChanged(bool val) {
if (val) {
Serial.println("ldc");
} else {
Serial.println("ldo");
}
}
void onRightDoorChanged(bool val) {
if (val) {
Serial.println("rdc");
} else {
Serial.println("rdo");
}
}Last updated