Control of motors

Dependencies:   MODSERIAL QEI mbed

Committer:
rubenlucas
Date:
Fri Sep 28 11:41:02 2018 +0000
Revision:
3:fea443c3be53
Parent:
2:e4f92118a829
Child:
4:f324aa81d7bd
MODSERIAL added

Who changed what in which revision?

UserRevisionLine numberNew contents of line
rubenlucas 0:2d34e3627dae 1 #include "mbed.h"
rubenlucas 0:2d34e3627dae 2 #include "QEI.h"
rubenlucas 3:fea443c3be53 3 #include "MODSERIAL.h"
rubenlucas 0:2d34e3627dae 4 #include "math.h"
rubenlucas 0:2d34e3627dae 5
rubenlucas 3:fea443c3be53 6 MODSERIAL pc(USBTX,USBRX)
rubenlucas 0:2d34e3627dae 7 DigitalOut DirectionPin1(D4);
rubenlucas 1:941f4059c0de 8 DigitalOut DirectionPin2(D7);
rubenlucas 0:2d34e3627dae 9 PwmOut PwmPin1(D5);
rubenlucas 1:941f4059c0de 10 PwmOut PwmPin2(D6);
rubenlucas 0:2d34e3627dae 11 AnalogIn potmeter1(A0);
rubenlucas 0:2d34e3627dae 12 AnalogIn potmeter2(A1);
rubenlucas 0:2d34e3627dae 13 Ticker TickerReadPots;
rubenlucas 0:2d34e3627dae 14
rubenlucas 0:2d34e3627dae 15 volatile float Duty1;
rubenlucas 0:2d34e3627dae 16 volatile float Duty2;
rubenlucas 0:2d34e3627dae 17 volatile float MotorSignal1;
rubenlucas 0:2d34e3627dae 18 volatile float MotorSignal2;
rubenlucas 0:2d34e3627dae 19
rubenlucas 0:2d34e3627dae 20 void ReadPots(void)
rubenlucas 0:2d34e3627dae 21 {
rubenlucas 0:2d34e3627dae 22 Duty1 = potmeter1.read(); // read value potentiometer 1
rubenlucas 0:2d34e3627dae 23 Duty2 = potmeter2.read(); // read value potentiometer 2
rubenlucas 0:2d34e3627dae 24
rubenlucas 0:2d34e3627dae 25 MotorSignal1 = 2*Duty1 - 1; //scaling potmeter to motor control signal [0 - 1] --> [(-1) - 1]
rubenlucas 3:fea443c3be53 26 MotorSignal2 = 1 - 2*Duty2;
rubenlucas 0:2d34e3627dae 27 }
rubenlucas 0:2d34e3627dae 28
rubenlucas 0:2d34e3627dae 29 int main()
rubenlucas 0:2d34e3627dae 30 {
rubenlucas 3:fea443c3be53 31 pc.baud(115200);
rubenlucas 3:fea443c3be53 32 pc.printf("Hello World!\r\
rubenlucas 0:2d34e3627dae 33 PwmPin1.period_us(60); // 16.66667 kHz (default period is too slow!)
rubenlucas 0:2d34e3627dae 34 TickerReadPots.attach(&ReadPots,0.05); // every 50 milli seconds.
rubenlucas 0:2d34e3627dae 35
rubenlucas 0:2d34e3627dae 36 while (true)
rubenlucas 0:2d34e3627dae 37 {
rubenlucas 0:2d34e3627dae 38 // motor 1
rubenlucas 0:2d34e3627dae 39 DirectionPin1 = MotorSignal1 > 0.0f; //either true or false, CW or CCW
rubenlucas 0:2d34e3627dae 40 PwmPin1 = fabs(MotorSignal1); //pwm duty cycle can only be positive, floating point absolute value
rubenlucas 0:2d34e3627dae 41
rubenlucas 0:2d34e3627dae 42 // motor 2
rubenlucas 0:2d34e3627dae 43 DirectionPin2 = MotorSignal2 > 0.0f;
rubenlucas 0:2d34e3627dae 44 PwmPin2 = fabs(MotorSignal2);
rubenlucas 0:2d34e3627dae 45
rubenlucas 0:2d34e3627dae 46 wait(0.01); //Do while loop a hundred times per second.
rubenlucas 0:2d34e3627dae 47 }
rubenlucas 0:2d34e3627dae 48 }