Skip to content

Getting started

Daniel edited this page Nov 3, 2018 · 11 revisions

Overview

This article goes over how to get started with this PID library.

Details

Including and instantiation

The first thing you need to do is to include the library.

#include <PIDController.h>

Then you need to create an instance of the class.

PIDController pid;

This creates an instance of the class PIDController called pid.

You can call it whatever you want, it can for example be myPIDController instead of pid.

It should look something like this:

#include <PIDController.h>

PIDController pid;

Setup

In the setup function you need to call some methods.

void setup () {
  Serial.begin(9600); // Required for graphing
  pid.begin();
  pid.setpoint(600);
  pid.tune(1, 1, 1);
  pid.limit(0, 255);
}
  • If you want the PID controller to graph the values during computing, you have to call Serial.begin() first.

  • You need to call begin() on your instance before you can call other methods. The method begin() initializes the properties in your PID instance.

  • The setpoint() method defines the setpoint (or "goal") for your PID.

  • The tune() method tunes your PID. It takes the arguments <kP> <kI> <kD>. The tuning variables are different for every control loop that uses a PID. You need to find the values that fit for your setup. Read more about tuning here.

  • The limit method limits the output from your PID. It takes the arguments <min> <max>. It's is important to set the limit to avoid integral windup. You can read more about integral windup here.

Loop

It's in the loop the magic happens...

void loop () {
  int sensorValue = analogRead(A0);
  int output = pid.compute(sensorValue, GRAPH, VERBOSE);
  delay(30);
}
  • Assuming you have a sensor connected as an input to your Arduino, you have to read it before you can calculate the output.

  • The compute method does all the hard work. Given an input from a sensor, it calculates the optimal output. Optionally you can also have a second argument GRAPH, if you do this, you can see a graph in the serial plotter. If you want the graph to show more values you can give the method a third argument: VERBOSE.

  • Delaying the loop is important. Depending on how fast you need to update your output you need to find a value that works for you. Say you are controlling an automatic car, and you want it to stay 40 meters behind the car in front, you'll have to get a new output fast in case of the car in front of you brakes suddenly. But if your PID is controlling a hot boiler, you don't need a fast update. Here is an article that explains how you find a delay that works for you.

More info soon

Clone this wiki locally