How do i remember switch state and the run different code

hello, im currently building a controller for a motor. im trying to implement star delta switching.

this is all mocked up and not using a real motor.

i have the below code but want to remember the motor switch state each loop as at the moment it repeats the start up sequence every loop?

   // read the state of the switch
  motor_on_switch_pin_state = digitalRead(motor_on_switch_pin);

if (motor_on_switch_pin_state == HIGH) {
    // turn output on:
    digitalWrite(motor_Contactor_km1, HIGH);
	  digitalWrite(motor_Contactor_km3, HIGH);
	  delay (star_delta_time);
	  digitalWrite(motor_Contactor_km3, LOW);
	  digitalWrite(motor_Contactor_km2, HIGH);
  } else {
  // turn output off:
  digitalWrite(motor_Contactor_km1, LOW);
	digitalWrite(motor_Contactor_km2, LOW);
	digitalWrite(motor_Contactor_km3, LOW);
  }

If the variables are in the loop function, put the reserved word: static in front of them. Then they’ll keep their values.

If they’re outside of the loop function, then they’re global and will also keep their values.

you can always read the digital output controlling the motor

not clear

hello!

i currently have all my variables before

void setup() {

but each loop it currently checks the switch, sees it as high and starts the motor.
next loop cycle and the motor is still running. the switch is still high so it begins the motor start up commands over again. i need the arduino to ignore the start up it its already running

I would recommend using State Change Detection on the switch. That way you perform the startup when the switch goes from LOW to HIGH and shutdown when the switch goes from HIGH to LOW. If the switch state doesn't change then no action is taken.

void loop()
{
  static byte last_motor_on_switch_pin_state = LOW;
  byte motor_on_switch_pin_state = digitalRead(motor_on_switch_pin);
  
  if (motor_on_switch_pin_state != last_motor_on_switch_pin_state)
  {
    delay(50); //debounce
    last_motor_on_switch_pin_state = motor_on_switch_pin_state;
    if (motor_on_switch_pin_state == HIGH) 
    {
      // LOW to HIGH: Perform Startup
      digitalWrite(motor_Contactor_km1, HIGH);
      digitalWrite(motor_Contactor_km3, HIGH);
      delay (star_delta_time);
      digitalWrite(motor_Contactor_km3, LOW);
      digitalWrite(motor_Contactor_km2, HIGH);
    }
    else
    {
      // HIGH to LOW: turn output off
      digitalWrite(motor_Contactor_km1, LOW);
      digitalWrite(motor_Contactor_km2, LOW);
      digitalWrite(motor_Contactor_km3, LOW);
    }
  }
}

define them globally, outside of any function

How about setting a flag such as bool themotorberunningmon=false; as a control for startup?

sorry, i mis-read this.

which variable are you talking about?

are you saying the following always returns HIGH?

please post your code?

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