Function to format a string

Hello,

I am using a Reyax rylr896 wireless radio that makes use of AT commands to send and receive data. What I am trying to do is create a function that will send some data to an address of variable lenth/size.

A valid AT command to send would look something like this:

AT+SEND=50,5,HELLO

AT+SEND=<Address 0-65535>,, (Data can be up to 240 bytes)

char inString[240];

void setup() {
  Serial.begin(115200);

  for (int i = 0; i < sizeof(inString); i++) {  //Fill array with some random data
    inString[i] = random(0, 10);
    Serial.print((int)inString[i]);
  }
  Serial.println();
}

void loop() {
  sendDATA(inString, 2);
  delay(2000);

}




void sendDATA (char dataToSend[], unsigned int to) {
  char data[sizeof(dataToSend) + 22];  //+22 because of extra chars needed for AT commands + \r\n on end
  char* ATSEND = "AT+SEND=";
  char* NEWLINE = "\r\n";
  char* COMMA = ",";
  sprintf(data, "%s%u%s%u%s%c%s", ATSEND, to, COMMA, sizeof(dataToSend), COMMA, dataToSend, NEWLINE);
  Serial.println(data);
}

Any ideas on how I should accomplish this? Probably need to be using a pointer and maybe a different
format function other than sprintf. Any help would be appreciated.

Thanks,

I’m not sure if your data is binary or text, but if it is text, you need to make sure it is null terminated. You also can’t use sizeof() on dataToSend since it will just return the size of a char *, not the string length. Use strlen().

const int BUFFER_SIZE = 240;
char inString[BUFFER_SIZE];

void setup() {
  Serial.begin(115200);
}

void loop() {
  int len = random(BUFFER_SIZE);
  for (int i = 0; i < len; i++) {  //Fill array with some random data
    inString[i] = random('0', '9'+1);
  }
  inString[len] = '\0'; //null terminate string
  sendDATA(inString, 2);
  delay(2000);
}

void sendDATA (char dataToSend[], unsigned int to) {
  char data[BUFFER_SIZE + 22];  //+22 because of extra chars needed for AT commands + \r\n on end
  sprintf(data, "AT+SEND=%u,%u,%s\r\n", to, strlen(dataToSend), dataToSend);
  Serial.println(data);
}

If your data is binary, you can’t use sprintf() unless you can guarantee there will not be any 0’s in the data

Some background reading for dealing with strings: avr-libc: <string.h>: Strings