Using Rotary Encoder/Arduino To Find Shaft Rotation Time

I am currently working on my Senior Project for schooling. The project involves a shaft that will be rotating, and we are trying to use an Arduino UNO to measure the time of rotation. The code I am currently using functionally operates only part of the time. When the shaft of the encoder stops on the right pulsing location, the output continues to count. The timer will stop if the shaft ends in the right location. Here is a link to the website that helps explain the encoder we are using. Please offer any advise regarding the code or the encoder. How to connect optical rotary encoder with Arduino - Electric Diy Lab

void setup() {
  Serial.begin (9600);

  pinMode(2, INPUT_PULLUP); // internal pullup input pin 2 
  
  pinMode(3, INPUT_PULLUP); // internal pullup input pin 3
  
  }

  double i = 0;
  double a;
  double c;
   
  void loop() 
  {
  // Send the value of counter
  if(digitalRead(2)==HIGH)
  {
    a = millis();
    while(digitalRead(2)==HIGH)
    while(digitalRead(3)==LOW)
    while(digitalRead(3)==HIGH)
  {
    c = millis();
    i = (c - a) / 1000;
    Serial.println(c);
    Serial.println(a);
    Serial.println(i);
    Serial.println("-------");
    delay(100);
  }
    while(digitalRead(2)==HIGH)
        while(digitalRead(3)==LOW)
            while(digitalRead(3)==HIGH) {
                  c = millis();
                  i = (c - a) / 1000;
                 Serial.println(c);
                 Serial.println(a);
                 Serial.println(i);
                 Serial.println("-------");
                 delay(100);
            }

I do believe I have never seen a block of code like that, and it will take a minute to see what you could possibly be meaning to do.

Also, please post code that compiles.

Also, wondering about the delay() in there.

It would probably be simpler to use regular encoder methods, or even a library, and watch what it reports rather than looking at the individual pins.

a7

one approach it to monitor the changes in the encoder which allow tracking its position and capturing a timestamp with each change.

tracking the encoder requires recognizing the change of one of the inputs. (the state of the other indicates direction).

if there are N encoder tics per revolution, calculate the change in time every N tics and the shaft rotation, 1 / (t1 - t0)

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.