Granulo Eldar Fahrudin Brbutović

Dependencies:   mbed sMotor

main.cpp

Committer:
tim003
Date:
2014-05-12
Revision:
0:f2c718b5cb18

File content as of revision 0:f2c718b5cb18:

#include "mbed.h"
#include "sMotor.h"

#include <string>


#define PIN1 dp13
#define PIN2 dp11
#define PIN3 dp10
#define PIN4 dp9

Serial pc(USBTX, USBRX); //tx, rx
sMotor stepper_motor(PIN1, PIN2, PIN3, PIN4);

int step_speed = 1200 ; // set default motor speed
int numsteps = 512;
int oldsteps = 0;

Ticker rotator;
bool cw = true, working = true;

int speed =1200;

string buffer = "";

bool is_digit(char c) {
    return c >= '0' && c <= '9';
}

void wrong_comm() {
    pc.printf("Wrong command\n");
    buffer = "";
}

void rotate() {
    if(working) {
        cw ? stepper_motor.step(numsteps, 0, speed) :
            stepper_motor.step(numsteps, 1, speed);    
    }
}

int main() {
    
    rotator.attach(&rotate, .001);
    
    /*
        PROTOCOL:
        
        Axxx - set angle to xxx (out of 360)
        Sxxx - set motor speed to xxx
        W - toggle turn motor on/off
        C - set cw/ccw rotation direction
    */
    
    while(true) {
        buffer.push_back(pc.getc());
        if(buffer.length() == 4) {
            if(!is_digit(buffer[1]) || !is_digit(buffer[2]) || !is_digit(buffer[3]))
                wrong_comm();
            int value = buffer[3] + buffer[2] * 10 + buffer[1] * 100;
            switch(buffer[0]) {
                case 'A':
                    oldsteps = numsteps;
                    numsteps = value;
                    if(numsteps > oldsteps)
                    stepper_motor.step(numsteps, 1, speed);
                    else if(numsteps < oldsteps) stepper_motor.step(numsteps, 0, speed); 
                    buffer = "";
                break;

                case 'S':
                    speed = value;
                    buffer = "";
                    
                break;
                
                default:
                    wrong_comm();
            }
        } else if(buffer.length() == 1 && buffer[0] == 'W')
            working = !working;
        else if(buffer.length() == 1 && buffer[0] == 'C')
            cw = !cw;
      //  stepper_motor.pins = 3;
    }

   
}