Rotary Encoder Decoder on mbed

Dependencies:   mbed

main.cpp

Committer:
hiromasaoku
Date:
2013-03-19
Revision:
0:665fbfcccab8

File content as of revision 0:665fbfcccab8:

#include "mbed.h"
#define PI 3.1415

InterruptIn clockEncoderPin(p5);
DigitalIn directionPin(p6);


Serial pc(USBTX, USBRX);

unsigned int encoderPos = 0;
float velo_rad = 0;
float angle_pos=0;

unsigned long time_before = 0;

bool newSpeed = false;
bool directionBool = true;

float deltaAngle = PI / 32;
Timer timer;

void encoder() {
    time_before = timer.read_us();
    directionBool = directionPin;
    if (directionBool) {
    angle_pos += PI / 32.0;
    encoderPos++; 
    }
    else {
    angle_pos -= PI / 32.0;
    encoderPos--;
    }
    newSpeed = true;
 } 
   
int main() {
    clockEncoderPin.rise(&encoder);
    timer.start();
    while(1) {
        if(newSpeed){
            unsigned long deltaT = timer.read_us();
            timer.reset();
            velo_rad = 1000000.0 * (float)deltaAngle / (float)deltaT * (directionBool? 1: -1);
            pc.printf("%f    " , velo_rad);
            newSpeed = false;
            //timer.reset();
        }
        
    }
}