Go Down

Topic: How to convert a int number to a string text? (Read 628 times) previous topic - next topic

Joshtan

Feb 11, 2019, 02:31 am Last Edit: Feb 11, 2019, 03:20 am by Joshtan
i wish to convert MQTT subscribe message sensor value to a string text so i  been able to send telegram message thru the MQTT message publishing.

Code: [Select]

String message = "Distance     94"
String numberString = message.substring(13) // How long "Distance     " is

if(numberString.toInt() > 80){
// do something
}
  some one teach me this but it was not working,is there any more ways ?

Code: [Select]

#include <WiFi.h>
#include <PubSubClient.h>
#include <UniversalTelegramBot.h>
const char* ssid = "";
const char* password =  "";
const char* mqttServer = "test.mosquitto.org";
const int mqttPort = 1883;
// ------- Telegram config ----------
#define BOT_TOKEN ""  // your Bot Token (Get from Botfather)
#define chat_id "" // Chat ID of where you want the message to go (You can use
long Bot_lasttime;
int bulk_messages_mtbs = 10000; // testing to delay 6sec to detecting another distance and which message been sent .
WiFiClient espClient;
PubSubClient client(espClient);
UniversalTelegramBot bot(BOT_TOKEN, espClient);

String ipAddress = "";

volatile bool telegramButton1PressedFlag = false;
volatile bool telegramButton2PressedFlag = false;

void callback(char* topic, byte* payload, unsigned int length) {
 
  Serial.print("Message arrived in topic: ");
  Serial.println(topic);
 
  Serial.println("Message");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
 
  Serial.println();
  Serial.println("-----------------------");
 
}
 
void setup() {
 
  Serial.begin(115200);
 
  WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("Connected to the WiFi network");
 
  client.setServer(mqttServer, mqttPort);
  client.setCallback(callback);
 
  while (!client.connected()) {
    Serial.println("Connecting to MQTT...");
 
    if (client.connect("ESP32Client")) {
 
      Serial.println("connected Server"); 
 
    } else {
 
      Serial.print("failed with state ");
      Serial.print(client.state());
      delay(2000);
 
    }
  }
 
  client.subscribe("testingdevice");
}
  void sendTelegramMessage() {
    String message = "testing 1";             
    if(bot.sendMessage(chat_id, message, "Markdown")){
      Serial.println("TELEGRAM Message 1 Successfully sent");
  }
      telegramButton1PressedFlag = false;
}
  void sendTelegramMessage2() {
    String message2 = "testing 2";             
    if(bot.sendMessage(chat_id, message2, "Markdown")){
      Serial.println("TELEGRAM Message 2 Successfully sent");
  }
      telegramButton2PressedFlag = false;
}
void loop() {
  client.loop();
  char topic;
  String Message = "Distance     100";
  String numberString = Message.substring(100); // How long "Distance     " is
  if(numberString.toInt() > 80){
      Serial.println(numberString.toInt());
      sendTelegramMessage();
      delay(bulk_messages_mtbs);
      Bot_lasttime = 0;
} else if(numberString.toInt() < 30) {
            Serial.println(numberString.toInt());
            sendTelegramMessage2();
            delay(bulk_messages_mtbs);
            Bot_lasttime = 0;
}
}
}

J-M-L

#1
Feb 11, 2019, 03:22 am Last Edit: Feb 11, 2019, 03:28 am by J-M-L
As you already use the String class, why don't you just use the dedicated methods for that?

Here we would not recommend using that class though and stick to c-strings and associated C functions in stdlib.h and string.h 

Converting an int to a cString could be done with itoa() for example and if you have enough flash memory (because it adds a heavy piece of code)  sprintf() could help too
Hello - Please do not PM me for help,  others will benefit as well if you post your question publicly on the forums.
Bonjour Pas de messages privés SVP, postez dans le forum directement pour que ça profite à tous

Joshtan

As you already use the String class, why don't you just use the dedicated methods for that?

Here we would not recommend using that class though and stick to c-strings and associated C functions in stdlib.h and string.h 

Converting an int to a cString could be done with itoa() for example and if you have enough flash memory (because it adds a heavy piece of code)  sprintf() could help too
did you have any example please ? caused i just join arduino for few month quit new ? thanks :)

Joshtan

just tired ITOA looks it need a sensor on the esp board . Mine was 2 different board 1 for publishing MQTT with sensor. One for subscribe MQTT message without sensor . It seems not working for me .  any more other ways ? ):

J-M-L

#4
Feb 11, 2019, 08:35 am Last Edit: Feb 11, 2019, 08:37 am by J-M-L
itoa() has nothing to do with sensors... not sure I get what you say.

Have you clicked on my first link with Strings ?

There is code in there
Code: [Select]
String stringOne =  String(13);                           // using a constant integer
String stringOne =  String(analogRead(0), DEC);           // using an int and a base
String stringOne =  String(45, HEX);                      // using an int and a base (hexadecimal)
String stringOne =  String(255, BIN);                     // using an int and a base (binary)
String stringOne =  String(millis(), DEC);                // using a long and a base
String stringOne =  String(5.698, 3);                     // using a float and the decimal places


And  there are also methods going the other direction (String to number)

 toDouble()
 toInt()
 toFloat()
Hello - Please do not PM me for help,  others will benefit as well if you post your question publicly on the forums.
Bonjour Pas de messages privés SVP, postez dans le forum directement pour que ça profite à tous

GolamMostafa

@OP

You may find the following examples helpful to understand the working mechanism of the itoa() function:

itoa() Function
In the context of itoa()b function, integer data refers to a data in the human world, which has no fractional part and the digits of the integer part are confined within 0 to 9. The number could be a positive or negative. Thus, 1234 is an integer data; 0x6B7C is also an integer data as it is actually 27516 in the human world; 0xB37C is also an integer as it is actually -19587 in the human world. The possible range of 4-digit integer data is: 0x8000 - 0x7FFF (-32768 to 32767).

The function prototype of itoa() (Integer To Ascii) function as given in the stdlib.h Library is:

Code: [Select]
char   *_CType itoa(int __value, char *__string, int __radix);

What does the function do? Assume that the argument-3 (radix = base) is 10; the itoa() function transforms the value of argument-1 into decimal digits (the decimal number); converts the digits of the decimal number into their respective ASCII codes; saves the ASCII codes in a character type array pointed by argument-2; places a null-character/null-byte ('\0'/0x00) as the last element of the array. The function will also return a numerical value (known as pointer) which is the base address of the array being pointed by argument-2.

Example-1:
Assume the argument-1 is 0x6B7C; it will be transformed into a decimal number of 27516; the digits will be converted to their respective ASCII codes like these: for 2, there will be 0x32; for 7, there will be 0x37; for 5, there will be 0x35; for 1, there will be 0x31; for 6, there will be 0x36. The Arduino codes are:

Code: [Select]
char *str; //str is a pointer variable; it will hold numerical value returned by function
char myData[20]; //this array will hold the ASCII codes generated by the function
char *ptr; //ptr is pointer variable; it points myData[] array and holds its base address
int x = &myData;
ptr = x; //now the pointer variable ptr holds the base address of myData[] array
Serial.println(x, HEX); // shows base address in numerical form of myData[] array

str = itoa(0x6B7C, ptr, 10); //or str = itoa(0x6B7C, myData, 10); or itoa(0x6B7C, myData, 10);

int y = str;
Serial.println (y, HEX); //shows base address of myData[] array; it should be equal to x
Serial.println(myData); //shows: 27516
Serial.println(myData[0], HEX); //shows: 0x32 - the ASCII code of 2


Example-2: Assume the argument-1 is 0xB37C; this number (and any other number with LH at MSBit) will be considered as the 2's complement form of a negative decimal number;  it will be transformed into a decimal number of -19587; the minus_sign and digits will be converted to their respective ASCII codes like these: for minus_sign (-), there will be 0x2D; for 1, there will be 0x31; for 9, there will be 0x39; for 5, there will be 0x35; for 8, there will be 0x38; for 7, there will be 0x37. The Arduino codes are similar to Example-1.

Example-3:  Convert the number 0x6B7C into an ASCII string without using itoa() function. Save the result in the character type array myData[ ].
Code: [Select]
Char myArray[20]="";  //initialized with 0x00 in all locations
int z = 0x6B7C;
for (i = 4; i>=0; i--)
{
  myArray[i] = (z % 10) + 0x30;  //modulus (%) and division (/) operations
  z = z / 10;
}
Serial.println(myArray); //shows: 27516

J-M-L

@GolamMostafa you forgot to explain in heavy details the different radix representation possible, what are your acronyms LH and MSBit and why they were called this way, where does the 0x notation come from and how do pointers work between stack and heap...

I'm very disappointed by such a short and uncompleted answer - I'm sure the OP is too...




 :o  :smiley-mr-green:  :smiley-roll-blue:
Hello - Please do not PM me for help,  others will benefit as well if you post your question publicly on the forums.
Bonjour Pas de messages privés SVP, postez dans le forum directement pour que ça profite à tous

PaulS

Quote
I'm sure the OP is too...
I'm sure OP is going WTF?
The art of getting good answers lies in asking good questions.

GolamMostafa

#8
Feb 11, 2019, 04:13 pm Last Edit: Feb 11, 2019, 06:00 pm by GolamMostafa
Why are there series of books of different writers on the same subject? It is because the later writer thinks that the former writer could discuss the topic in more details or he (the former writer) has provided inaccurate information which should be corrected/adjusted.

More elegant posts/presentations/examples are expected to overcome the limitations/inaccuracies/fallacies of Post#5.

you forgot to explain in heavy details the different radix representation possible, what are your acronyms LH and MSBit and why they were called this way, where does the 0x notation come from [...]
Galileo says, "I do not guess; I  measure, and then I predict." When I could not collect enough experimental evidences for my own understanding on the implication of base-16, how do I dare to talk about?

LH and MSBit are the local abbreviations for: 'Logic High Value (1)' and 'Most Significant Bit Position;.

0x has been appended to mean that the 'number following this 0x preamble' is a number in hexadecimal base.

I'm sure OP is going WTF?
Quote
or as an interjection: WTF! That's a load of bull! (what the fuck): WTF is sometimes spelled or written out in the NATO phonetic alphabet: whiskey tango foxtrot. (what the fuck): WTF is not usually considered as offensive as the full expression what the fuck.
K+ for the wit you have created!

Joshtan

@OP

You may find the following examples helpful to understand the working mechanism of the itoa() function:

itoa() Function
In the context of itoa()b function, integer data refers to a data in the human world, which has no fractional part and the digits of the integer part are confined within 0 to 9. The number could be a positive or negative. Thus, 1234 is an integer data; 0x6B7C is also an integer data as it is actually 27516 in the human world; 0xB37C is also an integer as it is actually -19587 in the human world. The possible range of 4-digit integer data is: 0x8000 - 0x7FFF (-32768 to 32767).

The function prototype of itoa() (Integer To Ascii) function as given in the stdlib.h Library is:

Code: [Select]
char   *_CType itoa(int __value, char *__string, int __radix);

What does the function do? Assume that the argument-3 (radix = base) is 10; the itoa() function transforms the value of argument-1 into decimal digits (the decimal number); converts the digits of the decimal number into their respective ASCII codes; saves the ASCII codes in a character type array pointed by argument-2; places a null-character/null-byte ('\0'/0x00) as the last element of the array. The function will also return a numerical value (known as pointer) which is the base address of the array being pointed by argument-2.

Example-1:
Assume the argument-1 is 0x6B7C; it will be transformed into a decimal number of 27516; the digits will be converted to their respective ASCII codes like these: for 2, there will be 0x32; for 7, there will be 0x37; for 5, there will be 0x35; for 1, there will be 0x31; for 6, there will be 0x36. The Arduino codes are:

Code: [Select]
char *str; //str is a pointer variable; it will hold numerical value returned by function
char myData[20]; //this array will hold the ASCII codes generated by the function
char *ptr; //ptr is pointer variable; it points myData[] array and holds its base address
int x = &myData;
ptr = x; //now the pointer variable ptr holds the base address of myData[] array
Serial.println(x, HEX); // shows base address in numerical form of myData[] array

str = itoa(0x6B7C, ptr, 10); //or str = itoa(0x6B7C, myData, 10); or itoa(0x6B7C, myData, 10);

int y = str;
Serial.println (y, HEX); //shows base address of myData[] array; it should be equal to x
Serial.println(myData); //shows: 27516
Serial.println(myData[0], HEX); //shows: 0x32 - the ASCII code of 2


Example-2: Assume the argument-1 is 0xB37C; this number (and any other number with LH at MSBit) will be considered as the 2's complement form of a negative decimal number;  it will be transformed into a decimal number of -19587; the minus_sign and digits will be converted to their respective ASCII codes like these: for minus_sign (-), there will be 0x2D; for 1, there will be 0x31; for 9, there will be 0x39; for 5, there will be 0x35; for 8, there will be 0x38; for 7, there will be 0x37. The Arduino codes are similar to Example-1.

Example-3:  Convert the number 0x6B7C into an ASCII string without using itoa() function. Save the result in the character type array myData[ ].
Code: [Select]
Char myArray[20]="";  //initialized with 0x00 in all locations
int z = 0x6B7C;
for (i = 4; i>=0; i--)
{
  myArray[i] = (z % 10) + 0x30;  //modulus (%) and division (/) operations
  z = z / 10;
}
Serial.println(myArray); //shows: 27516

is that only can be a fix number or the number can been float by the sensor?

J-M-L

#10
Feb 12, 2019, 08:47 am Last Edit: Feb 12, 2019, 08:48 am by J-M-L
The i in itoa() means integer (integer to ascii) so won't work for a float

There is a function dtostrf() that will do that for floating point numbers

As mentioned above sprintf() will also work at the expense of roughly 1.5k of program memory as it's a large function
Hello - Please do not PM me for help,  others will benefit as well if you post your question publicly on the forums.
Bonjour Pas de messages privés SVP, postez dans le forum directement pour que ça profite à tous

ARKF

Here is an example of how dtostrf() function works to get ASCII codes for the symbols of the floating number 17.35. After conversion, we will get (in HEX base) 31 for 1, 37 for 7, 2E for ., 33 for 3, 35 for 5 in the locations of a character type array named char ascArray[]. The codes are:
 
Code: [Select]
char ascArray[20] = "";
void setup()
{
  Serial.begin(9600);
  float x = 17.35;
  dtostrf(x, 5, 2, ascArray);// double to string float
  //x = float value to be converted
  //5 = number of ASCII codes in the output string
  //2 = number of digits after decimal point
  //ascArray = name of array that contains ASCII codes after conversion 
  Serial.println(ascArray);// validity check; shows 17.35.
  Serial.println(ascArray[0], HEX);//shows 31; validity check
}

void loop()
{
 
}

Go Up