Start - Stop button for DC motor

Hi all!

I have a question on programming my arduino and dc motor. I don't have any previous experience with programming, but for a school project I need to program a DC motor.

I got the motor to work with the start and stop button, but I can't figure out how to do a specific thing.
When the start button is pressed the motor needs to start (obviously) and the stop button (a limit switch) stops the motor. But when the start button is pressed when the limit switch is still activated I wan't the motor to start again. I can't figure out how to do this.

The setup I have is an Arduino Nano with a mosfet powering a 24V DC motor. The 'sensors' I use are buttons, for testing purposes.

Could someone please take a look at my code and give me advice on how to proceed?

This is my code:

// Pins

const int speedPinA = 3;
const int startPin = 4;
const int stopPin = 5;

int speedState =0;
int buttonState = 0;
int lastButtonState = 0;     


void setup() {
 
  pinMode (speedPinA , OUTPUT);
  pinMode (startPin, INPUT);
  pinMode (stopPin, INPUT);
  analogWrite(speedPinA, 0);

}

void loop() {


  buttonState = digitalRead(startPin);

   if (buttonState != lastButtonState) {
     if (buttonState == 1) { 
      if(speedState=255) speedState=0;
      else            speedState=255;         
 
    }
    
  }

  lastButtonState = buttonState;
  
  analogWrite(speedPinA, speedState);

  if (digitalRead(stopPin) == HIGH) {
    speedState=0;
  }



delay(50);
  }

when the start button is pressed when the limit switch is still activated I wan't the motor to start again

well this piece of code does not perform the check you are describing in your requirements, it only checks for limit switch being activated - so that's why your program don't do what you want....

  if (digitalRead(stopPin) == HIGH) {
    speedState=0;
  }

Do you have pull down resistors on your 2 switches? you might want to consider using the built in INPUT_PULLUP to make the design leaner

well this piece of code does not perform the check you are describing in your requirements, it only checks for limit switch being activated - so that's why your program don't do what you want....

Yeah, that's the problem. I dont't know how to improve the code. I tried working with switchcase, but didn't do what I wanted.

Do you have pull down resistors on your 2 switches? you might want to consider using the built in INPUT_PULLUP to make the design leaner

I did have 10K resistors on my switches, but this makes it way cleaner! Thanks, learning new things everyday.

What you are stating is that if 2 conditions are met, then you do something and if only one is met you do something else

explore what && or || boolean logic can do for you as well as nested/serial if conditions if () {} else if () {} else {}

Thanks for your help! Will look into these functions.

Technically they are not functions, && and || are operators, if/else is a statement.