Interface for the encoder of the red fischertechnik motors

Dependencies:   NeedfulThings

Simple Interface for the simple encoder of the red fischertechnik motors.

The interface counts both, rising and falling edges, resulting in 150 counts per revolution. The interface also provides a speed measurement updated with each edge.

Connect the green wire to GND, the red one to +3.3V and the black signal line to any of mbed numbered pins. Additionally connect the signal line via a pullup resitor to +3.3V. A 10K resistor works fine.

Revision:
1:9e595056c3da
Parent:
0:8cb1142a88d5
Child:
2:1bf9f7b6bf29
diff -r 8cb1142a88d5 -r 9e595056c3da FtEncoder.cpp
--- a/FtEncoder.cpp	Thu Mar 14 18:27:24 2013 +0000
+++ b/FtEncoder.cpp	Wed Mar 20 21:42:39 2013 +0000
@@ -1,16 +1,21 @@
 #include "FtEncoder.h"
 
 FtEncoder::FtEncoder(PinName pwm, unsigned int standStillTimeout)
-    :m_encIRQ(pwm), m_cnt(0), m_standStillTimeout(standStillTimeout), m_cursor(0), m_ready(false)
+    :m_encIRQ(pwm),
+     m_cnt(0),
+     m_standStillTimeout(standStillTimeout),
+     m_cursor(0)
 {
+    // initialize the edge timestamp ringbuffer
     unsigned int tmStmp = getCurrentTimeStamp() - c_nTmStmps * m_standStillTimeout;
-    for(int i=0; i<c_nTmStmps-1; ++i)
+    for(int i=0; i<c_nTmStmps; ++i)
         m_timeStamps[i] = tmStmp + i*m_standStillTimeout;
     m_cursor = c_nTmStmps-1;
 
+    m_encIRQ.mode(PullUp); // set it to pullup, but an external pullup is needed, the internal isn't sufficient
     m_encIRQ.rise(this, &FtEncoder::encoderISR);
     m_encIRQ.fall(this, &FtEncoder::encoderISR);
-    m_tmOut.attach_us(this, &FtEncoder::encoderISR, m_standStillTimeout);
+    m_tmOut.attach_us(this, &FtEncoder::timeoutISR, m_standStillTimeout);
 }
 
 unsigned int FtEncoder::getLastPeriod() const
@@ -21,7 +26,7 @@
         cursor = m_cursor;
         cnt = m_cnt;
         period = m_timeStamps[m_cursor] - m_timeStamps[(m_cursor-2)&(c_nTmStmps-1)];
-    } while(cursor!=m_cursor || cnt!=m_cnt); // stay in loop until we have an non intrrupted reading
+    } while(cursor!=m_cursor || cnt!=m_cnt); // stay in loop until we have a non intrrupted reading
     return period;
 }
 
@@ -37,8 +42,14 @@
     ++m_cursor;
     m_cursor &= c_nTmStmps-1;
     m_timeStamps[m_cursor] = getCurrentTimeStamp();
+    // restart the timeout
     m_tmOut.detach();
-    m_tmOut.attach_us(this, &FtEncoder::encoderISR, m_standStillTimeout);
+    m_tmOut.attach_us(this, &FtEncoder::timeoutISR, m_standStillTimeout);
+    ++m_cnt;
     m_callBack.call();
-    ++m_cnt;
+}
+
+void FtEncoder::timeoutISR(){
+    --m_cnt;
+    encoderISR();
 }
\ No newline at end of file