C Experiment 5
C Experiment 5
Aim - Integrate the concept of experiments number 3 with 4 and control the motor speed using
Ultrasonic sensor.
Objectives –
1. To control the rpm of a motor based on signal input using Ultrasonic sensor/ IR sensor.
Components Required –
Circuit Diagram:
Figure .1: Circuit Diagram of sensor and motor integration using Arduino.
Steps:
Note: This step is for multiple motor. You have to reduce for single motor.
Connect the first motor to motor controller module Out1 and Out2.
Connect the first motor to motor controller module Out3 and Out4.
Connect the positive wire from the battery pack to pin +12V on the module.
Connect the negative wire from the battery pack to pin GND on the module.
Connect the GND pin of the module to the GND pin of the Arduino.
Connect Arduino pin 5 to module pin In1.
Connect Arduino pin 4 to module pin In2.
Connect Arduino pin 3 to module pin In3.
Connect Arduino pin 2 to module pin In4.
Connect the sensor pin Vcc to Arduino pin 5V.
Connect the sensor pin GND to Arduino pin GND.
Connect the sensor pin Trig to Arduino pin 13.
Connect the sensor pin Echo to Arduino pin 12.
Inspect the wiring and ensure they are correct.
Code:
First Method:
1. #define trigPin 13
2. #define echoPin 12
3. #define motorPin 8
4. void setup()
5. {
6. Serial.begin (9600);
7. pinMode(trigPin, OUTPUT);
8. pinMode(echoPin, INPUT);
9. pinMode(motorPin, INPUT);
10. }
11. void loop ()
12. {
13. int duration, distance;
14. digitalWrite (trigPin, HIGH);
15. delayMicroseconds (1000);
16. digitalWrite (trigPin, LOW);
17. duration = pulseIn (echoPin, HIGH);
18. distance = (duration/2) / 29.1;
19. if (distance < 20) { // Distance from sensor
20. digitalWrite (motorPin, HIGH); // When in range, motor should start high
21. }
22. else
23. {
24. digitalWrite(motorPin, LOW);
25. }
26. if (distance > 20) { // Distance from sensor
27. Serial.println("Out of range");
28. }
29. else {
30. Serial.print(distance);
31. Serial.println(" cm");
32. }
33. delay(500);
34. }
Second Method: