void setup() {
Serial.begin (9600);
pinMode(7, OUTPUT);
pinMode(6, INPUT);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
}
void loop() {
long duration, distance;
digitalWrite(7, LOW);
delayMicroseconds(2);
digitalWrite(7, HIGH);
delayMicroseconds(10);
digitalWrite(7, LOW);
duration = pulseIn(6, HIGH);
distance = (duration/2) / 29.1;
if (distance > 30) //Jika jarak lebih dari 30cm
{
digitalWrite(3, HIGH); //Menyala
digitalWrite(4, LOW); //Mati
digitalWrite(5, LOW); //Mati
}
if (distance < 20) //Jika kurang dari 20cm
{
digitalWrite(3, LOW);
digitalWrite(4, HIGH);
digitalWrite(5, LOW);
}
if (distance < 10) //Jika kurang dari 10cm
{
digitalWrite(3, LOW);
digitalWrite(4, LOW);
digitalWrite(5, HIGH);
}
Serial.print("Jarak :");
Serial.print(distance);
Serial.println("cm");
delay(100);
}
Tidak ada komentar:
Posting Komentar