Programming Milestone 1 Group 7 BMT M9: Making robots move at different velocities/directions by adjusting potmeter.

Dependencies:   FastPWM MODSERIAL mbed

Fork of Programming_Milestone_1 by Marie-Laure Snijders

main.cpp

Committer:
brass_phoenix
Date:
2018-10-19
Revision:
8:e69799b5cce1
Parent:
7:e4b475fceb86

File content as of revision 8:e69799b5cce1:

#include "mbed.h"
#include "FastPWM.h"
#include "MODSERIAL.h"

Ticker motorTicker; // Ticker function
FastPWM pwmpin1(D5); // SPECIFIC PIN (hoeft niet aangesloten te worden) Tells you how fast the motor has to go (later: pwmpin.write will tell you the duty cycle, aka how much voltage the motor gets)
FastPWM pwmpin2(D6); // SPECIFIC PIN (hoeft niet aangesloten te worden) Tells you how fast the motor has to go (later: pwmpin.write will tell you the duty cycle, aka how much voltage the motor gets)
DigitalOut directionpin1(D4); // SPECIFIC PIN (hoeft niet aangesloten te worden) Direction value (0-1) that the mbed will give the motor: in which direction the motor must rotate
DigitalOut directionpin2(D7); // SPECIFIC PIN (hoeft niet aangesloten te worden) Direction value (0-1) that the mbed will give the motor: in which direction the motor must rotate
AnalogIn potmeter1(A4); // Analoge input van potmeter 1 -> Motor 1
AnalogIn potmeter2(A2); // Analoge input van potmeter 2 -> Motor 2


// Updates a motor connected to the specified pins with the given speed.
// The speed can be both positive and negative.
void update_motor(DigitalOut* dir, FastPWM* pwm, float speed) {
    // either true or false, determines direction (0 or 1)
    *dir = speed > 0;
    // pwm duty cycle can only be positive, floating point absolute value (if value is >0, the there still will be a positive value).
    *pwm = fabs(speed);
}

// Normalizes a potmeter value from it's original range of [0, 1] to [-1, 1]
float normalize_pot(float pot_value) {
    // scales value potmeter from 0-1 to -1 - 1.
    return pot_value * 2 - 1;
};


void motorfunction() {
        // reads out value potmeter 1 between 0-1
        float pot1 = potmeter1.read();
        float motor1_speed = normalize_pot(pot1);
        // reads out value potmeter 2 between 0-1 
        float pot2 = potmeter2.read();
        float motor2_speed = normalize_pot(pot2);
        
        // Update both motors.
        update_motor(&directionpin1, &pwmpin1, motor1_speed);
        update_motor(&directionpin2, &pwmpin2, motor2_speed);
}


int main()
{
    pwmpin1.period_us(60.0); // 60 microseconds PWM period, 16.7 kHz, defines all PWM pins (only needs to be done once)
    motorTicker.attach(motorfunction,0.5);
    while(true){} //Lege while loop zodat functie niet afloopt
}