Arduino C language use toCharArray() not correct

107 Views Asked by At

I read data from sensor and show to serial monitor like this.

  int humidity = dht.readHumidity();
  int temperature = dht.readTemperature();

  
  String place = "My Home";
  if (online)   {
    if (!client.connected()) {
      reconnect();
    }
    client.loop();
    
    String data = "{\"data\": {\"humidity\":" + String(humidity) + ",  \"temperature\":" + String(temperature) + ", \"place\": " +  place + "}}";

    data.toCharArray(msg, (data.length() + 1));
    Serial.println(msg);

The output is

{"data": {"humidity":60, "temperature":27, "place": My Home}}
{"data": {"humidity":2147483647, "temperature":2147483647, "place": My Home}}

After I run code it have no error but the output is not correct and the program will stop after show this output. If I comment at line data.toCharArray(msg, (data.length() + 1)); . Then, the program will show the correct output of temperature and humidity value. How to fix it?

1

There are 1 best solutions below

0
On

Use the basic itoa function. It is included in stdlib.h

char buf[12]; // "-2147483648\0"
lcd.printIn(itoa(random(1024)-512, buf, 10));

Source : Arduino Playground