Sumejja Porča Almir Husić

Dependencies:   mbed sMotor

main.cpp

Committer:
tim008
Date:
2014-06-09
Revision:
4:dae3f24939ab
Parent:
3:7f61e6ae0184

File content as of revision 4:dae3f24939ab:

#include "mbed.h"
#include "sMotor.h"
#include <string>
 
sMotor motor(dp9, dp10, dp11, dp13); // creates new stepper motor: IN1, IN2, IN3, IN4
Serial pc(USBTX, USBRX);

int step_speed = 1200 ; // set default motor speed
int numstep = 512 ; // defines full turn of 360 degree
int direction = 0; //0 for right, 1 for left

AnalogIn sensor(dp4);

enum State {Idle, Working};

State state = Idle;
int index = 0;
int buffer_size = 36;
int samples_num = 13;
float distances[13] = {15.0, 20.0, 25.0, 30.0, 35.0, 40.0, 45.0, 50.0, 55.0, 60.0, 65.0, 70.0, 75.0};
float voltages[13] = {0.78, 0.72, 0.63, 0.55, 0.47, 0.43, 0.39, 0.36, 0.34, 0.33, 0.32, 0.311, 0.31};
float value;
int angle(10);
    char number [4]={'0','0','0','0'};
void ToString(float num)
{
    number[0] = num/10 + '0';
    number[1] = int(num) % 10 + '0';
    number[2] = '.';
    number[3] = int((num - int(num)) * 10) + '0';

}

void MoveMotor()
{
   motor.step(int(numstep / 360.0 * (angle  % 360) + 0.5), direction, step_speed); // number of steps, direction, speed
}

void CheckState()
{     
     if (pc.readable())
    {
      string command;
       pc.scanf("%s",&command);
       if (command == "Start")
            {
                state = Working;
            }
        else if (command == "Stop")
        {  state = Idle;
        }
         
    
    }
}

float InterpolatedValue( int i )
{
    float alpha = (value - voltages[i]) / (voltages[i + 1] - voltages[i]);
    return (1 - alpha)* distances[i] + alpha*distances[i + 1];
}

void GenerateValue()
{

      value = sensor;
      if( value < 0.0001)
      value = -1.0;
      else
      for( int i = 0; i < samples_num - 1; i++)
      {
          if( value > voltages[0])
      {
          value = 10;
          break;
      }
      else if( value >= voltages[i] && value <= voltages[i + 1])
      {
          value = InterpolatedValue(i);
          break;
      }
      }
     int valueInt = int(value + 0.5);
     pc.printf("%d\n", value); 
}
int main() {
    pc.attach(&CheckState);
    while (1) {   
   
    
                if (state == Working)
                {
                    
                    GenerateValue();
                    MoveMotor();
                    wait(1);             
                }
         
        }
        }