Rotory_Encoder

Dependencies:   mbed-rtos mbed

Fork of rtos_basic by mbed official

main.cpp

Committer:
shivanandgowdakr
Date:
2018-08-06
Revision:
12:8149e37ca456
Parent:
11:0309bef74ba8

File content as of revision 12:8149e37ca456:




#include "mbed.h"

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);
}

}
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;
}