#define pinPir 7
#define pinRelay 5
#define trigPin 3
#define echoPin 2
int PirState = LOW;
int val = 0;
float X=400/397.63;
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(pinPir, INPUT);
pinMode(pinRelay, OUTPUT);
}
void loop() {
long duration, distance;
val = digitalRead(pinPir);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
Serial.print(distance);
Serial.println(" cm");
if(val == HIGH){
if (PirState == LOW && distance <= 100){
Serial.println("Awas Ada Maling!");
PirState = HIGH;
for(int i=0; i<5; i++){
digitalWrite(pinRelay, HIGH);
delay(1000);
digitalWrite(pinRelay, LOW);
delay(1000);
}
}
} else{
digitalWrite(pinRelay, LOW);
if(PirState == HIGH){
Serial.println("Tidak ada Gerakan!");
PirState = LOW;
}
}
delay(500);
}