Float to Char

Hi everyone
I'm very new to the world of Arduino's and coding, so this will most likely be an easy to fix issue.
I'm trying to output a reading from a HX711 module (which is a load cell amplifier) through RF 433mhz modules. However the output from the HX711 is in float form as it has a decimal place. The modules seem to only support const char transmission. In the research I have done it seems that the most common solution is to use a dtostrf function. However I can't see anywhere how exactly this is implemented. And further more it seems to primarily be used single values where as mine is variable. Any help as to how to combine the 2 codes below would be great.

First code is HX711 output

*/


#include "HX711.h"


#define calibration_factor +14720


#define DOUT  3
#define CLK  2


HX711 scale;


void setup() {
  Serial.begin(9600);
  Serial.println("HX711 scale demo");


  scale.begin(DOUT, CLK);
  scale.set_scale(calibration_factor); 
  scale.tare(); 


  Serial.println("Readings:");
}


void loop() {
  Serial.print("Reading: ");
  Serial.print(scale.get_units(), 1); 
  Serial.print(" kg"); 
  Serial.println();
}

Second code is RF output

#include <RH_ASK.h>
#include <SPI.h> // Not actually used but needed to compile


RH_ASK driver;


void setup()
{
    Serial.begin(9600);    // Debugging only
    if (!driver.init())
         Serial.println("init failed");
}


void loop()
{
    const char *msg = "Hello World!";
    driver.send((uint8_t *)msg, strlen(msg));
    driver.waitPacketSent();
    delay(1000);
}

you can use a float/double variable with dtostrf()

dtostrf(variable, width, precision, charBufferLargeEnough);

And you can send binary data with driver.send() if you want driver.send((uint8_t *)&variable, sizeof(variable));

This is safer, no need to get the charBufferLargeEnough correct.
The reserve(30) is not actually important here either just good practice

String sendStr;

void setup() {
  Serial.begin(115200);
  sendStr.reserve(30); // prevent heap fragmentation

}
float get_units() {
  return 1.234567;
}

void send(uint8_t *data, size_t len) {
  Serial.write(data,len);
}

void loop() {
  sendStr = "Reading " + String(get_units(), 4) + " kg";
  send(sendStr.c_str(),sendStr.length());
}

@OP

The following sketch could be helpful to understand the the usage of dtostrf() function.

void setup() 
{
  Serial.begin(9600);
  char myBuffer[10] = "";
  float y = 13.084;
  dtostrf(y, 6, 3, myBuffer); 
  //arg1=float value, arg2=number of symbols in arg1 includiing point
  //arg3=number of digits to show after decimal point, arg4=array to hold ASCII codes 
  for(int i=0; i<6; i++)
  {
    Serial.print(myBuffer[i], HEX); //shows: 31 33 2E 30 38 34
    Serial.print(' ');
  }
  Serial.println();
  Serial.println( myBuffer);  //show: 13.084

}

void loop() 
{


}

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