Вы находитесь на странице: 1из 76

Laboratory Manual for

Embedded Systems
B. TECH. SEM - VII (EC)

Faculty of Technology
Dharmsinh Desai University
Nadiad

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

NO.

LAB

PAGE
NO.

Introduction to Keil vision 4

Program Development Process

GPIO

10

A/D and D/A conversion

19

Start - up file

29

Array Processing

34

Inline Assembly & Thumb State

36

Software Interrupts & Subroutines

42

IRQ and FIQ Exception Handling

46

10

Thread and Fork

51

11

Fanning and Chaining

62

12

Semaphore

66

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

LAB 1
Introduction 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 a
robust editor, project manager, and makes facility. Vision4 integrates all tools including the
C compiler, macro assembler, linker/locator, and HEX file generator. Vision4 helps
expedite the development process of your embedded applications by providing the following:
Full-featured source code editor
Device database for configuring the development tool setting
Project manager for creating and maintaining your projects
Integrated 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 for
connection to KeilULINK
Flash programming utility for downloading the application program into Flash ROM,
Links to development tools manuals, device datasheets & users 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 help
you 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 AGDI
drivers) that connect the debugger to the target system. The ULINK allows you also to
download your application into Flash ROM of your target system. The figure below shows
the Keil Vision4.

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

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 selection
and 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 be
enabled or disabled from the View Menu commands.
The following sections list the Vision4 commands that can be reached by menu
commands, toolbar buttons, and keyboard shortcuts. The Vision4 commands are grouped
mainly based on the appearance in the menu bar:
File Menu and File Commands
Edit Menu and Editor Commands
Outlining Menu
Advanced Menu
Selecting Text Commands
View Menu
Project Menu and Project Commands
Debug Menu and Debug Commands
Flash Menu
Peripherals Menu
Tools Menu
SVCS Menu
Window Menu
Help 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.
Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad

1. Create Project File Folder and Specify Project Name


To create a new project file select from the Vision4 menu Project New Vision
Project. 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.

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

Select this folder and enter the file name for the new project, i.e. Project1. Vision4 creates a
new project file with the name PROJECT1.UV2 which contains a default target and file
group name. You can see these names in the Project Workspace Files.
Copy and Add the CPU Startup Code
An embedded program requires CPU initialization code that needs to match the configuration
of 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 be
copied 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).
Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad

The Startup Code performs configuration of the microcontroller device and initialization of
the compiler run-time system.
Create New Source Files
You may create a new source file with the menu option File New. This opens an
empty 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 a
filename 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. Vision4
offers several ways to add source files to a project. For example, you can select the file group
in the Project Workspace Files page and click with the right mouse key to open a local
menu. 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 Target
opens via the toolbar icon or via the Project - Options for Target menu item. In the Target tab
you specify all relevant parameters of your target hardware and the on-chip components of
the 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 new
application. You may translate all source files and link the application with a click on the
Build Target toolbar icon. When you build an application with syntax errors, Vision4 will
display errors and warning messages in the Output Window Build page. A double click on
a 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 two
operating modes: simulator that allows you to verify your application on your PC, or Target
Debugging with an Evaluation Board or your hardware platform
Program your application into Flash ROM. Vision4 integrates command-line driven Flash
Utilities or can use the ULINK USB-JTAG Adapter for Flash programming. You may need
to create a HEX file to use Flash programming utilities.
Create HEX File
Once you have successfully generated your application you can start debugging. After
you have tested your application, it is required to create an Intel HEX file to download the
software 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. The
FLASH 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 Debugger


This 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 different
options available for program debugging.
You can use Vision4 Debugger to test the applications you develop. The Vision4
Debugger offers two operating modes that are selected in the Options for Target Debug
dialog.
Use Simulator configures the Vision4 Debugger as software-only product that
simulates most features of a microcontroller without actually having target hardware. You
can test and debug your embedded application before the hardware is ready. Vision4
Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad

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 are
summarized below
The Breakpoint Dialog allows you to define stop conditions for program execution.
The Code Coverage Window provides execution statistic information of execute and not
executed program parts.
The CPU Registers may be reviewed and modified in the Regs page of the Project
Workspace 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 registers
and 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 function
execution.
The Watch Window lets you view and modify program variables and lists the current
function 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 are
configured 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 before
Debugging.

Conclusion:
________________________________________________________________
________________________________________________________________
________________________________________________________________
________________________________________________________________
________________________________________________________________
_______________________________________________________________

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

LAB 2
Program 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 select the device from
NXP (founded by Phillips) family. The board available with us is LPC 2368. So we will
select every time this hardware. After giving the name adds the startup code of LPC 2300.S
to the project file. After that the source codes save as text1.C. Add this file to the Source
Group 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
#include<stdio.h>
int main()
{
int a=1,b=2;
int c;
c=a+b;
}
Output:

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

2. Multiplication
#include<stdio.h>
int main()
{
int a=2,b=2;
int c;
c=a*b;
}
Output:

3. Subtraction
#include<stdio.h>
int main()
{
int a=5,b=2;
int c;
c=a-b;

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

}
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:
________________________________________________________________
________________________________________________________________
________________________________________________________________
________________________________________________________________
________________________________________________________________
________________________________________________________________
______________________________________________________________

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

LAB 3
GPIO
AIM: Programming General Purpose Input Output Ports
SPECIAL FUNCTION REGISTERS FOR GPIO:
FIOXDIR
FIOXMASK
FIOXSET
FIOXCLR
FIOPIN

SPECIAL FUNCTION REGISTERS DESCRIPTION:

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

10

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 of
registers. 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/O
timing 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 addressable
Entire port value can be written in one instruction
Bit-level set and clear registers allow a single instruction set or clear of any number of
bits in one port
Direction control of individual bits
All I/O default to inputs after reset
Backward compatibility with other earlier devices is maintained with legacy registers
appearing at the original addresses on the APB bus
PROGRAM:
Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad

11

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


LPC 2368.
#include <LPC23xx.H>
voidLED_init(void)
{
PINSEL10 = 1;
LEDs
FIO2DIR = 0x000000FF;
FIO2MASK = 0xFFFFFF00;
port 2
}

// Function that initializes LEDs

voidLED_on (unsigned intnum)


{
FIO2SET =(1 <<num);
}

// Function that turns on requested LED

voidLED_off (unsigned intnum)


{
FIO2CLR = (1 <<num);
}

//Function that turns off requested LED

void delay (void)


{
int i;
for ( i=0; i<7099999; i++) { }
}

// delay

int main (void)


{
int k;
LED_init ();
delay ();
while(1)
{
for ( k=0; k<8; k=k+1)
{

// Disable ETM interface, enable


// P2.0..7 defined as Outputs
// enable all pins for modification for

// Initialize the port for output

LED_on (k);
delay ();

// make k th LED on

LED_off (k);

// make k th LED off

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

12

delay ();
}
}
}
Output:

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

13

2. Program to generate alternate ON-OFF LED flashing pattern on hardware board LPC
2368.
#include <LPC23xx.H>
voidLED_init(void)
{
PINSEL10 = 1;
LEDs
FIO2DIR = 0x000000FF;
FIO2MASK = 0xFFFFFF00;
port 2

// Function that initializes LEDs


// Disable ETM interface, enable
// P2.0..7 defined as Outputs
// enable all pins for modification for

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

14

}
voidLED_on (unsigned intnum)
{
FIO2SET =(1 <<num);
}

// Function that turns on requested LED

voidLED_off (unsigned intnum)


{
FIO2CLR = (1 <<num);
}

//Function that turns off requested LED

void delay (void)


{
int i;
for ( i=0; i<7099999; i++) { }
}

// delay

int main (void)


{
int k;
LED_init ();
delay ();
while(1)
{
for ( k=0; k<8; k=k+1)
{
if(k%2==0)
LED_on (k);
delay ();
if(k%2==0)
LED_off (k);
delay ();
}
}
}

// Initialize the port for output

// make alternate kth LED on

// make alternate kth LED off

Output:

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

15

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

16

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 as
shown below.

ii.

Open Flash Download to download the program to the kit


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

17

Conclusion:
________________________________________________________________
________________________________________________________________
________________________________________________________________
________________________________________________________________
________________________________________________________________
________________________________________________________________
________________________________________________________________
________________________________________________________________
________________________________________________________________

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

18

LAB 4
A/D and D/A conversion
AIM: (A) A/D converter and programming
SPECIAL FUNCTION REGISTERS FOR A TO D CONVERTER:
AD0CR
AD0GDR
AD0STAT
ADDR0-7
FEATURES OF THE AVAILABLE A TO D CONVERTER ON LPC2368:
10 bit successive approximation analog to digital converter
Input multiplexing among 6 pins (LPC2364/66/68) or 8 pins (LPC2378)
Power down mode
Measurement range 0 to 3 V
10 bit conversion time >= 2.44 us
Burst conversion mode for single or multiple inputs
Optional conversion on transition on input pin or Timer Match signal
Individual 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 requires
11 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/D
converter will start a conversion when a transition occurs on a selected pin or Timer Match
signal. The choices include conversion on a specified edge of any of 4 Match signals, or
conversion on a specified edge of either of 2 Capture/Match pins. The pin state from the
selected pad or the selected Match signal, XORed with ADCR bit 27, is used in the edge
detection logic.

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

19

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/D
channels that are enabled for interrupts (via the ADINTEN register) are one. Software can
use 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 interrupt
must be read in order to clear the corresponding DONE flag.
SPECIAL FUNCTION REGISTER DESCRIPTION:

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

20

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

21

Programs:
1. A/D conversion for single channel
#include<LPC23xx.h>
int main()
{
inti,j;
AD0CR=0X00200301;
clks:11clks/10bits

//pdn enabled, sel:00, clkdiv:03,


//start:none

AD0CR=0X01200301;

//set start as :now

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


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

22

{}
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


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

23

#include<LPC23xx.h>
int main( )
{
int i[6],j[6],k,l;
k=0x00000001;
for(l=0;l<6;l++)
{
AD0CR=0X00200300+k;
AD0CR=0X01200300+k;
while((AD0STAT&k)!=k)
{
i[l]= AD0GDR/0x00000040;
j[l]=i[l]&0x000003ff;
k=k*2;
}
return 0;
}
Output: By providing different values, the digital equivalent is calculated.

AIM: (B) Digital to Analog converter and programming.


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

24

SPECIAL FUNCTION REGISTER OF DIGITAL TO ANALOG CONVERTER:


DACR
SPECIAL FUNCTION REGISTER DESCRIPTION: DACR

Programs:
1. Generation of sine wave using sin() function
#include <LPC23xx.h>
#include <math.h>
int main ()
{
int x;
int y;
PINSEL1=(1<<21);

// selecting pin no 21

while(1)
{
for(x=0;x<360;x=x++)
{
y=(int)(512+512*sin(x*3.14/180)); //applying eqn to create sinwave and
shifting it as if performing clamper
operation
DACR=y<<6;

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

25

}
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<lpc23xx.h>
#include<stdio.h>
#include<math.h>
int main()
{
inti,j,n;
int
arr[37]={512,601,687,768,841,904,955,993,1016,1023,1016,955,933,904,841,768,68
7,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<<21);
//selecting pin no 21
Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad

26

label:
for(i=0;i<36;i++)
{n=arr[i];
DACR=n<<6;

//keeping the value of n and shifting by


//6 places

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

Assignment:
1. Explain working of SAR
2. Explain conversion Equation of ADC.
3. What are the specifications of A/D converter?
4. What are the popular architectures of A/D converter?
5. How speed of conversion can be compromised with resolution?
6. What are the specifications of D/A converter?
Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad

27

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:________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________

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

28

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 an
arm microcontroller can execute main program. The startup file LPC2300.s code is executed
after CPU reset.
The file LPC2300.s is an assembler module provided by keil. As its name implies, the
startup code is located to run from the reset vector. It provides the exception vector table as
well as initialising the stack pointer for the different operating modes. It also initialises some
of 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 and
which the compiler you are using, so for your own project it is important to make sure you
are using the correct file.
First of all the startup provides the exception Vector table as shown below. The vector
table is located. At 0x00000000 and provides a jump to interrupt service routines(ISR) on
each vector to ensure that the full Address range of the processor is available, the LDR(load
Register)instruction is used. The area command is used by the linker to the Place the vector
table at the correct start address. for a Single chip use this is always 0x00000000,however if
you 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.
2.
3.
4.

Interrupt Vector Table


Clock Selection and PLL configuration
Peripheral configuration
Stack definition

LPC2300.S:
Mode_USR
EQU 0x10
Mode_FIQ
EQU 0x11
Mode_IRQ
EQU 0x12
Mode_SVC
EQU 0x13
Mode_ABT
EQU 0x17
Mode_UND
EQU 0x1B
Mode_SYS
EQU 0x1F
I_Bit
EQU 0x80
; when I bit is set, IRQ is disabled
F_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, READONLY
ARM
;Exception Vectors
;Mapped to Address 0
Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad

29

;Absolute addressing mode must be used


;Dummy Handlers are implemented as infinite loops which can be modified.
Vectors
LDR PC, Reset_Addr
LDR PC, Undef_Addr
LDR PC, SWI_Addr
LDR PC, PAbt_Addr
LDR PC, DAbt_Addr
NOP
; Reserved Vector ;
LDR PC, IRQ_Addr
LDR PC, [PC, #-0x0120]
; Vector from VicVectAddr
LDR PC, FIQ_Addr
Reset_Addr
DCD Reset_Handler
Undef_Addr
DCD Undef_Handler
SWI_Addr
DCD SWI_Handler
PAbt_Addr
DCD PAbt_Handler
DAbt_Addr
DCD DAbt_Handler
DCD 0
; Reserved Address
IRQ_Addr
DCD IRQ_Handler
FIQ_Addr
DCD FIQ_Handler
Undef_Handler B
Undef_Handler
SWI_Handler B
SWI_Handler
PAbt_Handler B
PAbt_Handler
DAbt_Handler B
DAbt_Handler
IRQ_Handler B
IRQ_Handler
FIQ_Handler B
FIQ_Handler
; Reset Handler
EXPORT Reset_Handler
Reset_Handler
; Enter the C code
IMPORT __main
LDR
R0, =__main
BX
R0
// Branch to main program
IF
:DEF:__MICROLIB
EXPORT __heap_base
EXPORT __heap_limit
ELSE ; User Initial Stack & Heap
AREA |.text|, CODE, READONLY
IMPORT __use_two_region_memory
EXPORT __user_initial_stackheap
__user_initial_stackheap
LDR R0, = Heap_Mem
LDR R1, =(Stack_Mem + USR_Stack_Size)
LDR R2, = (Heap_Mem +
Heap_Size)
LDR R3, = Stack_Mem
BX
LR
ENDIF
END
Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad

30

Procedure to write an ARM assembly program:


In built ARM starter file (lpc2300.s) is written for high language applications, i.e. C. To
write 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 start
LDR R0, =start
BX
R0
END
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 name
can be given.
CODE means its 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;
Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad

31

end
Output: Initially the memory window looks like below.

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

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

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

32

Conclusion:
________________________________________________________________
________________________________________________________________
________________________________________________________________
________________________________________________________________
________________________________________________________________
________________________________________________________________
________________________________________________________________

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

33

LAB 6
Array Processing
AIM: To study an ARM assembly language program to sort five numbers in ascending and
descending 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. To
write 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.
3. In startup file, replace actual code from line number 488 till end as shown below.
IMPORT start
LDR R0, =start
BX
R0
END
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 name
can be given.
CODE means its 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,READONLY
EXPORT start
start
MOV R0,#0X40000000
MOV R1,R0
MOV R4,#4
MOV R5,#4
HERE2
LDR R2,[R0]
HERE1
ADD R1,R1,#4
LDR R3,[R1]
CMP R2,R3
Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad

34

BLT HERE
MOV R6,R2
MOV R2,R3
MOV R3,R6
STR R2,[R0]
STR R3,[R1]
HERE
SUB R4,R4,#1
CMP R4,#0
BNE HERE1
ADD R0,R0,#4
MOV R1,R0
SUB R5,R5,#1
MOV R4,R5
CMP R5,#0
BNE HERE2
END
Output:

Conclusion:________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
__________________

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

35

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 to
write ARM assembly language program in higher language (C) program. Basic advantage
of such provision is to get high code density. This provision is mostly used where code
storage capacity of processor is less compared to the requirement.
Restrictions on inline assembly operations: There are a number of restrictions on the
operations that can be performed in inline assembly code. These restrictions provide a
measure of safety, and ensure that the assumptions in compiled C and C++ code are not
violated in the assembled assembly code.
Miscellaneous restrictions
The inline assembler has the following restrictions:
The inline assembler is a high-level assembler, and the code it generates might not
always be exactly what you write. Do not use it to generate more efficient code than the
compiler 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 prefix
instead. For example:__asm { AND x, y, 0xF00 }
The notation to specify the actual rotate of an 8-bit constant is not available in inline
assembly language. This means that where an 8-bit shifted constant is used, the C flag
must be regarded as corrupted if the NZCV flags are updated.
You must not modify the stack. This is not necessary because the compiler automatically
stacks and restores any working registers as required. The compiler does not permit you
to explicitly stack and restore work registers.
Registers
Registers, 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 flags
might 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 the
following intrinsics to access these registers:
current_pc in the Compiler Reference Guide
current_sp in the Compiler Reference Guide
return_address in the Compiler Reference Guide.

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

36

Thumb instruction set


The inline assembler is not available when compiling C or C++ for Thumb state, and
the inline assembler does not assemble Thumb instructions. Instead, the compiler
switches to ARM state automatically.
Unsupported instructions
The following instructions are not supported in the inline assembler:
BKPT , BX , BXJ, and BLX instructions
SVC instruction x LDR Rn, =expression pseudo-instruction. Use MOV Rn, expression
instead (this can generate a load from a literal pool)
LDRT, LDRBT, STRT, and STRBT instructions
MUL, MLA, UMULL, UMLAL, SMULL, and SMLAL flag setting instructions
MOV or MVN flag-setting instructions where the second operand is a constant
user-mode LDM instructions
ADR 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;
Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad

37

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 C
statements into their corresponding assembly language statements is shown below:

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

38

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 a
compressed form of a subset of the ARM instruction set. Thumb instructions map onto ARM
instructions, and the Thumb programmer's model maps onto the ARM programmer's model.
Implementations of Thumb use dynamic decompression in an ARM instruction pipeline and
then instructions execute as standard ARM instructions within the processor.
Thumb is not a complete architecture; it is not anticipated that a processor would execute
Thumb instructions without also supporting the ARM instruction set. Therefore the Thumb
instruction set need only support common application functions, allowing recourse to the full
ARM instruction set where necessary (for instance, all exceptions automatically enter ARM
mode).
Thumb is fully supported by ARM development tools, and an application can mix ARM and
Thumb 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, READONLY
EXPORT square
square
mov r1,#&44
movs r2,#44
adcs r3,r2,r1,asr#5
subs r7,r2,r1,lsl#4
ldr r5,=fun
movslr,pc
bx r5
add r1,#1
add r1,#1
add r1,#1
b function
THUMB
fun
ldr r6,=0x40000000
movs r7,r6
ldr r0,=65534
ldr r1,=280
movs r2,#54
movs r3,#0
Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad

39

stmia r6!,{r0-r3}
movs r2,#0
loop
ldr r3,[r7]
adds R2,R3
adds r7,#4
cmp r6,r7
bgt loop
bxlr
ARM
function
add r5,r0,r1
end

Output: By checking CPSR [5] (TBIT), we can always say whether the processor is in ARM
or 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 ARM
state.

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

40

Conclusion:________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
__________________

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

41

LAB 8
Software 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 desired
exception.
To write the assembly program we have to make some changes as shown below in startup
file.
-in C program block at line no.500 instead of import _main we have to write the name which
is given to our assembly block in our program.
; Enter the C code
IMPORT start
LDR R0, =start
BX
R0
END
The program 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.
Program: A program creating two SWIs is shown below. User defined handlers are returned
for 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 start
exportSWI_Handler
SWI_Handler
mov r7,lr
ldr 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;

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

42

mov pc,r14;

sw1

end

start

mov r1,#0x00000001;
add r1,r1,#0x01;
mov pc,r14;
movpc,lr;

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

Output: The execution of the above program goes in following manner. Firstly, the
execution begins in the startup file where it encounters an import startstatement due to which
it 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 import
SWI_Handlerstatement pertaining to which it returns to main program and starts executing
the 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 occurring
and the same procedure repeats. At the end execution again jumps back to startup file.

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

43

AIM (ii): To study subroutines.

THEORY:
The use of subroutine is to define function which required to call number of times. The
subroutine 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 startup
file.
-in C program block at line no.500 instead of import _main we have to write the name which
is given to our assembly block in our program.
; Enter the C code
IMPORT start
LDR R0, =start
BX
R0
END
The program 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.
Program:

doadd
domul

AREA subrout, CODE, READONLY


EXPORT start
IMPORT domul
ADD r4, r0, r1
BX lr;
MUL r5, r2, r1;
BX lr;

start
mov r0, #10
mov r1, #3
bldoadd ;
mov r2, r4;
bldomul;
mov r3, r5;
wait
B wait;
End

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

44

Output:

\\

Conclusion:________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad

45

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
VICIntSelect
VICSoftInt

VICFIQStatus
VICIntEnable
VICSoftIntClr

VICRawintr
VICIntEnClr

Special Function Register Description:

THEORY :
The ARM processor core has two interrupt inputs called Interrupt Request (IRQ) and Fast
Interrupt request (FIQ). The Vectored Interrupt Controller (VIC) takes 32 interrupt request
inputs and program assigns them as FIQ or vectored IRQ types. The programmable
assignment scheme means that priorities of interrupts from the various peripherals can be
dynamically assigned and adjusted. Vectored IRQs, which include all interrupt requests that
are not classified as FIQs, have a programmable interrupt priority. When more than one
Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad

46

interrupt is assigned the same priority and occur simultaneously, the one connected to the
lowest numbered VIC channel will be serviced first.
The VIC ORs the requests from all of the vectored IRQs to produce the IRQ signal to the
ARM 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 <lpc23xx.h>
__irq void IRQ_Handler (void)
{ int a=10,b=20,c;
c=a+b;
VICSoftIntClr= 0x00004000;
}

//IRQ handler definition

int main(void)
{
EXTMODE= 0x00000001; //Interrupt configuration, edge triggered
EXTPOLAR=0x00000001; //positive going interrupt
VICIntEnable=0x00004000; //Enable interrupt
VICIntSelect=0x00000000; //set interrupt as IRQ
VICVectAddr14 = (unsigned long) IRQ_Handler;
VICSoftInt=0x00004000;
//Software interrupt generation
while(1){//wait here
}
}
Output:

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

47

AIM(ii):To understand FIQ exception Handling mechanism


SPECIAL FUNCTION REGISTERS OF VECTORED INTERRUPT CONTROLLER:
VICIRQStatus
VICIntSelect
VICSoftInt

VICFIQStatus VICRawintr
VICIntEnable
VICIntEnClr
VICSoftIntClr

SPECIAL FUNCTION REGISTER DESCRIPTION:

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

48

THEORY:
Fast Interrupt request (FIQ) requests have the highest priority. If more than one request is
assigned 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 is
classified as FIQ, because then the FIQ service routine can simply start dealing with that
device. But if more than one request is assigned to the FIQ class, the FIQ service routine
can read a word from the VIC that identifies which FIQ source(s) is (are) requesting an
interrupt.

Program:

#include <lpc23xx.h>

__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

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

49

Output:

Conclusion:________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad

50

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 managed
independently by a scheduler [a part of an operating system]. The implementation of threads
and processes differs from one operating system to another, but in most cases, a thread is a
component of a process. Multiple threads can exist within the same process and share
resources and doing so run concurrently. When multiple threads are running concurrently,
this is known as multithreading. Typical example of multithreading is downloading a video
while playing it at the same time.
Compilation and Execution Steps
1.
2.
3.
4.

Open Terminal (ALT + CLT + T)


$ gedit program.c
$ gcc program.c -l pthread
$ ./a.out

Sample Program
#include <stdio.h>
#include <pthread.h>
#include <errno.h>
#include <sys/types.h>
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);
Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad

51

}
else
{
printf("Thread %u is joined\n\n",ptid);
}
return 0;
}
OUTPUT:

CONCLUSION:
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
______________________________

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

52

MODIFICATION
Modify the above program to create five threads and join them also.
#include<stdio.h>
#include<pthread.h>
#include<errno.h>
#include<sys/types.h>
void myfun()
{
printf("\nHello I am thread %u",(unsigned int)pthread_self());
}
int main()
{
int i=0;
pthread_t ptid[5];
for (i=0;i<5;i++)
{
if(pthread_create(&ptid[i],NULL,(void *)myfun,NULL)!=0)
{
printf("\nThread Creation Error : %d",errno);
}
else
{
printf("\nThread %u is created\n\n",ptid[i]);
}
}

for(i=0;i<5;i++)
{
if(pthread_join(ptid[i],NULL)!=0)
{
printf("Thread %u Join Error : %d\n",ptid[i],errno);
}
else
{
printf("Thread %u is joined\n\n",ptid[i]);
}
}
return 0;
}

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

53

OUTPUT:

EXERCISE
1. Write a program to create two different threads for addition and subtraction on a and b
variables.

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

54

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 the
same 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 and
init process becomes its parent process.
1. Create child process using single fork.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int pid, status;
fork();
printf("PID=%d and PPID=%d\n",getpid(),getppid());
}
Output:

Process Tree:

PID-1586
Bash Process

PID-1585

PID-1584

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

55

Printing PID and PPID before fork call:


#include<stdio.h>
#include<stdlib.h>
int 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 and
observe orphan processes.
2 subsequent fork calls:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int pid, status;
fork();
fork();
printf("PID=%d and PPID=%d\n",getpid(),getppid());
}

Output:

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

56

Process Tree:
PID-1586
Bash Process

PID-2188

PID-2190

PID-2189

PID-2191

3 subsequent fork calls:


#include<stdio.h>
#include<stdlib.h>
int main()
{
int pid, status;
fork();
fork();
fork();
printf("PID=%d and PPID=%d\n",getpid(),getppid());
}
Output:

Process Tree:

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

57

PID-1586
Bash Process

PID-2241

PID-2242

PID-2243

PID-2246

PID-2244

PID-2245

Observe that processes having PPID=1 are orphaned and driven by init process
3 subsequent fork calls with waitpid() function
#include<stdio.h>
#include<stdlib.h>
void 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<3;i++)
{
waitpid(-1,&status,0);
//making every parent to wait till all its child process //finishes thier work so that no process
will become orphan
}
}
else if(pid==0)
{
printf("I am child with PID %d and PPID %d\n",getpid(),getppid());
}
}

Output:

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

58

Process Tree:
PID-1586
Bash Process

PID-2302

PID-2303

PID-2305

PID-2304

PID-2307

PID-2306

PID-2309

PID--2308

4 subsequent fork calls with waitpid() function


#include<stdio.h>
#include<stdlib.h>
void 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<4;i++)
{
Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad

59

waitpid(-1,&status,0);
//making every parent to wait till all its child process finishes thier //work so that no process
will become orphan
}
}
else if(pid==0)
{
printf("I am child with PID %d and PPID %d\n",getpid(),getppid());
}
}

Output:

Process Tree:

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

60

Bash Process
PID-1586

PID-2364

PID-2365

PID-2371

PID-2367

PID-2373

PID-2374

PID-2366

PID-2369

PID-2376

PID-2375

PID-2379

PID-2377

PID-2368

PID-2370

PID-2372

PID-2378

EXERCISE:

Write a program to exhaust the process table.


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

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

61

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 fanning
option, one parent process generates multiple child processes. However, in the chaining
option, child process becomes the parent process for the next generated child process and so
on 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 processes
executes.
This system call is equivalent to generating hardware delay as and when
needed.
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int 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(count<nLevel)
{
pid=fork();
if(pid==0)
{
printf("I am Child %d with PID %d and PPID %d\n",++count,getpid(),getppid());
exit(0);
}
else if(pid>0)
{
count++;
continue;
}
else
{
printf("Error Condition\n");
}
}
Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad

62

int status;
for(i=0; i<nLevel; i++)
waitpid(-1, &status, 0);
}
if(option==2)
{
printf("I am Parent with PID %d and PPID %d\n",getpid(),getppid());
while(count<nLevel)
{
pid=fork();
if(pid>0)
{
int status1;
waitpid(-1, &status1, 0);
exit(0)
}
else if(pid==0)
{
printf("I am Child %d with PID %d and PPID %d\n",++count,getpid(),getppid());
continue;
}
else
{
printf("Error Condition\n");
}
}
}
return 0;
}

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

63

OUTPUT: Fanning with 3 process and Chaining with 3 processes

Process Tree:
1

Fanning
Bash Process
PID-1944

PID-1969

PID-1970

PID-1971

PID-1992

Chaining
Bash Process
PID-1994

PID-1978

PID-1979

PID-1980

PID-1981

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

64

CONCLUSION:
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
__________________________________________________________________________________
____________________________________

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

65

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 a
semaphore, all of which are atomic: initialize, increment and decrement. The decrement operation
may 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 needs
two 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 right
fork, one at a time in either order. If successful in acquiring two forks, she eats for a while, then puts
down the forks and continue to think. With a little bit of bad luck, all the philosophers could start the
algorithm 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 make
any progress is called Starvation.
SAMPLE PROGRAM:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<pthread.h>
#include<semaphore.h>

#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);
Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad

66

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<N; i++)
{
if(pthread_create(&Philosophers[i],NULL,(void *)init,(void *)ph[i]))
{
printf("Error in creating thread for philosopher %d.\n", i);
exit(1);
}
printf("Thread created for philosopher %d.\n", i);
}

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


{
pthread_join(Philosophers[i],NULL);
}
return 0;
}

void init (int id)


{
while(1)
{
think(id);
pickup(id);
eat(id);
putdown(id);
}
Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad

67

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);

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

68

OUTPUT:

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

69

2. Case of Producer-Consumer
AIM: To illustrate the race condition in case of Producer-Consumer while accessing the
shared 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 when
the 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 that
the 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 to
go to sleep (when buffer is empty) until producer puts something in the buffer and wakes it
up.
The sample program demonstrates the generation of race condition using M (=1) producers
and 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. Here
we have redirected the output to the outputfile.txt using > operator. In our case the
output 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<stdio.h>
#include<pthread.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdlib.h>
#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<SIZE)
//if buffer is not full
Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad

70

{
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,.,SIZE1,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=0
tb=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 in
thread
%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,.,SIZE1,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 <number of producer threads><number of
consumer threads>\n");
return -1;
}
else
{
Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad

71

size_producer = atoi(argv[1]);

//size of producer from command line

size_consumer = atoi(argv[2]);

//size of consumer from command line

arguments
arguments
pthread_t pTid[size_producer];
//to store producer threads ID
pthread_t cTid[size_consumer];
//to store consumer threads ID
for(index=0;index<SIZE;index++)
buffer[index]=-1;
//initialize buffer by -1
for(index=0;index<size_producer;index++)
//create producer thread
{
if(pthread_create(&pTid[index],NULL,(void *)producer,NULL)!=0)
{
printf("Error in creation of producer thread\n");
return -1;
}
else
printf("Producer thread is cretated\n");
}
for(index=0;index<size_consumer;index++)
//create consumer thread
{
if(pthread_create(&cTid[index],NULL,(void *)consumer,NULL)!=0)
{
printf("Error in creation of consumer thread\n");
return -1;
}
else
printf("Consumer thread is cretated\n");
}
for(i=0;i<size_producer;i++)
//join producer thread
{
if(pthread_join(pTid[i],NULL)!=0)
{
printf("Error in join of thread %d\n",pTid[i]);
return -1;
}
}
for(i=0;i<size_consumer;i++)
//join consumer thread
{
if(pthread_join(cTid[i],NULL)!=0)
{
printf("Error in join of thread %d\n",cTid[i]);
return -1;
}
}
}
return 0;
}
Department of Electronics & Communication, Faculty of Technology, Dharmsinh Desai University, Nadiad

72

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

MODIFICATION

Test the program for more producer and consumers.

EXERCISE

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


producers ii) number of consumers.

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

73

CONCLUSION:
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
______________________________________________________________________

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

74

Вам также может понравиться