Advertisement
Guest User

Untitled

a guest
May 27th, 2015
241
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1. // (Really Simple) PID Class by Ivan Seidel
  2. // GitHub.com/ivanseidel
  3. // Use as you want. Leave credits
  4.  
  5. class PID{
  6. public:
  7.  
  8. double error;
  9. double sample;
  10. double lastSample;
  11. double kP, kI, kD;
  12. double P, I, D;
  13. double pid;
  14.  
  15. double setPoint;
  16. long lastProcess;
  17.  
  18. PID(double _kP, double _kI, double _kD){
  19. kP = _kP;
  20. kI = _kI;
  21. kD = _kD;
  22. }
  23.  
  24. void addNewSample(double _sample){
  25. sample = _sample;
  26. }
  27.  
  28. void setSetPoint(double _setPoint){
  29. setPoint = _setPoint;
  30. }
  31.  
  32. double process(){
  33. // Implementação P ID
  34. error = setPoint - sample;
  35. float deltaTime = (millis() - lastProcess) / 1000; ;
  36. lastProcess = millis();
  37.  
  38. //P
  39. P = error * kP;
  40.  
  41. //I
  42. I = I + (error * kI) * (deltaTime/1000);
  43.  
  44. //D
  45. D = (lastSample - sample) * kD / deltaTime;
  46. lastSample = sample;
  47.  
  48. // Soma tudo
  49. pid = P + I + D;
  50.  
  51. return pid;
  52. }
  53. };
  54.  
  55. #define pSENSOR A1
  56. #define pCONTROLE 3
  57.  
  58. PID meuPid(1.0, 0, 0);
  59.  
  60. void setup() {
  61. Serial.begin(9600);
  62.  
  63. pinMode(pSENSOR, INPUT);
  64. pinMode(pCONTROLE, OUTPUT);
  65. }
  66.  
  67. int controlePwm = 50;
  68.  
  69. void loop() {
  70.  
  71. // Lê temperatura
  72. double temperature = map(analogRead(pSENSOR), 0, 1023, 0, 100);
  73.  
  74. // Manda pro objeto PID!
  75. meuPid.addNewSample(temperature);
  76.  
  77.  
  78. // Converte para controle
  79. controlePwm = (meuPid.process() + 50);
  80. // Saída do controle
  81. analogWrite(pCONTROLE, controlePwm);
  82.  
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement