I know this is Arduino Forum but I think this question is related to programming, I am using ESP8266 for the project. I need to convert the string incoming on the serial through UART lines and receiving those using the below code. Also I am converting the received string to char array as i need to insert some more characters in between hence I need the conversion. I have used 3 different commands to convert the above string into char array as you can see below
#include <SoftwareSerial.h>
#include <Arduino.h>
#include <stdio.h>
#include <string.h>
SoftwareSerial s; //RX TX
using namespace std;
String str= "";
String str_tx;
const char* c;
double buff[24];
unsigned long int str_len = 0;
double val;
char* token;
//char* rest = char_array;
int i=0;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
s.begin(115200, SWSERIAL_8N1, 13, 15, false, 256); //115200, SWSERIAL_8N1, 13, 15, false, 512
pinMode(13, INPUT);
pinMode(15, OUTPUT);
Serial.println("in setup 1");
Serial.println("in setup 2");
Serial.println("in setup 3");
}
void loop() {
// put your main code here, to run repeatedly:2
while(s.available() >0)
{
char ch=s.read();
str.concat(ch);
if( ch =='\n' )
{ str.trim();
Serial.println(str);
str_tx = str;
Serial.println(str_tx);
str_len = str_tx.length()+1;
Serial.println(str_len);
//char char_array[sizeof(str_tx)];
char char_array[str_len];
//strcpy(char_array, str_tx.c_str());
//str_tx.toCharArray(char_array, str_len);
std:copy(str_tx.begin(),str_tx.end(),char_array);
Serial.println(char_array);
char_array[sizeof(str_tx)] = '\0';
//char_array[65] = 0;
str="";
str_tx = "";
Serial.println("------------------------------------");
}
/*
str = "";
str = s.readStringUntil('\n');
str.trim();
Serial.println(str);
str_tx = str;
Serial.println(str_tx);
str_tx = str;
str_tx.replace("\n","");
str_len = str_tx.length();
Serial.println(str_len);
Serial.println(str_tx.c_str());*/
}
}
The output of the above code comes as below, you can see the first time conversion occurs but the next time only empty string shows up, in all the 3 cases its showing the same hence I need to find out what exactly this issue is caused by, would appreciate if anyone could thro some light on it.
Thankyou
String::toCharArray()
or, if you know what you are doing,String::c_str()
.