How To Ultrasonics Sensor With DC Motors

Required Hardware
For users who do not have Hackerspace Karachi Arduino Kit v1.0
- Arduino Board
- Breadboard
- Ultrasonic Sensor (HC-SR04)
- L293D driver IC
- DC motors
- Hook-up Wires
Circuit
For users who do not have Hackerspace Karachi Arduino Kit v1.0
Schematic
Code
1. /*
2. Ultrasonic Sensor with DC motors
3. This example shows how to use Ultrasonic Sensor with DC motors
4. The circuit:
5. – Ultrasonic sensor
6. echo pin connected to digital pin 13 of Arduino
7. trig pin connected to digital pin 12 of Arduino
8. Vcc pin connected to Vcc pin of Arduino
9. Gnd pin connected to Gnd pin of Arduino
10. -Motor 1 and 2
11. connected to output pins of driver IC
12.
13. -Driver IC
14. input and enable pins connected to digital pins of Arduino
15.
16. http://hackerspacekarachi.org/
17. */
18.
19. #define echoPin 13 // define output pin
20. #define trigPin 12 //define input pin
21. long duration; //store time taken for wave to trvel
22. int distance; // store distance travel by wave
23. int motor1pin1 = 8; //input pin of Driver ic for 1st motor connected to digital pin 8
24. int motor1pin2 = 9; //input pin of Driver ic for 1st motor connected to digital pin 9
25. int enA = 5; //enable pin of Driver ic for 1st motor connected to digital pin 5
26.
27.
28. int motor2pin1 = 10; //input pin of Driver ic for 2nd motor connected to digital pin 10
29. int motor2pin2 = 11;//input pin of Driver ic for 2nd motor connected to digital pin 11
30. int enB = 6; //enable pin of Driver ic for 2nd motor connected to digital pin 6
31.
32. void setup() {
33.
34. Serial.begin(9600); //initiate program
35. pinMode(trigPin, OUTPUT); //read and store output
36. pinMode(echoPin, INPUT); //read and store input
37. pinMode(motor1pin1, OUTPUT); //setting prins to be used as output
38. pinMode(motor1pin2, OUTPUT);
39. pinMode(motor2pin1, OUTPUT);
40. pinMode(motor2pin2, OUTPUT);
41. pinMode(enA, OUTPUT);
42. pinMode(enB, OUTPUT);
43. }
44.
45. void loop() {
46.
47. digitalWrite(trigPin, LOW); //trigger object with delay of 2micsec
48. delayMicroseconds(2);
49. digitalWrite(trigPin, HIGH);
50. delayMicroseconds(10);
51. digitalWrite(trigPin, LOW);
52.
53. duration = pulseIn(echoPin, HIGH); //time taken for the wave to travel
54. distance = (duration * 0.034 / 2); //distance divided by 2 for incoming
55. // outgoing waves
56. Serial.print(“Distance : “); //Display results
57. Serial.print(distance);
58. Serial.println(” cm “);
59. delay(1000);
60. if (distance < 10)
61. {
62. digitalWrite(motor1pin1, HIGH); //for motor 1 to move in one direction
63. digitalWrite(motor1pin2, LOW);
64. digitalWrite(enA, HIGH);
65.
66. digitalWrite(motor2pin1, HIGH); //for motor 2 to move in one direction
67. digitalWrite(motor2pin2, LOW);
68. digitalWrite(enB, HIGH);
69. delay(1000);
70.
71. }
72. }
73.