QEIx4 Example

Dependencies:   QEIx4 mbed

Revision:
2:7c787d83331e
Parent:
0:bbf48777e304
Child:
3:922c100de8cd
--- a/main.cpp	Tue Sep 02 18:29:18 2014 +0000
+++ b/main.cpp	Tue Sep 30 12:35:07 2014 +0000
@@ -1,32 +1,52 @@
 #include "mbed.h"
 #include "QEIx4.h"
 
-DigitalOut myled(LED1);
+DigitalOut LEDalive(LED1);
+DigitalOut LEDup(LED4);
+DigitalOut LEDdown(LED3);
+
 Timer t;
 
 // ports for nxp LPC 1768
-QEIx4 qei1(p30, p29, p28);          // QEI with index signal for zeroing
-QEIx4 qei2(p27, p26, NC);           // QEI only with AB signals
-QEIx4 qei3(p25, p24, NC, false);    // QEI without interrups for polling mode
+QEIx4 qei1(p30, p29, p28, (QEIx4::EMODE)(QEIx4::IRQ | QEIx4::SPEED));          // QEI with index signal for zeroing
+QEIx4 qei2(p21, p22, NC,  QEIx4::IRQ_NO_JAMMING);           // QEI with AB signals only
+QEIx4 qei3(p25, p24, NC,  QEIx4::POLLING);    // QEI without interrups in polling mode
+
+// The callback function.
+void myCallback(int value)
+{
+    static int valueLast=-1;
 
-int main() {
+    if ( value > valueLast ) {
+        LEDup = !LEDup;
+        LEDdown = 0;
+    } else {
+        LEDdown = !LEDdown;
+        LEDup = 0;
+    }
+    valueLast=value;
+}
+
+int main()
+{
     t.start();
 
-    qei1.SetZeroOnIndex(true);      // Set the flag to zero counter on next index signal rises
+    qei1.setZeroOnIndex(true);      // set the flag to zero counter on next index signal rises
+    qei1.setSpeedFactor(1.0f);      // factor to scale from Hz (edges pe second = 4 * CPS) to user units (1.0=Hz, 1/(4*CPR)=rps, 1/(60*4*CPR)=rpm, 360/(4*CPR)=°/s, ...)
+    
+    qei3.attachCounterChange(myCallback);
 
-    while(1) 
-    {
+    while(1) {
         qei3.poll();   // poll manually without interrupt - sampling in this loop with about 2kHz
-        
-        if ( t.read_ms() > 500 )   // every half second
-        {
+
+        if ( t.read_ms() > 250 ) { // every quater second (4 Hz)
             t.reset();
             t.start();
-            myled = !myled;
-            
-            printf ( "\r\n%6d %6d %6d", (int)qei1, (int)qei2, (int)qei3 );   // print counter values
+            LEDalive = !LEDalive;
+
+            printf ( "\r\n%6d  %6d  %6d  %10.3f", (int)qei1, (int)qei2, (int)qei3, (float)qei1.getSpeed() );   // print counter values
         }
 
-    wait_us(500);   // for about 2kHz
+        wait_us(20);   // for about 50kHz polling
     }
 }