State Machine code


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;
  }
}

@arduinonewbie78, your topic was moved to a more suitable location of the forum.

What happens when you run the code compared with what should happen ?

You cannot directly power a motor from the Arduino pins, you will need a motor driver.

Looks like your switch is wired wrong.

The 5v connection should be GND.

See S3 in the image below:

Simple on/off motor control:

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

You never write anything to “retract” except LOW.

And you go to some trouble to do that.

a7

It's an offspring of "Using 2 linear actuator..." crossposting #13.

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.

Already mentioned.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.