Advertisement
Guest User

Untitled

a guest
Jan 30th, 2023
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //define A pin for rotary encoder
  2. #define outputA 6
  3. //define B pin for rotary encoder
  4. #define outputB 7
  5. //define pin for pwm
  6. #define  PWM_pin  10
  7.  
  8. //define int for rotary encoder
  9.  int counter = 80;
  10.  int increment = 5;
  11.  int maxpwm = 180;
  12.  int minpwm = 35;
  13.  int aState;
  14.  int aLastState;
  15.  int truepwm = 0;
  16.  
  17. void setup() {
  18.    pinMode (outputA,INPUT_PULLUP);
  19.    pinMode (outputB,INPUT_PULLUP);
  20.    pinMode (PWM_pin, OUTPUT);
  21.  
  22. Serial.begin (115200);
  23.    // Reads the initial state of the outputA
  24.    aLastState = digitalRead(outputA);
  25.  
  26.  
  27.    //Speed up gently on firststart
  28.     for (int i = 25; i <= counter; i++) {
  29.     analogWrite(PWM_pin, i);
  30.     Serial.println(i);
  31.     delay(50);
  32. }
  33.     analogWrite(PWM_pin, counter);
  34.     Serial.println("Finished Start Sq  ");
  35.     Serial.print(counter);
  36. }
  37.  
  38. void loop() {
  39.   //Rotary encoder things
  40.    aState = digitalRead(outputA); // Reads the "current" state of the outputA
  41.    // If the previous and the current state of the outputA are different, that means a Pulse has occured
  42.    if (aState != aLastState){    
  43.      // If the outputB state is different to the outputA state, that means the encoder is rotating clockwise
  44.      if (digitalRead(outputB) != aState) {
  45.       if (counter >= maxpwm) {
  46.         counter = maxpwm;
  47.       } else {
  48.        counter = counter + increment;
  49.        }
  50.      } else {
  51.       if (counter <= minpwm) {
  52.         counter = minpwm;
  53.       } else {
  54.        counter = counter - increment;
  55.       }
  56.      }
  57.    }
  58.    aLastState = aState; // Updates the previous state of the outputA with the current state
  59.  
  60. //Set Speed
  61.    analogWrite(PWM_pin, counter);
  62.    Serial.println(counter);
  63. }
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement