I'm experiencing an issue with sending AT commands through a serial port in my code. The problem is that when I send the following commands:
while (true) {
thread_sleep_for(5000);
sendATCommand("AT+CIPSENDEX=0,64");
sendATCommand("test\\0");
}
The TCP receiver ends up receiving the string AT+CIPSENDEX=0,64 along with test.
To make it more clear: The expected behavior on TCP receiver is:
test
However, current behavior is:
AT+CIPSENDEX=0,64
test
When I did some further testing, I noticed some strange behaviour; when I uncomment a printf statement in sendATCommand, the issue seems to be resolved, and the TCP receiver only gets test:
Here's the relevant code for the sendATCommand function:
void sendATCommand(const char* command, ...) {
char fullCommand[256] = {0};
va_list args;
va_start(args, command);
vsnprintf(fullCommand, 256, command, args);
va_end(args);
// Uncommenting the following line magically fixes the issue:
// printf("the command is: %s\n", fullCommand);
strcat(fullCommand, "\r\n"); // Append carriage return and newline
serial_port.write(fullCommand, strlen(fullCommand));
}
Questions:
- Why does the TCP receiver receive the
AT+CIPSENDEX=0,64command along withtest? - What could be causing this behavior where the problem is fixed just by including a
printfstatement? - How can I resolve this issue so that only the intended message (
test) is sent and received correctly?
Thank you for your help!
vsnprintfnotice that it does not nul-terminate the string if it would have overflown, so you really really should make it a habit to always handle such cases correctly, although that is unrelated to the question you are asking here.