Está en la página 1de 51

CHAPTER 1

INTRODUCTION

1.1. DEFINITION OF THE PROBLEM:

Now-a-days, we are living in the world of automation. Everything is controlled with the
help of microcontrollers. Traffic Light Controller is also an area which incorporates such
type of control, i.e., using microcontrollers. But, this control is not flexible.

Transportation Research has the main aim to optimize the transportation flow of people
and goods. As the number of road users increases, and resources provided by the current
infrastructure are limited, intelligent control of traffic will become an important issue in
future. Avoiding traffic jams is thought to be beneficial to both environment and
economy [1].

To optimize the traffic control, one way would be to control the traffic using the traffic
density at that moment of time. Fuzzy control has been successfully applied to many
tasks of automatic control over the last decades and can very well used to facilitate this
approach [5]. This technique uses the real-time parameters like traffic density behind the
Red and Green lights which thereby controls the on and off timings of the red and green
lights. This technique provides the flexibility to the present inflexible approach.

1.2. MOTIVATION:

1.2.1. JUSTIFICATION:

Current traffic light controllers used to change the cycle time at a constant rate.
This approach increases the average waiting time and, thus, is not an optimized way
causing this method to be fruitless.
Fuzzy logic approach is based upon traffic density in a real-time environment. It
provides mathematical tools for solving and working out approximate reasoning

1
processes when having to deal with real-time data. This logic is composed of fuzzy sets,
which are provided by a mathematical definition rising from the concept of degrees of
membership. Thus, fuzzy logic may well hold the key to usefully capturing the real-time
traffic data and making the approach flexible. It works in the same manner as human
controls traffic.

1.2.2. OBJECTIVES:

 The objective of this project is centered on development of a method that is


capable of controlling the traffic using the real-time parameters which plague the
traffic light controller systems.
 Other objectives include creating a robust traffic light controller system which
reduces the average waiting time.

1.2.3. FOCUS:

The focus of this project is centered upon determining the on and off timings of
the green and red lights of the traffic light. A working model is being prepared in
order to implement the idea using any hypothetical situation. The same idea may
work for the real-time situations as well.

1.2.4 ORGANISATION OF THE THESIS:

The remaining of the document is organized as follows:


Section 2 contains the theoretical description of the fuzzy logic as well as the
hardware components.
Section 3 contains the feasibility study and the requirement analysis of the
project.
Section 4 contains the Present day technique.
Section 5 contains the proposed technique with all the assumptions and the
methodology.
Section 6 contains the System analysis and the design of the project.

2
Section 7 contains the experiments with results and the graphs.
Section 8 contains the conclusion.

3
CHAPTER 2
THEORETICAL BACKGROUND

2.1. FUZZY LOGIC:

2.1.1. BASIC CONCEPTS:

In classical or crisp sets, an element in the universe has a well defined membership or
non membership to a given set. Membership to a crisp set F can be defined through a
membership function defined for every element x of the universe as
1 xεF
µ=
0 xF
An example of a graphic for the membership function of a crisp set is illustrated in
Figure 1. Here, scanning the universe, there is an abrupt and well-defined transition from
membership to non membership and vice versa. It is said to be “crisp” [2].

Figure 2.1. Classic Sets [2]

For an element in a universe with fuzzy sets, the membership transition can be gradual.
So the membership function can take any value between 0 and 1. This transition among
various degrees of membership can be thought of as conforming to the fact that the

4
boundaries of the fuzzy sets are vague and ambiguous. Fuzzy membership counterpart
for Figure 1 would be that of Figure 2. Hence, membership of an element from the
universe in this set is measured by a function that attempts to describe vagueness and
ambiguity. In fuzzy logic, linguistic variables take on linguistic values which are words
(linguistic terms) with associated degrees of membership in the set.

Figure 2.2. Fuzzy sets


Formally, a fuzzy set is defined as a set of pairs where each element in the universe U
has a degree of membership associated with it:
F = {(x, µF(x)) | x ∈ U, µF(x) ∈ [0, 1]}

µF(x) is known as the membership function of the set F. Most often, one refers to the
fuzzy set just by mentioning the membership function, the universe being implicit.

2.1.2. FUZZY LOGIC SYSTEMS:

A FLS receives a crisp input and may deliver either a fuzzy set or a crisp value. The
basic FLS contains four components: a rule set, a fuzzifier, an inference engine, and
a defuzzifier. Rules may be provided by experts or can be extracted from numerical data.
In either case, the engineering rules are expressed as a collection of IF-THEN statements.
These statements are related to fuzzy sets associated with linguistic variables.

The fuzzifier maps the input crisp numbers into the fuzzy sets to obtain degrees of
membership. It is needed in order to activate rules, which are in terms of the linguistic
variables. The inference engine of the FLS maps the antecedent fuzzy (IF part) sets into

5
consequent fuzzy sets (THEN part). This engine handles the way in which the rules are
combined. In practice, only a very small number of rules are actually used in engineering
applications of Fuzzy Logic (FL).

2.1.2.1. FUZZIFICATION:

The first step in fuzzy logic processing involves a domain transformation


called fuzzification (Figure 2.3). Crisp inputs are transformed into fuzzy
inputs. To transform crisp input into fuzzy input, membership functions
must first be defined for each input.

Once membership functions are defined, fuzzification takes a real time


input value, such as temperature, and compares it with the stored
membership function information to produce fuzzy input values.

Figure 2.3 Fuzzification [4]

6
2.1.2.2. FUZZY INFERENCE:

Fuzzy logic based systems use RULES to represent the relationship


between observations and actions. These rules consist of a precondition
(IF-part) and a consequence (THEN-part). The precondition can consist of
multiple conditions linked together with AND or OR conjunctions.
Conditions may be negated with a NOT. The computation of fuzzy rules
is called Fuzzy Inference.

Fuzzy rule inference consists of two steps:

• Inferencing, which determines the fuzzy subset of each output variable


for each rule. Usually only MIN or PRODUCT are used as inference
rules. In MIN inferencing, the output membership function is clipped off
at a height corresponding to the rule premise’s computed degree of truth
(fuzzy logic AND). In PRODUCT inferencing, the output membership
function is scaled by the rule premises' computed degree of truth.

• Composition, which combines the fuzzy subsets for each output variable
into a single fuzzy subset. Usually MAX or SUM are used. In MAX
composition, the combined output fuzzy subset is constructed by taking
the point wise maximum over all of the fuzzy subsets assigned to variable
by the inference rule (fuzzy logic OR). In SUM composition, the
combined output fuzzy subset is constructed by taking the pointwise sum
over all of the fuzzy subsets assigned to the output variable by the
inference rule.

IF-THEN rules are a common way of representing and communicating


knowledge in everyday conversation. Anyone who has written a program
or machine code knows how complicated (and difficult to debug, read,
and maintain) the if-then lines can get. Fuzzy rules offer a way of getting
around that by trading the precise representation of the values that
variables must assume with much more intuitive fuzzy representations.

7
In binary logic the consequent is either true or false. In fuzzy logic partial
truths are allowed so the consequent is as partially true as the antecedent
allows it to be.

In general a rule by itself does not do much. What is needed are a set of
rules that can play off one another. The fuzzy inference methodology
allows “fair” competition between these rules to produce sophisticated
answers using seemingly simple premises.

Figure 2.4 Fuzzy Inference Process [4]

2.1.2.3. DEFUZZIFICATION:

This stage is used to convert the fuzzy output set to a crisp number. Two
of the more common techniques are the Centroid and Maximum methods.
In the Centroid method, the crisp value of the output variable is computed

8
by finding the value of the center of gravity of the membership function.
In the Maximum method, the crisp value of the output variable is the
maximum truth-value (membership weight) of the fuzzy subset.
Figure 2.5 illustrates the complete process with an example.

Figure 2.5 Defuzzification [4]

2.2. ABOUT MICROCONTROLLERS AND OTHER


HARDWARES:

2.2.1 TRANSMITTER CIRCUIT:

Figure 2.3. Transmitter Circuit [8]

9
Description [9]:

TSAL6200 is a high efficiency infrared emitting diode in GaAlAs on GaAs


technology, molded in clear, blue-grey tinted plastic packages. In comparison
with the standard GaAs on GaAs technology these emitters achieve more than
100 % radiant power improvement at a similar wavelength. The forward voltages
at low current and at high pulse current roughly correspond to the low values of
the standard technology. Therefore these emitters are ideally suitable as high
performance replacements of standard emitters.

Features [9]:

 Extra high radiant power and radiant intensity


 High reliability
 Low forward voltage
 Suitable for high pulse current operation
 Standard T–1(ø 5 mm) package
 Angle of half intensity  = ± 17
 Peak wavelength p = 940 nm
 Good spectral matching to Si photodetectors

Applications [9]:

Infrared remote control units with high power requirements


Free air transmission systems
Infrared source for optical counters and card readers
IR source for smoke detectors

10
Absolute Maximum Ratings:

Table 2.1 Absolute maximum Ratings of TSAL6200 [9]

Basic Characteristics:

Table 2.2 Basic Characteristics of TSAL6200 [9]

11
2.2.2. RECEIVER:

Figure 2.4.Pin Diagram of Receiver [7]


Description:

The TSOP17.. – series are miniaturized receivers for infrared remote control
systems. PIN diode and preamplifier are assembled on lead frame, the epoxy
package is designed as IR filter. The demodulated output signal can directly be
decoded by a microprocessor. TSOP17.. is the standard IR remote control
receiver series, supporting all major transmission codes. TSOP series is available
in frequency range 30-56 KHz. In the TSOP package, PIN Diode and
preamplifier are on the Lead frame and IR filter is in Epoxy package. The output
of the receiver can be decoded by a microcontroller. It consumes less power. It is
compatible with TTL and CMOS [7].

Figure 2.5 Basic Internal Block Diagram [7]

12
Figure 2.6 Receiver PIN-OUT [7]

2.2.3. MICROCONTROLLER PIN OUT:

ATMEGA8 MICROCONTROLLER:

Figure 2.7. Microcontroller Pin Diagram [6]

13
Description:

low-power Atmel 8-bit AVR RISC-based microcontroller combines 8KB of


programmable flash memory, 1KB of SRAM, 512K EEPROM, and a 6 or 8
channel 10-bit A/D converter. The device supports throughput of 16 MIPS at 16
MHz and operates between 2.7-5.5 volts [6].

Key Parameters of Atmega8: [6]

Table 2.3. Key parameters

PARAMETERS VALUE
AVR Core 8 bit
Flash (Kbytes) 8
Boot Code Included
Self Program Memory Yes
EEPROM(bytes) 512
SRAM(bytes) 1K
8-bit timers 2
16-bit timer 1
USB 0
Temp.sensor No
LCD No
Max I/O Pins 23
On-chip RC Oscillator 1 MHz+cal 1/2/4/8 MHz
Debug No

14
2.2.4. COMPLETE HARDWARE CIRCUIT:

Figure 2.8. Hardware circuit [8]

15
CHAPTER 3
FEASIBILITY STUDY AND REQUIREMENT
ANALYSIS

3.1. THREE PHASES OF FEASIBILITY STUDY

3.1.1 Technical Feasibility: The project requires the knowledge of various


hardware components as well microcontroller programming and fuzzy logic as
well. These can be easily learnt from any tutorials.

3.1.2 Economical Feasibility: The project cost includes only the hardware
component’s cost which is quite nominal. And, the software like AVR Studio for
microcontroller programming can be downloaded from the Internet free of cost.

3.1.3 Operational Feasibility: The project is fully automated as it is


controlled with the help of microcontrollers. So, the question of operational
feasibility does not arise.

3.2. REQUIREMENT ANALYSIS

A requirement is a condition or capability that must be met or possessed by a system to


satisfy a contract, standard, specification or other formally imposed specification of the
client. This phase ends with the Software Requirements Specifications (SRS). The SRS
is a document that completely describes what the proposed software should do without
describing how the software will do it.

16
3.2.1 SOFTWARE REQUIREMENTS:

 AVR Studio as editor for Microcontroller programming.


 WIN AVR as compiler for microcontroller programming.
 MATLAB for making graphs for membership values, rule viewer and Output in
Fuzzy logic.
 Microsoft Word for preparation of Report.

3.2.2 HARDWARE REQUIREMENTS:

 Processor: PC with a Pentium IV-class processor, 600 MHz, Recommended:


Pentium IV-class, 1.63 GHz.
 RAM: Windows XP Home -512 MB RAM.
 Transmitters
 Receivers
 ATMEGA 8 AVR Microcontrollers.
 Dummy Vehicles
 Burner
 LEDs

17
CHAPTER 4
SYSTEM ANALYSIS & SYSTEM DESIGN

Requirement analysis defines “WHAT” the system should do; design tells ‘HOW’ to do
it. This is the simplest way to defines system design. Any design has to be constantly
evaluated to ensure that it meet its requirements, is practical and workable in the given
environment. If there are number of alternatives, then all alternatives must be evaluated
and the best possible solution must be implemented.

4.1. SPECIFICATION OF PROJECT:

The proposed system should have following features:


1. AVR Studio should be able to save the file in .C format.
2. The program burnt in microcontroller should be in .HEX format.
3. The fuzzy rule base should be made in general.

4.2 SYSTEM DESIGN:

System Design is the technique of creating a system that takes into notice such factors
such as needs, performance levels, database design, hardware specifications, and data
management. It is the most important part in the development part in the development of
the system, as in the design phase the developer brings into existence the proposed
system the analyst through of in the analysis phase.

4.2.1. DATA FLOW DIAGRAMS (DFD):

The Traffic light controller system calculates the current cycle time. Firstly, the sensors
senses for the vehicle and pass the IR rays to the receiver which in turn acts as an input

18
to the microcontroller. In the microcontroller, the fuzzy logic approach is burnt which
helps us to calculate the current cycle time.

4.2.1.1. ZERO LEVEL DFD:

TRAFFIC
LIGHT
INPUT CONTROLLER OUTPUT
SYSTEM

Figure 4.1 Zero Level DFD

4.2.1.2. ONE LEVEL DFD:

INPUT SENSORS MICROCO OUTPUT


NTROLLER

Figure 4.2 1st Level DFD

4.2.1.3. TWO LEVEL DFD:

 Input to the transmitter:

senses INCRE
TRANS RECEIV MICRO
INPUT MENTS
MITTER ER CONTR COUNT
OLLER FOR
CARS
Figure 4.3 2nd Level DFD

19
 Calculation of current cycle time using fuzzy logic:

No. of cars Current


Fuzzifica Rule base Defuzzific
behind red cycle time
tion evaluation ation
and green
light.

Figure 4.4 2nd Level DFD

4.2.2. FLOWCHART:

For burning a program to microcontroller:

Figure 4.5 Flowchart depicting burning of a program to microcontroller

20
CHAPTER 5
PRESENT DAY TECHNIQUE

The most commonly used technique for traffic light controller is based on
microcontrollers, which controls four sets of traffic lights at the traffic crossing. The
timings for the red and green lights are prefixed according to the normal level of traffic at
that crossing as per the earlier experience or past records. They use previous years data
for the place and at particular time to set the on and off timing of the red and green
lights.

Another commonly used technique is to prefix the cycle time to a constant value and the
same value is being rotated to all the four sided of traffic for the on and off timings of
green and red lights [3].

21
CHAPTER 6
PROPOSED TECHNIQUE

The technique described above is a typical non-flexible technique. The optimal way
would be to pass more cars at the green interval if there are a few cars behind the red
light. Obviously, a mathematical model for this is enormously difficult to find. However,
a mathematical model for this is possible. The technique controls the traffic in the same
way as humans do. The human operator observes the traffic density in different
directions and then changes the timing keeping in mind the fair rotation of the turns. In
the same way, it controls the traffic according to the real-time situations of the traffic at
that moment of time.

6.1. ALGORITHM:

1. Take input from sensors.


2. Calculate density.
3. Calculate membership values for different values.
4. Use fuzzy rule to infer the fuzzy output.
5. For the output produced in step 4, find its crisp value.

6.2. ASSUMPTIONS:

6.2.1. METHODOLOGY:

This is explained with reference to the Fig. 6.1. [3].


 The first sensor behind each traffic light counts the number of cars
coming to the intersection.
 The second sensor counts the cars crossing the traffic light.

22
 The distance D is kept constant.
 The distance D is used to determine the maximum density of cars
allowed to wait in a crowded situation.
 This is done by calculating the number of cars between the path and
dividing it by the total distance D.

Figure 6.1. Illustration of control of traffic light using the proposed technique

 The fuzzy decision process uses the two inputs, cars behind the green
light and the cars behind the red light. The probability of change of
the current cycle time is dependent on the above two inputs [3].

6.2.2. FUZZIFICATION:

 For input One (Cars behind the red light)


Levels Ranges
Zero (0-4)
Low (0-7)
Medium (4-10)
High (7-10)

23
 For input Two (Cars behind the green light)
Levels Ranges
Zero (0-4)
Low (0-7)
Medium (4-10)
High (7-10)

 For output (Current cycle time)


Levels Ranges
Short (5-15)
Medium (5-25)
Long (15-35)
Very Long (25-35)

6.2.3 FUZZY RULE BASE:

If Cars behind Cars behind Then Current


red light green light cycle time
ZERO AND ZERO SHORT
ZERO AND LOW MEDIUM
ZERO AND MEDIUM LONG
ZERO AND HIGH VERY LONG
LOW AND ZERO SHORT
LOW AND LOW SHORT
LOW AND MEDIUM MEDIUM
LOW AND HIGH LONG
MEDIUM AND ZERO SHORT
MEDIUM AND LOW SHORT
MEDIUM AND MEDIUM MEDIUM
MEDIUM AND HIGH MEDIUM
HIGH AND ZERO SHORT

24
HIGH AND LOW SHORT
HIGH AND MEDIUM MEDIUM
HIGH AND HIGH LONG
Table 6.1 Fuzzy rule base

6.2.4. CALCULATING MEMBERSHIP VALUES FOR


INPUT AND OUTPUT:

 Membership graph for cars behind red lights:

Figure 6.2. Membership graph for cars behind red light

25
 Formula for fuzzification[4]:
1. If no. of car=(0-4)
Then membership value of x in zero=(4-x)/4
And membership of x in low=(x-1)/4
2. If no. of car=(4-7)
Then membership value of x in low=(7-x)/3
And membership of x in medium=(x-4)/3
3. If no. of car=(7-10)
Then membership value of x in medium= (10-x)/3
And membership of x in high=(x-7)/3

 Membership graph for cars behind green lights:

Figure 6.3. Membership graph for cars behind green light

26
 Formula for fuzzification[4]:

1. If no. of car=(0-4)
Then membership value of x in zero=(4-x)/4
And membership of x in low=(x-1)/4
2. If no. of car=(4-7)
Then membership value of x in low=(7-x)/3
And membership of x in medium=(x-4)/3
3. If no. of car=(7-10)
Then membership value of x in medium=(10-x)/3
And membership of x in high=(x-7)/3

 Membership graph for cycle time:

Figure 6.4. Membership graph for cycle time

27
 Formula for fuzzification[4]:

1. If cycle time=(5-15)
Then membership value of t in low=(15-x)/10
And membership of x in low=(x-5)/10
2. If cycle time=(15-25)
Then membership value of t in low=(25-x)/10
And membership of x in low=(x-15)/10
3. If cycle time=(25-35)
Then membership value of t in low=(35-x)/10
And membership of x in low=(x-25)/10

6.2.5 DEFUZZIFICATION:

The defuzzification Technique we have used in our project is Center of


Gravity method which is explained in Section 2.1.2.3.

28
CHAPTER 7
EXPERIMENT AND RESULTS

FOR EXAMPLE:

7.1. INPUTS:

1. Cars behind Red Light: 6


2. Cars behind Green Light: 3

Figure 7.1 Inputs And Output

29
7.2. FUZZIFICATION:

 For cars behind red light, they lie in the range (4-7).
So, membership in low=0.33
And, membership in medium=0.66
 For cars behind green light, they lie in the range (0-4)
So, membership in zero=0.25
And, membership in low=0.5

7.3. RULE BASE EVALUATION:

Rule 1: min(0,0.25)=0
Rule 2: min(0,0.5)=0
Rule 3: min(0,0)=0
Rule 4: min(0,0)=0
Rule 5: min(0.33,0.25)=0.25
Rule 6: min(0.33,0.5)=0.33
Rule 7: min(0.33,0)=0
Rule 8: min(0.33,0)=0
Rule 9: min(0.66,0.25)=0.25
Rule 10: min(0.66,0.5)=0.5
Rule 11: min(0.66,0)=0
Rule 12: min(0.66,0)=0
Rule 13: min(0,0.25)=0
Rule 14: min(0,0.5)=0
Rule 15: min(0,0)=0
Rule 16: min(0,0)=0

30
7.4. DEFUZZIFICATION:

The technique used for defuzzification is Center of Gravity.


So, in the rule base evaluation step we can see that Rule no. 6 will be applied
according to the Center of gravity approach.
So, according to rule 6, current cycle time will be short and will fall in the range
(5-15).

The exact value can be shown by the graph below:

Figure 7.2 Rule Viewer Graph and Output

So, with the help of the above graph, we can say that the current cycle time is
8.42 seconds.

31
7.5 COMPARISON WITH THE PRESENT DAY
TECHNIQUE:

In present day technique, the cycle time is kept fixed. So, according to our
assumption, let’s prefix the cycle time to 20 seconds for all the four sides.
Now, according to our given input,
Cars behind the green light=3
Cars behind the red light=6
As we can see that, the cars behind the green light is low, and the cycle time for
both lanes is same, i.e., 20 sec.
So, the waiting time for cars behind the red light is 20 seconds. Although this
time is very large for only 3 cars to pass. So, the rest of the time is wasted in this
case.
If the fuzzy logic approach would be used, the waiting time for cars behind the
red light would only be 8.42 seconds.

% reduction in waiting time


=(waiting time using((present day technique-fuzzy logic approach)/present
day technique)))*100.

% reduction in waiting time in the given example = ((20-8.42)/20)*100


= 58%
Hence, we can see that the waiting time is reduced using the fuzzy logic
approach.

32
CHAPTER 8
CONCLUSION

The system proposed here is very flexible. The maximum and minimum limits of
the cars behind the red and green lights can be altered without having the need to change
the structure of the rule set [2]. Presently, this is a proposed theoretical paper which has
only been implemented as a prototype. This is very promising application of fuzzy logic
in practical areas and can reduce the average waiting time relative to the conventional
traffic light controller.

8.1. LIMITATION OF OUR PROJECT:

1. In our proposed model, the cars are made to run in a serial manner. If two or
more cars are made to move parallel across the lane, then only one car would be
sensed by the sensor.

8.2. FUTURE WORK:

The further work could be to remove the limitation of the project, i.e. , to find a
technique such that it works well if two or more cars are passed parallely. It is able to
count the exact number of cars if two or more cars are passed parallely.

Another work could be to use the image capturing technique to count the number of cars
instead of sensors. This would require the study of digital image processing.

33
REFERENCES

[1]. Levinson, D. (2003). The value of advanced traveller information systems for route
choice. Transportation Research Part C: Emerging Technologies, 11-1:75-87.

[2]. M. Ganesh: Introduction to fuzzy logic and fuzzy sets. 169-199

[3]. Shahariz Abdul Aziz and Jeyakody Parthiban. Case Study: A Smart Traffic Light
Controller.

[4]. Neural Networks, Fuzzy logic and Genetic Algorithms- Synthesis and Applications,
202-219.

[5]. Robert Hoyer and Ultrich Jumar: Institute for Automation and Communication
Madgeburg Bahnhofstr, Fuzzy control of traffic lights.

[6].http://www.atmel.com/dyn/products/product_parameters.asp?category_id=163&fami
ly_id=607&subfamily_id=760&part_id=2004&ListAllAttributes=1.

[7]. www.datasheetcatalog.com/datasheet/T/TSOP17.

[8]. www.atmel.com.

[9]. Data Sheet Search Site: www.alldatasheet.com.

34
APPENDIX

Source code for counting the cars:

#include<avr/io.h>
int main(void)
{
DDRD = 0xFF; //set port D for output
DDRB = 0x00; //set port B for input
DDRC = 0xFF;

PORTD = 0x00;
PORTC = 0xFF;

unsigned int car_in = 0;


unsigned int car_out = 0;

char pre_in = 1;
char cur_in = PINB & 0x01;

char pre_out = 1;
char cur_out = PINB & 0x02;

char diff = 0;
while(1)
{
//for counting the incoming car
if(pre_in == 1 && cur_in == 0)
{
car_in++;
pre_in = 0;

35
PORTC = 0x00;
}
cur_in = PINB & 0x01;

if(cur_in == 1)
{
pre_in = 1;
PORTC = 0x01;
}
//for counting the outgoing car
if(pre_out == 1 && cur_out == 0)
{
car_out++;
pre_out = 0;
PORTC = 0x00;
}
cur_out = PINB & 0x02;
if(cur_out == 2)
{
pre_out = 1;
PORTC = 0x01;
}
//calculating the number of cars
diff = car_in - car_out;

//tranfering the difference to the output port


//i.e. PORTD
PORTD = diff;
}
return 0;
}

36
Snapshot:

Figure 7.3 Hardware circuitry

37
Source code of simulation:

#include <graphics.h>
#include <stdlib.h>
#include<alloc.h>
#include <stdio.h>
#include <conio.h>
#include<dos.h>
#include<math.h>
#define RED 1
#define GREEN 0

typedef struct RULE{


float val;
char st; //st: status output i.e. short,medium etc
};

int density_EW(int ,int);


int density_NS(int,int);
int gettime(int ,int ,char ,char);
float fuzzy(int);
float min(float,float);
int defuzzy(RULE[]);
void signal(char ,char);

int main()
{
/* request auto detection */
int gdriver = DETECT, gmode, errorcode;
int xmax, ymax,i,j,midx,midy,x,y,x1,x2,y1,y2,nx1,nx2,ny1,ny2,sx1,sx2,sy1,sy2;
int n,e,w,s,dns,dew,currtm,wx1,wx2,wy1,wy2,gap=10,k;
unsigned int size,size1,sizens1,sizens2;

38
void *imageew,*imagens;
char status;

/* initialize graphics and local variables */


initgraph(&gdriver, &gmode, "c:\\tc\\bgi");

/* read result of initialization */


errorcode = graphresult();

/* an error occurred */
if (errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1);
}

setcolor(getmaxcolor());
setbkcolor(5);
printf("\n\n\n \t\t\tLOADING.......");
delay(1000);
printf(".......");
delay(1000);
printf(".......");
delay(1000);
printf(".......");
delay(1000);
printf("\n\n\n\n \t\t\tPRESS ANY KEY TO CONTINUE........\n");
getch();
cleardevice();
gotoxy(1,1);
setbkcolor(10);
xmax = getmaxx();
39
ymax = getmaxy();
midx=xmax/2;
midy=ymax/2;

//HORIZONTOL LINE

setlinestyle(0,3,3);
line(0,midy-40,midx-40,midy-40);
line(0,midy+40,midx-40,midy+40);
line(midx+40,midy-40,xmax,midy-40);
line(midx+40,midy+40,xmax,midy+40);

//VERTICAL LINE

line(midx-40,0,midx-40,midy-40);
line(midx-40,midy+40,midx-40,ymax);
line(midx+40,0,midx+40,midy-40);
line(midx+40,midy+40,midx+40,ymax);
setlinestyle(2,3,2);

line(0,midy,midx-30,midy);
line(midx+30,midy,xmax,midy);
line(midx,0,midx,midy-30);
line(midx,midy+30,midx,ymax);
setlinestyle(0,2,3);
printf("\nENTER THECARS NORTH SOUTH EAST WEST");
scanf("%d%d%d%d",&n,&s,&e,&w);

printf("ENTER STATUS OF NORTH SOUTH g/r");


status=getch();
dew=density_EW(e,w);
dns=density_NS(n,s);

if(dew>10 || dns>10)
40
{
printf("\nENTER THE NUMBER OF VEHICHLE \nIN BETWEEN 0 AND 10 :");
exit(0);

}
printf("\t\t\t\tdew=%d dns=%d",dew,dns);
// move the cursor to other side
if(status=='g')
{
printf("\nNORTH SOUTH STATUS :-> GREEN ");
currtm=gettime(dew,dns,'r','g'); //currtm is the current cycle time
}
else if(status=='r')
{
printf("\nNORTH SOUTH STATUS :-> RED");
currtm=gettime(dns,dew,'r','g');
}
else
{
printf("\nENTER THE VALID STATUS");
exit(0);
}

if(status=='g')
printf("\ncycle time for NORTH SOUTH %d",currtm);
else
printf("\ncycle time for SOUTH WEST IS %d",currtm);

/* logic for moving the car */

size=(midx-70)/5; // vehichle size forEAST WEST


sizens1=(midy-70)/5;

x1=midx+40;
41
x2=midx+40+size;
y1=midy+5;
y2=midy+25;

wx1=midx-40-size;
wx2=midx-40;
wy1=midy-30;
wy2=midy-10;

//NORTH DIRECTION

nx1=midx+5;
nx2=midx+25;
ny1=midy-40-size;
ny2=midy-40;
//SOUTH DIRECTION

sx1=midx-25;
sx2=midx-5;
sy1=midy+40;
sy2=midy+40+size;

setcolor(14);
setfillstyle(1,RED); // sets current fill style and fill color
rectangle(x1,midy+5,x2,midy+25);
floodfill((x1+x2)/2,midy+15,14); // fill the area in which x y are bounded by RED

size1 =imagesize(x1,y1,x1+50,y1+50);
imageew=malloc(size1);

getimage(x1-4,y1-4,x2+4,y2+3,imageew); //saving the squre region in memory


in which circle lies

for(i=0;i<e;i++)
42
putimage(x1+i*(size+gap),y1-4,imageew,COPY_PUT);

for(i=0;i<w;i++)
putimage(wx1-i*(size+gap),wy1,imageew,OR_PUT);

// FOR NORTH SOUTH

gap=15;
rectangle(midx+5,midy-30-size,midx+25,ny2);

floodfill((nx1+nx2)/2,(ny1+ny2)/2,14); // fill the area in which x y are bounded by


RED

sizens2 =imagesize(nx1,ny1,nx1+50,ny1+50);
imagens=malloc(sizens2);
getimage(nx1-4,ny1-4,nx2+4,ny2+4,imagens); //saving the squre region in
memory in which circle lies

for(i=0;i<n;i++)
putimage(midx+5,ny1-5-i*(sizens1+gap),imagens,COPY_PUT);

for(i=0;i<s;i++)
putimage(sx1-5,sy1+i*(sizens1+gap),imagens,OR_PUT);
getch();

// MOVING THE CARS


for(k=0;k<3;k++)
{
if(status=='g')
{
signal('g','n');
while(!kbhit())
{
gap=15;

43
for(i=0;i<n;i++)
putimage(midx+5,ny1-5-
i*(sizens1+gap),imagens,XOR_PUT);
for(i=0;i<s;i++)
putimage(sx1-
5,sy1+i*(sizens1+gap),imagens,XOR_PUT);

// clears the Image from Screen

sy1=sy1-sizens1/2;
ny1=ny1+sizens1/2;
for(i=0;i<n;i++)
putimage(midx+5,ny1-5-
i*(sizens1+gap),imagens,OR_PUT);
for(i=0;i<s;i++)
putimage(sx1-
5,sy1+i*(sizens1+gap),imagens,OR_PUT);
delay(1000); // Waits for few Seconds.
}
status='p';
getch();
}
else
{
signal('r','e');
while(!kbhit())
{
gap=10;
for(i=0;i<e;i++)
putimage(x1+i*(size+gap),y1-4,imageew,XOR_PUT);

for(i=0;i<w;i++)
putimage(wx1-i*(size+gap),wy1,imageew,XOR_PUT);
// clears the Image from Screen
44
x1=x1-size/2+10;
wx1=wx1+size/2-10;

for(i=0;i<e;i++)
putimage(x1+i*(size+gap),y1-
4,imageew,OR_PUT);
// Puts the image on screen.

for(i=0;i<w;i++)
putimage(wx1-
i*(size+gap),wy1,imageew,OR_PUT);

delay(1000); // Waits for few Seconds.


}
status='g';
getch();
}
}
return 0;
}

int density_EW(int e,int w)


{
return (e+w);
}

int density_NS(int n,int s)


{
return (n+s);
}

int gettime(int dns,int dew, char stns,char stew)


{
45
int ct=0;
float rfz=0.0,rflo=0.0,rfm=0.0,rfla=0.0,gfz=0.0,gflo=0.0,gfm=0.0,gfla=0.0;
RULE r[15];

if(dns>0 && dns<=4 )


{
rfz=(4.0-dns)/4.0; //rfz->in r: red f:fuzzy z: zero
rflo=(dns-0.0)/4.0;
printf("\ndns \t zero=%f\n \tlow=%f\n",rfz,rflo);
}

if( dns>4 && dns<=7 )


{
rflo=(7.0-dns)/3.0;
rfm=(dns-4.0)/3.0;
printf(" \ndns\tlow=%f\n\t medium=%f\n",rflo,rfm);
}
if(dns>7 && dns<=10)
{
rfm=(10.0-dns)/3.0;
rfla=(dns-7.0)/3.0;
printf("\ndns\t medium=%f\n \tlarge=%f\n",rfm,rfla);

if(dew>0 && dew<=4 )


{
gfz=(4.0-dew)/4.0; //gfz->in g: red f:fuzzy z: zero
gflo=(dew-0.0)/4.0;
printf("\ndew\tzero=%f\n \tlow=%f\n",gfz,gflo);
}
if( dew>4 && dew<=7 )
{
gflo=(7.0-dew)/3.0;
46
gfm=(dew-4.0)/3.0;
printf("\ndew \tlow=%f\n medium=%f\n",gflo,gfm);
}
if(dew>7 && dew<=10)
{
gfm=(10.0-dew)/3.0;
gfla=(dew-7.0)/3.0;
printf("\ndew \t medium=%f\n large=%f\n",gfm,gfla);
}
getch();

r[1].val= min(rfz,gfz); r[1].st='s';


r[2].val= min(rfz,gflo); r[2].st='m';
r[3].val=min(rfz,gfm); r[3].st='l';
r[4].val= min(rfz,gfla); r[4].st='v';

r[5].val= min(rflo,gfz); r[5].st='s';


r[6].val= min(rflo,gflo);r[6].st='s';
r[7].val= min(rflo,gfm); r[7].st='m';
r[8].val=min(rflo,gfla); r[8].st='l';

r[9].val= min(rfm,gfz); r[9].st='s';


r[10].val= min(rfm,gflo); r[10].st='s';
r[11].val= min(rfm,gfm); r[11].st='m';
r[12].val= min(rfm,gfla); r[12].st='m';

r[13].val= min(rfla,gfz); r[13].st='s';


r[14].val= min(rfla,gflo); r[14].st='s';
r[15].val= min(rfla,gfm); r[15].st='m';
r[16].val= min(rfla,gfla); r[16].st='l';

ct=defuzzy(r); //now defuzzyfication using fuzzy OR operation


47
return ct;
}

float fuzzy(int density)


{
return 0.0;
}

float min(float value1, float value2)


{
if(value1>=value2)
return value2;
else
return value1;
//return ( (value1 < value2) ? value1 : value2);
}

int defuzzy(RULE r[])


{
int i,index;
float max=0.0, x=0.0, y=0.0, h1=0.0 ,h2=0.0 ,h3=0.0 ,x1=0.0 ,x2=0.0, x3=0.0,
cg=0.0, p=0.0, ct=0.0; //ct cycle time

for(i=1;i<=16;i++) // use algorithm to find the (FUZZY OR) maximum


{
if(r[i].val>max)
{
index=i;
max=r[i].val;
}
}
p=r[index].val;
if(r[index].st=='m' || r[index].st=='l')
{
48
if(r[index].st=='m')
{
x=5.0;
y=25.0;
printf("\n\n\n\n\n\nfuzzy output:-> m");
}
if(r[index].st=='l')
{
x=15.0;y=35.0;
printf("\n\n\n\n\n\nfuzzy output:-> l");
}

h1=p*(y-x)*.5; //slope=2/(y-x)
h2=(1.0-p)*(y-x);
h3=p*(y-x)*.5;

x1=h1*2.0/3.0;
x2=h2*0.5;
x3=h3/3.0;

cg=(h1*x1+2.0*h2*x3+h3*x3)/(h1+2.0*h2+h3);
}

if(r[index].st=='s' || r[index].st=='v')
{
if(r[index].st=='s')
{
x=5.0;y=15.0;
printf("\n\n\n\n\n\nfuzzy output:-> s");
}
if(r[index].st=='v')
{
x=25.0; y=35.0;
49
printf("\n\n\n\n\n\nfuzzy output:-> v");
}

h1=(1.0-p)*(y-x);
h2=p*(y-x); //slope=1/(y-x)
x1=h1*0.5;
x2=h2/3.0;
cg=(2.0*h1*x1+h2*x2)/(2.0*h1+h2);
}
if(r[index].st=='v')
cg=cg+25.0;

if(r[index].st=='s')
cg=cg+5.0;

if(r[index].st=='m')
cg=cg+5.0;

if(r[index].st=='l')
cg=cg+15.0;

ct=(int)ceil(cg);
return ct;
}

void signal(char sign,char dir) //signal is either green or red dir is the direction
{
int midx,midy;
midx=getmaxx()/2;
midy=getmaxy()/2;

// 2 for green signal 4 for red signal


if(sign=='g')
{
50
setfillstyle(1,2);
//NORTH SOUTH DIRECTION
circle(midx+50,midy-50,10);
circle(midx-50,midy+50,10);

floodfill(midx+50,midy-50,14);
floodfill(midx-50,midy+50,14);
setfillstyle(1,4);
circle(midx-50,midy-50,10);
circle(midx+50,midy+50,10);

floodfill(midx-50,midy-50,14);
floodfill(midx+50,midy+50,14);
}
else
{
setfillstyle(1,2);
circle(midx-50,midy-50,10);
circle(midx+50,midy+50,10);

floodfill(midx-50,midy-50,14);
floodfill(midx+50,midy+50,14);
setfillstyle(1,4);
circle(midx+50,midy-50,10);
circle(midx-50,midy+50,10);

floodfill(midx+50,midy-50,14);
floodfill(midx-50,midy+50,14);
}
setcolor(14);
setfillstyle(1,RED);
}

51

También podría gustarte