Introduction to 8051 microcontrollers

Embed Size (px)

Citation preview

  • 8/9/2019 Introduction to 8051 microcontrollers

    1/17

    Naveed Asif. +92-333-5234576.

    Introduction to 8051 microcontrollers

    1.1 Introduction to microcontrollers

    A micro-controller can be compared to a small stand alone computer, it is a verypowerful device, which is capable of executing a series of pre-programmed tasks and

    interacting with other hardware devices. Being packed in a tiny integrated circuit (IC)whose size and weight is usually negligible, it is becoming the perfect controller for

    robots or any machines requiring some kind of intelligent automation. A singlemicrocontroller can be sufficient to control a small mobile robot, an automatic

    washer machine or a security system. Any microcontroller contains a memory to

    store the program to be executed, and a number of input/output lines that can beused to interact with other devices, like reading the state of a sensor or controlling a

    motor.

    Nowadays, microcontrollers are so cheap and easily available that it is common touse them instead of simple logic circuits like counters for the sole purpose of gaining

    some design flexibility and saving some space. Some machines and robots will evenrely on a multitude of microcontrollers, each one dedicated to a certain task. Most

    recent microcontrollers are 'In System Programmable', meaning that you can modifythe program being executed, without removing the microcontroller from its place.

    Today, microcontrollers are an indispensable tool for the robotics hobbyist as well as

    for the engineer. Starting in this field can be a little difficult, because you usuallycan't understand how everything works inside that integrated circuit, so you have to

    study the system gradually, a small part at a time, until you can figure out the wholeimage and understand how the system works.

    1.2 The 8051 microcontroller architectureThe 8051 is the name of a big family of microcontrollers. The device which we are

    going to use along this tutorial is the 'AT89S52'which is a typical 8051microcontroller manufactured by Atmel. Note that this part doesn't aim to explain

    the functioning of the different components of a 89S52 microcontroller, but rather togive you a general idea of the organization of the chip and the available features,

    which shall be explained in detail along this tutorial.

    The block diagram provided by Atmel in their datasheet showing the architecture

    the 89S52 device can seem very complicated, and since we are going to use the Chigh level language to program it, a simpler architecture can be represented as the

    figure 1.2.A.

    This figures shows the main features and components that the designer can interact

    with. You can notice that the 89S52 has 4 different ports, each one having 8Input/output lines providing a total of 32 I/O lines. Those ports can be used to

    output DATA and orders do other devices, or to read the state of a sensor, or aswitch. Most of the ports of the 89S52 have 'dual function' meaning that they can be

    used for two different functions: the fist one is to perform input/output operationsand the second one is used to implement special features of the microcontroller like

    counting external pulses, interrupting the execution of the program according toexternal events, performing serial data transfer or connecting the chip to a computer

    to update the software.

  • 8/9/2019 Introduction to 8051 microcontrollers

    2/17

    Naveed Asif. +92-333-5234576.

    Each port has 8 pins, and will be treated from the software point of view as an 8-bit

    variable called 'register', each bit being connected to a different Input/Output pin.

    You can also

    notice two

    different memorytypes: RAM andEEPROM. Shortly,

    RAM is used tostore variable

    during programexecution, while

    the EEPROMmemory is used to

    store the programitself, that's why it

    is often referredto as the 'program

    memory'. Thememory

    organization will

    be discussed indetail later.

    The special

    features of the

    89S52microcontroller

    are grouped in theblue box at the

    bottom of figure1.2.A. At this

    stage of thetutorial, it is just

    important to notethat the 89S52

    incorporateshardware circuits

    that can be usedto prevent the

    processor fromexecuting various

    repetitive tasks

    and saveprocessing powerfor more complex

    calculations.Those simple

    tasks can be

    counting thenumber of

    external pulses on

    Figure 1.2.A

  • 8/9/2019 Introduction to 8051 microcontrollers

    3/17

    Naveed Asif. +92-333-5234576.

    a pin, orgenerating precise

    timing sequences.

    It is clear that the CPU (Central Processing Unit) is the heart of the microcontrollers,It is the CPU that will Read the program from the FLASH memory and execute it by

    interacting with the different peripherals discussed above.

    Figure 1.2.B shows the pin configuration of

    the 89S52, where the function of each pinis written next to it, and, if it exists, the

    dual function is written between brackets.The pins are written in the same order as in

    the block diagram of figure 1.2.A, exceptfor the VCC and GND pins which I usually

    note at the top and the bottom of anydevice.

    Note that the pin that have dual functions,

    can still be used normally as aninput/output pin. Unless you program uses

    their dual functions, All the 32 I/O pins of

    the microcontroller are configured asinput/output pins.

    Most of the function of the pins of the

    89S52 microcontroller will be discussed in

    detail, except for the pins required tocontrol an external memory, which are the

    pins number 29, 30 and 31. Since we arenot going to use any external memory, pins

    29 and 30 will be ignored through all thetutorial, and pin 31 (EA) always connected

    to VCC (5 Volts) to enable the micro-controller to use the internal on chip

    memory rather than an external one(connecting the pin 31 to ground would

    indicate to the microcontroller that anexternal memory is to be used instead of

    the internal one).

    Figure 1.2.B

    1.3. Memory organizationA RAM stands for Random Access Memory, it has basically the same purpose of theRAM in a desktop computer, which is to store some data required during the

    execution time of different programs. While an EEPROM, also called FLASH memoryis a more elaborated ROM (Read Only Memory) which is the memory where the

    program being executed is stored. Even if that's not exactly true, you can comparean EEPROM to the Hard-Disk of a desktop computer from a general point of view.

    The EEPROM term stands for Electronically Erasable and Programmable Read OnlyMemory.

  • 8/9/2019 Introduction to 8051 microcontrollers

    4/17

    Naveed Asif. +92-333-5234576.

    In microcontrollers, like in any digital system, memory is organized in Registers,Which is the basic unit of construction of a memory. Each register is composed of a

    number of bits (usually 8) where the data can be stored. In the 8051 family ofmicrocontrollers for example, most registers

    are 8-bit register, capable of storing values rangingfrom 0 to 255. In order to use bigger values, various

    register can be used simultaneously. Figure 1.3.Ashows a typical 8-bit registers, where the notation D0to D7 stands for the 8 DATA bits of the register.

    Typical register

    D7 D6 D5 D4 D3 D2 D1 D0Figure 1.3.A

    As you shall see, the RAM memory of the 89S52, which contains 256 registers, isdivided into to main parts, the GPR part, and the SFR part. GPR stands for 'General

    Purpose Register' and are the registers that you can use to store any data during theexecution of your program. SFRs (Special function Register) are registers used to

    control the functioning of the microcontroller and to assist the processor through thevarious operations being executed. For example, SFRs can be used to control

    Input/Output lines, to retrieve data transmitted through the serial port of a desktopcomputer, or to configure one of the on-chip counters and timers.

    In a memory each register has a specific address which is usedby the processor to read and write from specific memory

    location. Figure 1.3.B shows the memory organization of the

    256 registers of the RAM of the 89S52 microcontroller. Theaddress is noted in Hexadecimal format as this notation

    simplifies digital logic calculations for the designers, 00corresponds to the first location and FF which is equal to 256

    corresponds to the last location.

    A programmer that would use the assembly language, have to

    take this memory organization into consideration whilechoosing the locations where his variables are stored, as

    writing general purpose data into special function registerscould prevent the microcontroller from working correctly, but

    since we will use the C language using the KEIL IDE(integrated development environment), this part will be totally

    handled by the compiler.

    Figure 1.3.B

    1.4 Clock conceptThe clock concept is found in all modern digital electronics, it is a simple circuit that

    will generate pulses of electricity at a very specific frequency. Those pulses willcadence all the events happening inside a microcontroller, those pulses will also

    assure the synchronization of the events between various components inside the

    microcontroller. For example, if the CPU is waiting for some result of mathematicaloperation from the ALU (Arithmetic and Logic Unit), it will be known - according to

    very specific protocol - when and where the resulting data will be delivered to theCPU. The synchronization of those two devices is maintained because they share the

    same clock.

    The clock has another very important role which is to enable the microcontroller tocount timing. without a precise clock, it would be impossible to build a 'Real Time

    System', or any other device that relies on time measurements. It can be deducedthat the precision of the timing of a microcontroller depends on the frequency of its

  • 8/9/2019 Introduction to 8051 microcontrollers

    5/17

    Naveed Asif. +92-333-5234576.

    clock.

    In the 89S52 microcontroller, the clock can be fixed to different value by connectinga crystal to the pins 18 and 19. Those crystals are sold with the frequency written on

    them in Mega Hertz. The maximum operating frequency of the AT89S52 is 33 Mhz,however other manufacturers like philips built similar 8051 microcontrollers that can

    run at frequencies up to 120 Mhz.1.5 Life cycle of a microcontroller project

    Before passing to the next part of the tutorial, is important to have a general idea of

    the steps that are followed to realize a project, from the very beginning when youget an idea to the very end when you finalize your project.

    As you can see in figure1.5.A, after you settle

    on the choice of yourproject in the 'brain

    storming' part, itsimperative to imagine

    how it can beimplemented from the

    hardware point of view,before passing to the

    programming phase,because programming is

    much more flexible thanthe hardware design. In

    other words, you startby designing the

    hardware, then youwork on the

    programming whiletaking in consideration

    the eventual constraintsimposed by the

    hardware design.

    Figure 1.5.A

    The hardware design includes all the aspects of the electronic connections between

    other devices, like the compatibility of the voltage levels, or the required number of

    pins, etc...

    After you're done with a first version of your program, you can transfer it to the

    microcontroller mounted on the board that you realized already, resulting in a firstprototype. The transfer of the code is done using a special device called 'burner' or

    'programmer' that connect to the computer, reads the HEX file generated by the

    compiler, and sends it to the 'program memory' of the microcontroller. The prototypewill be used to test your project, correct eventual errors and enhance itsperformance, tacking in account the famous rule that states that any project never

    works the first time, at least it does not work as you expected!

    Your project will always stay in the prototyping cycle, even if you decide that it isfunctioning correctly, simply because perfect machines or inventions do not exist, so

    there is always some room for little changes and updates.

  • 8/9/2019 Introduction to 8051 microcontrollers

    6/17

    Naveed Asif. +92-333-5234576.

    From the C program to the machine languageThe C source code is very high level language, meaning that it is far from being at

    the base level of the machine language that can be executed by a processor. Thismachine language is basically just zero's and one's and is written in Hexadecimal

    format, that why they are called HEX files.

    There are several types

    of HEX files; we aregoing to produce

    machine code in theINTEL HEX-80 format,

    since this is the outputof the KEIL IDE that we

    are going to use. Figure2.1.A shows that to

    convert a C program tomachine language, it

    takes several steps

    depending on the toolyou are using, however,the main idea is to

    produce a HEX file atthe end. This HEX file

    will be then used by the'burner' to write every

    byte of data at the

    appropriate place in theEEPROM of the 89S52.

    figure 2.1.A

    2.2. Variables and constantsVariables

    One of the most basic concepts of programming is to handle variables. knowing theexact type and size of a variable is a very important issue for microcontroller

    programmers, because the RAM is usually limited is size. There are two main designconsiderations to be taken in account when choosing the variables types: the

    occupied space in ram and the processing speed. Logically, a variable that occupies abig number of registers in RAM will be more slowly processed than a small variable

    that fits on a single register.

    For you to chose the right variable type for each one of your applications, you willhave to refer to the following table:

    Data Type Bits Bytes Value Rangebit 1 -- 0 to 1

    signed char 8 1 -128 to +127unsigned char 8 1 0 to 255

    signed int 16 2 -32768 to +32767unsigned int 16 2 0 to 65535

  • 8/9/2019 Introduction to 8051 microcontrollers

    7/17

    Naveed Asif. +92-333-5234576.

    signed long 32 4 -2147483648 to 2147483647unsigned long 32 4 0 to 4294967295

    float 32 41.175494E-38 to3.402823E+38

    This table shows the number of bits and bytes occupied by each types of variables,noting that each byte will fit into a register. You will notice that most variables canbe either 'signed' or unsigned 'unsigned', and the major difference between the tow

    types is the range, but both will occupy the same exact space in memory.

    The names of the variables shown in the table are the same that are going to beused in the program for variables declarations. Note that in C programming

    language, any variable have to be declared to be used. Declaring a variable, willattribute a specific location in the RAM or FLASH memory to that variable. The size of

    that location will depend on the type of the variable that have been declared.

    To understand the difference between those types, consider the following example

    source code where we start by declaring three 'unsigned char' variables, and one'signed char' and then perform some simple operations:

    unsigned char a,b,c;

    signed char d;

    a = 100;b = 200;

    c = a - b;d = a - b;

    In that program the values of 'c' will be equal to '155'! and not '-100' as you though,because the variable 'c' is an unsigned type, and when a the value to be stored in a

    variable is bigger than the maximum value range of this variable, it overflows androlls back to the other limit. Back to our example, the program is trying to store '-

    100' in 'c', but since 'c' is unsigned, its range of values is from '0 to 255' so, trying tostore a value below zero, will cause the the variable to overflow, and the compiler

    will subtract the '-100' from the other limit plus 1, from '255 + 1' giving '156'. Weadd 1 to the range because the overflow and roll back operation from 0 to 255

    counts for the subtraction of one bit. On the other hand, the value of 'd' will be equalto '-100' as expected, because it is a 'signed' variable. Generally, we try to avoid

    storing value that are out of range, because sometime, even if the compiler doesn'thalt on that error, the results can be sometimes totally un-expected.

    Note that in the C programming language, any code line is ended with a semicolon

    ';', except for the lines ending with brackets '{' '}'.

    Like in any programming language, the concept of a variables 'array' can also be

    used for microcontrollers programming. an array is like a table or a group ofvariables of the same type, each one can be called by a specific number, for example

    an array can be declared this way:

    char display[10];

    this will create a group of 10 variables. Each one of them is accessible by its number,

  • 8/9/2019 Introduction to 8051 microcontrollers

    8/17

    Naveed Asif. +92-333-5234576.

    example:

    display[0] = 100;display[3] = 60;

    display[1] = display[0] - display[3];

    where 'display[1]' will be equal to '40'. Note that 'display' contains 10 differentvariables, numbered from 0 to 9. In that previous example, according to the variabledeclaration, there is not such variable location as 'display[10]', and using it will cause

    an error in the compiler.

    ConstantsSometimes, you want to store a very large amount of constant values, that wouldn't

    fit in the RAM or simply would take too much space. you can store this DATA in theFLASH memory reserved for the code, but it wont be editable, once the program is

    burned on your chip. The advantage of this technique is that it can be used to store ahuge amount of variables, noting that the FLASH memory of the 89S52 is 8K bytes,

    32 times bigger than the RAM memory. It is, however, your responsibility to

    distribute this memory between your program and your DATA.

    To specify that a variable is to be stored in the FLASH memory, we use exactly thesame variable types names but we add the prefix 'code' before it. Example:

    code unsigned char message[500];

    This line would cause this huge array to be stored in the FLASH memory. This can beinteresting for displaying messages on an LCD screen.

    To access the pins and the ports through programming, there are a number of pre-

    defined variables (defined in the header file, as you shall see later) that dramaticallysimplifies that task. There are 4 ports, Port 0 to Port 3, each one of them can be

    accessed using the charvariables P0, P1, P2 and P3 respectively. In those chartypes variables, each one of the 8 bits represents a pin on the port. Additionally, you

    can access a single pin of a port using the bit type variables PX_0 to PX_7, where Xtakes a value between 0 and 3, depending on the port being accessed. For example

    P1_3 is the pin number 3 of port 1.

    You can also define your own names, using the '#define' directive. Note that this iscompiler directive, meaning that the compiler will use this directive to read and

    understand the code, but it is not a statement or command that can be translated tomachine language. For example, you could define the following:

    #define LED1 P1_0

    With the definition above, the compiler will replace every occurrence ofLED1 by

    P1_0. This makes your code much more easier to read, especially when the new

    names you give make more sense.

    You could also define a numeric constant value like this:

    #define led_on_time 184

    Then, each time you write led_on_time, it will be replaced by 184. Note that this is

  • 8/9/2019 Introduction to 8051 microcontrollers

    9/17

    Naveed Asif. +92-333-5234576.

    not a variable and accordingly, you cannot write something like:

    led_on_time = 100;//That's wrong, you cannot change a constant's value in code.

    The utility of using defined constants, appears when you want to adjust some delaysin your code, or some constant variables that are re-used many times within the

    code: With a predefined constant, you only change it's value once, and it's applied tothe whole code. that's for sure apart from the fact that a word like led_on_time ismuch more comprehensive than simply '184'!

    Along this tutorial you will see how port names, and special function registers areused exactly as variables, to control input/output operations and other features of

    the microcontroller like timers, counters and interrupts.

    2.3. Mathematical & logic operationsNow that you know how to declare variables, it is time to know how to handle themin your program using mathematical and logic operations.

    Mathematical operations:The most basic concept about mathematical operations in programming languages,

    is the '=' operator which is used to store the content of the expression at its right,into the variable at its left. For example the following code will store the value of 'b'

    into 'a' :

    a = b;

    And subsequently, the following expression in totally invalid:

    5 = b;

    Since 5 in a constant, trying to store the content of 'b' in it will cause an error.

    You can then perform all kind of mathematical operations, using the operators'+','-','*' and '/'. You can also use brackets '( )' when needed. Example:

    a =(5*b)+((a/b)*(a+b));

    If you include 'math.h' header file, you will be able to use more advanced functionsin your equations like Sin, Cos and Tan trigonometric functions, absolute values and

    logarithmic calculations like in the following example:

    a =(c*cos(b))+sin(b);

    To be able to successfully use those functions in your programs, you have to know

    the type of variables that those functions take as parameter and return as a result.For example a Cosine function takes an angle in radians whose value is a float

    number between -65535 and 65535 and it will return a float value as a result. Youcan usually know those data types from the 'math.h' file itself, for example, the

    cosine function, like all the others is declared in the top of the math header file, andyou can read the line:

    extern float cos (float val);

  • 8/9/2019 Introduction to 8051 microcontrollers

    10/17

    Naveed Asif. +92-333-5234576.

    from this line you can deduce that the 'cos' function returns a float data type, and

    takes as a parameter a float too. (the parameter is always between brackets.). Usingthe same technique, you can easily know how to deal with the rest of the functions

    of the math header file. the following table shows a short description of thosefunctions:

    Function Description

    char cabs (char val); Return an the absolute value of a charvariable.

    int abs (int val); Return an the absolute value of a intvariable.long labs (long val); Return an the absolute value of a long variable.

    float fabs (float val); Return an the absolute value of a floatvariable.

    float sqrt (float val); Returns the square root of a float variable.

    float exp (float val);Returns the value of the Euler number 'e' to the power

    ofval

    float log (float val); Returns the natural logarithm ofvalfloat log10 (float val); Returns the common logarithm ofval

    float sin (float val);

    A set of standard trigonometric functions. They all take

    angles measured in radians whose value have to bebetween -65535 and 65535.

    float cos (float val);

    float tan (float val);float asin (float val);

    float acos (float val);float atan (float val);

    float sinh (float val);float cosh (float val);

    float tanh (float val);

    float atan2 (float y, float x);

    This function calculates the arc tan of the ratio y / x,

    using the signs of both x and y to determine thequadrant of the angle and return a number ranging

    from -pi to pi.

    float ceil (float val);Calculates the smallest integer that is bigger than val.

    Example: ceil(4.3) = 5.float floor (float val);

    Calculates the largest integer that is smaller than val.

    Example: ceil(4.8) = 4.

    float fmod (float x, float y);Returns the remainder of x / y. For example:

    fmod(15.0,4.0) = 3.float pow (float x, float y); Returns x to the power y.

    Logical operations:You can also perform logic operations with variables, like AND, OR and NOT

    operations, using the following operators:

    Operator Description

    ! NOT (bit level) Example: P1_0 = !P1_0;~ NOT (byte level) Example: P1 = ~P1;

    & AND| OR

    Note that those logic operation are performed on the bit level of the registers. To

    understand the effect of such operation on registers, it's easier to look at the bits ofa variable (which is composed of one or more register). For example, a NOT

    operation will invert all the bit of a register. Those logic operators can be used inmany ways to merge different bits of different registers together.

  • 8/9/2019 Introduction to 8051 microcontrollers

    11/17

    Naveed Asif. +92-333-5234576.

    For example, consider the variable 'P1', which is of type 'char', and hence stored inan 8-bit register. Actually P1 is an SFR, whose 8 bits represents the 8 I/O pins of

    Port 1. It is required in that example to clear the 4 lower bits of that register withoutchanging the state of the 4 other which may be used by other equipment. This can

    be done using logical operators according to the following code:

    P1 = P1 & 0xF0; (Adding '0x' before a number indicates that it is a hexadecimalone)

    Here, the value of P1 is ANDed with the variable 0xF0, which in the binary base is

    '11110000'. Recalling the two following relations:

    1 AND X = X0 AND X = 0

    (where 'X' can be any binary value)

    You can deduce that the 4 higher bits of P1 will remain unchanged, while the 4 lowerbits will be cleared to 0.

    By the way, note that you could also perform the same operation using a decimalvariable instead of a hexadecimal one, for example, the following code will haveexactly the same effect than the previous one (because 240 = F0 in HEX):

    P1 = P1 & 240;

    A similar types of operations that can be performed on a port, is to to set some of its

    bits to 1 without affecting the others. For example, to set the first and last bit of P1,without affecting the other, the following source code can be used:

    P1 = P1 | 0x81;

    Here, P1 is ORed with the value 0x81, which is '10000001' in binary. Recalling thetwo following relations:

    1 OR X = 1

    0 OR X = X(where 'X' can be any binary value)

    You can deduce that the first and last pins of P1 will be turned on, without affectingthe state of the other pins of port 1. Those are just a few example of the

    manipulations that can be done to registers using logical operators. Logic operatorscan also be used to define very specific conditions, as you shall see in the next

    section.

    The last types of logic operation studied in this tutorial is the shifting. It can beuseful the shift the bit of a register the right or to the left in various situations. this

    can be done using the following two operators:

    Operator Description

    >> Shift to the right

  • 8/9/2019 Introduction to 8051 microcontrollers

    12/17

    Naveed Asif. +92-333-5234576.

    P1 = 0x01; // After that operation, in binary, P1 = 0000 0001P1 = (P1

  • 8/9/2019 Introduction to 8051 microcontrollers

    13/17

    Naveed Asif. +92-333-5234576.

    != Not equal to

    The 'If' code block can get a little more sophisticated by introducing the 'else' and'else if' statement. Observe the following example source code:

    if (expression_1) {

    ...code block 1...

    }else if(expression_2) {

    ...code block 2

    ...}else if(expression_3) {

    ...code block 3

    ...}else{

    ...

    code block 4...}

    Here, There are four different code blocks, only one shall be executed if and only if

    the corresponding condition is true. The last code block will only be executed if noneof the previous expression is valid. Note that you can have as many 'else if' blocks as

    you need, each one with its corresponding condition, BUT you can only have one'else' block, which is completely logical. However you can chose not to have and

    'else' block at all if you want.

    There are some other alternatives to the 'if...else' code block, that can provide faster

    execution speeds, but also have some limitations and restrictions like the'Select...case' code block. For now, it is enough to understand the 'if...else' code

    block, whose performance is quite fair and have a wide range of applications.

    Another very important tool in the programming languages is the loop. In Clanguage like in many others, loops are usually restricted to certain number of loops

    like in the 'for' code block or restricted to a certain condition like the 'while' block.

    Let's start with the 'for' code block, which is a highly controllable and configurable

    loop. consider the following example source code:

    for(i=0;i

  • 8/9/2019 Introduction to 8051 microcontrollers

    14/17

    Naveed Asif. +92-333-5234576.

    following syntax:

    for(start;condition;step){...

    code block...

    }

    Wherestartrepresents the start value assigned to the count value before the loop

    begins. The condition is the expression that is is to remain true for the loop to

    continue; as long as this conditions is satisfied, the code will keep looping. Finally,step is the increase or decrease of the counting variable, it can be any statement

    that changes its value, whether by an addition or subtraction.

    The second type of loop that we are going to study is the 'while' loop. the syntax ofthis one is simpler than the previous one, as you can observe in the following

    example source code, that is equivalent to the previous method:

    while(i < 10){

    P0 = i;i = i +1;}

    Here there is only one parameter to be defined, which is the condition to keep this

    loop alive, which is 'i < 10' in our example. Then, it is the responsibility of theprogrammer to design the software carefully to provide an exit for that loop, or to

    make it an infinite loop. Both techniques are commonly used in microcontrollerprograms, as you shall see later on along this tutorial.

    2.5. Functions

    Functions are way of organizing your code, reducing its size, and increasing itsoverall performance, by grouping relatively small parts of code to be reused manytimes in the same program. A new function can be created according to the following

    syntax:

    Function_name(parameter_1, Parameter_2, Parameter_3){...

    function body...

    return value (optional)...

    }

    This is the general form of a function. The number of parameters of the function canbe more than the three parameters of the examples above, as it can be zero, all

    depends on the type and use of the function. The function's body is usually a subprogram that implies the parameters to produce the required result. some functions

    will also generate an output, like the cos() function, through the 'return' command,which will output the value next to it. Usually the 'return' command is used at the

    end of the function.

    A very common use of functions without return value is to create delays in a

  • 8/9/2019 Introduction to 8051 microcontrollers

    15/17

    Naveed Asif. +92-333-5234576.

    software, consider the following function:

    delay(unsigned int y){unsigned int i;

    for(i=0;i

  • 8/9/2019 Introduction to 8051 microcontrollers

    16/17

    Naveed Asif. +92-333-5234576.

    All C programs have this common organization scheme, sometimes it's followed,sometimes it's not, however, it is imperative for this category of programming that

    this organization scheme be followed in order to be able to develop your applicationssuccessfully. Any application can be divided into the following parts, noting that is

    should be written in this order:

    a. Headers Includes and constants definitionsIn this part, header files (.h) are included into your source code. those headers filescan be system headers to declare the name of SFRs, to define new constants, or to

    include mathematical functions like trigonometric functions, root square calculations

    or numbers approximations. Header files can also contain your own functions thatwould be shared by various programs.

    b. Variables declarations

    More precisely, this part is dedicated to 'Global Variables' declarations. Variablesdeclared in this place can be used anywhere in the code. Usually in microcontroller

    programs, variables are declared as global variables instead of local variables, unlessyour are running short of RAM memory and want to save some space, so we use

    local variables, whose values will be lost each time you switch from a function to

    another. To summarize, global variables as easier to use and implement than localvariables, but they consume more memory space.

    d. functions' bodyHere you group all your functions. Those functions can be simple ones that can be

    called from another place in your program, as they can be called from an 'interruptvector'. In other words, the sub-programs to be executed when an interrupt occurs is

    also written in this place.

    e. InitializationThe particularity of this part is that it is executed only one time when the

    microcontroller was just subjected to a 'RESET' or when power is just switched ON,

    then the processor continue executing the rest of the program but never executesthis part again. This particularity makes it the perfect place in a program to initialize

    the values of some constants, or to define the mode of operation of the timers,counters, interrupts, and other features of the microcontroller.

    f. Infinite loop

    An infinite loop in a microcontroller program is what is going to keep it alive, because

    a processor have to be allays running for the system to function, exactly like a hearthave to be always beating for a person to live. Usually this part is the core of any

    program, and its from here that all the other functions are called and executed.

    2.7. Simple C program for 89S52

    Here is a very simple but complete example program to blink a LED. Actually it is thesource code of the example project that we are going to construct in the next part of thetutorial, but for now it is important to concentrate on the programming to summarize the

    notions discussed above.#include #include

    delay(unsigned int y){

  • 8/9/2019 Introduction to 8051 microcontrollers

    17/17

    Naveed Asif. +92-333-5234576.

    unsigned int i;for(i=0;i