Advertisement
Guest User

Untitled

a guest
Dec 10th, 2016
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.37 KB | None | 0 0
  1.  
  2. #include<Servo.h>
  3. #include<PID_v1.h>
  4.  
  5.  
  6. const int servoPin = 9; //Servo Pin
  7.  
  8. float Kp = .08; //Initial Proportional Gain
  9. float Ki = 0.55; //Initial Integral Gain
  10. float Kd = 0; //Intitial Derivative Gain
  11. double Setpoint, Input, Output, ServoOutput;
  12.  
  13. PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, REVERSE); //Initialize PID object, which is in the class PID.
  14.  
  15. Servo myServo; //Initialize Servo.
  16.  
  17.  
  18. void setup() {
  19.  
  20.  
  21. Serial.begin(9600); //Begin Serial
  22. myServo.attach(servoPin); //Attach Servo
  23. pinMode(7, INPUT);
  24. Input = pulseIn(7, HIGH); //Calls function readPosition() and sets the balls
  25.  
  26. myPID.SetMode(AUTOMATIC); //Set PID object myPID to AUTOMATIC
  27. myPID.SetOutputLimits(-15, 15);
  28. }
  29.  
  30. float a1, a2, a3, a4, a5, runAvg;
  31. unsigned long duration;
  32. unsigned long lastDuration = 0;
  33.  
  34. void loop()
  35. {
  36. if(Serial.available()){
  37. Kp = Serial.readString().toFloat();
  38. }
  39.  
  40. Serial.print("Kp: ");
  41. Serial.print(Kp);
  42. Serial.print("\t");
  43. Serial.print("Kd: ");
  44. Serial.print(Kd);
  45.  
  46. myPID.SetTunings(Kp, Kd, Ki);
  47.  
  48. //Code for running average:
  49. duration = pulseIn(7, HIGH);
  50. long diff = abs(duration - lastDuration);
  51. if (diff <= 180) {
  52. a5 = a4;
  53. a4 = a3;
  54. a3 = a2;
  55. a2 = a1;
  56. a1 = duration;
  57.  
  58. runAvg = (a1 + a2 + a3 + a4 + a5) / 5;
  59. }
  60. lastDuration = duration;
  61.  
  62. Setpoint = 560;
  63. Input = runAvg;
  64. Serial.print("\tInput: ");
  65. Serial.print(Input);
  66.  
  67. myPID.Compute(); //computes Output in range of -80 to 80 degrees
  68.  
  69. Serial.print("\tOutput: ");
  70. Serial.print(Output);
  71.  
  72.  
  73.  
  74. ServoOutput = 110 + Output; // 110 degrees is my horizontal
  75. Serial.print("\tServoInput: ");
  76.  
  77. Serial.println(ServoOutput);
  78.  
  79.  
  80.  
  81. myServo.write(ServoOutput); //Writes value of Output to servo
  82.  
  83.  
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement