String constants to be stored in code memory, not in RAM

General discussion on mikroC PRO for 8051.
Post Reply
Author
Message
vlk
Posts: 2
Joined: 03 Jan 2010 17:54

String constants to be stored in code memory, not in RAM

#1 Post by vlk » 03 Jan 2010 18:13

Hello,

I have many texts that I need to send through UART by using
Uart1_Write_Text("This is text example").
I have realized that the compiler allocates the space for these texts in RAM and I very quickly run out of the MCU RAM space.
As these texts are constant, I want the compiler to store them in flash ( code memory ) and use RAM just for variables ( I am using quite many of them as well ).

Does anyone know how I can force the compiler to use flash memory to store the string constants. I am trying something like this:
const code unsigned char Const_Text1[] = "This is text 1";
Uart1_Write_Text(Const_Text1);
but this does not work, seems to be a pointer issue.

Compiler is microC Pro 8051 v.2.2
MCU is AT89S8253

Many thanks,
vlk

User avatar
anikolic
mikroElektronika team
Posts: 1775
Joined: 17 Aug 2009 16:51
Location: Belgrade
Contact:

#2 Post by anikolic » 04 Jan 2010 15:31

Hi,
I will literally quote myself here from another similar PIC-related post:
Uart1_Write_Text() function uses unsigned char * parameter which is a pointer to RAM, and therefore cannot use pointers to ROM, or ROM strings. This fact is the key for finding a way to print ROM string with Uart1_Write_Text(). This can be done by copying segment of the ROM into the flash and then working with that flash. One string at a time, so RAM consumption would be minimized. Here's the example:

Code: Select all

const code unsigned char Const_Text1[] = "This is text 1";
const code unsigned char Const_Text2[] = "This is text 2";
const code unsigned char Const_Text3[] = "This is text 3";

char* codetxt_to_ramtxt(const char* ctxt){
  static char txt[20];
  char i;
  for(i =0; txt[i] = ctxt[i]; i++);

  return txt;
}

//......other declarations and functions

void main(){
  //.... your code
  UART1_Init(9600);
  UART1_Write_Text(codetxt_to_ramtxt(Const_Text1));
  UART1_Write_Text(codetxt_to_ramtxt(Const_Text2));
  UART1_Write_Text(codetxt_to_ramtxt(Const_Text3));
}
Best regards,
Aleksandar
Web Department Manager

vlk
Posts: 2
Joined: 03 Jan 2010 17:54

#3 Post by vlk » 04 Jan 2010 22:20

Hi Aleksandar,

many thanks for such quick reply. I did not realize it could be used as a pointer to RAM, but not to ROM.

Your workaround works perfectly okay with my application.
Thanks again.
Appreciate.

vlk

Post Reply

Return to “mikroC PRO for 8051 General”