Sports Biomechanics Lab > Blog > Encoder Counting Code
Personal tools

Encoder Counting Code

by Eric Chan — last modified Feb 08, 2010 01:15 PM

Here is the code used for measuring the number of clock pulses per change in the encoder signal. It would appear that with timer 1, the internal clock counter can count up to 2^16. With an internal clock of 16MHz, the clock can only count to a maximum of 4.096 milliseconds. With 1024 hi/lo transitions on the encoder wheel, this means that we cannot get accurate readings if the wheel turns slower than 1 revolution per .004096*1024 seconds ( 0.238 rotations per second. With a 700cc tire, that means speeds below 0.5 m/s cannot be measured accurately. This is equivalent to about 1.12 MPH, which is a speed that the bike will not be tested at. Thus, the following code should be sufficient for the tests to be conducted.

volatile unsigned int counts;

void setup()
{
  Serial.begin(9600);
  // 0 for digital pin 2, 1 for digital pin 3
  attachInterrupt(0, storeCount, CHANGE); 

  //  TCCR1A=0b00000000; // normal counter mode pg135 
  bitClear(TCCR1A, 7);
  bitClear(TCCR1A, 6);
  bitClear(TCCR1A, 5);
  bitClear(TCCR1A, 4);
  bitClear(TCCR1A, 1);
  bitClear(TCCR1A, 0);
  //  TCCR1B=0b00000001; // set prescaler to 1 pg137
  bitClear(TCCR1B, 7);
  bitClear(TCCR1B, 6);
  bitClear(TCCR1B, 4);
  bitClear(TCCR1B, 3);
  bitClear(TCCR1B, 2);
  bitClear(TCCR1B, 1);
  bitSet(TCCR1B, 0);     // prescaler of 1
  // TCCR1C=0b00000000;
  bitClear(TCCR1C, 7);
  bitClear(TCCR1C, 6);
  // Check to make sure TCCR1n is as noted
  Serial.println(TCCR1A,BIN);
  Serial.println(TCCR1B,BIN);
  Serial.println(TCCR1C,BIN);
}

void loop()
{
  Serial.println(counts);
}

void storeCount()
{
  // stop clock
  bitClear(TCCR1B,0);
  counts=TCNT1;
  TCNT1=0x00;  // reset clock
  // start clock
  bitSet(TCCR1B,0);
}
 
Document Actions
Add comment

You can add a comment by filling out the form below. Plain text formatting.

(Required)
Please enter your name.
(Required)
(Required)
(Required)
Enter the word