PID Library question

Hello to all.

I would like to incorporate the pid library with the Adaptive tunings example on a Photon.
In particular I need to replace the Output to a servo angle, just a little stumped on how to go about that.

Input will be analogRead and Output should be servo angle.
If setpoint is analogRead = 2048;
myServo.write(90); //minimum is 45degrees, maximum is 135degrees

Any assistance would be appreciated.

Not sure how this pertains to the PID library, but in order to map a reading in the range of 0…4095 to a range of 45…135 you’d just use angle = map(setpoint, 0, 4095, 45, 135).

Or simple algebra would do the trick just the same - after all that’s what map() uses internally :wink:

1 Like

Thank you ScruffR.

I have tried to adapt that to the below example.
Getting a map overload error.


/********************************************************
 * PID Adaptive Tuning Example
 * One of the benefits of the PID library is that you can
 * change the tuning parameters at any time.  this can be
 * helpful if we want the controller to be agressive at some
 * times, and conservative at others.   in the example below
 * we set the controller to use Conservative Tuning Parameters
 * when we're near setpoint and more agressive Tuning
 * Parameters when we're farther away.
 ********************************************************/

#include "pid.h"


Servo myServo; 
#define servoPin D1

//Define Variables we'll be connecting to
double Setpoint, Input, Output;

//Define the aggressive and conservative Tuning Parameters
double aggKp=4, aggKi=0.2, aggKd=1;
double consKp=1, consKi=0.05, consKd=0.25;

//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint, consKp, consKi, consKd, PID::DIRECT);

void setup()
{
    
  myServo.attach(servoPin);  
  myServo.write(90);
  
  //initialize the variables we're linked to
  Input = analogRead(0);
  Setpoint = 2048;

  //turn the PID on
  myPID.SetMode(PID::AUTOMATIC);
}

void loop()
{
  Input = analogRead(0);
  Output = map(Setpoint, 0, 4096, 45, 135);


  double gap = abs(Setpoint-Input); //distance away from setpoint
  if(gap<10)
  {  //we're close to setpoint, use conservative tuning parameters
    myPID.SetTunings(consKp, consKi, consKd);
  }
  else
  {
     //we're far from setpoint, use aggressive tuning parameters
     myPID.SetTunings(aggKp, aggKi, aggKd);
  }
  
  myPID.Compute();
  myServo.write(Output);
}

Since you are using a double for Setpoint your number literals also need to be floating point types otherwise the compiler wouldn’t know whether to make Setpoint an int or the 4 integers into double - hence the ambiguity error.

This will provide the required hint

 Output = map(Setpoint, 0.0, 4095.0, 45.0, 135.0);