Rotary Encoder Decoder on mbed

Dependencies:   mbed

Committer:
hiromasaoku
Date:
Tue Mar 19 05:34:46 2013 +0000
Revision:
0:665fbfcccab8
Rotary Encoder Decoder on mbed.

Who changed what in which revision?

UserRevisionLine numberNew contents of line
hiromasaoku 0:665fbfcccab8 1 #include "mbed.h"
hiromasaoku 0:665fbfcccab8 2 #define PI 3.1415
hiromasaoku 0:665fbfcccab8 3
hiromasaoku 0:665fbfcccab8 4 InterruptIn clockEncoderPin(p5);
hiromasaoku 0:665fbfcccab8 5 DigitalIn directionPin(p6);
hiromasaoku 0:665fbfcccab8 6
hiromasaoku 0:665fbfcccab8 7
hiromasaoku 0:665fbfcccab8 8 Serial pc(USBTX, USBRX);
hiromasaoku 0:665fbfcccab8 9
hiromasaoku 0:665fbfcccab8 10 unsigned int encoderPos = 0;
hiromasaoku 0:665fbfcccab8 11 float velo_rad = 0;
hiromasaoku 0:665fbfcccab8 12 float angle_pos=0;
hiromasaoku 0:665fbfcccab8 13
hiromasaoku 0:665fbfcccab8 14 unsigned long time_before = 0;
hiromasaoku 0:665fbfcccab8 15
hiromasaoku 0:665fbfcccab8 16 bool newSpeed = false;
hiromasaoku 0:665fbfcccab8 17 bool directionBool = true;
hiromasaoku 0:665fbfcccab8 18
hiromasaoku 0:665fbfcccab8 19 float deltaAngle = PI / 32;
hiromasaoku 0:665fbfcccab8 20 Timer timer;
hiromasaoku 0:665fbfcccab8 21
hiromasaoku 0:665fbfcccab8 22 void encoder() {
hiromasaoku 0:665fbfcccab8 23 time_before = timer.read_us();
hiromasaoku 0:665fbfcccab8 24 directionBool = directionPin;
hiromasaoku 0:665fbfcccab8 25 if (directionBool) {
hiromasaoku 0:665fbfcccab8 26 angle_pos += PI / 32.0;
hiromasaoku 0:665fbfcccab8 27 encoderPos++;
hiromasaoku 0:665fbfcccab8 28 }
hiromasaoku 0:665fbfcccab8 29 else {
hiromasaoku 0:665fbfcccab8 30 angle_pos -= PI / 32.0;
hiromasaoku 0:665fbfcccab8 31 encoderPos--;
hiromasaoku 0:665fbfcccab8 32 }
hiromasaoku 0:665fbfcccab8 33 newSpeed = true;
hiromasaoku 0:665fbfcccab8 34 }
hiromasaoku 0:665fbfcccab8 35
hiromasaoku 0:665fbfcccab8 36 int main() {
hiromasaoku 0:665fbfcccab8 37 clockEncoderPin.rise(&encoder);
hiromasaoku 0:665fbfcccab8 38 timer.start();
hiromasaoku 0:665fbfcccab8 39 while(1) {
hiromasaoku 0:665fbfcccab8 40 if(newSpeed){
hiromasaoku 0:665fbfcccab8 41 unsigned long deltaT = timer.read_us();
hiromasaoku 0:665fbfcccab8 42 timer.reset();
hiromasaoku 0:665fbfcccab8 43 velo_rad = 1000000.0 * (float)deltaAngle / (float)deltaT * (directionBool? 1: -1);
hiromasaoku 0:665fbfcccab8 44 pc.printf("%f " , velo_rad);
hiromasaoku 0:665fbfcccab8 45 newSpeed = false;
hiromasaoku 0:665fbfcccab8 46 //timer.reset();
hiromasaoku 0:665fbfcccab8 47 }
hiromasaoku 0:665fbfcccab8 48
hiromasaoku 0:665fbfcccab8 49 }
hiromasaoku 0:665fbfcccab8 50 }