So I have two specific if statements that make sure to turn a motor at a specific time, besides that I want to have a flip switch that can turn the motor either way by flipping it.
My problem with my current code is that as soon as the motor is activated by the specific time my if statement further down flips the motor back. I have a really hard time wrapping my head around this and coming up with a solution to avoid this.
So currently at exactly 01:00:00, my code makes my motor spin, but for some reason, my motor spins back again. I believe it has to do with how I wrote the manual flip switch if the statement, that should only be activated when the physical flip switch is actually flipped.
#include <DS3231.h>
// Init the DS3231 using the hardware interface
DS3231 rtc(SDA, SCL);
//Motor pins
const int motorPin1 = 12;
const int motorPin2 = 11;
//Toggle Switch
const int doorSwitchPin = 10;
//Leds
const int ledRunning = 9;
const int ledDone = 8;
//Toggle Switch state
int doorSwitchState = 0;
//Door closed or opened
int doorStatus = 1;
//Door opening/closing process on
int timerOveride = 0;
//Other
char * time_tracker;
int rotationValue = 5000;
void setup() {
Serial.begin(9600);
rtc.begin();
// Set time and date, uncomment when time has been set.
//rtc.setDOW(TUESDAY); // Set Day-of-Week to SUNDAY
//rtc.setTime(14, 9, 40); // Set the time to 12:00:00 (24hr format)
//rtc.setDate(20, 8, 2019); // Set the date to January 1st, 2014
pinMode(doorSwitchPin, INPUT_PULLUP);
pinMode(ledRunning, OUTPUT);
pinMode(ledDone, OUTPUT);
pinMode(motorPin1, OUTPUT);
pinMode(motorPin2, OUTPUT);
}
void loop() {
doorSwitchState = digitalRead(doorSwitchPin);
time_tracker = rtc.getTimeStr();
// Send time
Serial.println( rtc.getTimeStr() );
Serial.println( doorStatus );
Serial.println( timerOveride );
//Open door at a given time
if(strcmp(time_tracker, "01:00:00") == 0 && doorStatus == 0) {
timerOveride = 1;
openDoor();
timerOveride = 0;
}
//Close door at a given time
if(strcmp(time_tracker, "01:00:30") == 0 && doorStatus == 1) {
timerOveride = 1;
closeDoor();
timerOveride = 0;
}
//Manually opening and closing of door via toggle switch
if(timerOveride == 0) {
if(doorSwitchState == HIGH && doorStatus == 0) {
openDoor();
}
if(doorSwitchState == LOW && doorStatus == 1) {
closeDoor();
}
}
}
void openDoor() {
//Spin motor
analogWrite(motorPin1, 180);
analogWrite(motorPin2, 0);
digitalWrite(ledRunning, HIGH);
delay(rotationValue);
analogWrite(motorPin1, 0);
digitalWrite(ledRunning, LOW);
digitalWrite(ledDone, HIGH);
doorStatus = 1;
delay(1000);
digitalWrite(ledDone, LOW);
}
void closeDoor() {
//Spin motor
analogWrite(motorPin1, 0);
analogWrite(motorPin2, 180);
digitalWrite(ledRunning, HIGH);
delay(rotationValue);
analogWrite(motorPin2, 0);
digitalWrite(ledRunning, LOW);
digitalWrite(ledDone, HIGH);
doorStatus = 0;
delay(1000);
digitalWrite(ledDone, LOW);
}