#define trigger 15
#define echo 2
#define ledBlue 19
#define ledRed 18
#define ledYellow 5
#define ledGreen 4
#define buzzer 22
long A;
int duration;
void setup() {
Serial.begin(115200);
pinMode(trigger, OUTPUT);
pinMode(echo,INPUT);
pinMode(ledBlue,OUTPUT);
pinMode(ledRed,OUTPUT);
pinMode(ledYellow,OUTPUT);
pinMode(ledGreen,OUTPUT);
pinMode(buzzer,OUTPUT);
}
void loop() {
sensor();
logic();
delay(1000); // this speeds up the simulation
Serial.println("Jarak: "+String(A));
}
void sensor() {
digitalWrite(trigger, LOW);
delayMicroseconds(2);
digitalWrite(trigger, HIGH);
delayMicroseconds(10);
digitalWrite(trigger, LOW);
duration = pulseIn(echo, HIGH);
A = duration / 29.41 / 2 ;
}
void logic(){
if(A>50&&A<100){
digitalWrite(ledBlue,HIGH);
digitalWrite(ledRed,LOW);
digitalWrite(ledYellow,LOW);
digitalWrite(ledGreen,LOW);
digitalWrite(buzzer,LOW);
}else if(A>100&&A<200){
digitalWrite(ledBlue,HIGH);
digitalWrite(ledRed,HIGH);
digitalWrite(ledYellow,LOW);
digitalWrite(ledGreen,LOW);
digitalWrite(buzzer,LOW);
}else if(A>200&&A<300){
digitalWrite(ledBlue,HIGH);
digitalWrite(ledRed,HIGH);
digitalWrite(ledYellow,HIGH);
digitalWrite(ledGreen,LOW);
digitalWrite(buzzer,LOW);
}else if(A>300){
digitalWrite(ledBlue,HIGH);
digitalWrite(ledRed,HIGH);
digitalWrite(ledYellow,HIGH);
digitalWrite(ledGreen,HIGH);
digitalWrite(buzzer,HIGH);
}
}