user4794598
user4794598

Reputation:

Arduino error: invalid conversion from 'const char*' to 'char*' [-fpermissive]

I get this error with PlatortmIO

src\main.cpp: In function 'void loop()': src\main.cpp:56:38: error: invalid conversion from 'const char*' to 'char*' [-fpermissive] static char msg = str_out.c_str(); ^ *** [.pio\build\esp01\src\main.cpp.o] Error 1 ========================== [FAILED] Took 3.48 seconds ==========================/ 433 MHz RF Module Transmitter BME280 */

#include <RH_ASK.h>
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#define SEALEVELPRESSURE_HPA (1013.25)

Adafruit_BME280 bme; // I2C
float hum;    // Stores humidity value in percent
float temp;   // Stores temperature value in Celcius
float press; // Stores pressor value
// Define output strings

String str_humid;
String str_temp;
String str_press;
String str_out;
// Create Amplitude Shift Keying Object
RH_ASK rf_driver;

void setup() 
{
    Serial.begin(9600);
    Serial.println(F("BME280 test"));
    bool status;
    // Initialize ASK Object
    rf_driver.init();
    // Start BME Sensor
    status = bme.begin(0x76);
   if (!status) 
   {
     Serial.println("Could not find a valid BME280 sensor, check wiring!");
     while (1);
   }
}

void loop()
{
  delay(2000);  // Delay so sensor can stabalize
    hum = bme.readHumidity();  // Get Humidity value
    temp= bme.readTemperature();  // Get Temperature value
    press= bme.readPressure(); //Get Pressoure
    // Convert Humidity to string
    str_humid = String(hum);
    // Convert Temperature to string
    str_temp = String(temp);
    //Convert  Pressessor
    str_press = String (press);
    // Combine Humidity and Temperature
    str_out = str_humid + "," + str_temp + "," + str_press;
    // Compose output character
    static char *msg = str_out.c_str();
    rf_driver.send((uint8_t *)msg, strlen(msg));
    rf_driver.waitPacketSent();
}

Upvotes: 0

Views: 2503

Answers (1)

hcheung
hcheung

Reputation: 4034

String.c_str() return a const char* array, which is not compatible with your static char* msg.

Looking at your code, instead of converting float to String in order to use String concatenation, then convert to an array, it will be much simpler to just directly create a char array with sprintf().

hum = bme.readHumidity();  // Get Humidity value
temp= bme.readTemperature();  // Get Temperature value
press= bme.readPressure(); //Get Pressoure
char msg[50];
sprintf(msg, "%f,%f,%f", hum, temp, press);

String concatenation isn't safe in Arduino which has only 2k memory and should avoid whenever is possible, especially if you are new to Arduino programming and not familiar with how dynamic memory allocation works internally.

Upvotes: 2

Related Questions