-
Notifications
You must be signed in to change notification settings - Fork 2
/
motor_FINAL_WITH_distance.ino
63 lines (50 loc) · 1.48 KB
/
motor_FINAL_WITH_distance.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/* This code transmits signals from transmitter to the
motor through arduino when the distance between quad and obstacle
is greater than 30 cm. If the distance comes within 30 cm then
the motors stop functioning.
*/
#include<Servo.h>
Servo quad;
int trigPin=12;
int echoPin=11;
long duration;
int distance;
int ch3;//because we use ch3 for normal cases of throttle
int servopin=9;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ch3,INPUT);
pinMode(servopin,OUTPUT);
quad.attach(servopin);
/* Intialize the motors with the minimum input value*/
quad.writeMicroseconds(1100);
Serial.begin(9600);
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= duration*0.034/2;
// Prints the distance on the Serial Monitor
//Serial.print(": ");
//Serial.println(distance);
ch3 = pulseIn(5, HIGH, 25000); // Read the pulse width of the channel
ch3= constrain(ch3,1100,1920);
Serial.println(ch3);
if(distance>30)
{
quad.write(ch3); // Write output from transmitter to the motor
}
else if(distance<30)
{
quad.write(1100); // Stop motor as distance is less than 30 cm.
}
}