Advertisement
Trainlover08

Basic PID library

Mar 5th, 2024 (edited)
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.80 KB | None | 0 0
  1. #pragma region VEXcode Generated Robot Configuration
  2. // Make sure all required headers are included.
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <stdbool.h>
  6. #include <math.h>
  7. #include <string.h>
  8.  
  9.  
  10. #include "vex.h"
  11.  
  12. using namespace vex;
  13.  
  14. // Brain should be defined by default
  15. brain Brain;
  16.  
  17.  
  18. // START V5 MACROS
  19. #define waitUntil(condition)                                                   \
  20.   do {                                                                         \
  21.     wait(5, msec);                                                             \
  22.   } while (!(condition))
  23.  
  24. #define repeat(iterations)                                                     \
  25.   for (int iterator = 0; iterator < iterations; iterator++)
  26. // END V5 MACROS
  27.  
  28.  
  29. // Robot configuration code.
  30. motor Motor1 = motor(PORT4, ratio18_1, false);
  31.  
  32.  
  33.  
  34.  
  35. // Helper to make playing sounds from the V5 in VEXcode easier and
  36. // keeps the code cleaner by making it clear what is happening.
  37. void playVexcodeSound(const char *soundName) {
  38.   printf("VEXPlaySound:%s\n", soundName);
  39.   wait(5, msec);
  40. }
  41.  
  42. #pragma endregion VEXcode Generated Robot Configuration
  43.  
  44. // Include the V5 Library
  45. #include "vex.h"
  46.  
  47. // Allows for easier use of the VEX Library
  48. using namespace vex;
  49.  
  50. int main (){
  51.   Motor1.setMaxTorque(20, percent);
  52.   Motor1.spin(forward);
  53.   float errorSum = 0.0;
  54.     float target = 50.0;
  55.     float pGain = 0.4;
  56.     float iGain = 0.0;
  57.     float dGain = 0.05;
  58.     while(true){
  59.     float r1 = Motor1.position(degrees);
  60.     wait(10, msec);
  61.     float r2 = Motor1.position(degrees);
  62.        
  63.     float error = target - r2;
  64.     errorSum = error + errorSum;
  65.     float deltaV = (r2 - r1) / 0.01;
  66.    
  67.     Motor1.setVelocity((error * pGain) + (errorSum * iGain) + (deltaV * dGain), percent);
  68.     }
  69.    
  70.     return 0;
  71. }
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement