The Program derives motor bots getting instructions(speed, turn, stop,etc) from accelerometer.
Dependencies: Motordriver mbed
main.cpp
- Committer:
- samgang
- Date:
- 2013-10-27
- Revision:
- 0:c5c22fd71be8
File content as of revision 0:c5c22fd71be8:
/* This program uses Christopher Hasler motor library to derive DC motors */ #include "mbed.h" #include "motordriver.h" // Array of Motor type objects to define 4 motors for two bots. Motor M[]= {Motor(p25, p9, p8, 1), Motor(p26, p11, p10, 1), Motor(p21, p13, p12, 1), Motor(p22, p15, p14, 1)}; // Array acc defines 4 analogin type objects to detect inputs of accelerometer. AnalogIn acc[]= {p16, p17, p19, p18}; /*@update reads recent values from accelerometer and uses them to control motors @param 'a' tell for which bot the vales should be updated( a=0 for 1st bot and a=2 for 2nd bot) */ int update(int a) { float offx=0, offy=0, map=0, turnp=0, turnn=0; /*output votage of accelerometer at x and y outs when x=0 and y=0; turnp and turnn specifies the positive and negative voltage difference(CurrentVoltage - offset) detected from offset value when accelerometer is tilted. I will be using turnp and turnn as the minimum required voltage difference(ie, the minimum required tilt) to turn the bot. The value below are default ones for my accelerometer */ if(a==0) { offx=0.340; offy=0.340; turnp=0.032; turnn=0.055; map=14.68; } else if(a==2) { offx=0.350; offy=0.440; turnp=0.040; turnn=0.045; map=13.40; } else return(-1); // return -1 as error when update is called with unexpected argument value float s=0, st=0; s=acc[a+1].read(); s=(s-offy)*map; // multiply by 'map' to linearly map difference (s-offy) to euivalent scale on 0 to 1 so that s can be used as speed // (s=0 for (s-offy)=0 and s=1 for max[(s-offy)] ) st=acc[a].read(); st=st-offx; if(st>0 && abs(st)>turnp) { // checking whether to turn or not ( st>0: right turn and st<0: left trun) M[a].speed(0); M[a+1].speed(1); } else if(st<0 && abs(st)>turnn) { M[a].speed(1); M[a+1].speed(0); } else { // if no turn input then run both motors with speed s M[a].speed(s); M[a+1].speed(s); } return 1; } int main() { while(1) { update(0); // Calling update for first bot(a=0) and second bot(a=2) update(2); wait(0.2); } }