How to Round the result up from the ultrasonic sensor?

Hello
how can i round up the value from mij ultrasonic sensor. Like now it shows 138.64 but i want it to round to 138.5 or something

#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16, 2); // I2C address 0x27, 16 column and 2 rows
int trigPin = 9;    // TRIG pin
int echoPin = 8;    // ECHO pin
int buttonpin = 2;

float duration_us, distance_cm;

void setup()
{
  Serial.begin(9600); //Serial baud rate
  lcd.begin (16, 2);
  lcd.init(); // initialize the lcd
  lcd.backlight();

  lcd.home ();
  lcd.print(distance_cm);
  //delay(2000);
  //lcd.clear();
  // configure the trigger pin to output mode
  pinMode(trigPin, OUTPUT);
  // configure the echo pin to input mode
  pinMode(echoPin, INPUT);
  pinMode(buttonpin, INPUT_PULLUP);
  ;
}

void loop()
{
  // generate 10-microsecond pulse to TRIG pin
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10000);
  digitalWrite(trigPin, LOW);

  // measure duration of pulse from ECHO pin
  duration_us = pulseIn(echoPin, HIGH);

  // calculate the distance
  distance_cm = 0.017 * duration_us;
  if(digitalRead(buttonpin) ==LOW)
  {
    delay(30);
    if(digitalRead(buttonpin) ==LOW)
    {
      lcd.clear();
      lcd.print(distance_cm);
    }
  } 
  //delay(5000);
  // print the value to Serial Monitor
  //lcd.print(distance_cm);
  //delay(5000);
  //if (digitalRead(buttonpin)==HIGH){
  //lcd.clear();
  //}

}

as you want it to show to an accuracy of 1mm why not display in mm?

Do you mean to the nearest 0.5 (8.2 >> 8.0, 8.3 >> 8.5) or to 1 decimal point?

nearest 0.5

      distance_cm = int(((distance_cm * 2.0) + 0.5);
      lcd.print(distance_cm/2.0, 1);

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.