I'm trying to triger a motor with a switch and stop it when I hit another switch. As you guys can see I'm a new to this and need a push.
Can anybody tell me what is wrong here.
Thanks
const int switchOpen = 2; // on/off
const int switchOpenStop = 3; //Switch open stop
const int powerMotor = 12; // energy to motor
// variables will change:
int switchOpenState = 0; // variable for reading the on/off status
int switchStopState = 0; //variable for switch stop
void setup() {
Serial.begin(9600);
// initialize the LED pin as an output:
pinMode(powerMotor, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(switchOpen, INPUT);
pinMode(switchOpenStop, INPUT);
}
void loop() {
// read the state of the pushbutton value:
switchOpenState = digitalRead(switchOpen);
switchStopState = digitalRead(switchOpenStop);
// check if the pushbutton is pressed. If it is, the buttonState is HIGH:
if (switchOpenState == HIGH) {
// turn LED on:
digitalWrite(powerMotor, HIGH);
Serial.println("Motor on");
if (switchOpenStop == LOW) {
Serial.println("stop");
} else {
Serial.println("run");
}
} else {
// turn LED off:
digitalWrite(powerMotor, LOW);
Serial.println("Motor off");
}
}
Don't ask me what I did but this piece of code now seems to read the 2 switches.
What I'm trying to achive is.
When switchOpen is realese the motor (right now just pin 12) start running until hits switchOpenStop and the motor stops.
When switchOpen is pushed the motor start running in the oposite direction ( until hits switchCloseStop (not yet in the code). Just trying to stablish the system.
The problem that I have now is that
[codedigitalWrite(powerMotor, LOW);][/code]
stays in a loop on/off and trying to figure out where has to be.
Thanks
const int switchOpen = 2; // on/off
const int switchOpenStop = 3; //Switch open stop
const int powerMotor = 12; // energy to motor
// variables will change:
int switchOpenState = 0; // variable for reading the on/off status
int switchStopState = 0; //variable for switch stop
void setup() {
Serial.begin(9600);
// initialize the LED pin as an output:
pinMode(powerMotor, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(switchOpen, INPUT);
pinMode(switchOpenStop, INPUT);
}
void loop() {
// read the state of the pushbutton value:
switchOpenState = digitalRead(switchOpen);
switchStopState = digitalRead(switchOpenStop);
// check if the pushbutton is pressed. If it is, the buttonState is HIGH:
if (switchOpenState == HIGH) {
// turn motor on:
digitalWrite(powerMotor, HIGH);
Serial.println("Motor");
delay(100);
if (switchStopState == LOW) {
Serial.println("run");
} else {
Serial.println("stop");
digitalWrite(powerMotor, LOW); // stays in a loop on/off <-----------------------------------------
delay(100); // don't need this delay. Just to troubleshoot why is not working
}
} else {
// turn LED off:
digitalWrite(powerMotor, LOW);
Serial.println("Motor off");
}
}