Sports Biomechanics Lab > Blog > Encoder Counting Code
Personal tools

Encoder Counting Code

by Eric Chan — last modified Feb 08, 2010 12:35 PM

This is the basic arduino code used for counting clock tics between encoder pulses.

Basic code rundown: 

 

Set timer1/counter1 prescaler to 1, thus incrementing at 16MHz.

Interrupt triggers on changing encoder reading.

On interrupt, clock is stopped, stored, reset, and restarted.

Last stored clock value is displayed in a loop.

 
//begin code
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()
{
  bitClear(TCCR1B,0);      // stop clock
  counts=TCNT1;            // store clock
  TCNT1=0x00;              // reset clock
  bitSet(TCCR1B,0);        // start clock
}
// end code
 
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