code using the sonic sensor to activate motor when the distance value dips beneath 50cm, seems to be a problem compiling with the else if statement. Apparently an unclosed bracket.

Dependencies:   SRF02 Servo mbed

Committer:
mspeed93
Date:
Thu Feb 16 22:41:28 2017 +0000
Revision:
0:928ee2609d39
Child:
1:b74e9a2a3fa5
A sample of coding activating/deactivating the servo motors when the sonic sensor registers beneath 50 cm

Who changed what in which revision?

UserRevisionLine numberNew contents of line
mspeed93 0:928ee2609d39 1 #include "mbed.h"
mspeed93 0:928ee2609d39 2 #include "SRF02.h"
mspeed93 0:928ee2609d39 3 #include "Servo.h"
mspeed93 0:928ee2609d39 4
mspeed93 0:928ee2609d39 5 Serial pc(USBTX, USBRX); //tx, rx
mspeed93 0:928ee2609d39 6 SRF02 sensor(p28,p27, 0xE0);
mspeed93 0:928ee2609d39 7 Servo cr_srv(p21);
mspeed93 0:928ee2609d39 8 DigitalOut myled(LED1);
mspeed93 0:928ee2609d39 9
mspeed93 0:928ee2609d39 10 void init_servo(){
mspeed93 0:928ee2609d39 11 //calibrate the servos for +/-45deg
mspeed93 0:928ee2609d39 12 cr_srv.calibrate(0.0005,45);
mspeed93 0:928ee2609d39 13 }
mspeed93 0:928ee2609d39 14
mspeed93 0:928ee2609d39 15 int main() {
mspeed93 0:928ee2609d39 16
mspeed93 0:928ee2609d39 17 float pos_val=0.5; //variable to hold posistion values
mspeed93 0:928ee2609d39 18 float step_size=0.01; //position increment/decrement value
mspeed93 0:928ee2609d39 19 float cr_srv_cmd=0.5; //continuous rotation servo command value (range: 0.0 - 1.0)
mspeed93 0:928ee2609d39 20
mspeed93 0:928ee2609d39 21 pc.baud(921600);
mspeed93 0:928ee2609d39 22
mspeed93 0:928ee2609d39 23 while(1){
mspeed93 0:928ee2609d39 24
mspeed93 0:928ee2609d39 25 int distance = sensor.getDistanceCm();
mspeed93 0:928ee2609d39 26 pc.printf("Distance = %d cm\n",distance);
mspeed93 0:928ee2609d39 27
mspeed93 0:928ee2609d39 28 if (distance <= 50)
mspeed93 0:928ee2609d39 29 myled = 0;
mspeed93 0:928ee2609d39 30 cr_srv_cmd = 0.5; //use a smaller scale for the cr servo due to its limited sensitivity
mspeed93 0:928ee2609d39 31 cr_srv.write(cr_srv_cmd); //write to the servo
mspeed93 0:928ee2609d39 32 pos_val = pos_val + step_size;
mspeed93 0:928ee2609d39 33 if (pos_val > 1.0) pos_val = 0.0;
mspeed93 0:928ee2609d39 34
mspeed93 0:928ee2609d39 35 wait(0.5);
mspeed93 0:928ee2609d39 36 else if (distance > 50)
mspeed93 0:928ee2609d39 37 myled = 1;
mspeed93 0:928ee2609d39 38 cr_srv_cmd = 0.9;
mspeed93 0:928ee2609d39 39 cr_srv.write(cr_srv_cmd);
mspeed93 0:928ee2609d39 40 pos_val = pos_val + step_size;
mspeed93 0:928ee2609d39 41 if (pos_val > 1.0) pos_val = 0.0;
mspeed93 0:928ee2609d39 42
mspeed93 0:928ee2609d39 43 wait(0.5);
mspeed93 0:928ee2609d39 44
mspeed93 0:928ee2609d39 45 }
mspeed93 0:928ee2609d39 46 }