Step #11-1 : ultrasonic front sensor test

arduino4fun
Site Admin
Posts: 37
Joined: Mon Jun 06, 2016 1:16 pm

Step #11-1 : ultrasonic front sensor test

Postby arduino4fun » Thu Jun 09, 2016 12:57 pm

Ultrasonic front sensor test (HC-SR04), this small sketch allows to measure the distance of an object in face of the sensor and displays this distance in the serial console; the US sensor is connected to the A0 and A1 pin; A0 = Rx (echo), A1 = Tx (trig); gnd and vcc are connected too

Code: Select all

// ---------------------------------------------------------------------------------------------------------------
 // This sketch tests the Ultrasonic Module HC-SR04 Distance Measuring
 // Ranging Transducer Sensor
 //
 // HC-SR04 -- Sensor Shield V5
 // GND -- - - black
 // Echo (RX) -- A0 - green
 // Trig (TX) -- A1 - yellow
 // VCC -- + - red
 //
 //
 // https://www.facebook.com/arduino4fun
 // http://www.arduino4fun.com
 // ---------------------------------------------------------------------------------------------------------------

‪#‎include‬ <Wire.h>

int rxPin = A0; // defines ultrasonic signal receiver pin ECHO (RX)
 int txPin = A1; // defines ultrasonic signal transmiter pin TRIG (TX)

int old_distance = 0;

void setup()
 {
 // start serial port
 Serial.begin(9600);
 Serial.println("Distance test");

pinMode( rxPin, INPUT );
 pinMode( txPin, OUTPUT );
 }

void loop()
 {
 digitalWrite( txPin, LOW );
 delayMicroseconds( 2 );
 digitalWrite( txPin, HIGH ); // pulse for 10msec to the trigger US detection
 delayMicroseconds( 10 );
 digitalWrite( txPin,LOW );
 int distance = pulseIn( rxPin,HIGH ); // read receiver pulse time
 distance = distance / 58; // pulse time > distance
 if( old_distance != distance )
 {
 old_distance = distance;
 Serial.print("H = ");
 Serial.print( distance );
 Serial.println("");
 }
 delay(200);
 }
 


Image
Image

Return to “Multifunction Bluetooth Controlled Robot Smart Car Kits For Arduino”

Who is online

Users browsing this forum: No registered users and 0 guests