-
Notifications
You must be signed in to change notification settings - Fork 0
/
arduino ultrasonic sensor relay
49 lines (44 loc) · 2.35 KB
/
arduino ultrasonic sensor relay
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
// Use the HC-SR04 to detect movement after 13 CM to turn on a light for 15 seconds
#define trigPin 6 //Define the HC-SE04 triger on pin 6 on the arduino
#define echoPin 5 //Define the HC-SE04 echo on pin 5 on the arduino
#define bulb 9 //Define the relay signal on pin 9 on the arduino
void setup()
{
Serial.begin (9600); //Start the serial monitor
pinMode(trigPin, OUTPUT); //set the trigpin to output
pinMode(echoPin, INPUT); //set the echopin to input
pinMode (bulb, OUTPUT); //set the bulb on pin 9 to output
}
void loop()
{
int duration, distance; //Define two intregers duration and distance to be used to save data
digitalWrite(trigPin, HIGH); //write a digital high to the trigpin to send out the pulse
delayMicroseconds(500); //wait half a millisecond
digitalWrite(trigPin, LOW); //turn off the trigpin
duration = pulseIn(echoPin, HIGH); //measure the time using pulsein when the echo receives a signal set it to high
distance = (duration/2) / 29.1; //distance is the duration divided by 2 becasue the signal traveled from the trigpin then back to the echo pin, then devide by 29.1 to convert to centimeters
if (distance < 7) //if the distance is less than 13 CM
{
ac(); //execute the Light subroutine below
}
else //if the distance is less than 13 CM
{
kapat(); //execute the Light subroutine below
}
// else
// Serial.print(distance); //Dispaly the distance on the serial monitor
// Serial.println(" CM"); //in centimeters
// delay(500); //delay half a second
}
void ac() //Start the Light subroutine
{
digitalWrite(bulb, HIGH); //turn on the light
delay (500); //wait 15 seconds
// digitalWrite(bulb, LOW); //turn off the light
}
void kapat() //Start the Light subroutine
{
// digitalWrite(bulb, HIGH); //turn on the light
delay (500); //wait 15 seconds
digitalWrite(bulb, LOW); //turn off the light
}