In this code I have a button which when pressed unlocks the door. There is a magnetic read switch placed in the frame of the door and a magnet in the door aligned to it. When the door is unlocked by the push of the button, then the door has to be manually opened and closed back again.
As soon as the the door closes, it must get locked by the feedback of the read switch.
Please HELP!
This is my code -
const int buttonPin1 = 2;
const int sensorPin1 = 6;
const int doorone = 8;
alllock();
unsigned int count = 0;
Serial.println("Idle");
if (buttonState1 == LOW) {
Serial.println("Button Pressed");
delay(1);
count += 1;
while (count >= 1) { // i have added this line to make the button work with one press.
unlockone(); // and not like a push button which has to be kept pressed.
while (sensorState1 == LOW) {
delay(1);
Serial.println("Door Idle"); //sensor is LOW when the door is unlocked but not opened.
break;
}
while (sensorState1 == HIGH) { //sensor is HIGH when door has been opened.
delay(1);
Serial.println("Door Opened");
}
while (sensorState1 == LOW) { //sensor is LOW when the door has been closed back
delay(1);
Serial.println("Door Closed");
alllock(); //this function locks the door back.
}
}
}
}
If the button is pressed but the door is not opened, does it stay unlocked forever? If not, how long does it stay unlocked?
It looks like you intend to handle multiple doors some day. Using arrays will make it easier to add as many doors as you have pin for. I put "AL" on the ends of the pin names as a reminder that they are all "Active Low". That means setting the unlock pin to LOW will unlock the door, the unlock button will return LOW when pressed, and the door closed sensors (reed switches) will return LOW when the door is closed.
const byte DoorCount = 1;
const int UnlockButtonPinsAL[DoorCount] = {2}; // Active Low
const int DoorClosedSensePinsAL[DoorCount] = {6}; // Active Low
const int UnlockSolenoidPinsAL[DoorCount] = {8}; // Active Low
// State Machine state for each door.
enum DoorStates {Locked, Unlocked, Open};
DoorStates States[DoorCount];
void setup()
{
Serial.begin(9600);
for (byte i = 0; i < DoorCount; i++)
{
digitalWrite(UnlockSolenoidPinsAL[i], HIGH); // Not Unlocked
pinMode(UnlockSolenoidPinsAL[i], OUTPUT);
pinMode(UnlockButtonPinsAL[i], INPUT_PULLUP);
pinMode(DoorClosedSensePinsAL[i], INPUT_PULLUP);
States[i] = Locked;
}
}
void loop()
{
for (byte i = 0; i < DoorCount; i++) // Each door
{
switch (States[i])
{
case Locked:
if (digitalRead(UnlockButtonPinsAL[i]) == LOW) // Unlock button is pushed
{
digitalWrite(UnlockSolenoidPinsAL[i], LOW); // Unlock
States[i] = Unlocked;
}
break;
case Unlocked:
if (digitalRead(DoorClosedSensePinsAL[i]) == HIGH) // Door was unlocked, now is open
{
States[i] = Open;
digitalWrite(UnlockSolenoidPinsAL[i], HIGH); // Set lock (but door is still open)
}
break;
case Open:
if (digitalRead(DoorClosedSensePinsAL[i]) == LOW) // Door is now closed, should still be locked
{
States[i] = Locked;
}
break;
}
}
}