Advertisement
NaroxEG

Line follower

May 2nd, 2024 (edited)
498
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.01 KB | None | 0 0
  1. #define leftMotorPin 3;
  2. #define rightMotorPin 5;
  3. #define leftIRPin A0;
  4. #define centerIRPin A1;
  5. #define rightIRPin A2;
  6.  
  7. #define setpoint 512; // analogRead returns 0-1023
  8.  
  9. // PID
  10. #define Kp 0.5;
  11. #define Ki 0.0;
  12. #define Kd 0.0;
  13.  
  14. double input, output;
  15. double previous_leftError = 0;
  16. double previous_centerError = 0;
  17. double previous_rightError = 0;
  18. double integral = 0;
  19.  
  20. #define sampleTime 100; // in milliseconds
  21. #define maxOutput 255;
  22.  
  23. unsigned long previousMillis = 0;
  24.  
  25. void setup() {
  26.   pinMode(leftMotorPin, OUTPUT);
  27.   pinMode(rightMotorPin, OUTPUT);
  28.  
  29.   pinMode(leftIRPin, INPUT);
  30.   pinMode(centerIRPin, INPUT);
  31.   pinMode(rightIRPin, INPUT);
  32. }
  33.  
  34. void loop() {
  35.   unsigned long currentMillis = millis();
  36.   if (currentMillis - previousMillis >= sampleTime) {
  37.     int leftIR = analogRead(leftIRPin);
  38.     int centerIR = analogRead(centerIRPin);
  39.     int rightIR = analogRead(rightIRPin);
  40.  
  41.     int leftError = leftIR - setpoint;
  42.     int centerError = centerIR - setpoint;
  43.     int rightError = rightIR - setpoint;
  44.  
  45.     double dt = (currentMillis - previousMillis) / 1000.0; // Convert milliseconds to seconds
  46.     double leftDerivative = (leftError - previous_leftError) / dt;
  47.     double centerDerivative = (centerError - previous_centerError) / dt;
  48.     double rightDerivative = (rightError - previous_rightError) / dt;
  49.  
  50.     output = Kp * (leftError + centerError + rightError) + Ki * integral + Kd * (leftDerivative + centerDerivative + rightDerivative);
  51.  
  52.     // Limit the output to the maximum value
  53.     output = constrain(output, -maxOutput, maxOutput);
  54.  
  55.     integral += (leftError + centerError + rightError);
  56.  
  57.     previous_leftError = leftError;
  58.     previous_centerError = centerError;
  59.     previous_rightError = rightError;
  60.  
  61.     previousMillis = currentMillis;
  62.  
  63.     int leftSpeed = constrain(255 - output, -255, 255);
  64.     int rightSpeed = constrain(255 + output, -255, 255);
  65.  
  66.     // Update motor speeds
  67.     analogWrite(leftMotorPin, leftSpeed);
  68.     analogWrite(rightMotorPin, rightSpeed);
  69.  }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement