title: How to control the motor using the rotary encoder
body: <p>I want to control the accuracy of the motor using a rotary encoder.</p>
  <p>For example, I want to move the motor to any side, for example, 70 degrees, and return to its original place using a rotary encoder. I wrote a code, but this code the motor does not move unless the rotary encode is moved.</p>
  <p>Used parts</p>
  <ul>
  <li>motor dc with gearbox</li>
  <li>arduino mega</li>
  <li>bts 7960</li>
  <li>encoder rotary</li>
  </ul>
  <p>Code:</p>
  <pre><code>// Rotary Encoder Inputs
  #define inputCLK 3
  #define inputDT 2
  int LPWM = 6; //   
  int LEN = 9; // 
  int RPWM =5; // 
  int REN = 8; // 
  int counter = 0; 
  int currentStateCLK;
  int previousStateCLK; 
  
  String encdir =&quot;&quot;;
   void setup() { 
    
    // Set encoder pins as inputs  
   pinMode (inputCLK,INPUT);
   pinMode (inputDT,INPUT);
   pinMode(LPWM, OUTPUT); 
   pinMode(RPWM, OUTPUT); 
   pinMode(LEN, OUTPUT);
   pinMode(REN, OUTPUT);
  
   digitalWrite(LEN, HIGH);
   digitalWrite(REN, HIGH);
      // Setup Serial Monitor
    Serial.begin (9600);
    
    // Read the initial state of inputCLK
    // Assign to previousStateCLK variable
    previousStateCLK = digitalRead(inputCLK);
  
  } 
  
  void loop() 
  { 
   
   // Read the current state of inputCLK
    currentStateCLK = digitalRead(inputCLK);
     
    // If the previous and the current state of the inputCLK are different then a pulse has occured
    if (currentStateCLK != previousStateCLK){ 
        
      // If the inputDT state is different than the inputCLK state then 
      // the encoder is rotating counterclockwise
      if (digitalRead(inputDT) != currentStateCLK) { 
        counter --;
        encdir =&quot;CCW&quot;;
          digitalWrite(RPWM,HIGH);   //move forward and backward
          digitalWrite(LPWM, LOW);
      
      } else {
        // Encoder is rotating clockwise
        counter ++;
        encdir =&quot;CW&quot;;
          digitalWrite(RPWM,LOW);
          digitalWrite(LPWM, HIGH);
              
      }
      Serial.print(&quot;Direction: &quot;);
      Serial.print(encdir);
      Serial.print(&quot; -- Value: &quot;);
      Serial.println(counter);
    } 
    // Update previousStateCLK with the current state
    previousStateCLK = currentStateCLK; 
  
  
  
  
  } 
  </code></pre>