I am working on a C program with some AT terminal and my code was needed to define many string variable like:
const char *AT_norn = "AT";
const char *AT = "AT\r\n";
const char *ATI = "ATI\r\n";
Like I have 30 or more AT command like above to Serialprint out. So I have question, I try to make a new string that like
const char *myeol = "\r\n";
IN Order to issue "AT\r\n"
I tried to write something like this, but no success:
UART_write(handle, AT_norn, sizeof(AT_norn));
UART_write(handle, myeol, sizeof(myeol));
How can I use above method to save some RAM size?
As was already mentioned, sizeof
does not work in your approach because it will evaluate to the size of a pointer, not the string literal where it points to.
If your purpose is to reduce RAM usage, you could replace your variables with macros.
#define AT "AT"
#define ATI "ATI"
This would remove pointer variables in RAM. The strings itself are probable located in ROM.
Depending on cleverness of compiler and linker, your pointers might be included in the final binary even if they are not used.
Defining macros causes only inclusion of those strings that are actually used. Strings that are used multiple times in a file should be stored in same location by the compiler.
This also allows you to use sizeof
because sizeof
evaluates to the number of characters used to store the string literal.
This would also work with arrays as suggested in David's answer.
Then you could remove need to store the EOL at all by adding a new function that does that for you:
void UART_write_AT(int handle, unsigned char *buf, size_t len) {
UART_write(handle, buf, len);
UART_write(handle, "\r\n", 2);
}
I didn't check for correct types of parameters or return value. You might adjust to your needs.
Then you can call it like this:
UAR_write_AT(handle,ATI,sizeof(ATI)-1);
Note the -1
because sizeof includes the terminating 0
byte for string literals which should not be sent to the UART.