Wednesday 29 June 2016

Stack Memory in Microcontrollers

Stack is a portion of memory that works on the principle of LIFO (last in first out).  It means that last in data will come out first.  In stack two operations are performed. First is PUSH and another is POP. PUSH function is used to save the data in stack memory and POP operation is performed to retrieve the data. In stack memory there is a pointer variable which monitor the top of the stack location in memory.  When a byte is pushed on to the stack this pointer value is increases by one to the next available address. When a byte is popped from the stack, this pointer contained value is decremented by one.

Uses of Stack
When a function is called stack memory is used to temporary store the local variables and return address from the function. On function call, current program counter (PC) value (stores the next instruction to be executed) and status register values are pushed on to the stack.
All the variables declared in to the function are managed in to the stack. This is the advantage of stack that we don required to allocate memory for the variable initialized in to the function. All the variables initialized in the functions are local to that function.
When program exists from the function all the variable popped from the stack and stack memory is cleared. We don’t require clearing this memory. When exist from the function stored status register and PC values are also popped to start execution after the function call.
In stack memory there is a limit of stack memory dependent on operating system. So we can store limited variables on to stack.
Heap Memory
Heap is the type of memory which is not managed automatically as stack memory is managed by the CPU. It is a free memory and there is no limit like stack memory. To allocate and deallocate memory in heap malloc() and calloc() and free() functions are used. Once the memory is allocated for the variables in heap it does not clear after exit form functions until we use free() function to clear the memory. When we use heap memory instead of Stack memory to store variables, these variables can be accessed globally.
Accessing the heap memory is slower as compare to access stack memory because we access the heap memory pointers.
Memory management is required in heap memory.  We have to free the memory location if it not used. If you are not able to free the memory using free() function memory leak problem may occurred.
Heap memory support dynamic memory allocation. It means we can resize the variables using realloc() functions.
malloc() Function
 malloc() function allocate specified size memory location for an object and returns a pointer to it. Syntax of malloc() is as follows:
            void *malloc(size_t size)
 Example:
                   int *ptr1     =       malloc(15);
This will allocate 15 memory location and return a pointer to ptr1.


calloc() Function
 calloc() function is also used to allocate the specified memory location for an object and returns a pointer to it. Syntax of calloc() is as follows:
void *calloc(size_t n, size_t siz)
 in put argument in calloc() is two variables one n, that defines the no of location to be reserved and siz will define the size of each location. The main difference between malloc() an calloc() is that it will initialized all location to Zero.
Example:
            int *ptr2     =       calloc(10,size(int));
realloc() Function
realloc() function used to resize the allocated area for an object and return a pointer according to new relocated memory location. Syntax of calloc() is as follows:
void * realloc (void * ptr, size_t size);
First argument define the address of firstly allocated memory and second argument is the modified size.
Example:
int *p1 =  calloc (5, sizeof (int));
int * p2 = (inrealloc (p1, sizeof(int));
What is Stack over Flow?

Stack has limited memory location. It can store a limited amount of memory location. Stack overflow occurs when try to push larger data from stack memory limitation. When we try to push more data on stack data will start over flowing in the memory and allocating in the other portion of memory location. This will cause the crash of system. To prevent from stack over flow don’t use many nested functions. Not initialize much of variable locally in any function, if it is required to initialize lot of variable then use heap to initialize the variable.

Monday 27 June 2016

Embedded system Architecture

Embedded system used in different application generally handles multiple tasks, interfacing with different sensors, actuators and different on board peripherals. In some application it also required to communicate with multiple processors in real time domain. Embedded system based project also used in the application where communication with external environment required. Communication may be wired or wireless, GPRS communication, Wi-Fi communication or Bluetooth communication.
Embedded software architecture should in manner that it should properly execute tasks such as communication with the interfaced devices, data sharing task with different modules, proper execution of interrupt service routine with latency required, and communication with network system.
Embedded software architecture designed in such a way that same architecture should be reused in future for decrease development time. In this case the initial development time will large and it require extra efforts to develop such architecture. Software developer may first develop the software according to client’s requirement and then convert it to modules which can be reused for future. Or they can give extra effort initially to developed software architecture in a manner that it can be used for future.
Main function of embedded software is to take data from the external word through Input pins and Input modules, performs operation on the data and gives output to user through output pins and Modules. It also takes care of data sharing between modules such that calculation result does not change due to hardware or software interrupt.
For example we take the example of simple calculator. User gives the input through key board and tells which operation to be performed on the data. Microcontroller displays the input data on the LCD and performed required operation on data and displays the result on the LCD.
Software Architecture Example
Software architecture can be in the form of polling method. In this method software always execute in the main routine. There will be no interrupt execution. In main routine software will poll from every module. If any module requires service then processor will give services to that module and then go in that manner. If the latency of event is high module can be inserted more than one time in the routine.
Another scenario can be in the form of interrupt control base execution. The image below gives the description of interrupt base software architecture:

As shown in figure above all execution will be done in the main routine. There will be a Timer ISR routine that will monitor the operation counter. Every time when timer ISR occurs Operation_Counter incremented by one.  In main routine there is switch statement that will execute the task according to Operation_counter Value.

If any task redundancy is large than this talk can be executed more than one time in a cycle. Here perform_operation1 is executed regularly.

In the last case “case n” Operation_Counter value becomes zero and next cycle will be start again from case 1.

In future if programmer wants to add some new module then module can be added easily according to execution redundancy of module. One thing to be monitored here that operation execution time in every case should not exceed the timer over flow time. If in any case operation execution time exceeds then try to break this execution in two steps.




Tuesday 21 June 2016

What is compiler in Embedded System?

In computing system compiler is a program which convert one type language to another language which is understandable by the computer or microcontroller.  In Computer programming programs are written in some type of high level language such as C,C++ etc and computer can understand the machine(in the form of 0’s and 1’s) language. 
So a compiler compile or translate the high level programming language to low level language which is understand able by computer. In this process it also take care of spotting the error done by programmers.



Compiler Main Functions:
The main function of compiler may be divided in following process. The sequence of execution of these processes may vary from one compiler to another compiler. Main functions of compilers are as follows:

Syntax Error Analysis: In this process compiler will check the code for if code violates the certain syntax requirement. This will spot the error in the code and notify to programmer to correct them. For example if programmer forget to add semicolon “;’ after the code line complier will scan the code tell the programmer about the line number where semicolon is missing.

Variable Type Check: In this process compiler will check syntax error regarding to variable.  For example a variable is used and but not declared, variable initialize with wrong data type and variable value exceeding in accordance to type defined.

Register Allocation: Every variable we defined in the program is in symbolic form. In this process these symbols is converted to some type of numbers which defines the registers in the specific machine.

Machine Code Generation: In this process program written in the C language first converted to assembly language program according to specific architecture of machine for which program is written. After this Assembly language code is converted in to machine code language which is the binary representation of code.  This code is burned in to the program memory of machine.

Difference between Microcontroller C and Assembly
S.No.
Parameter
Assembly Language
C Language
1
System Dependency
Assembly language is a low level language. Program written in this language will be machine level language. Every Mnemonic or operand equivalent to some binary numbers. These operand codes may changes form one architecture to architecture.
C is a middle high level language. Program written in c language does not required to be system dependent. If system architecture changes then same program can run on another system with some or no changes.
2
Code Size
Program written in assembly language will have small code size.
Code size will be large with C language program.
3
Faster Execution

In assembly language we get what we have written. All programs written will directly execution without any translation. Firmware engineer choose assembly language where faster execution is necessary.
Execution of program written in C language is slower then program written in assembly language. One line written in C language may represent many lines of assembly language program.
   4
Development Time

Development time of Assembly language code is large. Programmer should know the system architecture and all assembly instruction and register information of machine.
Development time in C language will be small. There are libraries to implement all the initialization and other processing tasks.
5
Portability

Program written in assembly language is not portable from one system to another system due to dependency on system architecture.
Program written in C language are Portable with no changes or with changes of header file.
6
Optimization

There will be no optimization in program written in Assembly language. Program is directly burned in to program memory without any changes.
There is optimization of code in compiling process. One line written in c language may be equivalent to 10 or more line of assembly language. Compiler has the capability to optimize the code
7
Easy Of Project Management

When program become large there will be problem in handling or managing the code.
It is easy to handle the c language program.
8
Complexity
Learning of Assembly language is hard due to dependent on machine and complexity is more.
It is easy to understand the C language code and complexity is less as compare to assembly language.


Monday 6 June 2016

What is Boot Loader?

All firmware developers listens the word BOOT LOADER. There is little bit confusion with this word in contrast to PC and Microcontroller.

In contrast to PC boot loader is a program that runs before an operation system start. Boot loader places the operating system in memory.  In computer is the process of initialization of all the peripherals.  

In microcontroller boot loader is the small piece of code which is used to reprogram the flash program memory. Boot loader resides in the program memory. Boot loader code should be small in size. Boot loader code may be place at the bottom of Flash Memory or at Top of Flash memory. Boot loader receives the code from any external communication module such as USB, UART, SPI, I2C, CAN etc and save this code in to program memory.



As shown in figure above after reset program start executing from Reset Vector 0x0000h. The Boot Load Code is available at bottom of Flash Memory.


Why Use Boot Loader?
·        Mostly microcontrollers use special hardware to program microcontroller. For example ST’s Microcontroller uses JTAG or single Interface module, AVR uses JTAG interface to program and debugging. They have some pins for programming. The hex file is of program originates in PC, So hardware to program the microcontroller is connected to PC by some interface like USB and Serial Communication and other end connected with the Microcontroller.  Some time this hardware is very expensive. In some cases Microcontrollers will be programmed with boot loader code with special hardware devices. Boot Loader code check communicates with host system through some type of communication like UART and if it gets any firmware upgrade command from Host system it will update the firmware of Microcontroller else it will execute existing code.



·        In Some case it is required to Firmware update in field then Boot Loader come in existence. In that cases Hex file will place in PC or other device which will communicates with microcontroller through serial communication.  When Microcontrollers get Reset command either by hardware or software, after reset boot loader check communication with Host system to upgrade the Firmware.


·        Firmware update over the air is the place where Boot Loader is required.  In this case we save the program to be updated receives from wireless communication in external memory or internal flash memory. After saving program we give the software reset command to microcontroller. After reset if new program exists in flash memory boot loader set program counter to execute program from new location.  If program saves in external memory then boot loader will first update the program in controller flash memory and then start execution updated program. 

Saturday 4 June 2016

Main Component of Microcontroller

Microcontroller is basically an On Chip Computer. I microcontroller all the Components such as CPU, Memory, I/O Devices, Interrupt Handler, Serial Communication Interface, Timer etc are fabricated on single chip.  As shown in figure below the entire component are connected to CPU via an internal bus and fabricated on the Chip. Module connects with the external word through I/O Module. There will be a fixed size of Program and Data memory in microcontroller. When developing product using Microcontroller we have to take care all these things in mind.


CPU (Central Processing Unit)
Central processing unit is the main part of microcontroller. CPU interacts with all modules through internal system bus. Main component of CPU are as follows:

ALU (Arithmetic Logic Unit) perform all the computational addition, subtraction, multiplication and digital operation task. ALU takes two input and give single output and store the data in specified address receives from registers.

Registers Files contains the working register of central processing unit. It contains the general purpose register for storing data address on which operation to be performed and special purpose register to such as Accumulator register or peripheral registers.

Control Unit (CU) determines which instruction to be executed next and configure the data path accordingly. Program counter register will use to monitor which instruction to be executed next. The control unit loads this instruction into the instruction register (IR), decodes the instruction, and sets up the data path to execute it. Data path configuration includes providing the appropriate inputs for the ALU (from registers or memory), selecting the right ALU operation, and making sure that the result is written to the correct destination (register or memory).

Stack Pointer points to the top of stack memory in microcontroller. Stack is the consecutive memory portion in the Data Ram memory to save the return address and status register during subroutine and interrupts call routine. There is a SFR register which points to the top of stack. When function call or interrupt occur Controller store the return address and status register to stack memory using PUSH instruction. When it will return from function of ISR it will retrieve the return address through POP instruction


Memory
In microcontroller there are mainly three types of memory, RAM, FLASH and EEPROM.  In microcontrollers the memory is limited. The architecture of microcontrollers may require that variable and constant should be in different memory.



RAM stands for random access memory. It is a type of Volatile memory. Means that this type of memory losses there data if power removed.  This memory stores the data that change repetitively in the program. The entire variables we defined in the program are stored in the RAM memory.

Flash Memory is non volatile memory. Means that data does not losses if power is removed. This type memory save data that does not change repetitive during program execution.  This memory also called program memory. This memory is same as BIOS in general computers.

EEPROM stands for electrically erasable programmable read only memory. This type of memory used to store variable which does not changes repetitively. This is a type of Non Volatile Memory. This memory is limited in Microcontrollers.


 I/O Module
This module used to communicate with the external environment. CPU communicated with this module with internal system bus.  The digital input functionality is used whenever the monitored signal should be interpreted digitally that is, when it only changes between the two states “high” (corresponding to logic 1) and “low” (corresponding to 0). The digital output functionality is used to set output pins to given voltage levels. The levels corresponding to high and low are again specified by the controller and depend on the controller’s operating voltage.

Timer
The timer module, which is strictly speaking a counter module, is an important part of every microcontroller, and most controllers provide one or more timers with 8 and/or 16 bit resolution. Timers are used for a variety of tasks ranging from simple delays over measurement of periods to waveform generation. The most basic use of the timer is in its function as a counter.


Serial Communication Devices
In microcontrollers Serial Communication module used to communicate with the external world.  In serial communication there is a specified protocol on which two modules communicates with each other.  In a microcontroller there one or more types of Serial communication modules.  Three basic serial communication peripherals are UART, SPI and I2C. 

Other devices

There are some other modules which are used for power optimization and proper working of microcontroller.  SLEEP module is used to reduce power consumption in the by entering controller in sleep mode. Watchdog Timer is used to monitoring the program execution. Once watch dog enabled it start down counting. When the counter value become zero a reset signal is triggered, which reset the microcontroller. To avoid reset software should update the watchdog counter before it becomes zero. 

Thursday 2 June 2016

Microcontroller Different form Microprocessor

These two terms Microcontroller and Microprocessor have always confused with each other. Both are designed for real time application. Microcontrollers are used for application specific applications and on other hand Microprocessor is used for General Purpose Application.

Following diagram illustrate the difference between Microcontroller and processor:




  • Microprocessor is a single on chip Central Processing Unit. It includes ALU (Arithmetic Logic Unit), CU (Control Unit) registers, instruction decoders, bus control circuit etc. On the other hand Microcontroller is the association of Microprocessor, Program and data Memory, Peripheral I/O Devices, Timers Clock Circuitry etc.
  • A microcontroller is a application specific computer on a single Chip that runs a single dedicated task. Microprocessor is used in general purpose application systems as Desktop and Laptops. 
  • For development of Project using Microprocessor required all external components (Program and data memory, I/O Devices) to interface. This makes the larger PCB Size, Expensive system.  On the other hand there will be no requirement of external peripherals so this makes the system cheap and small in size.
  • Microprocessor Instruction sets is data processing intensive. Means power full addressing mode and many instructions to move data between memory and CPU to handle big amount of data. Microcontrollers have instructions sets that are related to control of input and output.
  • Microprocessor based product are designed to interact with Humans and are more flexible to design. On the other hand Microcontroller based product are designed to interact with machine or for specific purpose, so these systems are less flexible.
  • Software Protection is not possible because program stores in external Memory.  In Microcontroller the Code protection is possible because of on chip program memory.
  • General Power consumption and heat dissipation is more because of external devices. Power Consumption in Microcontroller is very less compare to Microprocessors.
  • Clock Frequency used in microprocessor is in GHz. Where as in Microcontroller Clock is in MHz.