+ All Categories
Home > Documents > Embedded Sys Manual

Embedded Sys Manual

Date post: 05-Jul-2018
Category:
Upload: yagnesh-badiyani
View: 225 times
Download: 0 times
Share this document with a friend

of 76

Transcript
  • 8/16/2019 Embedded Sys Manual

    1/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad

    Laboratory Manual for

    Embedded Systems

    B. TECH. SEM - VII (EC)

    Faculty of TechnologyDharmsinh Desai University

    Nadiad

  • 8/16/2019 Embedded Sys Manual

    2/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad

    NO. LAB PAGE

    NO.

    1 Introduction to Keil µvision 4 1

    2 Program Development Process 7

    3 GPIO 10

    4 A/D and D/A conversion 19

    5 Start - up file 29

    6 Array Processing 34

    7 Inline Assembly & Thumb State 36

    8 Software Interrupts & Subroutines 42

    9 IRQ and FIQ Exception Handling 46

    10 Thread and Fork 51

    11 Fanning and Chaining 62

    12 Semaphore 66

  • 8/16/2019 Embedded Sys Manual

    3/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 1

    LAB 1Introduction to Keil µvision 4

    AIM: To study the environment of Keil µvision 4.

    µVision4 OVERVIEW

    The µVision4 IDE is a Windows-based software development platform that combines arobust editor, project manager, and makes facility. µVision4 integrates all tools including theC compiler, macro assembler, linker/locator, and HEX file generator. µVision4 helpsexpedite the development process of your embedded applications by providing the following:

    Full-featured source code editorDevice database for configuring the development tool settingProject manager for creating and maintaining your projectsIntegrated make facility for assembling, compiling, and linking your embedded

    applications,Dialogs for all development tool settings,True integrated source-level Debugger with high-speed CPU and peripheral simulator,Advanced GDI interface for software debugging in the target hardware and forconnection to KeilULINKFlash programming utility for downloading the application program into Flash ROM,Links to development tools manuals, device datasheets & user‟s guides.

    The µVision4 IDE offers numerous features and advantages that help you quickly and

    successfully develop embedded applications. They are easy to use and are guaranteed to helpyou achieve your design goals.The µVision4 IDE and Debugger is the central part of the Keil development

    toolchain. µVision4 offers a Build Mode and a Debug Mode.In the µVision4 Build Mode you maintain the project files and generate the

    application.In the µVision4 Debug Mode you verify your program either with a powerful CPU

    and peripheral simulator or with the Keil ULINK USB-JTAG Adapter (or other AGDIdrivers) that connect the debugger to the target system. The ULINK allows you also todownload your application into Flash ROM of your target system. The figure below showsthe Keil µVision4.

  • 8/16/2019 Embedded Sys Manual

    4/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 2

    Menu Commands, Toolbars, and Shortcuts

    The menu bar provides you with menus for editor operations, project maintenance,development tool option settings, program debugging, external tool control, window selectionand manipulation, and on- line help.

    The toolbar buttons allow you to rapidly execute µVision4 commands. A Status Bar provides editor and debugger information. The various toolbars and the status bar can beenabled or disabled from the View Menu commands.

    The following sections list the µVision4 commands that can be reached by menucommands, toolbar buttons, and keyboard shortcuts. The µVision4 commands are groupedmainly based on the appearance in the menu bar:

    File Menu and File CommandsEdit Menu and Editor Commands

    Outlining MenuAdvanced MenuSelecting Text CommandsView MenuProject Menu and Project CommandsDebug Menu and Debug CommandsFlash MenuPeripherals MenuTools MenuSVCS Menu

    Window MenuHelp Menu

    Creating Applications

    This part describes the Build Mode of µVision4 and is grouped into the following sections: Create a Project: explains the steps required to setup a simple application and to generate

    HEX output. Project Target and File Groups: shows how to create application variants and organized

    the files that belong to a project. Tips and Tricks: provides information about the advanced features of the µVision4

    Project Manager.

  • 8/16/2019 Embedded Sys Manual

    5/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 3

    1. Create Project File Folder and Specify Project Name

    To create a new project file select from the µVision4 menu Project – New – µVisionProject. This opens a standard Windows dialog that asks you for the new project file name.You should you use a separate folder for each project. You can simply use the icon Create

    New Folder in this dialog to get a new empty folder.

  • 8/16/2019 Embedded Sys Manual

    6/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 4

    Select this folder and enter the file name for the new project, i.e. Project1. µVision4 creates anew project file with the name PROJECT1.UV2 which contains a default target and filegroup name. You can see these names in the Project Workspace – Files.

    Copy and Add the CPU Startup CodeAn embedded program requires CPU initialization code that needs to match the configurationof your hardware design. This Startup Code depends also on the tool chain that you are using.Since you might need to modify that file to match your target hardware, the file should becopied to your project folder.For most devices, µVision4 asks you to copy the CPU specific Startup Code to your project.This is required on almost all projects (exceptions are library projects and add-on projects).

  • 8/16/2019 Embedded Sys Manual

    7/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 5

    The Startup Code performs configuration of the microcontroller device and initialization ofthe compiler run-time system.Create New Source Files

    You may create a new source file with the menu option File – New. This opens anempty editor window where you can enter your source code. µVision4 enables the C color

    syntax highlighting when you save your file with the dialog File – Save As… under afilename with the extension *.C. We are saving our example file under the name MAIN.C.Add Source Files to Project

    Once you have created your source file you can add this file to your project. µVision4offers several ways to add source files to a project. For example, you can select the file groupin the Project Workspace – Files page and click with the right mouse key to open a localmenu. The option Add Files opens the standard files dialog. Select the file MAIN.C you have

    just created.Set Tool Options for Target

    µVision4 lets you set options for your target hardware. The dialog Options for Targetopens via the toolbar icon or via the Project - Options for Target menu item. In the Target tabyou specify all relevant parameters of your target hardware and the on-chip components ofthe device you have selected. The following dialog shows the settings for our example.Build Project

    Typical, the tool settings under Options – Target are all you need to start a newapplication. You may translate all source files and link the application with a click on theBuild Target toolbar icon. When you build an application with syntax errors, µVision4 willdisplay errors and warning messages in the Output Window – Build page. A double click ona message line opens the source file on the correct location in a µVision4 editor window.The next steps are:

    Test Programs with the µVision4 Debugger. The µVision4 Debugger offers twooperating modes: simulator that allows you to verify your application on your PC, or TargetDebugging with an Evaluation Board or your hardware platformProgram your application into Flash ROM. µVision4 integrates command-line driven FlashUtilities or can use the ULINK USB-JTAG Adapter for Flash programming. You may needto create a HEX file to use Flash programming utilities.Create HEX File

    Once you have successfully generated your application you can start debugging. Afteryou have tested your application, it is required to create an Intel HEX file to download thesoftware into an EPROM programmer or simulator. µVision4 creates HEX files with each

    build process when Create HEX file under Options for Target – Output is enabled. TheFLASH Fill Byte, Start and End values direct the OH166 utility to generate a sorted HEX

    files; sorted files are required for some Flash programming utilities.

    Test Programs with the µVision4 DebuggerThis chapter describes the Debug Mode of µVision4 and shows you how to use the

    user interface to test a sample program. Also discussed are simulation mode and the differentoptions available for program debugging.

    You can use µVision4 Debugger to test the applications you develop. The µVision4Debugger offers two operating modes that are selected in the Options for Target – Debugdialog.

    Use Simulator configures the µVision4 Debugger as software-only product that

    simulates most features of a microcontroller without actually having target hardware. Youcan test and debug your embedded application before the hardware is ready. µVision4

  • 8/16/2019 Embedded Sys Manual

    8/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 6

    simulates a wide variety of peripherals including the serial port, external I/O, and timers. The peripheral set is selected when you select a CPU from the device database for your target.

    2. Debug Windows and Dialogs

    During Debug Mode µVision4 offers additional Debug Windows and Dialogs that aresummarized below

    The Breakpoint Dialog allows you to define stop conditions for program execution.The Code Coverage Window provides execution statistic information of execute and notexecuted program parts.The CPU Registers may be reviewed and modified in the Regs page of the ProjectWorkspace window.The Disassembly Window allows program testing at the level of assembly instructions.The Logic Analyzer provides a graphical display for value changes of peripheral registersand variables.

    The Memory Window may be used to review and modify memory content.The Serial Window displays the UART communication with the application program.The Symbol Window shows debug symbol information of the application program.The Toolbox provides configurable buttons for debug command and debug functionexecution.The Watch Window lets you view and modify program variables and lists the currentfunction call nesting.

    Flash ProgrammingµVision4 integrates Flash Programming Utilities in the project environment. All

    configurations are saved in context with your current project.You may use external command-line driven utilities (usually provided by the chip

    vendor) or the Keil ULINK USB-JTAG Adapter. The Flash Programming Utilities areconfigured under Project - Options - Utilities.

    Flash Programming may be started from the Flash Menu or before starting theµVision4 Debugger when you enable Project - Options - Utilities - Update Target beforeDebugging.

    Conclusion: ________________________________________________________________ ________________________________________________________________

    ________________________________________________________________ ________________________________________________________________ ________________________________________________________________

    ____________________________________________________________ ___

  • 8/16/2019 Embedded Sys Manual

    9/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 7

    LAB 2Program Development Process

    AIM: Write a program in „C‟ that adds and multiply two numbers.

    PROGRAM DEVELOPMENT PROCESS

    First, create a new project named first with extension “.Uv2”.We will se lect the device from NXP (founded by Phillips) family. The board available with us is LPC 2368. So we willselect every time this hardware. After giving the name adds the startup code of LPC 2300.Sto the project file. After that the source codes save as text1.C. Add this file to the SourceGroup 1. Build the project and Debug the project in simulator by selecting the option for

    target 1. You can see the contents of user registers while running the program step by step.

    PROGRAM:

    1. Addition

    #includeint main(){int a=1,b=2;

    int c;c=a+b;}

    Output:

  • 8/16/2019 Embedded Sys Manual

    10/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 8

    2. Multiplication

    #includeint main()

    {

    int a=2,b=2;int c;c=a*b;

    }

    Output:

    3. Subtraction

    #includeint main()

    {

    int a=5,b=2;int c;c=a-b;

  • 8/16/2019 Embedded Sys Manual

    11/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 9

    }

    Output:

    ASSIGNMENT:

    1. What is significance of disassembly window?

    2. What is significance of memory window? How to open it and modify it?

    3. What information is contained in project workspace?

    Conclusion: ________________________________________________________________ ________________________________________________________________ ________________________________________________________________

    ________________________________________________________________ ________________________________________________________________ ________________________________________________________________

    ______________________________________________________________

  • 8/16/2019 Embedded Sys Manual

    12/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 10

    LAB 3

    GPIO

    AIM: Programming General Purpose Input Output Ports

    SPECIAL FUNCTION REGISTERS FOR GPIO:

    FIOXDIRFIOXMASKFIOXSETFIOXCLRFIOPIN

    SPECIAL FUNCTION REGISTERS DESCRIPTION:

  • 8/16/2019 Embedded Sys Manual

    13/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 11

    FEATURES OF DIGITAL GPIO PORTS:

    GPIO PORT0 and PORT1 are ports accessible via either the group of registers providing enhanced features and accelerated port access or the legacy group ofregisters. PORT2/3/4 are accessed as fast ports only.

    Accelerated GPIO functions:GPIO registers are relocated to the ARM local bus so that the fastest possible I/Otiming can be achieved Mask registers allow treating sets of port bits as a group,leaving other bits unchanged All GPIO registers are byte and half-word addressableEntire port value can be written in one instructionBit-level set and clear registers allow a single instruction set or clear of any number of

    bits in one portDirection control of individual bitsAll I/O default to inputs after resetBackward compatibility with other earlier devices is maintained with legacy registersappearing at the original addresses on the APB bus

    PROGRAM:

  • 8/16/2019 Embedded Sys Manual

    14/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 12

    1. Program to generate continuous ON-OFF LED flashing pattern on hardware boardLPC 2368.

    #include

    voidLED_init(void) // Function that initializes LEDs{

    PINSEL10 = 1; // Disable ETM interface, enableLEDs

    FIO2DIR = 0x000000FF; // P2.0..7 defined as OutputsFIO2MASK = 0xFFFFFF00; // enable all pins for modification for

    port 2}

    voidLED_on (unsigned intnum) // Function that turns on requested LED{

    FIO2SET =(1

  • 8/16/2019 Embedded Sys Manual

    15/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 13

    delay ();}

    }}

    Output:

  • 8/16/2019 Embedded Sys Manual

    16/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 14

    2. Program to generate alternate ON-OFF LED flashing pattern on hardware board LPC2368.

    #include voidLED_init(void) // Function that initializes LEDs{

    PINSEL10 = 1; // Disable ETM interface, enableLEDs

    FIO2DIR = 0x000000FF; // P2.0..7 defined as Outputs

    FIO2MASK = 0xFFFFFF00; // enable all pins for modification for port 2

  • 8/16/2019 Embedded Sys Manual

    17/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 15

    }

    voidLED_on (unsigned intnum) // Function that turns on requested LED{

    FIO2SET =(1

  • 8/16/2019 Embedded Sys Manual

    18/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 16

  • 8/16/2019 Embedded Sys Manual

    19/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 17

    Flashing the program on hardware kit:

    After writing any program, it can be flashed into ARM controller kit by following the steps below:

    i. Open Project → Options for target „target 1‟ → Debug → Select proper debugger asshown below.

    ii. Open Flash → Download to download the program to the kit

  • 8/16/2019 Embedded Sys Manual

    20/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 18

    Conclusion: ________________________________________________________________ ________________________________________________________________ ________________________________________________________________ ________________________________________________________________ ________________________________________________________________ ________________________________________________________________ ________________________________________________________________ ________________________________________________________________ ________________________________________________________________

  • 8/16/2019 Embedded Sys Manual

    21/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 19

    LAB 4

    A/D and D/A conversion

    AIM: (A) A/D converter and programming

    SPECIAL FUNCTION REGISTERS FOR A TO D CONVERTER:

    AD0CRAD0GDRAD0STATADDR0-7

    FEATURES OF THE AVAILABLE A TO D CONVERTER ON LPC2368 :

    10 bit successive approximation analog to digital converterInput multiplexing among 6 pins (LPC2364/66/68) or 8 pins (LPC2378)Power down modeMeasurement range 0 to 3 V10 bit conversion time >= 2.44 usBurst conversion mode for single or multiple inputsOptional conversion on transition on input pin or Timer Match signalIndividual result registers for each A/D channel to reduce interrupt overhead

    DESCRIPTION

    Basic clocking for the A/D converters is provided by the APB clock (PCLK). A programmable divider is included in each converter, to scale this clock to the 4.5 MHz (max)clock needed by the successive approximation process. A fully accurate conversion requires11 of these clocks.

    OPERATION

    Hardware-triggered conversion

    If the BURST bit in the ADCR is 0 and the START field contains 010-111, the A/Dconverter will start a conversion when a transition occurs on a selected pin or Timer Matchsignal. The choices include conversion on a specified edge of any of 4 Match signals, orconversion on a specified edge of either of 2 Capture/Match pins. The pin state from theselected pad or the selected Match signal, XORed with ADCR bit 27, is used in the edgedetection logic.

    Interrupts

  • 8/16/2019 Embedded Sys Manual

    22/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 20

    An interrupt is requested to the Vectored Interrupt Controller (VIC) when the ADINT bit in the ADSTAT register is 1. The ADINT bit is one when any of the DONE bits of A/Dchannels that are enabled for interrupts (via the ADINTEN register) are one. Software canuse the Interrupt Enable bit in the VIC that corresponds to the ADC to control whether this

    results in an interrupt. The result register for an A/D channel that is generating an interruptmust be read in order to clear the corresponding DONE flag.

    SPECIAL FUNCTION REGISTER DESCRIPTION:

  • 8/16/2019 Embedded Sys Manual

    23/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 21

  • 8/16/2019 Embedded Sys Manual

    24/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 22

    Programs:

    1. A/D conversion for single channel

    #includeint main(){

    inti,j;AD0CR=0X00200301; //pdn enabled, sel:00, clkdiv:03,

    clks:11clks/10bits//start:none

    AD0CR=0X01200301; //set start as :now

    while((AD0STAT&0x00000001)!=0x00000001) // monitor done flag inAD0STAT

  • 8/16/2019 Embedded Sys Manual

    25/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 23

    {}

    i= AD0GDR/0x00000040; j=i&0x00003ff;

    return 0;}

    Output: By providing input value=3.6V the digital equivalent is calculated.

    2. A/D conversion for six channels

  • 8/16/2019 Embedded Sys Manual

    26/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 24

    #includeint main( ){

    int i[6],j[6],k,l;k=0x00000001;

    for(l=0;l

  • 8/16/2019 Embedded Sys Manual

    27/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 25

    SPECIAL FUNCTION REGISTER OF DIGITAL TO ANALOG CONVERTER:

    DACR

    SPECIAL FUNCTION REGISTER DESCRIPTION: DACR

    Programs:

    1. Generation of sine wave using sin() function

    #include #include

    int main (){int x;int y;PINSEL1=(1

  • 8/16/2019 Embedded Sys Manual

    28/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 26

    }return 0;}

    Output: By opening the logic analyser window, the sine wave can be observed as below:

    2. Generation of sine wave using lookup table

    #include#include#includeint main(){inti,j,n;intarr[37]={512,601,687,768,841,904,955,993,1016,1023,1016,955,933,904,841,768,687,601,512,423,336,256,183,120,69,31,8,0,8,31,69,120,183,256,336,423,512}; //creating

    //lookup table//intarr1[9]={};//intarr2[9]={};//intarr3[9]={};i=0;n=0;

    PINSEL1=(1

  • 8/16/2019 Embedded Sys Manual

    29/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 27

    label:for(i=0;i

  • 8/16/2019 Embedded Sys Manual

    30/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 28

    7. What are the popular architectures of D/A converter?

    8. Modify above program to generate sawtooth waveform.

    9. What is logic Analyzer? How it is useful?

    10. How amplitude of the waveform generated can be varied?

    Conclusion:________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________

  • 8/16/2019 Embedded Sys Manual

    31/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 29

    LAB 5

    Startup file

    AIM: To study startup file for LPC2300 and do basic assembly language programming.

    THEORY:

    A startup code performs stack initialization and the microcontroller setup, before anarm microcontroller can execute main program. The startup file LPC2300.s code is executedafter CPU reset.

    The file LPC2300.s is an assembler module provided by keil. As its name implies, thestartup code is located to run from the reset vector. It provides the exception vector table aswell as initialising the stack pointer for the different operating modes. It also initialises someof the on-chip system peripherals and the on-chip RAM before it jumps to the main function

    in c code. The startup code will vary depending on which arm7 device you are using andwhich the compiler you are using, so for your own project it is important to make sure youare using the correct file.

    First of all the startup provides the exception Vector table as shown below. The vectortable is located. At 0x00000000 and provides a jump to interrupt service routines(ISR) oneach vector to ensure that the full Address range of the processor is available, the LDR(loadRegister)instruction is used. The area command is used by the linker to the Place the vectortable at the correct start address. for a Single chip use this is always 0x00000000,however ifyou are using the external bus and want to boot from external Memory, the vector table must

    be located at 0x80000000.

    SECTIONS OF A STARTUP FILE:

    1. Interrupt Vector Table2. Clock Selection and PLL configuration3. Peripheral configuration4. Stack definition

    LPC2300.S:

    Mode_USR EQU 0x10Mode_FIQ EQU 0x11Mode_IRQ EQU 0x12Mode_SVC EQU 0x13Mode_ABT EQU 0x17Mode_UND EQU 0x1BMode_SYS EQU 0x1FI_Bit EQU 0x80 ; when I bit is set, IRQ is disabledF_Bit EQU 0x40 ; when F bit is set, FIQ is disabled;Startup Code must be linked first at Address at which it expects to run.

    AREA RESET, CODE, READONLYARM

    ;Exception Vectors;Mapped to Address 0

  • 8/16/2019 Embedded Sys Manual

    32/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 30

    ;Absolute addressing mode must be used;Dummy Handlers are implemented as infinite loops which can be modified.VectorsLDR PC, Reset_AddrLDR PC, Undef_Addr

    LDR PC, SWI_AddrLDR PC, PAbt_AddrLDR PC, DAbt_Addr

    NOP; Reserved Vector ;LDR PC, IRQ_AddrLDR PC, [PC, #-0x0120] ; Vector from VicVectAddrLDR PC, FIQ_AddrReset_Addr DCD Reset_HandlerUndef_Addr DCD Undef_HandlerSWI_Addr DCD SWI_HandlerPAbt_Addr DCD PAbt_HandlerDAbt_Addr DCD DAbt_HandlerDCD 0; Reserved AddressIRQ_Addr DCD IRQ_HandlerFIQ_Addr DCD FIQ_HandlerUndef_Handler B Undef_HandlerSWI_Handler B SWI_HandlerPAbt_Handler B PAbt_HandlerDAbt_Handler B DAbt_HandlerIRQ_Handler B IRQ_HandlerFIQ_Handler B FIQ_Handler; Reset HandlerEXPORT Reset_HandlerReset_Handler; Enter the C codeIMPORT __mainLDR R0, =__mainBX R0 // Branch to main programIF :DEF:__MICROLIBEXPORT __heap_base

    EXPORT __heap_limitELSE ; User Initial Stack & HeapAREA |.text|, CODE, READONLYIMPORT __use_two_region_memoryEXPORT __user_initial_stackheap __user_initial_stackheapLDR R0, = Heap_MemLDR R1, =(Stack_Mem + USR_Stack_Size)LDR R2, = (Heap_Mem + Heap_Size)LDR R3, = Stack_MemBX LR

    ENDIFEND

  • 8/16/2019 Embedded Sys Manual

    33/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 31

    Procedure to write an ARM assembly program:

    In built ARM starter file (lpc2300.s) is written for high language appl ications, i.e. „C‟. Towrite the low language program (assembly program), it is required to make certain

    modifications in startup file. Steps are mentioned below to write ARM assembly language program / application.

    1. In startup file, replace actual code from line number 488 till end as shown below.

    IMPORT startLDR R0, =startBX R0END

    Here, “start” is a block of area in which assembly program / application code exists. 2. An assembly program / application code will start with AREA directive, which instructs

    the assembler to assemble a new code or data section. Sections are independent, named,indivisible chunks of code or data that are manipulated by the linker.Here, “niket” is name of block where program code resides, instead of “niket”, any namecan be given.CODE means it‟s program code. READONLY means given area code is read-only.“start” is starting point of program. “end” is ending point of program.

    Programs:

    1. Copy an array of size=10 to another memory location

    areaniket,code ,readonly

    export start

    start mov r3,#10;

    mov r0,#0x40000000;

    mov r2,#0x40000030;

    loop ldrb r1,[r0];

    strb r1,[r2];

    add r0,r0,#0x01;

    add r2,r2,#0x01;

    sub r3,r3,#0x01;

    cmp r3,#0;

    bne loop;

  • 8/16/2019 Embedded Sys Manual

    34/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 32

    end

    Output: Initially the memory window looks like below.

    So first of all an array is created on the required memory locations by double clickingon that location. The created array looks like below:

    After the successful execution of program, the array gets copied to the requiredmemory location which is as shown below:

  • 8/16/2019 Embedded Sys Manual

    35/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 33

    Conclusion: ________________________________________________________________ ________________________________________________________________ ________________________________________________________________ ________________________________________________________________ ________________________________________________________________

    ________________________________________________________________ ________________________________________________________________

  • 8/16/2019 Embedded Sys Manual

    36/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 34

    LAB 6

    Array Processing

    AIM: To study an ARM assembly language program to sort five numbers in ascending anddescending order.

    THEORY:Procedure to write an ARM assembly program:In built ARM starter file (lpc2300.s) is written for high language applications, i.e. „C‟. Towrite the low language program (assembly program), it is required to make certainmodifications in startup file. Steps are mentioned below to write ARM assembly language

    program / application.

    3. In startup file, replace actual code from line number 488 till end as shown below.

    IMPORT startLDR R0, =startBX R0END

    Here, “start” is a block of area in which assembly program / application code exists. 4. An assembly program / application code will start with AREA directive, which instructs

    the assembler to assemble a new code or data section. Sections are independent, named,indivisible chunks of code or data that are manipulated by the linker.Here, “ykm” is name of block where program code resides, instead of “ykm”, any namecan be given.CODE means it‟s program code. READONLY means given area code is read-only.“start” is starting point of program. “end” is ending point of program.

    SAMPLE PROGRAM:

    AREA EMB,CODE,READONLYEXPORT start

    startMOV R0,#0X40000000MOV R1,R0MOV R4,#4MOV R5,#4

    HERE2LDR R2,[R0]

    HERE1ADD R1,R1,#4

    LDR R3,[R1]CMP R2,R3

  • 8/16/2019 Embedded Sys Manual

    37/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 35

    BLT HEREMOV R6,R2MOV R2,R3MOV R3,R6

    STR R2,[R0]STR R3,[R1]HERE

    SUB R4,R4,#1CMP R4,#0BNE HERE1ADD R0,R0,#4MOV R1,R0SUB R5,R5,#1MOV R4,R5CMP R5,#0BNE HERE2END

    Output:

    Conclusion:________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________

    ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ __________________

  • 8/16/2019 Embedded Sys Manual

    38/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 36

    LAB 7

    Inline Assembly & Thumb State

    AIM: (i) To study a C program that allows inline assembly instructions.

    THEORY:

    Inline assembly is a special provision in the ARM processors which allows user towrite ARM assembly language program in higher language (“C”) program. Basic advantageof such provision is to get high code density. This provision is mostly used where codestorage capacity of processor is less compared to the requirement.

    Restrictions on inline assembly operations: There are a number of restrictions on theoperations that can be performed in inline assembly code. These restrictions provide ameasure of safety, and ensure that the assumptions in compiled C and C++ code are not

    violated in the assembled assembly code.Miscellaneous restrictionsThe inline assembler has the following restrictions:

    The inline assembler is a high-level assembler, and the code it generates might notalways be exactly what you write. Do not use it to generate more efficient code than thecompiler generates. Use embedded assembler or the ARM assembler armasm for this

    purpose.Some low-level features that are available in the ARM assembler armasm, such as

    branching and writing to PC, are not supported. x Label expressions are not supported.You cannot get the address of the current instruction using dot notation (.) or {PC}.

    The & operator cannot be used to denote hexadecimal constants. Use the 0x prefixinstead. For example:__asm { AND x, y, 0xF00 }The notation to specify the actual rotate of an 8-bit constant is not available in inlineassembly language. This means that where an 8-bit shifted constant is used, the C flagmust be regarded as corrupted if the NZCV flags are updated.You must not modify the stack. This is not necessary because the compiler automaticallystacks and restores any working registers as required. The compiler does not permit youto explicitly stack and restore work registers.

    RegistersRegisters, such as r0-r3, sp, lr, and the NZCV flags in the CPSR must be used with caution.

    If you use C or C++ expressions, these might be used as temporary registers and NZCV flagsmight be corrupted by the compiler when evaluating the expression.The pc, lr, and sp registers cannot be explicitly read or modified using inline assembly code

    because there is no direct access to any physical registers. However, you can use thefollowing intrinsics to access these registers:

    current_pc in the Compiler Reference Guidecurrent_sp in the Compiler Reference Guidereturn_address in the Compiler Reference Guide.

  • 8/16/2019 Embedded Sys Manual

    39/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 37

    Thumb instruction set

    The inline assembler is not available when compiling C or C++ for Thumb state, andthe inline assembler does not assemble Thumb instructions. Instead, the compilerswitches to ARM state automatically.

    Unsupported instructionsThe following instructions are not supported in the inline assembler:

    BKPT , BX , BXJ, and BLX instructionsSVC instruction x LDR Rn, =expression pseudo-instruction. Use MOV Rn, expressioninstead (this can generate a load from a literal pool)LDRT, LDRBT, STRT, and STRBT instructionsMUL, MLA, UMULL, UMLAL, SMULL, and SMLAL flag setting instructionsMOV or MVN flag-setting instructions where the second operand is a constantuser-mode LDM instructionsADR and ADRL pseudo-instructions.

    Program Format:

    //*******************************************//Include header files//*******************************************//

    int main(){

    //*******************************************//Higher language (“C”) program //*******************************************//

    __asm{//*******************************************//ARM Assembly language program//*******************************************//}//*******************************************//Higher language (“C”) program

    //*******************************************//

    }

    Programs:

    1. Illustration of basic usage of inline assembly code

    int main(){

    inta,b,c,d,e,f,g;a=10;

    b=20;

  • 8/16/2019 Embedded Sys Manual

    40/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 38

    c=a+b;

    __asm{

    mov e,0x04;mov f,0x02;addg,e,f;

    }

    d=a*b;return 0;}

    Output: The disassembly & register window for the above program showing the Cstatements into their corresponding assembly language statements is shown below:

  • 8/16/2019 Embedded Sys Manual

    41/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 39

    AIM: (ii) To study an ARM assembly language program having ARM state & thumb state.

    The Thumb instruction set addresses the issue of code density. It may be viewed as acompressed form of a subset of the ARM instruction set. Thumb instructions map onto ARMinstructions, and the Thumb programmer's model maps onto the ARM programmer's model.

    Implementations of Thumb use dynamic decompression in an ARM instruction pipeline andthen instructions execute as standard ARM instructions within the processor.

    Thumb is not a complete architecture; it is not anticipated that a processor would executeThumb instructions without also supporting the ARM instruction set. Therefore the Thumbinstruction set need only support common application functions, allowing recourse to the fullARM instruction set where necessary (for instance, all exceptions automatically enter ARMmode).

    Thumb is fully supported by ARM development tools, and an application can mix ARM andThumb subroutines flexibly to optimize performance or code density on a routine-by-routine

    basis.

    Programs:

    1. Illustration of switching from thumb to ARM state and vice-versa

    AREA nik, CODE, READONLYEXPORT square

    square

    mov r1,#&44movs r2,#44adcs r3,r2,r1,asr#5subs r7,r2,r1,lsl#4ldr r5,=funmovslr,pc

    bx r5add r1,#1add r1,#1add r1,#1

    b function

    THUMBfun

    ldr r6,=0x40000000movs r7,r6ldr r0,=65534ldr r1,=280

    movs r2,#54movs r3,#0

  • 8/16/2019 Embedded Sys Manual

    42/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 40

    stmia r6!,{r0-r3}movs r2,#0

    loopldr r3,[r7]

    adds R2,R3adds r7,#4cmp r6,r7

    bgt loop bxlrARM

    functionadd r5,r0,r1end

    Output: By checking CPSR [5] (TBIT), we can always say whether the processor is in ARMor Thumb state. If TBIT=1, it is in Thumb state otherwise it is in ARM state.

    The figure below shows the initial execution of program while the processor is still in ARMstate.

  • 8/16/2019 Embedded Sys Manual

    43/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 41

    Conclusion:________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ __________________

  • 8/16/2019 Embedded Sys Manual

    44/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 42

    LAB 8Software Interrupts & Subroutines

    AIM (i): Write a program that shows software interrupts with their handlers.

    THEORY:

    In ARM7TDMI, vector table is available in ROM which consists of vector address of desiredexception.To write the assembly program we have to make some changes as shown below in startupfile.-in C program block at line no.500 instead of import _main we have to write the name whichis given to our assembly block in our program.

    ; Enter the C codeIMPORT startLDR R0, =startBX R0END

    The program will start with AREA directive, which instructs the assembler to assemble a newcode or data section. Sections are independent, named, indivisible chunks of code or data thatare manipulated by the linker.

    Program: A program creating two SWIs is shown below. User defined handlers are returnedfor each. To do so in startup the SWI_Handler line is commented and is made as an import

    and a separate user defined export handler is written in the program file.

    area niket1, code ,readonly

    export startexportSWI_Handler

    SWI_Handlermov r7,lrldr r8,[r7]sub r7,r7,#0x04;ldr r1,[r7];and r1,#0x00ffffff;cmp r1,#0x00000000;

    beq sw0;cmp r1,#0x00000001;

    beq sw1; b end;

    sw0 mov r0,#0x00000001;add r0,r0,#0x01;

  • 8/16/2019 Embedded Sys Manual

    45/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 43

    mov pc,r14;

    sw1 mov r1,#0x00000001;

    add r1,r1,#0x01;mov pc,r14;

    end movpc,lr;

    start mov r2,#0x00000002;swi 0;mov r3,#0x00000003;swi 1;

    end

    Output: The execution of the above program goes in following manner. Firstly, theexecution begins in the startup file where it encounters an import start statement due to whichit jumps to the main program file to the start label. Having generated SWI0 in start it jumps

    back to the startup file to the SWI_Handler where it encounters another importSWI_Handler statement pertaining to which it returns to main program and starts executingthe code written for SWI_Handler for SWI0. After the completion of that it returns to the

    start section where it left initially when SWI0 was generated. Then it finds SWI1 occurringand the same procedure repeats. At the end execution again jumps back to startup file.

  • 8/16/2019 Embedded Sys Manual

    46/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 44

    AIM (ii): To study subroutines.

    THEORY:

    The use of subroutine is to define function which required to call number of times. Thesubroutine may be defined within the file or in separate assembly file.To write the assembly program we have to make some changes as shown below in startupfile.-in C program block at line no.500 instead of import _main we have to write the name whichis given to our assembly block in our program.; Enter the C code

    IMPORT startLDR R0, =startBX R0

    END

    The program will start with AREA directive, which instructs the assembler to assemble a newcode or data section. Sections are independent, named, indivisible chunks of code or data thatare manipulated by the linker.

    Program:

    AREA subrout, CODE, READONLYEXPORT startIMPORT domul

    doadd ADD r4, r0, r1BX lr;

    domul MUL r5, r2, r1;BX lr;

    startmov r0, #10mov r1, #3

    bldoadd ;

    mov r2, r4; bldomul;mov r3, r5;

    waitB wait;End

  • 8/16/2019 Embedded Sys Manual

    47/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 45

    Output:

    \\

    Conclusion:________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________

    ___________________________________________________________________________

  • 8/16/2019 Embedded Sys Manual

    48/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 46

    LAB 9

    IRQ and FIQ Exception Handling

    AIM(i): To understand IRQ exception Handling mechanism and ISRs.

    SPECIAL FUNCTION REGISTERS OF VECTORED INTERRUPT CONTROLLER

    VICIRQStatus VICFIQStatus VICRawintrVICIntSelect VICIntEnable VICIntEnClrVICSoftInt VICSoftIntClr

    Special Function Register Description:

    THEORY :

    The ARM processor core has two interrupt inputs called Interrupt Request (IRQ) and FastInterrupt request (FIQ). The Vectored Interrupt Controller (VIC) takes 32 interrupt requestinputs and program assigns them as FIQ or vectored IRQ types. The programmableassignment scheme means that priorities of interrupts from the various peripherals can bedynamically assigned and adjusted. Vectored IRQ‟s, which include all interrupt requests thatare not classified as FIQs, have a programmable interrupt priority. When more than one

  • 8/16/2019 Embedded Sys Manual

    49/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 47

    interrupt is assigned the same priority and occur simultaneously, the one connected to thelowest numbered VIC channel will be serviced first.The VIC ORs the requests from all of the vectored IRQs to produce the IRQ signal to theARM processor. The IRQ service routine can start by reading a register from the VIC and

    jumping to the address supplied by that register. IRQ is the Interrupt mode for general

    purpose interrupt handling. The program and run mode is shown in following snaps.

    Program:

    #include

    __irq void IRQ_Handler (void) //IRQ handler definition{ int a=10,b=20,c;c=a+b;

    VICSoftIntClr= 0x00004000;}

    int main(void){EXTMODE= 0x00000001; //Interrupt configuration, edge triggeredEXTPOLAR=0x00000001; //positive going interruptVICIntEnable=0x00004000; //Enable interruptVICIntSelect=0x00000000; //set interrupt as IRQVICVectAddr14 = (unsigned long) IRQ_Handler;VICSoftInt=0x00004000; //Software interrupt generationwhile(1){//wait here} }

    Output:

  • 8/16/2019 Embedded Sys Manual

    50/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 48

    AIM(ii): To understand FIQ exception Handling mechanism

    SPECIAL FUNCTION REGISTERS OF VECTORED INTERRUPT CONTROLLER:

    VICIRQStatus VICFIQStatus VICRawintrVICIntSelect VICIntEnable VICIntEnClrVICSoftInt VICSoftIntClr

    SPECIAL FUNCTION REGISTER DESCRIPTION:

  • 8/16/2019 Embedded Sys Manual

    51/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 49

    THEORY:

    Fast Interrupt request (FIQ) requests have the highest priority. If more than one request isassigned to FIQ, the VIC ORs the requests to produce the FIQ signal to the ARM

    processor. The fastest possible FIQ latency is achieved when only one request isclassified as FIQ, because then the FIQ service routine can simply start dealing with thatdevice. But if more than one request is assigned to the FIQ class, the FIQ service routinecan read a word from the VIC that identifies which FIQ source(s) is (are) requesting aninterrupt.

    Program:

    #include

    __irq void FRQ_Handler (void) //FRQ handler definition

    { int a=10,b=30,c;

    c=a*b;

    VICSoftIntClr= 0x00008000;

    }

    int main(void)

    {

    EXTMODE= 0x00000001; //Interrupt configuration, edge triggered

    EXTPOLAR=0x00000001; //positive going interrupt

    VICIntEnable=0x00008000; //Enable interrupt

    VICIntSelect=0x00008000; //set interrupt as FRQ

    VICSoftInt=0x00008000; //Software interrupt generation

    while(1){

    } //wait here

    }

  • 8/16/2019 Embedded Sys Manual

    52/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 50

    Output:

    Conclusion:________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________

  • 8/16/2019 Embedded Sys Manual

    53/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 51

    LAB 10

    Thread and Fork

    AIM: (i) To implement thread creation program and orderly releasing of same.

    THEORY:A thread is the smallest sequence of programmed instructions that can be managedindependently by a scheduler [a part of an operating system]. The implementation of threadsand processes differs from one operating system to another, but in most cases, a thread is acomponent of a process. Multiple threads can exist within the same process and shareresources and doing so run concurrently. When multiple threads are running concurrently,this is known as multithreading. Typical example of multithreading is downloading a videowhile playing it at the same time.

    Compilation and Execution Steps

    1. Open Terminal (ALT + CLT + T)2. $ gedit program.c3. $ gcc program.c -l pthread4. $ ./a.out

    Sample Program

    #include #include #include #include

    void thread_func( ){

    printf("Hurray!!!!\n"); printf("I am thread %u\n",(unsigned int)pthread_self());return;

    }int main( )

    { pthread_t ptid;if(pthread_create(&ptid,NULL,(void *)thread_func,NULL)!=0){

    printf("Thread Creation Error : %d\n",errno); }else{

    printf("Thread %u is created\n\n",ptid); }if(pthread_join(ptid,NULL)!=0)

    { printf("Thread %u Join Error : %d\n",ptid,errno);

  • 8/16/2019 Embedded Sys Manual

    54/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 52

    }else{

    printf("Thread %u is joined\n\n",ptid); }

    return 0; }

    OUTPUT:

    CONCLUSION:

    ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________

    ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ______________________________

  • 8/16/2019 Embedded Sys Manual

    55/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 53

    MODIFICATION

    Modify the above program to create five threads and join them also.

    #include

    #include#include#includevoid myfun(){

    printf("\nHello I am thread %u",(unsigned int)pthread_self());}

    int main(){

    int i=0;

    pthread_t ptid[5];for (i=0;i

  • 8/16/2019 Embedded Sys Manual

    56/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 54

    OUTPUT:

    EXERCISE

    1. Write a program to create two different threads for addition and subtraction on a and bvariables.

  • 8/16/2019 Embedded Sys Manual

    57/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 55

    AIM: (ii) To implement child process creation program.

    THEORY :

    Fork is a system call to create a new process. This call creates an exact clone

    of the calling process. After the fork, the two processes, the parent and the child, have thesame memory image, the same environment strings, and the same open files. If parent

    process terminates when child process is executing then child process becomes orphan andinit process becomes its parent process.

    1. Create child process using single fork.

    #include#includeint main(){

    int pid, status;fork();

    printf("PID=%d and PPID=%d\n",getpid(),getppid());}Output:

    Process Tree:

    PID-1586Bash Process

    PID-1585

    PID-1584

  • 8/16/2019 Embedded Sys Manual

    58/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 56

    Printing PID and PPID before fork call:

    #include#includeint main(){

    int pid, status; printf("PID=%d and PPID=%d\n",getpid(),getppid());fork();

    }

    Output:

    2. Create Child processes using more than one fork() without waitpid function andobserve orphan processes.

    2 subsequent fork calls:

    #include#includeint main(){

    int pid, status;fork();fork();

    printf("PID=%d and PPID=%d\n",getpid(),getppid());

    }

    Output:

  • 8/16/2019 Embedded Sys Manual

    59/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 57

    Process Tree:

    3 subsequent fork calls:

    #include#includeint main(){

    int pid, status;fork();fork();fork();

    printf("PID=%d and PPID=%d\n",getpid(),getppid());}

    Output:

    Process Tree:

    PID-1586Bash Process

    PID-2188

    PID-2190

    PID-2191

    PID-2189

  • 8/16/2019 Embedded Sys Manual

    60/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 58

    Observe that processes having PPID=1 are orphaned and driven by init process

    3 subsequent fork calls with waitpid() function

    #include#includevoid main(){

    int pid,status; pid=fork(); pid=fork(); pid=fork();if(pid>0){

    printf("I am Parent with PID %d and PPID %d\n",getpid(),getppid());int i;for(i=0;i

  • 8/16/2019 Embedded Sys Manual

    61/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 59

    Process Tree:

    4 subsequent fork calls with waitpid() function

    #include#includevoid main(){

    int pid,status; pid=fork(); pid=fork(); pid=fork(); pid=fork();if(pid>0){

    printf("I am Parent with PID %d and PPID %d\n",getpid(),getppid());int i;

    for(i=0;i

  • 8/16/2019 Embedded Sys Manual

    62/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 60

    waitpid(-1,&status,0);//making every parent to wait till all its child process finishes thier //work so that no processwill become orphan

    }

    }else if(pid==0){

    printf("I am child with PID %d and PPID %d\n",getpid(),getppid());}

    }

    Output:

    Process Tree:

  • 8/16/2019 Embedded Sys Manual

    63/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 61

    EXERCISE:

    Write a program to exhaust the process table.

    CONCLUSION: __________________________________________________________________________________ __________________________________________________________________________________ __________________________________________________________________________________ __________________________________________________________________________________ __________________________________________________________________________________ __________________________________________________________________________________ __________________________________________________________________________________ __________________________________________________________________________________ __________________________________________________________________________________ __________________________________________________________________________________ __________________________________________________________________________________ __________________________________________________________________________________ _________________________________

    Bash ProcessPID-1586

    PID-2364

    PID-2365

    PID-2371 PID-2367

    PID-2373

    PID-2378

    PID-2374

    PID-2369

    PID-2375

    PID-2366

    PID-2376

    PID-2379

    PID-2377

    PID-2368

    PID-2372

    PID-2370

  • 8/16/2019 Embedded Sys Manual

    64/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 62

    LAB 11

    Fanning and Chaining

    AIM: Process generation and linking (Fanning and Chaining)

    THEORY:In this experiment, fork ( ) system call is used to generate different processes. In the fanningoption, one parent process generates multiple child processes. However, in the chainingoption, child process becomes the parent process for the next generated child process and soon as a result chain of parent and child processes are established in this particular option.

    getpid ( ) and getppid ( ) system calls are used to get child and parent process id respectively.waitpid ( ) system call is used to wait (block) the parent process until all the child processesexecutes. This system call is equivalent to generating hardware delay as and whenneeded.

    PROGRAM:#include#include#includeint main(){

    int pid,nLevel,option,count=0; printf("What you want (Fanning [1] Chaining [2]) ? \n");scanf("%d",&option);

    printf("Number of Processes you want ? \n");scanf("%d",&nLevel);int i;if(option==1){

    printf("I am Parent with PID %d and PPID %d\n",getpid(),getppid());while(count0){count++;continue;}else{

    printf("Error Condition\n");

    }}

  • 8/16/2019 Embedded Sys Manual

    65/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 63

    int status;for(i=0; i

  • 8/16/2019 Embedded Sys Manual

    66/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 64

    OUTPUT: F anni ng wi th 3 process and Chaini ng wi th 3 processes

    Process Tree:

    1 Fanning

    2 Chaining

    Bash ProcessPID-1944

    PID-1969

    PID-1970 PID-1971 PID-1992

    Bash Process

    PID-1994

    PID-1978

    PID-1979 PID-1980 PID-1981

  • 8/16/2019 Embedded Sys Manual

    67/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 65

    CONCLUSION:

    __________________________________________________________________________________ __________________________________________________________________________________ __________________________________________________________________________________

    __________________________________________________________________________________ __________________________________________________________________________________ __________________________________________________________________________________ __________________________________________________________________________________ __________________________________________________________________________________ __________________________________________________________________________________ __________________________________________________________________________________ __________________________________________________________________________________ __________________________________________________________________________________ ____________________________________

  • 8/16/2019 Embedded Sys Manual

    68/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 66

    LAB 12

    Semaphore

    OBJECTIVE: To study the concept of semaphore.

    THEORY:

    An integer value used for signaling among processes. Only three operations may be performed on asemaphore, all of which are atomic: initialize, increment and decrement. The decrement operationmay result in the blocking of a process, and the increment operation may result in the unblocking of a

    process. Also known as a counting semaphore or a general semaphore.

    1. DINING PHILOSOPHER PROBLEM

    This problem can be stated quit simply as follows. Five philosophers are seated around a circular

    table. Each philosopher has a plate of spaghetti. The spaghetti is so slippery that a philosopher needstwo forks to eat it. Between each pair of plates is one fork. The life of philosopher consists of alternate

    periods of eating and thinking. When a philosopher gets hungry, she tries to acquire her left and rightfork, one at a time in either order. If successful in acquiring two forks, she eats for a while, then putsdown the forks and continue to think. With a little bit of bad luck, all the philosophers could start thealgorithm simultaneously, picking up their left forks, seeing that their right forks were not available,

    putting down their left forks, waiting, picking up their left forks again simultaneously, and so on,forever. A situation like this, in which all the programs continue to run indefinitely but fail to makeany progress is called Starvation.

    SAMPLE PROGRAM:#include#include#include#include#include

    #define N 5#define LEFT (id+1)%N

    #define RIGHT id#define THINKING 0#define HUNGRY 1#define EATING 2

    int state[N];sem_t s[N];

    void init(int id);

    void think(int id);void pickup(int id);

  • 8/16/2019 Embedded Sys Manual

    69/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 67

    void eat(int id);void putdown(int id);

    int main()

    {int i, ph[N];

    pthread_t Philosophers[N];

    for(i = 0; i < N; i++)

    { ph[i] = i;

    state[i] = THINKING;

    sem_init(&s[i],0,1);}for(i=0; i

  • 8/16/2019 Embedded Sys Manual

    70/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 68

    }

    void think(int id){

    printf("Philosopher %d is Thinking.\n",id);sleep(1);

    }

    void eat(int id){

    printf("Philosopher %d is Eating.\n",id);sleep(1);

    }

    void pickup(int id){

    printf("Philosopher %d is trying to take forks.\n",id);

    state[id]=HUNGRY;if((id % 2) == 0 && state[id]==HUNGRY && state[LEFT]!=EATING){

    sem_wait(&s[LEFT]);sem_wait(&s[RIGHT]);state[id]=EATING;

    }

    else if(state[id]==HUNGRY && state[RIGHT]!=EATING){

    sem_wait(&s[RIGHT]);sem_wait(&s[LEFT]);state[id]=EATING;

    }//sleep(3);

    }

    void putdown(int id){

    printf("Philosopher %d has put down forks.\n",id);state[id]=THINKING;sem_post(&s[LEFT]);sem_post(&s[RIGHT]);//sleep(3);

  • 8/16/2019 Embedded Sys Manual

    71/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 69

    }

    OUTPUT:

  • 8/16/2019 Embedded Sys Manual

    72/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 70

    2. Case of Producer-Consumer

    AIM: To illustrate the race condition in case of Producer-Consumer while accessing theshared resources.Two or more processes share a common resource (fixed size buffer). One (or more) of them,the producer, puts the information in to the buffer, and the other, the consumer, takes it out.The system is to be designed to prevent the overlap of the buffer operations i.e. only one

    process (producer or consumer) may access the buffer at any time. The trouble arises whenthe producer wants to put a new item in the buffer, but it is already full. Similarly, the

    problem will arise when the consumer wants to remove an item from the buffer and sees thatthe buffer is empty. The solution for the producer is to go to sleep when the buffer is full, to

    be awakened when the consumer has removed the item(s). The solution to the consumer is togo to sleep (when buffer is empty) until producer puts something in the buffer and wakes itup.

    The sample program demonstrates the generation of race condition using M (=1) producersand N(=3) consumers.Compilation and Execution Steps

    1. Open terminal 2. gedit filename.c 3. gcc filename.c – lpthread 4. ./a.out M N >outputfile.txt. where M is number of producer and N is number of

    consumer as command line argument. Here, we have taken M as1 and N as 3. Herewe have redirected the output to the outputfile.txt using > operator. In our case theoutput is redirected in lab3-3.txt

    5. tail outpufile.txt to see the end part of output where race condition has occurred

    Sample Program

    //program to understand consumer producer model#include#include#include#include#include#include#include#define SIZE 1000

    long count=0,in=0,out=0;long buffer[SIZE];int retVal=0;int size_producer=0;int size_consumer=0;void producer(){

    printf("In Producer %u\n",pthread_self());while(retVal==0) //keep looping until error occurs{

    if(count

  • 8/16/2019 Embedded Sys Manual

    73/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 71

    { buffer[in]=in; //write in buffer(produce) printf("Producer %u : Item %ld produced\n",pthread_self(),in);count++;in = (in+1)%SIZE; //increment circularly 0,1,2, 3,….,SIZE -

    1,0,1,2,… }

    } printf("At end of Producer %u\n",pthread_self());

    }void consumer(){

    long tb, ti; printf("In Consumer %u\n",pthread_self());while(retVal==0) //keep executing until error occurs{

    while(count==0); //sleep if count=0tb=buffer[out]; //read from buffer(consume)ti = out;if((tb!=ti) && tb>-1) //if the error occurs{retVal=-1;

    printf("Race condition has occured at place %ld by reading %ld value inthread

    %u\n", ti,tb,pthread_self());return;}else{

    printf("Consumer %u : Item %ld consumed at index%ld\n",pthread_self(),tb,ti);

    count--;out=(out+1)%SIZE; //increment circularly 0,1,2,3,….,SIZE -

    1,0,1,2,… }

    } printf("At end of Consumer %u\n",pthread_self());

    }int main(int argc, char** argv){

    int i=0;long index=0;if(argc!=3) //if command line arguments are not given properly{

    printf("Usage : ./prodcons.out \n");

    return -1;}

    else{

  • 8/16/2019 Embedded Sys Manual

    74/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 72

    size_producer = atoi(argv[1]); //size of producer from command linearguments

    size_consumer = atoi(argv[2]); //size of consumer from command linearguments

    pthread_t pTid[size_producer]; //to store producer threads‟ ID

    pthread_t cTid[size_consumer]; //to store consumer threads‟ IDfor(index=0;index

  • 8/16/2019 Embedded Sys Manual

    75/76

    Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad 73

    OUTPUT: The snapshot of the output (tail part of the output file) is given below.

    MODIFICATION

    Test the program for more producer and consumers.

    EXERCISEHow probability of occurring race condition changes with change in i) number of

    producers ii) number of consumers.

  • 8/16/2019 Embedded Sys Manual

    76/76

    CONCLUSION:

    ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ___________________________________________________________________________ ______________________________________________________________________


Recommended