Shivanand Gowda / Mbed 2 deprecated Rotory_Encoder

Dependencies:   mbed-rtos mbed

Fork of rtos_basic by mbed official

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 
00002 
00003 
00004 #include "mbed.h"
00005 
00006 DigitalIn aPin(D2);
00007 DigitalIn bPin(D3);
00008 DigitalIn buttonPin(D4);
00009 DigitalOut redPin(D5);
00010 DigitalOut yellowPin(D6);
00011 DigitalOut greenPin(D7);
00012 
00013 void setLights (int red, int yellow, int green);
00014 float getEncoderTurn ();
00015 int setState ();
00016 int longPeriod = 5000; // Time at green or red
00017 int shortPeriod = 700; // Time period when changing
00018 int targetCount = shortPeriod;
00019 int count = 0;
00020 int state=0;
00021 int main()
00022 {
00023 
00024 while(1)
00025 {
00026   count++;
00027   if (buttonPin==1)
00028   {
00029     setLights (1, 1, 1);
00030   }
00031   else
00032   {
00033     int change = getEncoderTurn ();
00034     int newPeriod = longPeriod + (change * 1);
00035     if (newPeriod  >= 1000 && newPeriod <= 10000)
00036     {
00037       longPeriod = newPeriod;
00038     }
00039     if (count> targetCount)
00040     {
00041       setState ();
00042       count = 0;
00043     }
00044   }
00045  wait_ms(1);
00046 }
00047 
00048 }
00049 float getEncoderTurn ()
00050 {
00051   // Return -1, 0, or +1
00052   static float oldA = 0;
00053   static float oldB= 0;
00054   float result = 0;
00055   float newA = aPin.read();
00056   float newB = bPin.read();
00057   
00058   
00059   if (newA != oldA || newB != oldB)
00060   {
00061     //Something has changed
00062     if (oldA == 0 && newA == 1)
00063     {
00064       result = - (oldB * 2 - 1);
00065     }
00066   }
00067   oldA = newA;
00068   oldB = newB;
00069   return result;
00070 }
00071 int setState ()
00072 {
00073   if (state == 0)
00074   {
00075     setLights (1, 0, 0);
00076     targetCount = longPeriod;
00077     state = 1;
00078   }
00079   else if (state == 1)
00080   {
00081     setLights (1, 1, 0);
00082     targetCount = shortPeriod;
00083     state = 2;
00084   }
00085   else if (state == 2)
00086   {
00087     setLights (0, 0, 1);
00088     targetCount = longPeriod;
00089     state = 3;
00090   }
00091   else if (state == 3)
00092   {
00093     setLights (0,1,0);
00094     targetCount = shortPeriod;
00095     state = 0;
00096   }
00097 }
00098 void setLights (int red, int yellow, int green)
00099 {
00100     redPin=red;
00101     yellowPin= yellow;
00102     greenPin= green;
00103 }