Advertisement
Guest User

Untitled

a guest
Jun 18th, 2024
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.14 KB | None | 0 0
  1. #include <CapacitiveSensor.h>
  2.  
  3. #define touchSendPin 14
  4. #define touchReceivePin 15
  5.  
  6. //Arduino Pin Assignments
  7. const int motorDown    = 18;   //H-Bridge control to make the motor go down
  8. const int motorUp      = 19;   //H-Bridge control to make the motor go up
  9.  
  10. //Inputs
  11. const int wiper        = 17;   //Position of fader relative to GND
  12. const int pot          = 16;   //Potentiometer to set position of fader
  13.  
  14. double faderMax        = 0;   //Value read by fader's maximum position (0-1023)
  15. double faderMin        = 0;   //Value read by fader's minimum position (0-1023)
  16.  
  17. CapacitiveSensor touchSensor(touchSendPin, touchReceivePin);
  18.  
  19. volatile bool touched  = false; //Is the fader currently being touched?
  20.  
  21. long previousTime = 0;
  22. float ePrevious = 0;
  23. float eIntegral = 0;
  24.  
  25. int position = analogRead(wiper);
  26.  
  27. void setup() {
  28.   Serial.begin(9600);
  29.   pinMode (motorUp, OUTPUT);
  30.   pinMode (motorDown, OUTPUT);
  31. }
  32.  
  33. void loop()                    
  34. {
  35.   checkTouch();
  36.  
  37.   // Setpoint
  38.   int target = analogRead(pot);
  39.   position = analogRead(wiper);
  40.  
  41.   float kp = 2.0;
  42.   float kd = 0.1;
  43.   float ki = 0.01;
  44.   float u = pidController(target, kp, kd, ki);
  45.  
  46.   if (!touched) {
  47.     moveMotor(u);
  48.   }
  49.  
  50.   Serial.print(target);
  51.   Serial.print(", ");
  52.   Serial.println(position);
  53.  
  54. }
  55.  
  56. float pidController(int target, float kp, float kd, float ki) {
  57.   long currentTime = micros();
  58.   float deltaT = ((float)(currentTime - previousTime)) / 1.0e6;
  59.  
  60.   int e = position - target;
  61.   float eDerivative = (e - ePrevious) / deltaT;
  62.   eIntegral = eIntegral + e * deltaT;
  63.  
  64.   float u = (kp * e) + (kd * eDerivative) + (ki * eIntegral);
  65.  
  66.   previousTime = currentTime;
  67.   ePrevious = e;
  68.  
  69.   return u;
  70. }
  71.  
  72. void moveMotor(float u) {
  73.   float speed = fabs(u);
  74.   if (speed > 255) {
  75.     speed = 255;
  76.   }
  77.  
  78.   if (u < 0) {
  79.     analogWrite(motorUp, LOW);
  80.     analogWrite(motorDown, speed);
  81.   } else if (u > 0) {
  82.     analogWrite(motorDown, LOW);
  83.     analogWrite(motorUp, speed);
  84.   } else {
  85.     analogWrite(motorUp, LOW);
  86.     analogWrite(motorDown, LOW);
  87.   }
  88. }
  89.  
  90. void checkTouch() {
  91.   touched = touchSensor.capacitiveSensor(30) > 3000;
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement