Control a dual DC motor powered buggy using the BBC MicroBit

Dependencies:   microbit

buggy_functions.cpp

Committer:
elijah_ubit
Date:
2016-06-22
Revision:
1:e2fc7f9cbdde
Parent:
0:370b7f440dcf

File content as of revision 1:e2fc7f9cbdde:

/*********************************************************
*buggy_functions.h                                       *
*Author: Elijah Orr & Dan Argust                         *
*                                                        *
*A library of functions that can be used to control a    *
*buggy using the BBC MicroBit                            *
*********************************************************/

#ifndef BUGGY_FUNCTIONS_C
#define BUGGY_FUNCTIONS_C

/* necessary includes */
#include "MicroBit.h"
#include "buggy_functions.h"

/*set up pins that will be used to control motors */
PwmOut Lmotor(MICROBIT_PIN_P1);
PwmOut Rmotor(MICROBIT_PIN_P2);

//set up LED matrix display
MicroBitDisplay display;

//Trim is an offset that you can adjust to help the buggy drive straight
//Trim = -0.3 is a left trim
//Trim =  0.3 is a right trim
float trim = 0.3;

/* Functions (listed below) contain the code that runs the buggy.
These functions can be used in the main.cpp file */

extern void hold(float time) //waits for (time) seconds
{
    for (float i = time;i>0;i-=0.01){ //code in the loop will execute every 0.01s during the delay
        char display_buffer [1];                    //buffer to store display string
        int time_int = i;             
        sprintf(display_buffer, "%d", time_int);    //format the time as a string
        display.enable();                           //enable display
        display.printAsync(display_buffer);         //diplay string
        wait(0.01);
        display.disable();                          //disable display
    }
}

extern void forward(float time) //moves forward for (time) seconds
{
    Lmotor = 1.0 + trim;
    Rmotor = 1.0 - trim; //set the left and right motor to 1.0 (full speed) - the trim offset
    hold(time); //wait for (time) seconds while the motors are on
    stop(); //stops the motors
}

extern void left(float time) //moves left for (time) seconds
{
    Rmotor = 1.0 - trim; //set the right motor to full speed
    Lmotor = 0.0; //set the left motor to off
    hold(time); //waits for (time) seconds
    stop(); //stops the motors
}

extern void right(float time) //moves right for (time) seconds
{
    Lmotor = 1.0 + trim; //set the left motor to full speed
    Rmotor = 0.0; //set the right motor to off
    hold(time); //waits for (time) seconds
    stop(); //stops the motors
}

extern void stop() //stops the motors
{
    Lmotor = Rmotor = 0; //set the speed of each motor to 0
}

#endif // BUGGY_FUNCTIONS_C