PID control with fans and ultrasonic sensor (HC_SR04)

I am using PID control to control the speed of a fan based on the height of an ultrasonic sensor, but for some reason, it is not supplying enough power to the fans even though I have analogWrite at 255. However, when I just send power to the fans using analogWrite and no PWM (Basic_Control.ino), it works out just fine. I am using an Arduino Motor Shield, a 12V 3A 3-pin fan, an Arduino UNO R3, and an Ultrasonic Sensor. Also, when I vary the k-values for proportional, integral, and derivative control, there is no discernible difference between the control as I vary the height of the ultrasonic sensor. Thanks in advance.

PROJECT_CODE.ino (4.31 KB)

Basic_Control.ino (1.25 KB)

const int trigPin = 11; //10

const int echoPin = 12; //13

Those comments look pretty silly.

I am using PID control to control the speed of a fan based on the height of an ultrasonic sensor

No, you are not. Regardless of what the distance reading is, you MIGHT write 255 to the PWM pin.

if (currentMillis-prevMillis <= period)

Less than?

It might be difficult to use the same pin for motor speed and ranger control.

How did you actually wire everything up?

const int trigPin = 11;   //10
...
digitalWrite(trigPin, HIGH);
...
analogWrite(11, 0);     //Channel B Speed 0%

Google "PID tuning" to learn how to set the three constants. This will not work when starting out.

  double ki = 1;

  double kd = 1;