I'm trying to write a code in C (Using Keil µVision 5, device: AT89C51AC3) that lets me enter 2 Integer numbers, add them and then print them out. The problem is that I'm limited to a byte code size of max. 2048.
My actual code needs 2099 Bytes to run.
Any idea how I could do the same thing using less memory?
#include <stdio.h>
#include <REG52.H>
int main()
{
int a, b;
/*------------------------------------------------
Setup the serial port for 1200 baud at 16MHz.
------------------------------------------------*/
#ifndef MONITOR51
SCON = 0x50; /* SCON: mode 1, 8-bit UART, enable rcvr */
TMOD |= 0x20; /* TMOD: timer 1, mode 2, 8-bit reload */
TH1 = 221; /* TH1: reload value for 1200 baud @ 16MHz */
TR1 = 1; /* TR1: timer 1 run */
TI = 1; /* TI: set TI to send first char of UART */
#endif
printf("Enter 2 numbers\n");
scanf("%d%d",&a,&b);
printf("%d\n",a+b);
return 0;
}
You should hiccup when you see this simple code take up 2k+ of memory. That's a lot! The reason for this is that the stdio functions are terribly inefficient.
If you need to save memory and execution speed, you need to code these yourself. Which is not so hard, since you probably just need to read integers and not everything else those function can handle (float numbers, strings etc).
Also get rid of the int
type, use the fixed size types from stdint.h
instead. (If this is a 8 bit MCU, you should also avoid 16 bit numbers unless they are necessary.)
In addition, you will have to code the I/O part as well. On a microcontroller this would probably mean writing your own UART driver.
You should be able to reduce the code size to a couple of hundred bytes, depending on how code (in)efficient your microcontroller is.