Advertisement
pleasedontcode

PID Controller Code

Aug 19th, 2024
572
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Arduino 2.07 KB | Source Code | 0 0
  1. #include <PID_v1.h>
  2.  
  3. // Define the input, output, and setpoint variables
  4. double Setpoint, Input, Output;
  5.  
  6. // Specify the PID tuning parameters
  7. double Kp = 2.0, Ki = 5.0, Kd = 1.0;
  8. PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT);
  9.  
  10. // Motor control pins
  11. const int motorPin1 = 18;
  12. const int motorPin2 = 19;
  13.  
  14. // Encoder input pins
  15. const int encoderPin1 = 34;
  16. const int encoderPin2 = 35;
  17.  
  18. // Variables for encoder
  19. volatile int encoderPos = 0;
  20. int encoderPosLast = 0;
  21.  
  22. // Timer for PID sampling
  23. unsigned long lastTime = 0;
  24. unsigned long sampleTime = 100; // 100ms
  25.  
  26. void setup() {
  27.   // Set motor control pins as outputs
  28.   pinMode(motorPin1, OUTPUT);
  29.   pinMode(motorPin2, OUTPUT);
  30.  
  31.   // Set encoder pins as inputs
  32.   pinMode(encoderPin1, INPUT);
  33.   pinMode(encoderPin2, INPUT);
  34.  
  35.   // Attach interrupts for encoder
  36.   attachInterrupt(digitalPinToInterrupt(encoderPin1), readEncoder, CHANGE);
  37.   attachInterrupt(digitalPinToInterrupt(encoderPin2), readEncoder, CHANGE);
  38.  
  39.   // Initialize PID controller
  40.   Setpoint = 200; // Desired RPM
  41.   myPID.SetMode(AUTOMATIC);
  42.   myPID.SetOutputLimits(-255, 255);
  43.  
  44.   Serial.begin(115200);
  45. }
  46.  
  47. void loop() {
  48.   // Read the current speed from the encoder
  49.   Input = readRPM();
  50.  
  51.   // Run the PID computation if sample time has passed
  52.   if (millis() - lastTime >= sampleTime) {
  53.     lastTime = millis();
  54.     myPID.Compute();
  55.    
  56.     // Control the motor based on PID output
  57.     if (Output > 0) {
  58.       analogWrite(motorPin1, Output);
  59.       analogWrite(motorPin2, 0);
  60.     } else {
  61.       analogWrite(motorPin1, 0);
  62.       analogWrite(motorPin2, -Output);
  63.     }
  64.  
  65.     Serial.print("RPM: ");
  66.     Serial.println(Input);
  67.   }
  68. }
  69.  
  70. // Encoder reading function
  71. void readEncoder() {
  72.   int state1 = digitalRead(encoderPin1);
  73.   int state2 = digitalRead(encoderPin2);
  74.   if (state1 == state2) {
  75.     encoderPos++;
  76.   } else {
  77.     encoderPos--;
  78.   }
  79. }
  80.  
  81. // Function to calculate RPM
  82. double readRPM() {
  83.   int deltaPos = encoderPos - encoderPosLast;
  84.   encoderPosLast = encoderPos;
  85.   return (deltaPos / 20.0) * 60.0; // Convert to RPM
  86. }
  87.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement