Professional Documents
Culture Documents
I56/20369/2010
DEPARTMENT OF PHYSICS
A thesis submitted in partial fulfillment of the requirements for the award of the Degree
of Master of Science (Electronics & Instrumentation) in the School of Pure and Applied
Sciences of Kenyatta University.
June 2014
ii
DECLARATION
I declare that the work presented in this thesis is my original work and has not been
presented for the award of a degree or any other award in any University.
Signature Date ..
We confirm that the candidate carried out the work reported in this thesis under our
supervision
Signature .. Date
Signature .. Date
iii
DEDICATION
ACKNOWLEDGEMENTS
Prof. Elijah Mwangi and Dr. Patrick Karimi for their invaluable guidance, motivation,
constant inspiration and above all their ever co-operating attitude that enabled me come
up with this thesis in the present form. Special acknowledgement is accorded to the
National Commission for Science, Technology and Innovation (NACOSTI) for offering
me a grant that assisted to carry out my research work and Kenyatta University for
providing a favorable environment in attaining the set goals. Special thanks are also
Wycliffe Machuki, Irene Muchira, and Nelson Mbithi for sharing all moments of joy,
laughter and sadness throughout my study days. My sincere thanks are also extended to
all lecturers in the Physics Department and physics laboratory technical staff for their
Abraham Chesaina, Fredrick Mudimba, Peris Nuna, Stephen Mwangangi and Joseph
Wataka.
The most important part of my life is my family. I would never have been able to
accomplish any of my goals without the support of my brothers; Masaku, Muuo and
Tom. Thank you. I do believe that there is a bigger word than thank you for my mum
and dad whos been always there for my highs and lows. Their unfading support has
given me strength and enthusiasm. I would also like to thank my fiance, Christine for
her love and encouragement throughout my study. Most importantly, I wish to thank the
almighty God for everything, for I believe that his sacred blessings have put me where I
am right now.
v
TABLE OF CONTENTS
DECLARATION ............................................................................................................... ii
DEDICATION ..................................................................................................................iii
ACKNOWLEDGEMENTS .............................................................................................. iv
ABSTRACT ....................................................................................................................xiii
INTRODUCTION ............................................................................................................ 1
REFERENCES ............................................................................................................... 71
APPENDICES ................................................................................................................ 76
LIST OF TABLES
Table 3.1: The PIC16F690 microcontroller memory bank addressing modes. ............... 19
microcontroller ................................................................................................................. 21
Table 3.3: Registers associated with the PIC16F690 analog to digital converter............ 27
Table 5.1: Table illustrating calculations of a 555 timer connected in astable mode ...... 65
LIST OF FIGURES
Figure 3.1: PIC16F690 pin diagram illustrating PORTA, PORTB and PORTC
configuration ................................................................................................................... 14
Figure 3.2: Schematic illustration of PIC16F690 showing program memory map and the
microcontroller ................................................................................................................ 18
Figure 3.6: A picture of the PICkit Starter Kit including LPC board.......32
Figure 3.7: Schematic showing the block diagram of a regulated power supply ........... 34
Figure 3.11: Schematic illustrating output voltage waveforms for the Astable
multivibrator ................................................................................................................... 44
Figure 4.1: Block diagram of the automatic room light controller ................................ 466
Figure 4.2: Schematic illustrating how to interface PIC microcontroller pin to a relay
coil.................................................................................................................................... 48
Figure 4.5: Schematic diagram illustrating Infrared receiver interface to PIC16F690 .... 54
Figure 4.7: Screenshot of MPLAB software showing selection of the HI-TECH ANSI C
compiler ........................................................................................................................... 57
Figure 4.8: Screenshot of MPLAB software illustrating summary of parameters used for
Figure 4.9: Screenshot of MPLAB software showing associated development files and
programme code............................................................................................................... 59
Figure 5.1: System response schematic of the designed system on circuit simulation.... 62
Figure 5.2: System response schematic of the designed system on using actual sensors
.......................................................................................................................................... 62
Figure 5.3: Photograph of the waveforms produced by a 555 timer connected in the
astable mode..................................................................................................................... 64
Figure 5.5: Output voltage versus power supply loading .............................................. 689
xi
COM Common
IR Infrared Radiation
NC Normally Closed
NO Normally Open
RC Resistor-Capacitor
ABSTRACT
Despite the installation of light energy waste control systems in modern buildings, many
people end up paying for high energy bills. The cost of installation of these systems is
usually high, and most of them are inefficient making it a major concern to the normal
user. Due to technological advancement, sensors and microcontrollers are employed in a
wide range of applications. This includes domestic and industrial fields where they aid
in control of automated processes. In these applications, manual operation is greatly
reduced hence making the systems more efficient. In order to control energy wastage,
researchers have devised different technologies all geared towards minimization of
energy waste. In this research a prototype of light control system has been designed,
fabricated and tested for stability. It consists of TSOP1738 receiver, TIL38 infrared
sensors, DH-G03 passive infrared motion sensor, PIC16F690 microcontroller interfacing
board, system software and lighting loads operated by OM1H-5H-105D relay. Passive
Infrared motion sensor (PIR) has been used for motion detection while the entire system
is controlled by the PIC16F690 microcontroller. In order to avoid false triggering of the
system, infrared transmitter and receiver together with the microcontroller have been
used to count people entering and leaving the room. When a person enters the room and
comes into the motion sensor coverage area, a register configured as a counter is
incremented by one and the lights are switched ON automatically. When a person leaves
the room, the counter is decremented by one and the status of the room occupancy is
shown on a liquid crystal display. The room lights are switched OFF within 200
milliseconds when the motion sensor detects no obstacle in its field of view hence
avoiding energy wastage. In addition, the designed system is programmable, automated,
portable and cost effective.
1
CHAPTER ONE
INTRODUCTION
In this chapter, the need for an automated light control system is presented in the context
of efficient utilization of energy. The statement of research problem and the objectives of
the research work are given. Lastly, the rationale of the research in terms of the use of an
The energy crisis is one of the major problems that the world needs to resolve for
sustainable economic development. Electrical energy lighting makes up the largest part of
power consumption in the world particularly through the use of lamps (Matta et al.,
2010). These lamps are mainly controlled using ordinary switches that are manually
operated. Sometimes the intensity from outside is sufficient to illuminate the room
therefore there is no need to turn any light ON. Due to busy schedule and competitive
world, human beings cannot spare time to perform their daily activities manually. One of
the most common things that one forgets to do is switching off the lights whenever they
are not required. This leads to wastage of electrical power and an increase in the payment
for such services hence the need of some power management to save energy.
generation, transmission and distribution of electrical energy is quite high. For this reason
minimize the existing losses, to reduce the generation costs and to protect the
2
waste does not occur because the lamps are not fitted with energy efficiency systems but
mainly because these devices require manual operation, for instance the use of on/off
switches to control the lights. The designed systems involve manual control to some
extend hence more energy is consumed .Energy efficiency systems have thus been a
subject of interest to many researchers. Many of these researchers have made great
support. A few systems have been automated but use microprocessors which require
external peripherals for the systems to work as expected. The additional peripherals
require more design space making these systems bulky and more expensive.
language of the target processor (Dogan, 2006). This consists of a series of instruction in
from different manufacturers have different assembly languages and the user is forced to
learn a new language every time a new processor is chosen. Assembly language is also
difficult to work with especially during the development, testing and maintenance of
complex projects. The solution to this is to use the high level programming languages to
systems.
3
Control systems that aim to improve the efficient utilization of electrical energy for
lighting purposes have been produced and are available in the market. However, these
systems do not provide a means of automating the activation of light control equipment.
The rapid growth of technology employing computerized systems and the availability of
suitable sensors has led to the possibility of automated light control systems. This is
1.3 Objectives
The main objective of this research work is to design an electrical energy saving system
that senses human presence in a room and uses the outcome to switch ON/OFF the lights
ii. To design and fabricate a switching device for switching the lighting load
the room.
platform.
4
A majority of the existing light control systems are manually operated and employ the
management especially in cases with many users or where the users fails to switch off
lights whenever they are not required. The automated light saving systems use
input/output lines, memory, A/D and D/A converters for their operation. The mid-range
and high performance architecture microcontroller family based systems solves all these
problems. This is attributed to the fact that these microcontrollers have reduced chip
count hence more compact products can be realized. In addition they have extended
applications whereby they have peripherals integrated on the same chip and can be
interfaced directly to the sensors and are supported by Microchip`s MPLAB software.
They also allow In Circuit Serial Programming (ICSP) whereby they can be programmed
CHAPTER TWO
LITERATURE REVIEW
2.1 Introduction
This chapter highlights briefly some of the light control designs that have been made
using different control modules to assist in the reduction of electrical energy waste.
It has been reported that lighting consumes more than 2000 terawatt-hours of electricity
globally and 48% of lighting electricity is attributed to the commercial sector (Rubinstein
et al., 1997). Various lighting control technologies have been developed for increased
energy efficiency, including daylight harvesting, occupancy sensing and light level
tuning. An excellent way of reducing lighting energy waste while enhancing lighting
quality is through the use of controls; Passive Infrared sensors (PIR) have been used to
allow occupants to adjust light levels to their preference are becoming more affordable
and can thus be incorporated into these lighting systems. Lighting controls have shown to
reduce lighting consumption by 50% in existing buildings and by at least 35% in new
construction (RLW Analytics, Inc 1999). Agogino et al. (2007) presented a lighting
optimization approach for open plan offices capable of tuning lighting to each occupants
various lighting configurations without any physical rewiring. The study used two novel
features: a versatile `plug and play` wireless networked sensing and actuation system
promising, this system has exorbitant initial costs, including unit price and installation.
Wayne and Steve (2007) studied digital systems and noted that they can perform the
same lighting automation functions that independent, stand-alone systems perform. They
can override the set schedule to match the changes in operating schedules and monitor
occupancy patterns in an area and adjust the operation of the lighting system as required.
Yandan et al. (2008) designed an intelligent lighting control system with adjustable
illuminance, uniformity, correlated color temperature (CCT) and duration and transition
by ergonomic experiments (study of designing equipment and devices that fit human
body, its movements and cognitive abilities) to be a suitable adjustable system to meet
Jinsoo et al. (2008) proposed and designed an automatic standby power cutoff outlet and
a zigbee controller with Infra-Red code learning functionality. The proposed power outlet
monitored the power consumption for the predetermined time and completely cut off the
power supply when the monitored power was below the threshold. Based on the zigbee
controller, it plays a role of switches for the power outlet and dimming lights.
7
Ranjit et al. (2010) used an infrared door sensor based on electronic combinational logic
circuit technology to develop an automatic light switching system. The system was
developed with safety environment when switching `ON` or `OFF` the light during the
room occupancy or unoccupancy. Apart from the safety environment, it also comprises
manual switching in case user needs to have light during the day. Haskew et al. (2010)
proposed an optimal control strategy for a high voltage dc light system using a direct
current vector control method for different HVdc control requirements, such as active
power, reactive power and grid voltage support control. A limitation of the conventional
control mechanism was analyzed through a theoretical study and computer simulation. In
this study, closed-loop control evaluation demonstrated that the proposed approach works
well for HVdc light system control both within and beyond the physical constraints of the
system, such as rated power and saturation of pulse width modulation (PWM). The
evaluation showed that the conventional control technique could result in over-voltage
Changhong et al. (2010) designed a street smart controller with dual functions including
timing control and automatic photoelectric control. The proposed system allowed street
lamps to be automatically lit in the evening, lighting the road for a few hours which was
adjustable. After midnight, when a few vehicles or pedestrians go past, it turned off
automatically. It had a terminal controller that had wake-up function. When the vehicles
or pedestrians pass through, the street lights are switched on by the terminal controller.
8
The waste of energy is a result of inefficient use of the electrical energy consumed by
artificial light devices such as light bulbs (Matta et al., 2010). A system for saving
electrical energy by controlling the intensity of artificial light to a satisfactory level was
designed and took into account the use of the day light when possible with the best effort
systems was introduced while counting for over illumination cases. The idea behind was
to count the venetian blinds or curtains in such a way to make use of the daylight if
available. Otherwise it uses the artificial internal building light. The system used a
controller area network as the media of communication with the sensors and the
actuators.
Wang and Devaney (2004) proposed an intelligent lighting control system that was based
on the CIE gamut standard and the dual-CPU embedded system architecture. By
employing light adjustment of the multi-colored LED, color control and scene settings of
the assembled light the intelligent light control system with the graphic user interface and
reduce operational cost by avoiding wastage. The controls can be simple as manually
turning off a switch but often automated controls ranging from simple combinational
logic circuit to complex timing devices are employed. By moving through the hierarchy
capital. For instance the automated controls are more expensive but are more flexible and
offer reliable solutions compared to the manual controls. Thomann and Younger (2003)
proposed that computers can help energy managers in the analysis of proposed and
present energy systems. By using these computer based systems, some excellent large
scale computer simulation programs have been written that enable the energy analyst to
with both analog and digital interfaces to control dimming ballasts through traditional
toggle switches. The dimming ballasts have high efficiency and contributes highly in
energy saving. Bai and Ku (2008) designed a system for light intensity detection and
control using both microprocessor and light sensors. In this design, the home light
control module (HLCM) made up of four blocks; the Passive Infrared (PIR) sensor
circuit, microprocessor and radio frequency module was installed in every light fixture.
and input/output devices on one chip unlike for a microprocessor whereby these elements
are provided as separate chips and are linked through bus connections. Since the
inception of microcontrollers, many researchers have come up with various systems with
street light controller system based on the AT89S52 microcontroller as the control core.
The product combined the following technologies: a digital clock, a timer, an LCD, a
alarm function. The system also included a time cut-out function and an automatic
10
control pattern for even more electricity conserving, namely when vehicles passed by, the
lights switched on automatically and later switched off. The system implemented traffic
condition and information collection. The system also had auto-alarm function which
switched off if any light was damaged and showed the serial number of the damaged
Chau-shing and Changhua (2008) presented a light dimmer system that did not amplify
light flicker on incandescent lamps. The development of this dimmer was motivated by
the fact that the incandescent lamp is very sensitive to voltage fluctuation and the typical
R-C circuit dimmer for incandescent lamps amplifies the light flicker considerably. The
proposed method used 16-bit microcontroller to calculate the fluctuation voltage and
determine the appropriate firing angle for a power switch device in the circuit of the
dimmer. By dynamically adjusting the firing angle to compensate for the voltage, the
proposed dimmer could substantially diminish the light flicker. Most of the current high
power light emitting diode street lighting systems are designed for illumination without
any intelligent control and cannot adjust the illumination status efficiently (Niu and Qin
2012). A few of the LED street lighting systems have intelligent control; however, they
can neither automatically detect the illumination management systems nor adjust the
systems manually. To overcome the drawbacks of the current LED lighting systems
module based on DS18B20 and a clock module based on DS1302. The MCU was then
These systems in most cases involved manual operation and those automated are too
expensive to implement. A low cost and portable automatic intelligent room light
controller was thus designed to reduce electrical energy waste using infrared sensors, PIC
CHAPTER THREE
3.1 Introduction
The chapter begins with a detailed discussion on the PIC16F690 microcontroller with
emphasis on its internal architecture. The power supply, Liquid Crystal Display (LCD),
Microchip Technology Inc. The microcontrollers are popular with industrial application
developers due to reduced chip count and reduced power consumption. In addition they
are supported by low cost or free development tools provided by the manufacturer. The
PIC family is available in three main ranges. These are the low-range, mid-range and
high-range. The low-range family has a 12-bit wide instruction with only 33 single-
architecture while the high-range utilize a 16-bit program word architecture and
level-deep stack. This provides a suitable chip selection basis for a developer since a
Among the mid-range PIC microcontrollers, the 16 series PIC16F690 has emerged as a
suitable chip due to the low pin count and availability of A/D conversion as well as to
extremely low cost. The PIC16F690 has typical range of interfaces including:
In common with the current chips, the 16F690 has analogue inputs, which allow voltage
measurement interfaces to be connected. These inputs use a single analog to digital (A/D)
13
converter, which can be connected to any one of the twelve analogue inputs (AN0 to
AN11) via a multiplexer. The A/D converts an input voltage to a corresponding 10-bit
binary code, which is placed automatically in the special function registers ADRESH and
ADRESL once the conversion is finished. The conversion is triggered by setting bit 1 of
A/D control register and is completed when the same bit is set low by the hardware. This
The PIC16F690 has a high-performance reduced instruction set computer with only 35
instructions all single cycle except program branches. It has special features that include:
The peripheral features associated with PIC16F690 are; seventeen I/O pins and one input-
only pin (RA3), two analogue comparators, three timer modules (Timer0, Timer1 and
Timer2), synchronous serial port (SSP) and In-Circuit Serial Programming (ICSP)
via pins RA0 and RA1. Figure 3.1 below shows how the PIC16F690 pins are configured.
The chip has 4K of program memory, 256 bytes each of random access memory and
simple digital input/output (I/O) on 18 of the 20 pins which are grouped as PORTA
which is 6-bit wide (RA5:RA0), 4-bit wide PORTB (RB7:RB4) and 8-bit wide PORTC
(RC7:RC0).
14
Figure 3.1: PIC16F690 pin diagram illustrating PORTA, PORTB and PORTC
configuration (www.microchip.com).
The PIC16F690 architecture is characterized by separate program code and data spaces.
These two exist as separate memories and are accessed from separate buses as is typical
of Harvard architecture. The separate bus improves bandwidth over traditional von
Neumann architecture in which program and data are fetched from the same memory
using the same bus. In the PIC16F690 all instructions are 14-bit except those which
The data memory is on an independent bus and can thus be read from and written into
while the program memory is being accessed. The data memory is further simplified into
general purpose random access memory and the special function registers (SFRs). Mid-
program memory space. As shown in the program memory map (Figure 3.2), the
PIC16F690 has a 13-bit program counter which can address a 4K x 14 program memory
15
space. The width of the program memory bus is 14-bits. Since all instructions are a single
word, a device with an 8K x 14 program memory has space for 8K of instructions. This
makes it much easier to determine if a device has sufficient program memory for a
desired application.
The program memory is the place where the user can write the code of his program. This
is usually the largest in size memory of the PIC microcontroller. Inside the
microcontroller the program is stored in the electrically erasable programmable read only
memory which is a non-volatile memory and is retained even after power is switched off.
The reset vector at address 0000H is the position where the program counter will go after
a reset or a power ON and is positioned at the beginning of the program memory. After
an execution of an instruction, the program counter will increase its content by 1. The
instruction that is located at this position will be the next to be executed. The interrupt
vector on the other hand is located at 0004h and is accessed by the program counter when
an interrupt occurs.
Based on the fact that the PIC16F690 has 13-bit width, the program counter can get
values up to 8K, but only the first 4K (0000h-0FFFh) as shown in Figure 3.2 is physical
memory. Accessing a location above these boundaries causes a wrap around whereby it
loops back to the beginning of the program memory (0000h). The programme counter is
composed of two registers; Programme Counter Low register (PCL) and Program
Counter Latch High register (PCLATH). The PCL is a readable and writable register that
carries the first 8 bits of the program counter. This register can be directly accessed and is
16
located in the third position of all four banks. The other 5 bits are not readable, but they
can be indirectly written through the PCLATH register. The PCLATH is a 5-bit width
The data memory is partitioned into four banks (Figure 3.3) which contain the General
Purpose Registers and the Special Function Registers. The SFRs are located in the first
32 locations of each bank and are used by the CPU and peripheral modules for
controlling the desired operation of the device. The file register RAM block tends to
increase in size with the program memory size and the chip complexity. It ranges from 16
to 4096 bytes in 8-bit PIC microcontrollers. Some blocks of RAM are unique while
others are common to all the RAM banks i.e. the same register is accessed at the
17
corresponding address in different banks while other address ranges may not be
implemented at all. This implies that the total amount of RAM cannot simply be
The PIC16F690 has four banks of 128 locations equivalent to 512 addresses in which the
first 32 locations in each bank are assigned as special function registers (total 128), but
there are only 256 bytes in total of unique random access memory locations (20h-7Fh,
A0h-EFh and 120h-16Fh). The remaining 128 bytes are duplicates or unimplemented.
18
microcontroller (www.microchip.com)
19
The bit assignments of the status register are shown in Figure 3.4. The 7th bit of this
Bit 7 of the STATUS register (Figure 3.4) is used for indirect addressing. In PIC16F690,
the file register is organized as 256 x 8 with each register being accessed either directly or
indirectly through the file select register. The file register 0000h (INDF) is used for
indirect file register addressing. Any instruction using the INDF register will access data
pointed to by the File Select Register (FSR). Reading INDF itself indirectly produces
00h while writing to the INDF register indirectly results in a no operation although status
bits may be affected. A generalized form of accessing the PIC16F690 memory banks
using the two addressing modes is also shown on table 3.1 below.
1 0 1
2 1 0 1
3 1 1
20
General purpose I/O pins allow the PIC microcontroller to monitor and receive signals
from sensors and actuators. In addition, the output lines allow control of peripheral
devices. In the PIC microcontroller, every I/O port has the port data register and an
associated port control register. The port data register has the same name as the port it
controls. The ports in a PIC microcontroller are bi-directional thus each pin of a port can
be used as an input or an output pin. The port control register is used to configure the port
pins as either inputs or outputs with every port having a TRIS register named after its port
name. A 1 in the TRIS bit corresponds to that pin being an input, while a 0
corresponds to that pin being an output. The port register is the latch for the data output.
Reading the port register reads the status of the pins whereas writing to it will modify the
port latch. All write operations are read-modify-write hence to write to a port implies that
the port pins are read; this value is modified, and then written to the port data latch.
For the PIC16F690, PORTA is a 6-bit wide bidirectional port and has the TRISA as its
corresponding data direction register. Setting a TRISA register bit makes the
corresponding PORTA pin an input while clearing a TRISA bit puts the content of the
output latch on the selected pin or making it an output. The exception is RA3, which is
input only and its TRIS bit will always read as 1. Every PORTA pin on the PIC16F690
has an interrupt on change option and a weak pull-up option. The control bits WPUAx in
WPUA register enable or disable the pull up with each pull-up being automatically turned
off when the port is configured as an output. The pull-ups are disabled on a power-on
pin. Control bits IOCAx of the IOCA register enable or disable the interrupt function for
each pin. The interrupt-on-change is disabled on a Power-on Reset. For enabled interrupt-
on-change pins, the values are compared with the old value latched on the last read of
PORTA. The mismatch outputs of the last read are ORd together to set the PORTA
change interrupt flag bit (RABIF) in the INTCON register. Reading PORTA will end the
microcontroller.
PORTB is a 4-bit wide, bidirectional port. The corresponding data direction register is
TRISB. Setting a bit in the TRISB register puts the corresponding output driver in a high-
impedance input mode. On the other hand clearing a bit in TRISB register puts the
contents of the output latch on the selected pin(s). Each of the PORTB pins has a weak
internal pull-up. A single control bit can turn all the pull-ups. This is performed by
22
clearing bit RBPU (OPTION<7>). The weak pull-up is also automatically turned off
when the port pin is configured as an output. The pull-ups are disabled on a Power-on-
Reset. PORTB pins RB<7:4> have an interrupt on change feature. Only pins configured
as inputs can cause this interrupt to occur. The input pins (of RB7:RB4) are compared
with the old value latched on the last read of PORTB. The mismatch outputs of RB7:RB4
are ORed together to generate the RB Port Change Interrupt with flag bit RABIF (Table
3.2). This interrupt can wake the device from SLEEP. A mismatch condition will
continue to set flag bit RABIF. Reading PORTB will end the mismatch condition, and
corresponding data direction register is TRISC which controls the direction of PORTC
pins, even when they are used as analogue inputs. To configure an analogue channel as a
digital input, the ANSEL (11Eh) and ANSELH (11Fh) must be initialised. Pins
configured as analog inputs will read 0. Setting a TRISC bit to 1 will make the
corresponding PORTC pin an input while on the other hand clearing a TRISC bit makes
the corresponding pin an output. Reading PORTC register reads the status of the pins,
whereas writing to it will write to the port latch. All write operations are read-modify-
write operations.
The number of hardware timers available increases with the chip complexity. In PIC
chips, timers are either 8-bit or 16-bit counters, with postscalers or prescalers, which
23
divide down the input or output of the counter to extend its range. The hardware timers
can be used in the usual counter or timer mode, but in addition can be used in capture,
compare or pulse width modulation (PWM) mode. Capture implies that the timer value is
stored when a selected input changes. Compare mode on the other hand is the inverse
operation whereby the timer is compared on each increment to a reference register and an
output changed or an interrupt generated when they match. The Pulse Width Modulation
mode generates Pulse-Width Modulated signal on the CCP1 pin whereby the duty cycle,
period and resolution are determined by the PR2, T2CON, CCPR1L and CCP1CON
registers. In the PWM mode, the CCP module produces up to a 10-bit resolution PWM
output on the CCP1 pin. The PIC16F690 has three hardware timers:
The 8-bit timers (Timer 0 and Timer 2) count from 0 to 255 then overflow back to 0
whereas the 16-bit timer (Timer 1) counts from 0 to 65535 then overflows back to 0.
When the overflow occurs an interrupt is generated showing that the delay has passed.
These timers are used to carry out timing operations simultaneously in the program,
3.2.5.1 Timer 0
Timer 0 uses an 8-bit register, TMR0, file register address 01. Its output is an overflow
flag, TOIF bit 2 in the Interrupt Control Register INTCON shown in Table 3.3 below.
The timer register is incremented via a clock input which is derived either from the MCU
oscillator (fosc) or an external pulse train. The register counts from 0 to 255d in binary,
24
and then rolls over to 00 again. When the register goes from FF to 00, TOIF is set. On
using the internal clock, the register acts as a timer. Each instruction in the MCU takes
four cycles to execute, hence the instruction clock is fosc/4. The timer can be driven from
the instruction, which can be monitored externally at CLKOUT, if the chip is operating
with an RC clock. If the chip is driven from a crystal of 4 MHz, the instruction clock will
be 1 MHz and the timer will overflow after 100s. alternatively, a count of external
pulses can be made and read from the register when finished or the read triggered by
3.2.5.2 Timer 1
Timer 1 is a 16-bit counter, consisting of two 8-bit registers TMR1H and TMR1L. When
the low byte rolls over from FF to 00, the high byte is incremented. The T1CON register
is used to enable/disable Timer 1 and select the various features of the Timer 1 module. It
can operate either as a timer or as a counter, selected by bit TMR1CS of the T1CON.
When operated in timer mode, TMR1 increments every oscillator frequency fosc/4.
TMR1 can be enabled or disabled by setting or clearing control bit TMR1ON whereby it
can count from 0 to 65535 and generate an overflow when changing from 65535 to 0. A
timer interrupt is generated if the TMR1 interrupt enable bit TMR1IE is enabled. TMR1
increments on every rising edge (from logic 0 to logic 1) of the clock input if operated in
counter mode.
3.2.5.3 Timer 2
match with PR2 and an 8-bit period register PR2. A prescaler is an electronic device used
25
to reduce the frequency by a predetermined factor and is used when measuring longer
periods of time. On the other hand a postscaler is used to extend the time period that a
timer can generate. The PIC16F690 TMR2 is controlled by T2CON register with the
prescaler options (1:1, 1:4 and 1:16) being selected by T2CKPS1 and T2CKPS0 bits of
T2CON. The clock input to the Timer 2 module is the system instruction clock (fosc). This
clock is fed into the Timer 2 prescaler whose output is used to increment the TMR2
register. The values of TMR2 and PR2 are constantly compared to determine when they
match. TMR2 will increment from 00h until it matches the value in PR2. On matching
TMR2 is reset to 00h on the next increment cycle or the TMR2 postscaler is incremented.
The match output of the Timer 2/PR2 comparator is fed into the Timer 2 postscaler which
has postscaler options of 1:1 and 1:16 inclusive. The output of the postscaler is used to
set the TMR2 interrupt flag bit of the PIR1 register. In addition, TMR2 can be turned on
by setting the TMR2ON of the T2CON register to 1 and turned off by clearing
TMR2ON bit to a 0.
converts continuous signals into discrete signals. The converter registers are used to
approximation method (Bates, 2008) and uses the system clock to drive the converter that
higher than 0.1%. One of the analogue inputs is selected at a time for conversion, and the
converter output is stored in an ADC result register. The maximum voltage level to be
converted (reference voltage) can be set externally, or the internal supply voltage (+5v)
can be used. The voltage reference is needed by the Analog to Digital Converter
which must be supplied from a constant voltage circuit, usually based on a zener diode.
By setting this bit to 0 means we choose the PIC16F690 input voltage as the voltage
reference. The 10-bit ADC result is presented in both ADRESH and ADRESL register as
follow:
By setting the ADFM bit to logical 1 we use the right justified result. This mean the
higher 2 bits value will be placed in the ADRESH register and the lower 8 bits value are
in the ADRESL register. Powering the ADC circuit is simply turning on the ADON bit
by setting it to logical 1 and to instruct the PIC microcontroller to start the conversion
we just turn on the GO/DONE bit (logical 1) and wait until this bit turn off when the
In order for ADC circuit inside the PIC16F690 microcontroller to work, it needs to be
supplied with a clock for doing the conversion. The ADCON1 register is used to select
the clock sources. To use the internal clock (FRC) of 8 MHz, the ADC clock selection
Table 3.3: Registers associated with the PIC16F690 analog to digital converter
execute the program code. The PIC16F690 has an in-built oscillator circuit that can be
operated in four different modes. These are the LP, XT, HS, RC modes. In LP, XT and
microcontroller. This can be a crystal based oscillator, or simple logic gates can be used
to design an oscillator circuit. In crystal operation, the crystal is connected across the
OSC1 and OSC2 pins, with a capacitor (15-22 pF) to ground from each pin, and an
internal amplifier completing the circuit. The values of C1 and C2 are selected based on
the load capacitance as suggested by the crystal manufacturer. Ideally, the capacitance is
chosen so that it oscillates at the highest temperature and lowest V DD that the circuit is
expected to perform under. Besides loading the crystal for proper frequency response,
28
these capacitors can have the effect of lowering the loop gain if their value is increased.
The PIC16F690 oscillator module has a wide variety of clock sources and selection
features that allow it to be used in wide range of applications. Increasing the oscillator
frequency shortens the length of machine cycles hence the time needed for executing the
instructions. The clock sources can be configured from external oscillators, quartz crystal
clock source can be configured from one of the two internal oscillators, with a choice of
speeds selectable via software. The clock source mode is configured by programming the
fosc<2:0> bits in the Configuration word register (CONFIG). The internal clock can be
generated from two internal oscillators namely the HFINTOSC (calibrated high-
3.2.8 Interrupts
suspend the current operation and execute an interrupt service routine (ISR). The ISR
thus has a higher priority than the background process. An interrupt can either occur
(i.e. not linked to the program timing) which interrupt the microcontroller and request
service. The interrupt signal can be received at any time during the execution of another
process. The code that is executed as a result of the interrupt is known as the interrupt
service routine. On completion of the ISR execution, the process that was interrupted is
resumed as though nothing had happened. The information being processed at the time of
the interrupt needs to be stored temporarily for recalling later. As part of the ISR
29
execution, the program counter is saved automatically on the stack, as when a subroutine
is called, so that the program can return to the execution point after the ISR has been
executed.
Synchronous interrupts on the other hand are usually timer generated interrupts, such as
the timer overflow generating an interrupt. In the PIC16F690, all interrupts have to be
serviced through the interrupt service routine that is located at address 0004h of the
program memory. In order to differentiate between these sources, the ISR needs to check
the relevant control flags to determine which interrupt source is active and then branch to
the required routine. Interrupts are enabled and disabled by the INTCON register. Each
interrupt source has two bits to control it, whereby one enables interrupts while the other
detects when an interrupt has occurred. The GIE bit of the INTCON register shown in
table 3.3 is used to disable all sources of interrupts. As the number of peripheral devices
such as serial ports and timers increases, the number of potential interrupt sources also
A watchdog timer (WDT) is an internal independent timer that automatically forces the
PIC to restart after a selectable period. The PIC16F690 microcontroller has one watchdog
timer which is refreshed by the user program, with a reset occurring if the program code
fails to refresh the watchdog. When a user intends to detect serious problems in programs
such as the program code falling into an endless loop, the watchdog timer is used. It is a
safety feature that prevents runaway software and stops the microcontroller from
executing irrelevant and unwanted code. Once a watchdog timeout occurs, it disrupts the
normal operation of the user program hence it should be disabled by selecting the
30
the configuration word in the source code. On the contrary, if the watchdog is to be
enabled, the WDT must be regularly reset within the program loop using the CLRWDT
The essential components of the microchip toolset are the MPLAB IDE and a hardware
programmer. Initially, PIC chips had to be removed from the circuit in order to be
programmed in a separate module and then be replaced in the target application board.
chip to be programmed without being removed from the working circuit. This provides
ease in program code debugging and also avoids possible mechanical damage to the chip
such as broken pins and also electrostatic charge related chip damage. To facilitate In-
Circuit serial programming and Debugging (ICD), the board is usually designed with a
six-pin connector, which connects the programming pins on the chip to the
programmer/debugger module that is in turn connected to the universal serial bus (USB)
Once the hardware has been connected, the appropriate programmer/debugger is selected
from the programmer menu upon which the programme is downloaded subject to
confirmation of the connection. Figure 3.5 below shows the common connections to
programmer/debugger modules. The PICkit2 uses a single in-line (SIL) connector on the
31
target board whereby program is downloaded into the target chip via ICSPDAT/PGD and
synchronized by ICSPCLK/PGC.
APPLICATION
BOARD
HOST PROGRAMMER/
PC DEBUGGER PIC
+ MODULE MCU
MPLAB
Data ICSPDAT/PGD
Clock ICSPCLK/PGC
Program VPP/!MCLR
USB
+5V VDD
0V VSS
In cases where the target board does not need too much current, it can be powered from
the host computer via the universal serial bus (USB) programming module (VSS and
VDD). PIC16F690-based low-pin count (LPC) demo board can be programmed without
an external supply. The target board reset can be controlled from MPLAB (!MCLR) and
In order to develop a control algorithm for the microcontroller system, the MPLAB
microcontroller interface circuitry are used. The host computer contains the MPLAB IDE
and PICkit2 software versions with the programmer being interfaced to this computer
includes the low pin count board incorporating the PIC16F690 MCU and some minimal
Figure 3.6: A picture of the PICkit2 Starter Kit including LPC board (Bates,
2011)
The programmer can be connected to the USB port of the host PC running MPLAB, with
a six-pin in-line output plugged into a six-pin male connector on the target board. The
board has four light-emitting diodes (LEDs) that are used to output/display the
programmed output sequences, a push button connected to !MCLR and a small pot
providing an analog test input. The LPC board can be powered from the USB port via
pins 2 and 3. When programming the microcontroller, +12 V is applied to pin 1, but after
programming is complete, it reverts to the reset (!MCLR) input function. When under the
control of the host PC, the on-board reset button is overridden by a command/button in
the MPLAB toolbar. On detaching from the programmer, the push button can be
configured as a reset input or as a digital input. The Pins 4 and 5 are the ICSPDAT/PGD
and the ICSPCLK/PGC lines which are used to carry the programme code to be burned in
33
the PIC memory and the system clock respectively. The functionality of each of the six-
that includes a MPASM macro assembler, MPLAB SIM software simulator with
symbolic debugger, color-coded editor, and project manager with high-level language
computer to develop applications for PIC MCU families and the dsPIC digital signal
iii) Debug the executable logic by watching program flow with the built-in simulator
In order to create code that is executable by the target microcontroller, source files need
to be put into a project. This enables the code to be built into executable code using the
selected language tools (assemblers, compilers or linkers). In MPLAB IDE, the project
A regulated dc power supply is an electrical circuit that is designed to convert the 230V
AC mains electricity to a suitable low voltage supply for electronic circuits and other
devices. A regulated power supply can by broken down into a series of blocks, each of
12 V AC 12 V DC 5 V DC
Figure 3.7: A schematic showing the block diagram of a regulated power supply
35
3.5.1 Transformer
A transformer is a device that transforms electric energy from a certain voltage and
current levels to another voltage and current levels keeping the frequency of the supply
the secondary which is proportional to the number of turns in the secondary and the flux
linking the secondary. The ratio of the number of turns in the primary coil to the number
of turns in the secondary coil determines the ratio of the voltages in the two coils. A step-
down transformer has a large number of turns on its primary coil which is connected to
the high voltage mains supply, and a small number of turns on its secondary coil to give a
(3.1)
3.5.2 Rectification
types namely; half wave and full wave rectifiers. Both use diodes to convert AC into DC
with the diode only allowing current to flow through it in one direction. In this case the
diode is said to be forward biased and the only effect on the signal is that there will be a
voltage drop of around 0.7 V. In the opposite direction the diode is said to be reverse
biased and no current will flow through it. A bridge rectifier can be made using four
individual diodes, but it is also available in special packages containing the required four
diodes. It is referred to as a full-wave rectifier because it uses the entire AC wave (both
36
positive and negative sections) as depicted by Figure 3.8. The four diodes are arranged so
that both positive and negative parts of the AC waveform are converted to DC.
Approximately, 1.4 V is used up in the bridge rectifier because each diode uses 0.7 V
when conducting and there are always two diodes conducting. Bridge rectifiers are rated
by the maximum current they can pass and the maximum reverse voltage they can
withstand.
across the DC supply to act as a reservoir such that it supplies current to the output when
the varying DC voltage from the rectifier is falling. An unsmoothed varying DC (dotted
Smoothing significantly increases the average DC voltage to almost the peak value (1.4
multiplied by the root mean square value). It is not perfect because the capacitor voltage
falls a little as it discharges, giving a small ripple voltage. A large capacitor gives fewer
ripples and must be doubled when smoothing half-wave DC. To obtain the value of the
where: C = smoothing capacitance in Farads (F), IO = output current from the supply in
amps (A), VS = supply voltage in volts (V) and F= frequency of the AC supply in Hz.
3.5.4 Regulation
While a number of circuits can tolerate a smoothed power supply, others must have a
completely regular supply with no ripple voltage. The LM78XX series of three terminal
regulators has several fixed output voltages making them useful in a wide range of
applications. Although they are primarily designed as fixed voltage regulators, these
devices can be used with external components to obtain adjustable voltages and currents.
The LM78XX is available in an aluminum TO-3 package which will allow over 1.0A
38
load current if adequate heat sinking is provided. Current limiting is also included to limit
changeover switches. When a supply voltage is connected to the coil, current flows and a
magnetic field will be produced that attracts the armature to close one set of contacts
and/or open another set which in turn switch a load on/off. On de-energizing the relay,
the magnetic flux in the coil collapses and produces a fairly high voltage in the opposite
direction. This resulting voltage can damage the driver transistor and thus a reverse-
biased diode is connected across the coil to short-out the spike when it occurs.
Based on the fact that the PIC microcontroller pins can only provide up to 25 mA in
transistor is used for adjustment purposes with its collector circuit connecting to the relay
coil. When +5 V is delivered to transistor base, transistor activates the relay, which then
using its contacts, connects to the load in the circuit. The purpose of the resistor at the
transistor base is to keep a 0 V on base to prevent the relay from activating by mistake.
Relay coils normally operate at +12 V or +24 V, but a 5 V relay can be connected
A liquid crystal display (LCD) is a low cost module that can be interfaced to a
segments are easy to use they are bulky and quite limited in the set of characters that they
can display. When many letters and digits are to be displayed, seven segment displays
become inadequate. The LCDs are preferred to seven segments and other multi-segment
LEDs because:
ii) Have small foot print and the ability to display both characters and graphics in
iii) They possess an internal refreshing controller. This relieves the CPU from
The most common type of LCDs allow light to pass through when activated. A segment
is activated when a low frequency bipolar signal in the range of 30 to 1000Hz is applied
to it. The polarity of this voltage must alternate or the Liquid Crystal Display will not be
able to change very quickly. On applying a voltage across the segment, an electrostatic
field which aligns the crystals in the liquid is set up. This alignment allows light to pass
through the segment. If no voltage is applied across a segment the crystals appear to be
opaque because they are randomly aligned. Random alignment is assured by the AC
Most character liquid crystal displays manufactured today are compatible with the
Hitachi 44780 controller, making a wide range of microcontrollers have libraries that
40
make displaying messages as easy as a single line of code. A 2x16 LCD implies that it
can display sixteen characters per line and there are two such lines. In this LCD, each
character is displayed in a 5x8 pixel matrix with the LCD having two registers; command
and data registers. Most liquid crystal display modules available in the market are
compatible with the Hitachi 44780 controller. These LCDs have 14- or 16-pin connection
shown on Figure 3.10. This connection may be a single or double row header at one edge
predefined task such as initializing it, clearing its screen, setting the cursor position and
controlling the display. On the other hand, data register stores the data to be displayed on
the LCD. This data is the American standard code for information interchange (ASCII)
value of the character to be displayed. The LCD requires 3 control lines from the
microcontroller namely:
The Enable line allows access to the display through R/W and RS lines. When this line is
low, the LCD is disabled and ignores signals from R/W and RS. The LCD checks the
state of the two control lines and responds accordingly in the event the E line is high. The
R/W line on the other hand determines the direction of data between the LCD and the
microcontroller. When this line is low, data is written to the LCD and when high data is
read from the LCD. The RS is used to interpret the type of data on data lines. For instance
when it is low, an instruction is being written to the LCD but when high a character is
A passive infrared sensor is an electronic device which measures infrared light radiation
from objects within its field of view. On the electromagnetic spectrum, infrared radiation
exists in the wavelength region from 0.75 m to 1000 m that lies between visible light
and microwaves. The sensor is termed as passive because it is a detector rather than
emitter of radiation. It simply accepts the incoming infrared radiation emitted by a body
within its field of view. The PIR sensor is preferable for human detection because it is
sensitive to the changes of infrared radiation induced by the human motion and robust to
environmental changes (Kakuta et al., 2001). When a person walks into the field of view
of the detector a sharp increase in infrared energy is registered. All objects with an
absolute temperature of over 0 K emit infrared radiation whereby the infrared radiant
In a PIR based motion detector sometimes also referred to as passive infrared detector, is
mounted on a printed circuit board which also contains the circuitry that interprets the
signals from the pyro-electric sensor chip. A typical PIR sensor gives a logic-0 when
there is no motion or to the background IR level, and gives a logic-1 on detecting a hot
body motion. Infrared energy can reach the pyro-electric sensor through the window
because the plastic used is transparent to infrared radiation. This plastic sheet prevents the
intrusion of dust or insects which could obscure the sensor`s field of view or in the case
of insects trigger false alarms. A person entering the monitored area is detected when the
infrared energy emitted from the intruder`s body is focused by a Fresnel lens and
overlaps a section of the chip which had previously been looking at some much cooler
part of the protected area. That portion of the chip is now warmer than when the intruder
was not there (Sakurai et al., 2011). The lens of the sensor divides coverage into zones
whereby occupancy is assumed when a change in infrared energy is detected in one of the
zones. PIR sensors use a dual-element pyroelectric sensing device to detect occupancy.
As the intruder moves, so does the hot spot on the surface of the chip. This moving hot
spot causes the electronics connected to the chip to output logic high on the output pin of
the detector. A classical PID sensor is sensitive to the IR radiation hence its response is
affected by factors like the ambient temperature, moving object`s speed, direction of
motion, distance to the sensor, humidity, among others. Since PID gives a logic one or a
logic zero as its output, the amplitude of the response is not affected but the duration and
The 555 Timer is a monolithic circuit that can produce accurate and highly stable time
In the monostable mode, it is used to produce accurate time delays ranging from
microseconds to hours. Other applications for the timer in this mode include; missing
pulse detection, frequency dividers, pulse width modulation and bounce free switches. In
the astable or free running mode, the 555 timer is a wave-generating circuit in which
neither of the output levels is stable. The output in this case keeps on switching between
the two unstable states and is a periodic rectangular waveform. The time for which the
output remains in one particular state is usually determined by the two resistors and a
capacitor externally connected to the 555 timer. The 555 can source or sink 200 mA of
output current and is capable of driving a wide range of output devices. The applications
of the 555 timer in the astable mode include: LED and lamp flashers, security alarms
pulse and tone generation, pulse position modulation and also in logical clocks.
As shown on the circuit diagram (Appendix A), pin 5 is bypassed to ground using a
0.01F capacitor. The power supply is connected to common of pin 4 and 8 while pin 1 is
grounded. Initially if the output is high, capacitor C starts charging towards V CC through
RA and RB. Once the voltage across the capacitor becomes equal to VCC shown on
Figure 3.11, the upper comparator triggers the flip-flop and the output becomes low. The
capacitor now starts discharging through RB and transistor Q1. When the voltage across
44
the capacitor becomes VCC, the lower comparators output triggers the flip-flop and
Figure 3.11: Schematic illustrating output voltage waveforms for the Astable
multivibrator (Thomann and Younger 2003).
45
CHAPTER FOUR
RESEARCH METHODOLOGY
4.1 Introduction
This chapter describes the methodologies used for the design of the hardware and
software parts. It begins by giving an overview of the automatic room light controller and
then describes how the specific hardware and the software for the system were designed.
sensors that produced digital output were employed. In this research, two types of sensors
namely; PIR motion sensors and infrared sensors were used. These sensors were
connected directly to the microcontroller pins and acted as the inputs to the system. For
notification purposes, a 2x16 LCD was employed to indicate room occupancy. The 2x16
diagram for the system is shown in Figure 4.1. It is made up of a person counter circuitry,
PIC16F690 microcontroller, PIR motion sensor, an LCD and a relay circuitry. The person
counter comprises a pair of infrared transmitter and receiver which involve a wireless
link. The two sets are directly aligned such that the light pulse from the each transmitter
falls on the receiver. The receiver outputs are interfaced to PORTB of the PIC16F690
which under the control programme stored in its memory displays the room occupancy
on the LCD and makes decision on when to switch on/off the lights through a relay. The
motion sensor works together with the transmitter-receiver pairs and acts as the inputs to
the system. The next section outlines on how the hardware parts of the system were
46
designed. This includes PIC16F690 program code, infrared transmitter, receiver, PIR
microcontroller, relay, Liquid Crystal Display (LCD) and light bulb. For schematic
editing, Labcenter ISIS which is a component of Proteus VSM was used (Bates, 2008).
A relay is an electromagnetic switch that opens and closes under the control of another
electrical circuit. Since the relay can control an output circuit of higher voltage than the
microcontroller pin connected to the relay circuit goes high i.e. logic-1, current flows
through the relay coil and the resulting magnetic field attracts an armature that is
47
connection with a fixed contact. On the contrary, when the microcontroller pin goes to
logic-0, the current to the coil is switched off and the armature is returned by a force
Since in this case the coil is energized with DC, IN4001 diode was connected across the
coil to dissipate the energy from the collapsing magnetic field at deactivation, which
would otherwise generate a spike of voltage and may cause damage to circuit
components. The relay switch connections are usually labeled COM, NC, NO whereby:
ii. NC- Normally Closed, COM is connected to this when the relay coil is off
iii. NO- Normally Open , COM is connected to this when the relay coil is on
Unlike the 555 timer IC that can supply a relatively large current of up to 200 mA that is
sufficient for many 5 V relay coils, PIC microcontroller can only provide 25 mA on its
pins hence the need of a transistor to switch larger currents. The BC547 NPN transistor,
Figure 4.2 was wired as a switch and carries the current required for the operation of the
relay. When the pin RB5 of the PIC microcontroller goes high, the transistor BC547 turns
on and current flows through the relay. The diode connected across the relay contacts is
used to protect the transistor and microcontroller from back electromotive force
generated in the relay coil. The IN4001 also known as freewheeling diode was used as it
is a fast switching diode having a peak forward current of 450 mA (Horowitz, 1989). The
switched circuit in this design was to be ON when the relay coil is energized hence the
COM was connected to NO contact otherwise the COM should be connected to NC.
48
The 2x16 character LCD has two rows with 16 characters each. One popular 2x16 LCD
is the 1602ZFA which is pin compatible with the Hitachi HD44780 and is equipped with
a backlight function. The LCD pins and functions are given in the Table 4. It has 16 pins
with register select, read/write and enable control lines. In addition it has a display
contrast voltage line. The 4-bit interface was used because it saves on port pins which
could otherwise be used for other additional functions. Pins 15 and 16 were employed to
enable visibility in the dark and for characters to be viewed with ease from a distance.
The third pin (Vo) is connected to a variable resistor to control the LCD contrast, while
the R/W (Read/Write) pin is connected to ground indicating that the LCD is receiving
data only. The display receives ASCII codes for each character at DB4 to DB7 which was
connected directly to the lower PORTC pins (RC3 to RC0) of the PIC16F690. The data
are presented to the display inputs by the microcontroller and latched in by pulsing the E
49
(Enable) input. To initiate the LCD, RS must be set to logic 0 (low) indicating that we are
In the circuit given in Figure 4.3, the data are being sent in 4-bit mode. The 8-bit code for
each ASCII character is sent in two halves; high nibble first, low nibble second. Although
this makes the software only slightly more complex, it saves on I/O pins and allows the
LCD to be driven using only six lines of PORTC as shown in Figure 4.3.
50
4 X IN4001
+12V
TR1 U3
BRIDGE 7812
1 3 R18
VI VO 10k
LCD1
GND
LM016L
C2 D5
0.1uF
2
U2
7805
LED
TRAN-2P2S 1 3
C1 VI VO
VDD
VSS
VEE
RW
4.75k
RS
D0
D1
D2
D3
D4
D5
D6
D7
GND
2200u
E
R19
RV1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
C3
2
10k
0.1uF D6
DIODE-LED
C7 X1 CRYSTAL
GND
U1
33pF
19 16
RA0/AN0/C1IN+/ICSPDAT/ULPWU RC0/AN4/C2IN+
18 15
RA1/AN1/C12IN0-/VREF/ICSPCLK RC1/AN5/C12IN1-
17 14
RA2/AN2/T0CKI/INT/C1OUT RC2/AN6/C12IN2-/P1D
C8 4
RA3/MCLR/VPP RC3/AN7/C12IN3-/P1C
7
3 6
RA4/AN3/T1G/OSC2/CLKOUT RC4/C2OUT/P1B
2 5
RA5/T1CKI/OSC1/CLKIN RC5/CCP1/P1A
33pF 8
RC6/AN8/SS
13 9
RB4/AN10/SDI/SDA RC7/AN9/SDO
12
RB5/AN11/RX/DT
11
RB6/SCK/SCL
10
RB7/TX/CK
PIC16F690
PROGRAM=C:\Users\janja\Desktop\shads\shads\MyProject.HEX
The Passive Infrared Sensor (PIR) works by the pyroelectricity principle whereby certain
crystalline materials have the property to generate a surface electric charge when exposed
to thermal infrared radiation. Human body radiates heat in the form of infrared radiation
creates a sudden change in the surrounding that is sensed by the pyroelectric sensor. The
familiar with the surrounding environment and also function properly. Most of the
ii) Output is the sensors output and in this case was connected to a microcontroller
pin to serve the purpose of an input. The sensors output pin goes high when
In this study the DH-G03 model PIR sensor was employed. It has coverage of 180
degrees, 2 to 4 meters installation height and detection distance of 82 meters. The output
of the PIR sensor module is monitored through the RB4 of the microcontroller. When
motion is sensed, this output is high at about 3.8 V as depicted by the 3.8 V regulator IC
on board in the PIR detector module used. This voltage was used as a valid logic high for
the microcontroller. However, in order to get a full swing of the logic voltages, the sensor
output was employed to drive the base of BC547 NPN transistor. The PIC16F690
microcontroller here monitors the voltage at the collector of the transistor. During normal
condition, the transistor is cut off and the collector output is at logic high i.e. +5 V. On
sensing motion the high output from the sensor saturates the transistor and the voltage at
In the astable mode, the 555 timer gives out a continuous stream of rectangular pulses
having a specified frequency. The resistor R1 was connected between VCC and the
discharge pin (pin 7). Another resistor (R2) connected between the discharge pin (pin 7),
the trigger (pin 2) and threshold (pin 6) that share a common node. Hence the capacitor is
charged through R1 and R2, and discharged only through R2, since pin 7 has low
impedance to ground during output low intervals of the cycle, therefore discharging the
52
capacitor. In the astable mode, the frequency of the pulse stream depends on the values
of R1, R2 and C. This was operated in astable multi-vibrator mode. So as to generate the
square wave of frequency 38 KHz since the infrared receiver (TSOP 1738) activates only
at 38 KHz, the 555 timer IC was wired in the astable mode to generate pulses of 38 kHz.
constant resistor of 4.7 k and adjusted the potentiometer to a value of 6.7 k. The
output of IC555 is obtained at pin 3 whereby it is given to the transistor pair that acts as a
The Infrared Receiver is used to receive infrared signals from an infrared transmitter and
also used for remote control detection. On the Infrared Receiver which is used to get the
infrared light emitted by the Infrared Emitter lies an IR detector. The IR detector has a
demodulator inside that looks for modulated IR at 38 kHz. The Infrared Receiver can
receive signals well within 10 meters. If more than 10 meters, the receiver may not get
the signals. The TSOP1738 which is a member of infrared remote control receiver series
was used in this study. This module helps us to reduce interference from other natural IR
signals from the environment. The IR sensor module consists of a pin diode and a
preamplifier which are embedded into a single package. Its output is active low in that it
gives +5 V in the off state. When IR waves from a source with a centre frequency of 38
kHz is incident on it, its output goes low. The pin configuration of the module (Figure
4.5) is namely:
i) Pin 1- Ground
The 4.7 F capacitor (C3) and 100 (R7) were used to suppress power supply
disturbances while resistor R8 was used to avoid the output voltage not to be continuously
held at a voltage lower than 3.3 V by the PIC16F690 microcontroller circuit (Vishay,
2001). The TSOP module has an inbuilt control circuit for amplifying the coded pulses
from an IR transmitter. A signal is generated when PIN photodiode receives the signals.
This input signal is received by an automatic gain control (AGC) circuit. For a range of
inputs, the output is fed back to AGC in order to adjust the gain to a suitable level. The
54
signal from AGC is passed to a band pass filter to filter undesired frequencies. After this,
the signal goes to a demodulator and this demodulated output drives an NPN transistor.
+5V
TSOP1738 R7
100
2 U1
19 16
C3 18
RA0/AN0/C1IN+/ICSPDAT/ULPWU RC0/AN4/C2IN+
15
4.7uF R8 17
RA1/AN1/C12IN0-/VREF/ICSPCLK RC1/AN5/C12IN1-
14
10k RA2/AN2/T0CKI/INT/C1OUT RC2/AN6/C12IN2-/P1D
4 7
3 RA3/MCLR/VPP RC3/AN7/C12IN3-/P1C
3 6
RA4/AN3/T1G/OSC2/CLKOUT RC4/C2OUT/P1B
2 5
RA5/T1CKI/OSC1/CLKIN RC5/CCP1/P1A
8
RC6/AN8/SS
13 9
RB4/AN10/SDI/SDA RC7/AN9/SDO
12
1 RB5/AN11/RX/DT
11
RB6/SCK/SCL
10
RB7/TX/CK
PIC16F690
PROGRAM=C:\Users\janja\Desktop\shads\shads\MyProject.HEX
centre frequency.
The program code was written in C using the MPLAB IDE platform. The code enables
the output signals to be received, processed and a message sent to the LCD output. In the
proposed circuit the lines RB6 and RB7 pins of PORTB were configured to act as inputs
In order to write the code to control the microcontroller operations, the following
algorithm which is illustrated in Figure 4.6 in form of a flow chart was used.
i) Start: In this step the microcontroller is reset and the first instruction to be
ii) Initialize the LCD: The LCD display is cleared the cursor moves to the start of
first line
iii) The LCD displays the Message ROOM LIGHT CONTROLLER which is the
iv) Display the Message "BY SHADRACK" who in this case is the designer
vi) Check if receiver one is cut If not then go to step no. viii, if cut it is interpreted as
viii) If yes then check if receiver one is cut. If yes then Decrement the person
ix) Go to step vi
56
Normally, the infrared transmitter sends a pulse to the receiver which is connected to the
microcontroller. In this project two sets of transmitter to receiver were used for the bi-
directional counting purposes. If the pulse on receiver one is cut then followed by that of
receiver two, this is registered as an inward count and lights are activated implying
someone has entered the room under surveillance. The number of persons in the room is
then displayed on the LCD screen. On the contrary, if the pulse on receiver two is cut
then followed by that of receiver one, this is registered as outward motion and the count
on the LCD is decremented by one. If the status of the counter is zero implying no
57
occupancy in the room, the relay automatically cuts off the lights and the process loops
The program code was written as text file and converted to a machine code using the
editor, project manager and design desktop for application development of embedded
designs using Microchip PICmicro and dsPIC microcontrollers. Once the code is
compiled, a hex file is obtained which is burned into the program memory of the PIC
chip. This process involves the steps that are described below.
i) The PIC16F690 is first picked from the device list and the HI-TECH universal
compiler.
Figure 4.7: Screenshot of MPLAB software showing selection of the HI-TECH ANSI
C compiler
58
ii) A new project file is then created and a project directory selected where the
iii) A summary of the project parameters is then outlined on the next window.
written and saved with a .c file extension. A new window with .mcw file
extension opens and the c file created earlier on is added to the source file on this
window.
vi) Once this is complete the project is built by selecting Build option from the
project menu or by pressing F10. If there are no errors in the code a message
Build Successful is displayed. Here the compiler generates a hex file which is
The programme code was first tested in simulation mode before downloading it to the
target board. Once edited and assembled in MPLAB, the MPSIM routine can be invoked
and the program run with the SFRs and stopwatch displayed. Owing to the fact that an
60
analogue input stimulus is not available in MPSIM, Interactive simulation using Proteus
VSM (Figure B.1) was used since it is simpler and more convenient. The program was
written, assembled and attached to the MCU in the schematic, and simulation run with
the source code. The simulation test allowed the basic program syntax and logic to be
checked before program downloading. Any syntax errors is detected by the assembler,
with a line number indicated and the error type indicated in the output window. On
confirmation of successful build on the project, the resulting hex file is downloaded into
CHAPTER FIVE
5.1 Introduction
This chapter discusses the results obtained on testing the designed system.
In order to count the number of persons accessing the controlled room, a person counter
circuit comprising a pair of infrared transmitter and receiver was used. They were
arranged in a manner such that for one to enter the controlled room both sets of sensors
must be cut subsequently. If the first pair of sensors is traversed followed by the second
pair, the counter is incremented indicating that someone has entered the room under
surveillance and the count is shown on the liquid crystal display. On the contrary, when
second pair is traversed followed by first pair, the status of the counter is decremented by
one and this is also shown on the LCD. The lights only go ON when the person in the
room happens to be in the vicinity of the motion sensor. If the person moves away from
the sensors field of view, the lights remain on for a minute then go off. The system is
designed in such a way that for the lights to be ON, the counter state should be equal or
i) Simulation using Proteus virtual system modeling (VSM) whereby the source
code file obtained from the development environment was added to the
followed by switch 2 the status of the counter incremented and this count was
Figure 5.1: System response schematic of the designed system on circuit simulation
ii) The second method involved loading the source code file obtained from the
entry into the controlled room. The number of people in the room was displayed
On both setups when there was no person in the room the liquid crystal display
Figure 5.2: System response schematic of the designed system on using actual
sensors
modulated at a particular frequency and ignores any other IR signals. The components
were wired as shown in Figure 4.4 whereby the output voltage alternates between V CC
and 0 volts on a continuous basis. By selecting values for R 1, R2 and C, the period/
frequency and the duty cycle were determined using equation 4.1. In this case the period
64
is the time it takes for the on/off cycle to repeat itself while the duty cycle is the
(5.1)
Whereby the capacitor charging time (TC) is given by equation 5.2 below
According to the relation 5.1, a duty cycle of 50 % which corresponds to a square wave
connected to VCC. A constant square wave signal, Figure 5.3 was generated using the
IC555 centered at 38 kHz and used to drive a led connected to the BC337 transistor. The
sharp spikes seen on the figure was a result of the high current drawn by the relay
Figure 5.3: Photograph of the waveforms produced by a 555 timer connected in the
astable mode
65
Once the signal bounces off the obstacles, the receiver detects it and changes its output.
An increase on the value of the capacitor increased the cycle time hence reducing the
frequency. As shown on Table 5.1 below, increasing R2 increased time high, time low
and decreased the duty cycle down to a minimum of 50 %. On the contrary, on increasing
Table 5.1: Table illustrating calculations of a 555 timer connected in astable mode
The PIR motion sensor used here has a single output that goes HIGH when motion is
detected. Using Figure 5.4, the motion sensor was connected to the rest of the circuitry
and after powering an initial stabilization time of about 10 to 60 seconds was allowed
during which it familiarized with the surrounding environment (Matta, 2010). The
sensors Fresnel lens divides the coverage area into zones. If someone passes by, he first
66
intercepts one half of the PIR sensor which causes a positive differential change between
On leaving the sensing area, the reverse happens, whereby the sensor generates a
negative differential change. These change pulses are what is detected. The output of the
sensor is monitored through pin RB4 of PIC16F690 as shown in Figure 5.4 where the
output is high at about 3.8 V (the sensor used has a 3.8V regulator IC on board) when the
motion is sensed. This voltage was used to drive the base of BC547 NPN transistor so
that at the collector we have a full swing of logic voltages. The microcontroller in this
case monitored the voltage at the collector of the transistor. During the normal condition
the transistor is cut-off and the collector output is at logic-1 (+5 V). When motion is
sensed, the high output from the sensor module saturates the transistor and the voltage at
A power supply is a system that converts electrical power from one form to another;
commonly from AC utility power to direct current (DC) power. To ascertain the stability
of the designed power supply, resistors were connected in a cascading manner across the
power supply outputs to act as the load. The results obtained were recorded as shown in
Table 5.2.
Percentage of regulation is the commonly used figure of merit for a power supply. It
gives an indication of how much the output voltage varies over a range of load resistance
68
values. The percentage of regulation aids in determining of the type of load regulation
needed. It compares the change in output voltage at the two loading extremes to the
Using Table 5.1, the power supply produces 11.9 V when the load current is zero and
also produces 11.9 V on maximum load current. This is in line with the ideal situation
whereby the output voltage should not change over the full range of operation. As
depicted by Figure 5.5 above, the designed power supply produces 11.9 V and 4.99 V
simultaneously at no load, at full load and at all points in between. In this design the
percent of regulation is zero % which is the ideal situation hence the output is constant
CHAPTER SIX
6.1 Conclusions
required for energy waste control has been designed and implemented. An entry/exit
sensing unit that uses two sets of infrared transmitter and receiver for determining the
number of people accessing the controlled room has also been created. The Microchip
MPLAB Integrated Development Environment has been used to write, develop and
debug codes for the PIC microcontroller with Proteus ISIS being used for simulating the
designed circuits. The system integrates infrared transmitter and receiver, passive infrared
detector, PIC16F690 microcontroller, relay control circuit and an LCD output module.
The designed system managed to acquire three inputs from sensors and based on the code
stored in the microcontroller`s program memory, displayed the count on the LCD. If the
pulse from the first set of transmitter-receiver is cut then followed by the second pair, this
was processed by the microcontroller and registered on the LCD as an inward count. The
PIC16F690 microcontroller waits for 500 milliseconds upon which the controlled lights
go ON. On the contrary, when second pair of infrared transmitter - receiver is cut first
followed by pair one, an outward count is registered. The lights remains in the OFF state
if the status of the counter is zero else they remain on. With the counter being equal or
greater than one, the status of the PIR motion detector output pin is monitored. If
someone moves away from the field of view of the sensor, the output of the detector is at
microcontroller waits for 1000 milliseconds before the lights go off. The time delay
70
transitions for the designed system can also be modified in the program code for it to suit
different user preferences. With achievement of all the objectives of this research, we can
conclude that the system is reliable, compact and portable hence can be employed in light
Though the designed system was able to reduce energy wastage, a few developments can
the system to improve on the system robustness. This can be achieved by using
detectors with a wider field of view and longer detection distance. This would be
suitable for multiple door access and higher detection rates of occupants to
In daytime natural light may be sufficient if the room has a suitable architectural
design and less artificial light would be needed. In such a situation, photo
detectors can be interfaced to the system to provide the user with override option
and also allow one to select the preferred light intensity for a particular task.
The designed system can also be configured in such a way that the duration of
time for which the lights remain on/off within a 24 hour period is recorded. This
REFERENCES
Agogino L., Alice M. and Wen H. (2007). Personalized dynamic design of networked
lights for energy efficiency in open plan offices. Energy and Buildings 43 (8): 22-34.
Atkinson B. (1995). Energy efficient Lighting technologies and their application in the
press.
Bai Y. and Ku Y. (2008). Automatic Room Light Intensity Detection and Control using a
London. pp 331.
Changhong S., Wu Y., Zhang X. and Yang W. (2010). Design of new intelligent street
light control system. 8th IEEE International Conference on Robotics & Control Systems:
1423-1427, Xiamen.
Network. Master thesis, Graduate school of Natural and Applied Sciences, Sakarya.
Turkey
Dogan, I. (2006). Microcontroller Projects in C for the 8051: Newness. Oxford. pp 178.
Using Artificial Neural Networks. PhD thesis, Graduate School of Natural and Applied
Hengyu W., Minli T. and Guo H. (2010). Design of multi-functional street light control
Robotics & Control Systems, Wuhan, China: IEEE Conference Publications: 134-137.
Horowitz P. and Hill W. (1989). The Art of Electronics. 2nd Edition, Cambridge
Repeater and its control Message frame format, Proceedings of the 2008 International
Publications: 1- 4.
Li D., Bai Y., Wang H. and Li H. (2011). Design of intelligent lighting control system,
IEEE International Conference on Robotics & Control Systems, 134- 137, Xi``an.
73
Lovine, J. (2000). PIC Microcontroller Project Book, 3rd Edition, McGraw Hill,
Lovine, J. (2011). PIC Projects for Non-Programmers, 1st Edition, Newness. ISBN-10:
1856176037
Matta S. and Mahmud S. (2010). An intelligent light control system for power saving,in
the proceedings of the 36th Annual Conference on IEEE Industrial Electronics Society,
Mohamed F., Mounir B. and Bedda M. (2008). Microcontroller based heart rate monitor.
Niu M. and Qin H. (2012). Design of LED street lamps intelligent control system based
Processing: 1- 4, Hangzou.
Ranjit S., Baljit S., Tuani I. and Ahamed F. (2010). Designing Switching System for AC
Washington.
74
Richard, B. (2002). Energy Management Systems and Digital direct control, 1st Edition,
RLW Analytics, Inc (1999). Non-Residential New construction baselines study for the
1- 11.
advanced lighting controls test bed, Journal of the Illuminating Engineering Society, 28:
130-141.
Sakurai A., Nakamura M., Nakamura J. (2011). Self-organizing map analysis of sensor
networks for human movement tracking Sensors and Actuators. 166: 141-148.
Shuhui L., Haskew T. and Ling X. (2010). Control of HVDC light system using
conventional and direct current vector control approaches. IEEE Transactions on Power
Thomann A. and Younger J. (2003). The Handbook of Energy Audits, 6th Edition
Tien-shang L. and Chun-lin, L. (2011). Proposals for dimming ballast control through
Wayne, C. and Steve, D. (2007). Energy Management Handbook, 6th Edition, Fairmount
Ying-bai B. and Chi-huang H. (2008). Remote power on/off control and current
measurement for Home Electric outlets based on a low power embedded board and
Electronics, 24: 1- 4.
76
APPENDICES
The schematics in figure was created using Labcenter ISIS which is a component of
Proteus VSM. Once the application has been installed and opened, an edit screen appears
Before starting to use the editor, an application folder with a suitable name, such as shadrack
which holds the design and program files is created. Open ISIS and save the design as:
78
shadrack.DSN. To start creating the schematic the P button at the top of the object selector
window figure B.1 is clicked and the Pick Device window shown below opens.
order. In cases where the component number is known, its number may be entered in the
keywords search box. With all components included in the device list, they can be
positioned and dropped on the circuit with a second click. Finally the components are
connected up and their positions adjusted for the neatest arrangement. Wiring is done by
clicking on the component connections and dropping the other end by clicking on the
destination pin. When finished and saved, the schematic can be printed or exported as a
bitmap shadrack.BMP file for the example above or a screen shot taken for insertion into
a document.
79
/* PHYSICS DEPARTMENT */
/* KENYATTA UNIVERSITY */
/* January 2014 */
/*-------------------------------------------------------------------------------------------------------*/
/* the code displays status of room occupancy in a controlled room. Based on the count
and status of the motion sensor output, the lights are switched on and off automatically
and the status of the room occupancy is shown on an LCD */
/*------------------------------------------------------------------------------------------------------*/
#include <pic.h>
#define RS RC5;
#define EN RC4;
#define D4 RC0;
#define D5 RC1;
#define D6 RC2;
#define D7 RC3;
char MSG5[7];
void InitTimer0(){
OPTION_REG = 0x88;
TMR0 = 7;
INTCON = 0xA0;
void Interrupt(){
if (T0IF_bit){
T0IF_bit = 0;
TMR0 = 7;
cnt++;
{cnt=0;cnt2++;}
if(LED >=1)
{flag = 1;}
81
else
{flag =0;}
void main(){
ANSELH = 0;
C2ON_bit = 0;
PORTB = 0x00;
TRISB = 0xC0;
PORTC = 0x00;
TRISC = 0x00;
OPTION_REG = 0x83;
TMR0 = 97;
INTCON = 0xA0;
82
Delay_ms(1000);
Delay_ms(1000);
InitTimer0();
if(button_3==1){
if(counter>=1)
{LED =1;cnt=0;}
else
{LED =0;}
83
IntToStr(counter,MSG5);
if(counter==1)
{Lcd_Out(2,3,MSG6);}
else
{Lcd_Out(2,3,MSG7);}
if(button_1)
{flip =1;}
if(button_2)
while(flip==1){
if(button_2)
delay_ms(500);flip = 0;}
while (flip2==1){
if(button_1)
if(counter==-1)
counter=0;
delay_ms(500);flip2 = 0;}
}
84
else if(button_3==0)
{IntToStr(counter,MSG5);
Lcd_Out(1,4,MSG5);
Lcd_Out(2,3,MSG6);
}
85