Im using a reed switch as a push button but it only changes direction when its being held down. How can I make it switch direction permanently until its pushed again?
boolean reverse, lastState; // set global, at top of code
.
.
.
//inside loop function
if(digitalRead(switchPin) == LOW && digitalRead(switchPin) != lastState) // looking to see if button state is LOW and does not equal the last state.
{
reverse = !reverse; // will only change when button state is LOW
}
lastState = digitalRead(switchPin);
boolean reverse, lastState; // set global, at top of code
int enablePin = 11;
int in1Pin = 10;
int in2Pin = 9;
int switchPin = 7;
int potPin = 0;
void setup()
{
pinMode(in1Pin, OUTPUT);
pinMode(in2Pin, OUTPUT);
pinMode(enablePin, OUTPUT);
pinMode(switchPin, INPUT_PULLUP);
}
void loop()
{
int speed = analogRead(potPin) / 4;
boolean reverse = digitalRead(switchPin);
setMotor(speed, reverse);
//-------------------------------------------------------------------------------------
if(digitalRead(switchPin) == LOW && digitalRead(switchPin) != lastState) // looking to see if button state is LOW and does not equal the last state.
{
reverse = !reverse; // will only change when button state is LOW
}
lastState = digitalRead(switchPin);
}
//---------------------------------------------------------------------------------------
void setMotor(int speed, boolean reverse)
{
analogWrite(enablePin, speed);
digitalWrite(in1Pin, ! reverse);
digitalWrite(in2Pin, reverse);
}
You still have "boolean reverse = digitalRead(switchPin);" in your code, which needs to be taken out and "setMotor(speed, reverse);" should be after the button check.
You also might want to give these an actual value. I didn't specify before, but they should be set.
"boolean reverse, lastState;"
Change them to these instead.