Rotory_Encoder

Dependencies:   mbed-rtos mbed

Fork of rtos_basic by mbed official

Files at this revision

API Documentation at this revision

Comitter:
shivanandgowdakr
Date:
Mon Aug 06 10:34:28 2018 +0000
Parent:
11:0309bef74ba8
Commit message:
Rotary_Encoder

Changed in this revision

main.cpp Show annotated file Show diff for this revision Revisions of this file
diff -r 0309bef74ba8 -r 8149e37ca456 main.cpp
--- a/main.cpp	Wed Feb 15 14:04:02 2017 -0600
+++ b/main.cpp	Mon Aug 06 10:34:28 2018 +0000
@@ -1,22 +1,103 @@
+
+
+
 #include "mbed.h"
-#include "rtos.h"
- 
-DigitalOut led1(LED1);
-DigitalOut led2(LED2);
-Thread thread;
- 
-void led2_thread() {
-    while (true) {
-        led2 = !led2;
-        Thread::wait(1000);
+
+DigitalIn aPin(D2);
+DigitalIn bPin(D3);
+DigitalIn buttonPin(D4);
+DigitalOut redPin(D5);
+DigitalOut yellowPin(D6);
+DigitalOut greenPin(D7);
+
+void setLights (int red, int yellow, int green);
+float getEncoderTurn ();
+int setState ();
+int longPeriod = 5000; // Time at green or red
+int shortPeriod = 700; // Time period when changing
+int targetCount = shortPeriod;
+int count = 0;
+int state=0;
+int main()
+{
+
+while(1)
+{
+  count++;
+  if (buttonPin==1)
+  {
+    setLights (1, 1, 1);
+  }
+  else
+  {
+    int change = getEncoderTurn ();
+    int newPeriod = longPeriod + (change * 1);
+    if (newPeriod  >= 1000 && newPeriod <= 10000)
+    {
+      longPeriod = newPeriod;
+    }
+    if (count> targetCount)
+    {
+      setState ();
+      count = 0;
     }
+  }
+ wait_ms(1);
 }
- 
-int main() {
-    thread.start(led2_thread);
-    
-    while (true) {
-        led1 = !led1;
-        Thread::wait(500);
+
+}
+float getEncoderTurn ()
+{
+  // Return -1, 0, or +1
+  static float oldA = 0;
+  static float oldB= 0;
+  float result = 0;
+  float newA = aPin.read();
+  float newB = bPin.read();
+  
+  
+  if (newA != oldA || newB != oldB)
+  {
+    //Something has changed
+    if (oldA == 0 && newA == 1)
+    {
+      result = - (oldB * 2 - 1);
     }
+  }
+  oldA = newA;
+  oldB = newB;
+  return result;
 }
+int setState ()
+{
+  if (state == 0)
+  {
+    setLights (1, 0, 0);
+    targetCount = longPeriod;
+    state = 1;
+  }
+  else if (state == 1)
+  {
+    setLights (1, 1, 0);
+    targetCount = shortPeriod;
+    state = 2;
+  }
+  else if (state == 2)
+  {
+    setLights (0, 0, 1);
+    targetCount = longPeriod;
+    state = 3;
+  }
+  else if (state == 3)
+  {
+    setLights (0,1,0);
+    targetCount = shortPeriod;
+    state = 0;
+  }
+}
+void setLights (int red, int yellow, int green)
+{
+    redPin=red;
+    yellowPin= yellow;
+    greenPin= green;
+}
\ No newline at end of file