Logic behind a PID controller?
... my aim is to have the PID value be zero, is that correct? 


Not quite. You are hoping that the error will be zero.


  Anything different than zero and the relay would activate and make the heating element get hot until the error reaches zero? 


Not always. The PID controller may suppress the output if the output is increasing at a rate that would cause it to overshoot - even though it is below setpoint at the moment.


  Is it possible to calculate how much time the relay needs to be activated to reach the temperature or is it better to activate it on really small intervals and check the error?


Generally you will be limited by the number of switching cycles the relay can tolerate. You might decide that switching once every 5 s to 10 s is slow enough to prolong the life of the relay but fast enough that thermal response of the load doesn't allow the temperature to vary too much.

Having done that, you then apply proportional time control to the relay. Let's say you decide on a 5 s cycle then if the PID output is 20% the output is on for 1 s out of 5 s. For 60% it's 3 s out of 5 s, etc.



Figure 3. The classic PID control function. Source: Wikipedia - PID controller.

As explained in one of my linked answers below, as the integral action corrects the output the error falls to zero so the contribution of the proportional control also falls to zero. The output when the error is zero is maintained purely by the integral action.

See my answers to the questions below for more on the topic.


Please explain in layman&#39;s terms how a PID accounts for inertia in temperature control.
Understanding the flow of a PI Controller?




From the comments:


  When you say for example "if the PID output is 20% the output is on for 1 s out of 5 s", the 20% is in relation to what? The setpoint? Because I thought the output was a numeric value.


The 20% will be the percentage of full-scale (or maximum) PID output. For the cruise control on your car this maximum would be accelerator pedal pressed to the floor; for a refrigeration system it would be cooling valve fully open; for a ship's steering control it would be 100% rudder; for your heater it is 100% output.

The output of your PID will be a number between 0 and a maximum. If you're working with an 8-bit micro then that might be 0 to 255 (28 -1) while for a 16-bit micro it might be 216 -1 = 65535. Meanwhile, for a micro with floating point capability you might set it as 0 to 1.0.

What ever value the PID outputs has to be converted to a percentage of your heater duty-cycle, 5 s in our example. This part is just simple mathematics.