I have this GSM module I got for my arduino project and I am trying to access the call feature, but the function makes no sense.
boolean Adafruit_FONA::callPhone(char *number) {
char sendbuff[35] = "ATD";
strncpy(sendbuff+3, number, min(30, strlen(number)));
uint8_t x = strlen(sendbuff);
sendbuff[x] = ';';
sendbuff[x+1] = 0;
//Serial.println(sendbuff);
return sendCheckReply(sendbuff, "OK");
}
This is the function however how is char being used to display a phone number in the parameter?
2 Answers 2
It's passed as a char*
. This can be derived from either a string literal (e.g. "212555121"
) or from a String
via its c_str()
method.
-
so if i wanted to use the function all i have to do is enter a string with the number inside?Joe salad– Joe salad2015年03月13日 20:11:58 +00:00Commented Mar 13, 2015 at 20:11
-
If you want to use a fixed string then you can call it with the literal. If you have a
char*
with the string then you can pass it directly. If you have aString
then you need to call thec_str()
method. Arduino string referenceIgnacio Vazquez-Abrams– Ignacio Vazquez-Abrams2015年03月13日 20:13:25 +00:00Commented Mar 13, 2015 at 20:13 -
can u give an example of how i would create the char* with the stringJoe salad– Joe salad2015年03月14日 01:57:13 +00:00Commented Mar 14, 2015 at 1:57
-
What's wrong with how your posted code does it (other than that fiasco with
strncpy()
, of course)?Ignacio Vazquez-Abrams– Ignacio Vazquez-Abrams2015年03月14日 02:01:12 +00:00Commented Mar 14, 2015 at 2:01
Keeping it simple:
char *number;
a variable pointing to a character (or string of them).
char sendbuff[35];
35 characters in a row, making a string.
The first 3 chars at locatiion sendbuff are initialised to "A", "T", & "D", then the string at "number" is copied to it (to a maximum of 30 characters, by taking the lesser of the length of "number" or 30. This is important to avoid over-running the space allocated.
This string of characters gets sent out; & a check is made for an "O" & a "K"
If you don't 'get' pointers, you need to look it up, as it's pretty central stuff.
-
2I don't know why
strncpy
has become so popular as a "safe" replacement forstrcpy
. It isn't. If the number string is longer than 30 charactersstrncpy
will copy the first 30 characters and stop without adding a NUL terminator. The subsequent call tostrlen
can then run off the end of the buffer, and if that happens, the two bytes subsequently stored will go outside the buffer.Pete Becker– Pete Becker2015年03月13日 05:07:14 +00:00Commented Mar 13, 2015 at 5:07
strlen
isn't needed;x
is the sum of the length of the first string and the number of characters that were copied. Setting aside the incorrect use ofstrncpy
that I mention in a comment below, if the input string is to long, the code truncates it and dials the truncated number! It shouldn't do that; it should return an error code. Don't try to learn programming from stuff like this. You'll pick up lots of bad habits.