#define ECHO_PIN 21
#define TRIG_PIN 22
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}
float readDistanceCM(){
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
int duration = pulseIn(ECHO_PIN,HIGH);
return duration * 0.034/2;
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
int duration = pulseIn(ECHO_PIN,HIGH);
float distance = duration * 0.034 / 2;
Serial.println("Jarak: ");
Serial.println(distance);
delay(10); // this speeds up the simulation
}