I am trying to build a unlocker on my hardlid for my ute. I have replaced the manual unlocking mechanism with 2 of these https://www.jaycar.com.au/slave-door-lock-actuator/p/LR8813.
Now my code below works sometimes and I cannot work out why. The way the code should work is
- Press Unlock Button (Count increments)
- Press Unlock Button again
- When count = 2 turn relay on for 4 seconds then turn off
- reset count to 0
- If time between presses is longer than 10 seconds reset count to 0
Basic diagram below. Please note the push button is actually wired to a relay which is triggered by the car unlock remote and the LED is the actuators.
This is my code
int switchPin = 2; // choose the input pin (for a pushbutton)
int relayPin = 4; // choose the input pin (for a pushbutton)
int val = 0; // variable for reading the pin status
int counter = 0;
int currentState = 0;
int previousState = 0;
bool lockOn = false;
unsigned long currentMillis = 0;
unsigned long previousMillis = 0;
unsigned long LockcurrentMillis = 0;
unsigned long LockpreviousMillis = 0;
const long interval = 10000;
const long Lockinterval = 4000;
void setup() {
Serial.begin(9600);
pinMode(switchPin, INPUT); // declare pushbutton as input
pinMode(relayPin, OUTPUT); // declare pushbutton as input
Serial.println("Ready");
Serial.print("IP address: ");
}
void loop() {
currentMillis = millis();
LockcurrentMillis = millis();
/*
Serial.print("Current ");
Serial.print(currentMillis);
Serial.print(" | Previous ");
Serial.println(previousMillis);
//Serial.println(lockOn);
Serial.print("Lock Current ");
Serial.print(LockcurrentMillis);
Serial.print(" | Lock Previous ");
Serial.println(LockpreviousMillis);
*/
if (lockOn == true){
if (LockcurrentMillis - LockpreviousMillis >= Lockinterval) {
// save the last time you blinked the LED
LockpreviousMillis = LockcurrentMillis;
digitalWrite(relayPin, LOW); // turn relayPin off
lockOn = false;
Serial.println("relay off");
}
}
val = digitalRead(switchPin); // read input value
if (val == HIGH) { // check if the input is HIGH (button released)
currentState = 1;
}
else {
currentState = 0;
}
if (currentState != previousState) {
if (currentState == 1) {
counter = counter + 1;
previousMillis = currentMillis; //reset timer
Serial.println(counter);
}
}
if (counter == 2) {
counter = 0;
digitalWrite(relayPin, HIGH); // turn relayPin on
//delay(4000);
//digitalWrite(relayPin, LOW); // turn relayPin off
lockOn = true;
LockpreviousMillis = LockcurrentMillis;
Serial.println("relay on");
}
previousState = currentState;
//delay(250);
if (currentMillis - previousMillis >= interval) {
// save the last time you presse the button
previousMillis = currentMillis;
//LockpreviousMillis = LockcurrentMillis;
//if (counter >= 1) {
Serial.println("Took too long reset count");
counter = 0;
lockOn = false;
//}
}
}
Any Help would be highly appreciated
Thanks
