Devices & Components
Arduino Uno Rev3
Ultrasonic Sensor - HC-SR04 (Generic)
adafruit motor shield V1
battery 18650
DC Motor, 12 V
Battery Holder, 18650 x 2
Hardware & Tools
Hot glue gun (generic)
Software & Tools
Arduino IDE
Project description
Code
follow the object code
arduino
1#include <AFMotor.h> 2 3AF_DCMotor MotorL(4); // motor for drive Left on M4 4AF_DCMotor MotorR(3); // motor for drive Right on M3 5 6//ultrasonic setup: 7 const int trigPin = A4; // trig pin connected to Arduino's pin A4 8 const int echoPin = A5; // echo pin connected to Arduino's pin A5 9 10// defines variables 11long duration; 12int distanceCm=0; 13 14int distanceKeep = 8; 15 16void setup() { 17 Serial.begin(115200); // set up Serial library at 115200 bps 18 Serial.println("robot Follow Object Mod"); 19 pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output 20 pinMode(echoPin, INPUT); // Sets the echoPin as an Input 21 22 // Set the speed to start, from 0 (off) to 255 (max speed) 23 // sometimes the motors don't have the same speed, so use these values tomake your robot move straight 24 MotorL.setSpeed(125); 25 MotorR.setSpeed(125); 26 // turn off motor 27 MotorL.run(RELEASE); 28 MotorR.run(RELEASE); 29} 30 31// main program loop 32void loop() { 33 distanceCm=getDistance(); //variable to store the distance measured by the sensor 34 35 Serial.println(distanceCm); //print the distance that was measured 36 37 //if the distance is less than 5cm, robot will go backward for 1 second, and turn right for 1 second 38 if(distanceCm < distanceKeep && distanceCm >= 5){ 39 MotorL.run(BACKWARD); 40 MotorR.run(BACKWARD); 41 } 42 if(distanceCm > (distanceKeep+3) && distanceCm < (distanceKeep+20)){ 43 MotorL.run(FORWARD); 44 MotorR.run(FORWARD); 45 } 46 if(distanceCm > (distanceKeep+20)){ 47 MotorL.run(FORWARD); 48 MotorR.run(BACKWARD); 49 } 50 if(distanceCm >= distanceKeep && distanceCm <= (distanceKeep+3)){ 51 MotorL.run(RELEASE); 52 MotorR.run(RELEASE); 53 } 54} 55 56 57 58//RETURNS THE DISTANCE MEASURED BY THE HC-SR04 DISTANCE SENSOR 59int getDistance() { 60 int echoTime; //variable to store the time it takes for a ping to bounce off an object 61 int calcualtedDistance; //variable to store the distance calculated from the echo time 62 63 //send out an ultrasonic pulse that's 10ms long 64 digitalWrite(trigPin, HIGH); 65 delayMicroseconds(10); 66 digitalWrite(trigPin, LOW); 67 68 echoTime = pulseIn(echoPin, HIGH); //use the pulsein command to see how long it takes for the 69 //pulse to bounce back to the sensor 70 71 calcualtedDistance = echoTime / 58.26; //calculate the distance of the object that reflected the pulse (half the bounce time multiplied by the speed of sound) 72 return calcualtedDistance; //send back the distance that was calculated 73} 74
Comments
Only logged in users can leave comments