////////////////////////////////////////////////////////////////////
// Author: RSP @KMUTNB
// Date: 2022-02-08
// File: nano_ultrasonic_pulsein_demo.ino
////////////////////////////////////////////////////////////////////
// see also: https://docs.wokwi.com/parts/wokwi-hc-sr04
#define TRIG_PIN (5) // Arduino pin for the TRIG signal
#define ECHO_PIN (2) // Arduino pin for the ECHO signal
#define TIMEOUT_USEC (30000) // timeout in usec
#define SOUND_SPEED (343) // in msec per sec
#define USEC_TO_CM(x) ((SOUND_SPEED*100UL)*(x)/1000000)
void setup() {
Serial.begin( 115200 ); // set baudrate to 115200
pinMode( ECHO_PIN, INPUT_PULLUP ); // set ECHO pin as output
pinMode( TRIG_PIN, OUTPUT ); // set TRIG pin as input
digitalWrite( TRIG_PIN, LOW ); // output LOW to TRIG pin
}
void loop() {
// Step 1) send a short pulse (e.g. 20 usec) on TRIGGER pin.
digitalWrite( TRIG_PIN, HIGH );
delayMicroseconds(20);
digitalWrite( TRIG_PIN, LOW );
// Step 2) busy-wait to read the pulse width of the signal
// on the ECHO pin with timeout (30 msec max.).
uint32_t pw = pulseIn( ECHO_PIN, HIGH, TIMEOUT_USEC );
// Step 3) compute the distance from the obstacle
uint16_t distance_cm = USEC_TO_CM(pw/2);
// Step 4) send text messages to Serial
Serial.print( F(" ECHO [us]: ") );
Serial.println( pw );
Serial.print( F("Range [cm]: ") );
Serial.println( distance_cm );
delay(200);
}
////////////////////////////////////////////////////////////////////