 # ESC and motor control with if/else and threshold. Transition problem.

Hello
Im trying to control motor speed relative to a specific vacuum. Vacuum sensor is analog in 0-5v. Motor is controlled via ESC 0-5 analog out (PWM). The if/else attempts to speed up the motor when vacuum drops below the threshold value. It works, but its crude.... A video of the rig in action, go straight to 120-sec to see my transition problem.

If vacuum moves away from the threshold gradually the motor speeds up to maintain the threshold. However any big changes in vacuum past the threshold value and the motor bumps between my "if" and "else" settings.

I have tried increasing the delay and adding a fade amount to smooth the transition, no luck :o . Im sure there is a better way to do this or a function that I am aware of? Thanks

``````const int analogInPin = A0;    // sensor in
const int analogOutPin = 9;       // ESC
const int threshold = 330;   // 257 = 5-in/Hg, 335 = 1-KPA
void setup() {
// initialize the LED pin as an output:
pinMode(analogOutPin, OUTPUT);
// initialize serial communications:
Serial.begin(9600);
analogWrite(analogOutPin, 102);   // send 2v to arm ESC (arming range 1.55-2.25v)
delay(5000);                       // hold 2v for 5 seconds
}

void loop() {
// read the value of the potentiometer:

if (analogValue > threshold) {
analogWrite(analogOutPin, 247);  // 247 = 95% of 255, 240 stable high 150 + fadeAmount
} else {
analogWrite(analogOutPin, 150);  // 150 stable low with 330 threshold
}

Serial.println(analogValue);

delay(1);
}
``````

Two suggestions. One easy, one complicated

The easy one would be to introduce some hysteresis into the system so that hunting between between high and low states is reduced.

The complicated one would be to use PID control so that the amount of correction applied is proportional to the difference between the current and target values

A part-way solution before going all the way to PID is just a 'P' (proportional) control loop:

``````   int error = analogValue - threshold;  // negative value means Too Low,  positive means Too High
error = constrain(error, -50, +50);  // Constrain to a reasonable range.

analogWrite(analogOutPin, 200 - error);  // Uses 250 if way too low and 150 if way too high
``````

PID did the trick. After some fine tuning transition is smooth and predictable. I appreciate the help guys, thanks.