Here is some example code using one HCSR04 rangefinder to get distance and send via a HC05 Bluetooth module on an Uno to another Uno with a bound HC05. Serial reception code from the serial input basics tutorial. This code has been tested and works as advertised.
Sender (master):
//Bluetooth Master
//Sends the ultrasonic distance to the Slave
#include <SoftwareSerial.h>
SoftwareSerial BTserial(4, 7); // RX | TX
// defines pins numbers
const int trigPin = 5;
const int echoPin = 6;
// defines variables
long duration;
int distance;
void setup()
{
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
BTserial.begin(9600);
Serial.println("Sonar sender starting");
BTserial.println("Sonar sender starting");
}
void loop()
{
static unsigned long timer = 0;
unsigned long interval = 1000;
if (millis() - timer >= interval)
{
timer = millis();
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
// Send the distance via Bluetooth
BTserial.println(distance);
}
}
Receiver (slave):
//Bluetooth Slave
//Receives the ultrasonic distance from the Master
#include <SoftwareSerial.h>
SoftwareSerial BTserial(4, 7); // RX | TX
const int numChars = 10;
char receivedChars[numChars];
bool newData = false;
void setup()
{
Serial.begin(9600);
BTserial.begin(9600);
Serial.println("Sonar receiver starting");
}
void loop()
{
recvWithEndMarker();
showNewData();
}
void recvWithEndMarker()
{
static byte ndx = 0;
char endMarker = '\n';
char rc;
while (BTserial.available() > 0 && newData == false)
{
rc = BTserial.read();
if (rc == '\r') // ignore carruage return
{
return;
}
if (rc != endMarker)
{
receivedChars[ndx] = rc;
ndx++;
if (ndx >= numChars)
{
ndx = numChars - 1;
}
}
else
{
receivedChars[ndx] = '\0'; // terminate the string
ndx = 0;
newData = true;
}
}
}
void showNewData()
{
if (newData == true)
{
Serial.print("Distance = ");
Serial.println(receivedChars);
newData = false;
}
}
If you send multiple ranges, separate them with commas in the payload packet and use example #5 code to parse and convert the data.