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;
}
......
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);
}