IF function loop issue with motorised fader

Hey there,

I’m trying to get a motorised pot to jump to a specific position and then switch off the motor unless the fader is moved. If it is moved then it should jump back to the assigned position. However, I’m stuck with the fader bouncing around wildly when it reaches close to the assigned position in the first place.

Please ignore the extra INT that I have there - these will be used later on

// Fetch Motor Shield library
#include <AFMotor.h>

int fader1;
int post;
AF_DCMotor motor(1); // Turn on motor for fader1
int pwm = 11;
int upDown = 13;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  motor.setSpeed(250);
  motor.run(RELEASE);

}

void loop() {
  // put your main code here, to run repeatedly:
  fader1 = analogRead(A0);
  int pos = 161;
  pinMode(upDown, OUTPUT);

  
  if ((fader1 - pos) < 1) {
    Serial.println("if 1");
    digitalWrite(upDown, LOW);
  }
 
  if ((fader1 - pos) > 1) {
   
     Serial.println("if 2");
     digitalWrite(upDown, HIGH);
  }
  else {
   
  }

 

  }

That's probably because it just overshoots. It's hard to exactly hit the right spot. So you need a control loop like a PID or give it more hysteresis.

You'll never get a stable end position with bang-bang control like this - the motor is being driven at maximum all the time and rapidly being reversed.

You need to wind down the drive as the destination is approached smoothly - this means two things:

1) PWM motor drive is required. 2) A control loop is needed. The standard approach is PID, and once tuned can perform well. Tuning is necessary and can be a bit tricky. Read up a little on PID loops and tuning. Hopefully you can get away with only P or PI (unless you want rapid response).

Bang-bang is PWM, isn't it?

No, bang-bang is reacting to a change in input with a change in output. Typically hysteretic control strategies use it.