Skip to content

Categories:

Cytron Optical Encoder with Arduino

One of the advantages of a vehicle with variable track width is that it can easily counteract the forces due to centrifugal acceleration. This acceleration can be calculated as the square of the velocity divided by the radius of curvature of the vehicle. The controller will therefore need to monitor the vehicle’s instantaneous velocity since the radius of curvature can be determined geometrically from the arm positions.

There are many ways to measure velocity with a microcontroller, and I have chosen to use an optical encoder to as the rotational direction provided by mechanical quadrature encoders is not necessary. Specifically, I am using a Cytron simple rotary encoder kit, available here. It is simple and relatively cheap, but I was unable to find any sample code to measure velocity with an Arduino. I wrote my own and have posted it below, hopefully it is helpful to someone just learning. It uses interrupts to count the pulses of the encoder and then sends the velocity serially every second. The wheel radius and rate of velocity calculations can be adjusted as desired. It is important to note that the current_time variable has to be volatile so it doesn’t get buried under the stack when other processes are running.

The 5v and ground pins can use the Arduino’s built in supply, and the signal pin is connected to digital pin 2:The Code:

int hits = 0;
float wheel_radius = 1;
volatile unsigned int current_time;
long time_interval = 1000; //how often do you want to know velocity (milliseconds)
float velocity; //this is the velocity in length units / time_interval

void setup ()
{
  Serial.begin(9600);
  attachInterrupt(0, count, CHANGE);
  current_time = millis();
}

void loop ()
{
  if ( millis() >= current_time + time_interval)
  {
    velocity = (hits*(wheel_radius * 392.7))/time_interval;//the constant is 2*pi*1000/16
    Serial.println(velocity);
    hits = 0;
    current_time = millis();
  }
}  

void count()
{
 hits++;
}

Posted in Uncategorized. Tagged with , , .

2 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. Chris said

    Hi, Gavin
    Great code but how would you do two encoders? I want to use two encoders to give my velocity average in x-y.

    Thanks,
    Chris

  2. admin said

    You would need to attach the second encoder’s signal to the arduino’s other interrupt pin (interrupt 0 is digital pin 2, interrupt 1 is digital pin 3) then just create new velocity and hits variables for the second wheel and a new count function.

Some HTML is OK

(required)

(required, but never shared)

or, reply to this post via trackback.

Powered by WP Hashcash