It is a common situation in electronics to have a control loop, that is some sort of feedback that drives the input to a system such as a motor or a heater based upon a sensor to measure something like position or temperature. You’ll have a set point — whatever you want the sensor to read — and your job is to adjust the driving thing to make the sensor read the set point value. This seems easy, right? It does seem that way, but in realitythere’s a lot of nuance to doing it well and that usually involves at least some part of a PID (proportional, integral, derivative) controller. You can bog down in math trying to understand the PID but [Electronoobs] recent video shows a very simple test setup that clearly demonstrates what’s going on with an Arduino, a motor, a distance sensor, and a ping-pong ball. You can see the video below.
Imagine for a moment heating a tank of water as an example. The simple approach would be to turn on the heater and when the water reaches the setpoint, turn the heater off. The problem there is though that you will probably overshoot the target. The proportional part of a PID controller will only turn the heater fully on when the water is way under the target temperature. As the water gets closer to the right temperature, the controller will turn down the input — in this case using PWM. The closer the sensor reads to the setpoint, the lower the system will turn the heater.