Mini-code : using SR04, ultrasonic sensor

Here is the small program I wrote to implement the use of an ultrasonic SR04 sensor on the Gamebuino Meta. Feel free to reuse and modify this code as much as you want to implement your own functionnalities.

#include <Gamebuino-Meta.h>

#define US_PIN_INPUT_ECHO   3   // attach pin D3 Arduino to pin Echo of HC-SR04
#define US_PIN_OUTPUT_TRIG  4   //attach pin D4 Arduino to pin Trig of HC-SR04
float f32_distance = 0;     // compute filter to stabilize distance measure

void setup() 
{
  // put your setup code here, to run once:
  gb.begin();
  pinMode( US_PIN_OUTPUT_TRIG, OUTPUT);   // Sets the trigPin as an OUTPUT
  pinMode( US_PIN_INPUT_ECHO, INPUT);     // Sets the echoPin as an INPUT
  digitalWrite(US_PIN_OUTPUT_TRIG, LOW);  // Set the trigPin to LOW level (=0)
}

float ultrasonic_measure() {

  digitalWrite(US_PIN_OUTPUT_TRIG, HIGH); 
  delayMicroseconds(10);                  // Sets the trigPin HIGH (ACTIVE) for 10 microseconds
  digitalWrite(US_PIN_OUTPUT_TRIG, LOW);
  
  long duration = pulseIn(US_PIN_INPUT_ECHO, HIGH, 20000);   // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = duration * 144 / 100;  // fix pulse measure : add 44% to pulseIn() return value to get correct time in microseconds
  
  // Calcul de la distance
  long distance = duration * 0.034 / 2; // Compute distance from sound wave (Speed of sound wave divided by 2 for go and back)

  f32_distance = f32_distance*.9 + 0.1 * distance; // filter for stable measure
  return f32_distance;
}


void  display_bar(float distance) 
{
    // Affichage des valeurs
  gb.display.print( "Distance : ");
  gb.display.println(f32_distance);
    // display graphical progress bar
  gb.display.drawRect(5, gb.display.height() - 15, gb.display.width() - 10, 10);

    // fill the progress bar
  int32_t i32_bar_len = (((distance + 0.5) * 100) / 50) * (gb.display.width()- 12) / 100;
  gb.display.setColor(GREEN);
  if(distance < 35)
  {
    gb.display.setColor(ORANGE);
  }
  if(distance < 15)
  {
    gb.display.setColor(RED);
  }
  gb.display.fillRect(6, gb.display.height() - 14, i32_bar_len, 8);
}


void loop() {
  while ( gb.update() ) ;
  
  float d = ultrasonic_measure();
  if ( d > 50 ) d = 50;
  if ( d < 5 ) d = 5;
  
  gb.display.clear();
  display_bar(d);
}

Howto connect ?

SR04 Backpack Couleur Description
TRIG 4 GREEN Trig output (start measure)
ECHO 3 YELLOW Echo signal input
VCC 3V3 RED 3v3 sensor power supply
GND GND BROWN power ground