Advertisement
pleasedontcode

Fuzzy Logic

Aug 22nd, 2024
380
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Arduino 1.90 KB | Source Code | 0 0
  1. // Define fuzzy sets for error and change in error
  2. #define LOW_ERROR 0
  3. #define MEDIUM_ERROR 1
  4. #define HIGH_ERROR 2
  5.  
  6. #define NEGATIVE 0
  7. #define ZERO 1
  8. #define POSITIVE 2
  9.  
  10. // Motor control pins
  11. const int motorPin1 = 18;
  12. const int motorPin2 = 19;
  13.  
  14. // Encoder input pins
  15. const int encoderPin1 = 34;
  16. const int encoderPin2 = 35;
  17.  
  18. // Variables for encoder and control
  19. volatile int encoderPos = 0;
  20. int encoderPosLast = 0;
  21. double speedSetpoint = 200;
  22. double speedMeasured = 0;
  23.  
  24. void setup() {
  25.   pinMode(motorPin1, OUTPUT);
  26.   pinMode(motorPin2, OUTPUT);
  27.   pinMode(encoderPin1, INPUT);
  28.   pinMode(encoderPin2, INPUT);
  29.  
  30.   attachInterrupt(digitalPinToInterrupt(encoderPin1), readEncoder, CHANGE);
  31.   attachInterrupt(digitalPinToInterrupt(encoderPin2), readEncoder, CHANGE);
  32.  
  33.   Serial.begin(115200);
  34. }
  35.  
  36. void loop() {
  37.   speedMeasured = readRPM();
  38.   int error = speedSetpoint - speedMeasured;
  39.   int dError = error - (speedSetpoint - encoderPosLast);
  40.   int output = fuzzyLogicControl(error, dError);
  41.  
  42.   // Control motor speed
  43.   analogWrite(motorPin1, output);
  44.   analogWrite(motorPin2, 0);
  45.  
  46.   Serial.print("RPM: ");
  47.   Serial.println(speedMeasured);
  48.   delay(100);
  49. }
  50.  
  51. void readEncoder() {
  52.   int state1 = digitalRead(encoderPin1);
  53.   int state2 = digitalRead(encoderPin2);
  54.   encoderPos += (state1 == state2) ? 1 : -1;
  55. }
  56.  
  57. double readRPM() {
  58.   int deltaPos = encoderPos - encoderPosLast;
  59.   encoderPosLast = encoderPos;
  60.   return (deltaPos / 20.0) * 60.0;  // Convert to RPM
  61. }
  62.  
  63. int fuzzyLogicControl(int error, int dError) {
  64.   int output = 0;
  65.  
  66.   // Fuzzy rules implementation
  67.   if (error == LOW_ERROR && dError == ZERO) {
  68.     output = 150; // Moderate speed
  69.   } else if (error == HIGH_ERROR && dError == POSITIVE) {
  70.     output = 255; // Full speed
  71.   } else if (error == LOW_ERROR && dError == NEGATIVE) {
  72.     output = 100; // Low speed
  73.   }
  74.   // Add more rules as necessary
  75.  
  76.   return output;
  77. }
  78.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement