Arduino deadband for servo control

Hello !
Im having trouble with my servo. When my joystick is at "zero" position, my servo still moves a little. I want to know how can i add a deadband to my code so that it wont move. Meaning, when the arduino reads the potentiometer from let's say ... 450 to 600, i went it to servo.write(90) and when it doesnt it should write the normal way. Thanks in advance

#include <Servo.h>         			// include a library that does all the hard work controlling the servo

Servo servo1;              			// declare servo #1
int leftJS = 0;               			// analog input pin for left position
void setup() {
  Serial.begin(9600);                  
  pinMode(leftJS, INPUT);            	  	// let Arduino know that this is an input
}
void loop() {
  leftPOS = analogRead(leftJS);         	// Left joystick position value (between 0 and 1023)
  leftPOS = map(leftPOS, 0,1023,180,0);		// Map the values between 180 and 0 degrees
  servo1.write(leftPOS);                 	// Make Servo 1 go to angle defined by left joystick position
}

Some servo/pot test code.

//zoomkat dual pot/servo test 12-29-12
//view output using the serial monitor

#include <Servo.h> 
Servo myservo1;
Servo myservo2;

int potpin1 = 0;  //analog input pin A0
int potpin2 = 1;

int newval1, oldval1;
int newval2, oldval2;

void setup() 
{
  Serial.begin(9600);  
  myservo1.attach(2);  
  myservo2.attach(3);
  Serial.println("testing dual pot servo");  
}

void loop() 
{ 
  newval1 = analogRead(potpin1);           
  newval1 = map(newval1, 0, 1023, 0, 179); 
  if (newval1 < (oldval1-2) || newval1 > (oldval1+2)){  //dead band
    myservo1.write(newval1);
    Serial.print("1- ");
    Serial.println(newval1);
    oldval1=newval1;
  }

  newval2 = analogRead(potpin2);
  newval2 = map(newval2, 0, 1023, 0, 179);
  if (newval2 < (oldval2-2) || newval2 > (oldval2+2)){  
    myservo2.write(newval2);
    Serial.print("2- ");    
    Serial.println(newval2);
    oldval2=newval2;
  }
  delay(50);  //delay for easier viewing in the serial monitor
}
const int centerPOS = 90; // set to the neutral position for your servo
const int deadband = 5; 
...
if(abs(leftPOS - centerPOS) < deadband)
{
    // position is within the deadband
    leftPOS = centerPOS;
}
1 Like