Ultrasonic via bluetooth

Hi,

i'm using processing on a project and i want to have the distance result from ultrasonic sensor via blutooth whenever i press a button , so i made this code on the arduino :

.........  

  if(HC05.available())
   {
    c = HC05.read();
   }
  
  if(c==1)
 {
  cm = dist();
  HC05.write(cm);
 } 
   


}

float dist()
{
  long lecture_echo;
  long cm;
  
  digitalWrite(trig, HIGH); 
  delayMicroseconds(10); 
  digitalWrite(trig, LOW); 
  lecture_echo = pulseIn(echo, HIGH); 
  cm = lecture_echo / 58; 
  return cm;
}

......

and this in processing :

.....

void keyPressed() {
 
  if(key == 'Q' || key == 'q')
  {
    port.write(1);
    delay(20);
    dist=port.read();
    println(dist);
  }

but it keep giving me 0 as the distance

but it keep giving me 0 as the distance

Nonsense. The code you post won't even compile.

You REALLY need to learn the difference, on the Arduino side, between print() and write().

Sending a response some random time later does not seem like a good idea.

float dist()
{
  long lecture_echo;
  long cm;

// Snipped some stuff
 
  return cm;
}

Why does the function promise to return a float, but then actually return a long?

The following code may give you distances properly. If so, you could adapt it to your needs and use it along with bluetooth.

#define PIN_HC05_TRIGGER 5
#define PIN_HC05_ECHO 4
#define soundSpeed 341.777 // in meters/sec s = 331.4 + 0.6*Tcelsius (consider this in yor math)
 
float pingTime; // This variable represents the time required for reaching the target and return
float targetDistance; // This variable represents the distance from the sensor to the target.


void setup()
{
  Serial.begin(9600);
  
pinMode(PIN_HC05_TRIGGER,OUTPUT);
  pinMode(PIN_HC05_ECHO,INPUT); 

}

void loop(){
digitalWrite(PIN_HC05_TRIGGER,LOW);
delayMicroseconds(2000); // pause to set signal
digitalWrite(PIN_HC05_TRIGGER,HIGH);
delayMicroseconds(15); // Pause in High state
digitalWrite(PIN_HC05_TRIGGER,LOW);

 pingTime = pulseIn(PIN_HC05_ECHO,HIGH); //measure the time ping echo pin,  (positive peak)
 pingTime = pingTime/(pow(10,6)); //  converting measured time from microseconds to seconds

 targetDistance = soundSpeed * pingTime; // calculates distance in meters
 targetDistance = targetDistance/2;
 Serial.print("The distance to the target is: ");
 Serial.print(targetDistance);
 Serial.println("meters");
 delay(1000);
}

Do not forget to share your improvements.

Regards,

Rezik