Hello, I'm just learning and struggling a bit with a programming issue. What I am trying to do is control a motor. Essentially I want the motor to run for 3 seconds, stop for 3 seconds in between limit switches. Once it reaches a limit switch, I want it to reverse and go in the other direction. I have the hardware part figured out. Just having a bit of trouble with the code. Here is what I have:
const int onButton = 7;
const int openLimit = 2;
const int closeLimit = 4;// the pin that the pushbutton is attached to
const int motorOpen = 8;
const int motorClose = 13;// the pin that the LED is attached to
// Variables will change:
int openLimitState;
int lastOpenLimitState;// current state of the button
int closeLimitState;
int lastCloseLimitState;
int onButtonState;
void setup() {
// initialize the button pin as a input:
pinMode(openLimit, INPUT);
// initialize the LED as an output:
pinMode(closeLimit, INPUT);
pinMode(motorOpen, OUTPUT);
pinMode(motorClose, OUTPUT);
pinMode(onButton, INPUT);
}
void loop() {
// read the pushbutton input
onButtonState = digitalRead(onButton);
if (onButtonState == HIGH) {
openLimitState = digitalRead(openLimit);
closeLimitState = digitalRead(closeLimit);
// compare the buttonState to its previous state
if (openLimitState == HIGH && closeLimitState == HIGH) {
digitalWrite(motorOpen, LOW);
digitalWrite(motorClose, LOW);
}
else if (openLimitState == HIGH) {
// if the current state is HIGH then the button
// wend from off to on:
motorRunClose();
}
else if (closeLimitState == HIGH) {
motorRunOpen();
}
else {
motorRunClose();
}
}
else if (onButtonState == LOW) {
digitalWrite (motorOpen, LOW);
digitalWrite (motorOpen, LOW);
}
}
void motorRunOpen() {
while (openLimitState == LOW) {
digitalWrite (motorOpen, HIGH);
delay (3000);
digitalWrite (motorOpen, HIGH);
delay (3000);
digitalWrite (motorOpen, HIGH);
delay (3000);
}
}
void motorRunClose() {
while (closeLimitState == LOW) {
digitalWrite (motorClose, HIGH);
delay (3000);
digitalWrite (motorClose, HIGH);
delay (3000);
digitalWrite (motorClose, HIGH);
delay (3000);
}
}
Essentially what happens is if the on button attached to input 7 is high, the 13 output just stays on all the time and ignores any other input. What am I doing wrong?
Thanks in advance for any guidance!