I'm trying to use nRF24L01 module to send a messages between 2 arduinos
Transmiter code:
const char text[] = "Hello World";
radio.write(&text, sizeof(text));
delay(1000);
Reciver code:
char text[32] = {0};
radio.read(&text, sizeof(text));
Serial.println(text);
How I can put into char array an int value? I tried doing it in this way
For example: int a = 60; const char text[] = String(a); radio.write(&text, sizeof(text));
delay(1000);
3 Answers 3
Are you just looking for a way to get an arbitrary number expressed as a string? If so, you'll likely want to use some existing functions to help you along.
I recommend using sprintf
sprintf(char * str, char * format, args)
Where str is the string you're storing results in, format is the string you're inserting your values into for, you guessed it, formatting, and args are all the args, separated by commas, that you'll be passing into the format string to be inserted into the str string. An example might be:
char[x] result; //x is the number of elements in your array, atleast one for every letter and one for the end character, ex: "hello" needs 6.
int number = 24;
sprintf(result, "My number is %d", number);
sendSomewhere(result); //sends "My number is 24"
-
1You forgot to declare the size of
result
. Also, if your "somewhere" inherits fromPrint
(most things that implementwrite()
do), then you cansomewhere.print("My number is "); somewhere.print(24);
.Edgar Bonet– Edgar Bonet2016年07月08日 12:12:03 +00:00Commented Jul 8, 2016 at 12:12 -
I did forget to declare a size for result! for OP, that line should read "char[x] result" where x is the number of elements in your char array. As for sendSomewhere(result), it was just supposed to be an open-ended function for the OP to get the concept with.Turner Bowling– Turner Bowling2016年07月08日 23:54:37 +00:00Commented Jul 8, 2016 at 23:54
-
11) By
char[x] result;
you probably meanchar result[x];
. 2) I understand the virtues of an open-ended answer, but usingsprintf()
instead ofPrint::print()
will make the compiled program grow by 1 K or so. If the program already usesPrint::print()
(which is likely, since it is so common in Arduinoland), then the cost ofsprintf()
is more like 1.5 K.Edgar Bonet– Edgar Bonet2016年07月09日 13:08:09 +00:00Commented Jul 9, 2016 at 13:08 -
1
sprtintf()
returns the length of the string created so you can doint length=sprintf(result, "My number is %d", number); radio.write(result, length);
This saves usingstrlen()
to calculate how many bytes to send.Andrew– Andrew2016年10月07日 08:02:39 +00:00Commented Oct 7, 2016 at 8:02
You can not have 'const' prefixed the 'text' variable as it then become 'read-only'.
char text[32];
int a = 60;
sprintf(text, "Number %d", a);
radio.write(&text, sizeof(text));
The simplest method is to send the integer in binary format (skipping the conversion to text).
int a = 60;
radio.write((char*) &a, sizeof(a));
Cheers!
Explore related questions
See similar questions with these tags.
radio.println(a)
maybe?