How can I implement a margin of error in my code?

The code is for controlling the position of a continuous servo by attaching a potentiometer to it, I need an error margin so that it doesn't wobble from side to side and I don't know how.

void loop() {
  if (mySerial.available()){
  wntangle = mySerial.read();
    }
  potvalue = analogRead(potpin);
  posangle =  map(potvalue, 0, 1023, 0, 180);
  
  if (wntangle > posangle){
    servo1.write(80);
  }
  else if (wntangle < posangle){
    servo1.write(100);
    
  }
  else{
    servo1.write(90);    
  }
}

You likely need some Hysteresis.

Maybe change that to

if (wntangle > posangle + 5

and the other to


if (wntangle < posangle - 5

2 Likes

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