I am very new to coding and arduino. I am trying to write a code for the motor,, button, and slide switch. What I want it press the button once when slide switch is on left side, the motor will start spinning, and when I press the button once when slide switch is on right side, the motor stop.
I dont know what is missing in my code to make that happen.
Here is my code:
int pushbutton = 2;
int switchbutton_on = 3;
int switchbutton_off = 4;
int extract = 7;
int retract = 8;
int state = 0;
void setup()
{
pinMode(pushbutton, INPUT_PULLUP);
pinMode(switchbutton_on, INPUT_PULLUP);
pinMode(switchbutton_off, INPUT_PULLUP);
pinMode(extract, OUTPUT);
pinMode(retract, OUTPUT);
}
void loop()
{
if (digitalRead(pushbutton) == HIGH && digitalRead(switchbutton_off) == HIGH) {
state = 0;
}
if (digitalRead(pushbutton) == HIGH && digitalRead(switchbutton_on) == HIGH) {
state = 0;
}
if (digitalRead(pushbutton) == LOW && digitalRead(switchbutton_off) == HIGH) {
state = 1;
}
if (digitalRead(pushbutton) == LOW && digitalRead(switchbutton_on) == HIGH) {
state = 0;
}
switch (state) {
case 0:
digitalWrite(extract, LOW);
digitalWrite(retract, LOW);
break;
case 1:
digitalWrite(extract, HIGH);
digitalWrite(retract, LOW);
break;
}
}
It sound like you should be detecting when the buttons become pressed rather than when they are pressed
Look at the StateChangeDetection example in the IDE to see how to do it
When debugging code that includes making decisions based on the value of variables it can be helpful to print the values being tested to see if they are what you expect.
If the tests of input states are mutually exclusive it would be better to use if/else rather than a series of ifs
The slide switch should not be connected to 5 V. The centre pin should connect to ground just as the pushbutton, otherwise it will not work with INPUT_PULLUP.
Unless the slide switch has three positions, you only need to read it via a pin connected to one side.