Just make sure your timing code doesn’t significantly affect the timing measurement! For example, printing to an LCD or sending serial data can be relatively slow, so try to account for that. You might want to time how long it takes to sample the line 100 or 1000 times and then divide that result to get a good estimate for the average sample rate. Also, note that you should be concerned with the worst-case delay between sampling, too. For example, does your main loop occasionally block execution for 50 ms to blink an LED, play music, or transmit data? Do you have any slow interrupts enabled? I suggest you look through your code to try to identify all the things that could delay your main loop and by how much. What microcontroller/development board are you using?
If there is a lot of variation in your sampling rate, you might want to incorporate time in to your derivative term. The derivative is intended to be a measure of the rate at which the error is changing, so time is inherently a part of it, but you can often just fold it into the constant if your main loop timing is relatively constant.
Perhaps contrary to what you might be reading in other PID tutorials, I suggest you just get in the right ballpark for P at low speeds and then start adding in D (make sure you get the sign right or tuning will be very frustrating!). I also suggest you make an educated guess when picking your terms. For example, if I have an 8-bit measure of where the line is (i.e. the error) and I am using 8-bit speeds for my motors, I might pick an initial P constant of 1, since that means motors will get full power when I detect the line is at an extreme. I can immediately see that a P value less than 1 is probably too small (I’ll never get full speed out of my motors), but I know I might need to make it bigger to get my bot to be more responsive, especially if my line sensor array is much wider than the actual line. Similarly, if my error ranges from -1000 to 1000 and my motor speeds range from -10 to 10, I might start with a P constant of 1/100. Once I know what P constant logically makes sense, I can take a stab at D by noting that the D constant usually needs to be much bigger than the P constant in order for it to have a comparable effect. This is because the successive difference in errors is typically quite small over short time scales. The ideal D will proportional to your sampling rate since it effectively has the sampling period in the denominator of the calculation, but in my experience it has usually be around 10 to 20 times the P constant.
One last bit of advice: if you aren’t already, I suggest you limit your motor speeds to be between 0 and MAX_SPEED. The PID calculation can lead to negative motor speeds, but letting your motors run backwards during line following is generally not helpful.
- Ben