You are on page 1of 101

DESIGN OF AN INTELLIGENT ROOM LIGHT CONTROLLER

WITH BIDIRECTIONAL COUNTERS FOR ENERGY EFFICIENCY


APPLICATIONS

KIMONYI SHADRACK MUTHOKA (B.Ed. (Sc.))

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.

Kimonyi Shadrack Muthoka

Signature Date ..

We confirm that the candidate carried out the work reported in this thesis under our

supervision

Dr. Patrick Karimi


Department of Physics
Kenyatta University
P.O. Box 43844-00100
NAIROBI - KENYA

Signature .. Date

Prof. Elijah Mwangi

Electrical & Electronic Engineering Department


University of Nairobi
P.O. Box 30197-00100
NAIROBI - KENYA

Signature .. Date
iii

DEDICATION

This thesis is dedicated to my parents.


iv

ACKNOWLEDGEMENTS

It gives me immense pleasure to express my deep sense of gratitude to my supervisors

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

given to my postgraduate colleagues: Peter Kinyua, Isaac Kwembur, Naftali Kimani,

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

support. I wish to acknowledge the support accorded to me by Jonathan Kinyua,

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

TABLE OF CONTENTS ................................................................................................... v

LIST OF TABLES ..........................................................................................................viii

LIST OF FIGURES .......................................................................................................... ix

ABBREVIATIONS AND ACRONYMS ......................................................................... xi

ABSTRACT ....................................................................................................................xiii

CHAPTER ONE .............................................................................................................. 1

INTRODUCTION ............................................................................................................ 1

1.1 Background to the study ..................................................................................... 1


1.2 Statement of the research problem ...................................................................... 3
1.3 Objectives ........................................................................................................... 3
1.3.1 Main objective ........................................... Error! Bookmark not defined.
1.3.2 Specific objectives ....................................................................................... 3
1.4 Rationale for the research ................................................................................... 4

CHAPTER TWO ............................................................................................................. 5

LITERATURE REVIEW ............................................................................................... 5

2.1 Introduction ......................................................................................................... 5


2.2 Detector based control systems ........................................................................... 5
2.3 Microprocessor based systems ............................................................................ 8
2.4 Microcontroller based systems............................................................................ 9

CHAPTER THREE ....................................................................................................... 11

THE MICROCHIP PIC16F690 ARCHITECTURE ....12


vi

3.1 Introduction ....................................................................................................... 11


3.2 The PIC16F690 Chip ........................................................................................ 12
3.2.1 PIC16F690 Architecture ............................................................................ 14
3.2.2 Program memory ....................................................................................... 15
3.2.3 Data memory .............................................................................................. 16
3.2.4 Input/output registers ................................................................................. 20
3.2.5 Timer modules ........................................................................................... 22
3.2.6 Analog to Digital Converter module.......................................................... 25
3.2.7 Oscillator configuration ............................................................................. 27
3.2.8 Interrupts .................................................................................................... 28
3.2.9 Watchdog ................................................................................................... 29
3.3 In-Circuit Programming .................................................................................... 30
3.4 PICkit 2 Demo System .................................................................................. 32
3.5 Power supply ..................................................................................................... 33
3.5.1 Transformer................................................................................................ 35
3.5.2 Rectification `............................................................................................. 35
3.5.3 Capacitor filter ........................................................................................... 36
3.5.4 Regulation .................................................................................................. 37
3.6 Relay Control .................................................................................................... 38
3.7 Liquid Crystal Displays (LCDs) ....................................................................... 39
3.8 Passive Infrared Sensor ..................................................................................... 41
3.9 555 Timer .......................................................................................................... 43
3.10 MPLAB Integrated Development Environment ............................................... 33

CHAPTER FOUR .......................................................................................................... 45

RESEARCH METHODOLOGY ................................................................................. 45

4.1 Introduction ....................................................................................................... 45


4.2 Hardware design ............................................................................................... 46
4.2.1 Relay to microcontroller interface circuit .................................................. 46
4.2.2 Liquid Crystal Display to microcontroller interface .................................. 48
4.2.3 Passive Infrared Sensor interface to PIC16F690 microcontroller ............. 50
vii

4.2.4 Infra-red transmitter circuitry..................................................................... 51


4.3 Software design ................................................................................................. 54
4.3.1 Flowchart for the system software ............................................................. 55
4.3.2 Code development ..................................................................................... 57
4.3.3 Simulation Test .......................................................................................... 59

CHAPTER FIVE ........................................................................................................... 61

RESULTS AND DISCUSSION .................................................................................... 61

5.1 Introduction ....................................................................................................... 61


5.2 System response to person entry/exit ................................................................ 61
5.3 Pulse generation ................................................................................................ 63
5.4 PIR motion sensor response to motion detection .............................................. 65
5.5 Power supply load regulation ............................................................................ 67

CHAPTER SIX .............................................................................................................. 69

CONCLUSIONS AND RECOMMENDATIONS ....................................................... 69

6.1 Conclusions ............................................................................................................ 69


6.2 Recommendations .................................................................................................. 70

REFERENCES ............................................................................................................... 71

APPENDICES ................................................................................................................ 76

Appendix A: Circuit diagram ....................................................................................... 76


Appendix B: Schematic Edit ........................................................................................ 77
Appendix C: PIC16F690 data sheet ............................................................................. 79
Appendix D: PIC16F690 Block diagram ..................................................................... 86
Appendix E: Plates showing hardware components of the proposed automatic room
light controller ............................................................................................................. 87
viii

LIST OF TABLES

Table 3.1: The PIC16F690 microcontroller memory bank addressing modes. ............... 19

Table 3.2: Summary of Registers associated with PORTA of the PIC16F690

microcontroller ................................................................................................................. 21

Table 3.3: Registers associated with the PIC16F690 analog to digital converter............ 27

Table 3.4: The PICkit 2 programmer pin functions ..................................................... 33

Table 4.1: Liquid Crystal Display pins configuration ..................................................... 50

Table 5.1: Table illustrating calculations of a 555 timer connected in astable mode ...... 65

Table 5.2: Output Voltage against loading of power supply67


ix

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

stack levels ..................................................................................................................... 166

Figure 3.3: Schematic diagram showing memory banking of the PIC16F690

microcontroller ................................................................................................................ 18

Figure 3.4: Schematic showing the Status Register bits .................................................. 19

Figure 3.5: Figure illustrating programmer/ debugger connections ............................... 31

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.8: Schematic illustration of a bridge rectifier .................................................... 36

Figure 3.9: Smoothed varying Direct Current ................................................................ 37

Figure 3.10: Schematic diagram of a 16-pin LCD connection ....................................... 40

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.3: PIC16F690 Microcontroller to LCD interface ................. .50

Figure 4.4: Schematic diagram of an Infrared transmitter ............................................. 522

Figure 4.5: Schematic diagram illustrating Infrared receiver interface to PIC16F690 .... 54

Figure 4.6: Flowchart for system software design .......................................................... 56


x

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

configuring the programme code ..................................................................................... 58

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.4: Motion sensor to microcontroller interface circuit ........................................ 67

Figure 5.5: Output voltage versus power supply loading .............................................. 689
xi

ABBREVIATIONS AND ACRONYMS

A/D Analog to Digital

AGC Automatic Gain Control

ADRESH Address Register High

ADRESL Address Register Low

ASCII American Standard Code for Information Interchange

CMOS Complementary Metal Oxide Semiconductor

COM Common

CONFIG Configuration word register

CPU Central Processing Unit

EEPROM Electrically Erasable Programmable Read Only Memory

HCLM Home Light Control Module

HFINTOSC High-Frequency Oscillator

ICSP In-Circuit Serial Programming

ICSPDAT In-Circuit Serial Programming Data

ICSPCLK In-Circuit Serial Programming Clock

IDE Integrated Development Environment

INTCON Interrupt Control

IR Infrared Radiation

ISR Interrupt Service Routine

LCD Liquid Crystal Display

LFINTOSC Low Frequency Oscillator

MCU Micro Controller Unit


xii

NC Normally Closed

NO Normally Open

PGC Programming Clock

PGD Programming Data

POR Power-On Reset

PIC Peripheral Interface Controller

PIR Passive Infrared Sensor

PWM Pulse Width Modulation

RAM Read and Write Memory

ROM Read Only Memory

RISC Reduced Instruction Set

RC Resistor-Capacitor

SFRS Special Function Registers

SPI Serial Peripheral Interface

SSP Synchronous Serial Port

TSOP Thin Small Outline Package

USB Universal Serial Bus

VSM Virtual System Modeling

WDT Watch Dog Timer


xiii

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

embedded microcontroller is discussed.

1.1 Background to the study

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.

The importance of electrical energy is increasing everyday with the impact of

technological advancements (Gunturkun, 2003). The cost of investment made for

generation, transmission and distribution of electrical energy is quite high. For this reason

it has gained significant importance to use the electrical energy efficiently so as to

minimize the existing losses, to reduce the generation costs and to protect the
2

environment by reducing the consumption (Dermirkol, 2006). In most cases, energy

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

attempts in automating the energy efficiency systems to be independent of human

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.

Microcontrollers have traditionally been programmed using the low-level assembly

language of the target processor (Dogan, 2006). This consists of a series of instruction in

the form of mnemonics. The disadvantage of assembly language is that microcontrollers

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

program microcontrollers. The programming language used in this work was C

programming language due to its portability from one microcontroller to another. In

addition, the use of C simplifies the testing and maintenance of microcontroller-based

systems.
3

1.2 Statement of the research problem

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

expected to improve the efficiency of energy consumption by reducing wastage.

1.3 Objectives

1.3.1 General objective

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

in order to conserve energy.

1.3.2 Specific objectives

The specific objectives are:

i. To develop an infrared sensor system to detect human presence in a room

ii. To design and fabricate a switching device for switching the lighting load

ON/OFF in order to save electrical energy when there is no human presence in

the room.

iii. To develop and implement a C based program to control the PIC16F690

microcontroller using the MPLAB Integrated Development Environment as the

platform.
4

1.4 Rationale for the research

A majority of the existing light control systems are manually operated and employ the

contact/break light switches. This poses a great challenge in electrical energy

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

microprocessors and baseline microcontrollers which require additional peripherals like

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

program memory and are available at low cost compared to microprocessor-based

systems. The mid-range architecture microcontrollers are designed for embedded

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

once the chip has been mounted on a circuit board.


5

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.

2.2 Detector based control systems

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

eliminate wasted lighting in unoccupied spaces. In addition, manual dimmers which

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

preference. Each luminaires was dynamically actuated at different levels to realize

various lighting configurations without any physical rewiring. The study used two novel

features: a versatile `plug and play` wireless networked sensing and actuation system

together with a control method incorporating multiple management strategies to provide


6

occupantspecific lighting. Although wireless technology has been identified as

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

of different modes, whose control strategy is based on ergonomic research. It is verified

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

different situation of human needs.

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

and system oscillation.

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

for energy saving. An improvement to daylight harvesting and controlled dimming

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

the touch control technology it could be used in entertainment places.

2.3 Microprocessor based systems

The main aim of controlling energy consumption is to conserve resources as well as

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

of controls each level of automation and complexity requires additional expenditure of


9

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

try alternative arrangement of energy equipment and controls.

Tien-shang and Chun-lin (2011) proposed a microprocessor based dimming controller

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.

2.4 Microcontroller based systems

A microcontroller is a computer integrated on a single chip. It has the processor, memory

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

single dedicated functions or embedded applications. Hengyu et al. (2010) presented a

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

statistics of traffic flowing magnitude, a photosensitive induction, an infrared control and

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

flow magnitude statistics without adding any hardware facilitating transportation

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

light, thus being easy to be located and replaced.

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

mentioned above, a real-time intelligent control system based on a Microchip

PIC16F877A Micro Controller Unit (MCU) was designed. It combined a temperature


11

module based on DS18B20 and a clock module based on DS1302. The MCU was then

programmed to output pulse width modulation to control the output current.

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

microcontroller and a relay.

CHAPTER THREE

THE MICROCHIP PIC16F690 ARCHITECTURE

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

relay and passive infrared sensors are also highlighted.


12

3.2 The PIC16F690 Chip

The PIC family of microcontrollers is based on Harvard architecture and is produced by

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-

word/single-cycle instructions. The mid-range devices feature a 14-bit program word

architecture while the high-range utilize a 16-bit program word architecture and

incorporates an advanced reduced instruction set computer (RISC) architecture with a 32

level-deep stack. This provides a suitable chip selection basis for a developer since a

device with the required functionality can be identified.

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:

i) Twelve analogue inputs

ii) Digital input/output

iii) 4 MHz internal clock oscillator

iv) Three multi-mode timers

v) Serial ports (USART, SPI, I2C)

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

bit can be checked repeatedly in a loop or an interrupt set to indicate completion.

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:

1) Precision internal oscillator

2) Wide operating voltage range (2.0 V- 5.5 V)

3) Power-On Reset (POR) and Enhanced Low-Current Watchdog Timer (WDT)

with on-chip oscillator amongst others.

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

electrically erasable programmable read-only memory. It can be initialized to provide

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

3.2.1 PIC16F690 Architecture

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

implement program branching.

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-

range MCU devices have a 13-bit program counter capable of addressing an 8K x 14

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.

3.2.2 Program memory

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

register which carries the bits 8 through 12 of the program counter.

Figure 3.2: Schematic illustration of PIC16F690 showing program memory map

and the stack levels (www.microchip.com).

3.2.3 Data memory

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

calculated as number of locations per bank multiplied by the number of banks.

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

Figure 3.3: Schematic diagram showing memory banking of the PIC16F690

microcontroller (www.microchip.com)
19

The bit assignments of the status register are shown in Figure 3.4. The 7th bit of this

register is used for indirect addressing.

Figure 3.4: Schematic showing the Status Register bits (www.microchip.com)

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.

Table 3.1: The PIC16F690 microcontroller memory bank addressing modes

Accessed Direct Indirect


Bank (RP1:RP0) (IRP)
0 0 0 0

1 0 1

2 1 0 1

3 1 1
20

3.2.4 Input/output registers

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.

3.2.4.1 PORTA and the TRISA Registers

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

reset by the !RABPU bit of the Option Register, Table 3.2.


21

Each of the PORTA pins is individually configurable as an interrupt-on-change (IOCA)

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

mismatch condition and allow flag bit RABIF to be cleared.

Table 3.2: Summary of Registers associated with PORTA of the PIC16F690

microcontroller.

Name Bit7 Bit6 Bit5 Bit4 Bit3 Bit2 Bit1 Bit0


ADCON0 ADFM VCFG CHS3 CHS2 CHS1 CHS0 GO/!DONE ADON
ANSEL ANS7 ANS6 ANS5 ANS4 ANS3 ANS2 ANS1 ANS1
CM1CON0 C1ON C1OUT C10E C1POL ---- C1R C1CH1 C1CH0
INTCON GIE PEIE TOIE INTE RABIE TOIF INTF RABIF
IOCA ----- ----- IOCA5 IOCA4 IOCA3 IOCA2 IOCA1 IOCA0
OPTION_REG !RAPBU INTEDG T0CS T0SE PSA PS2 PS1 PS0
PORTA ------ ------- RA5 RA4 RA3 RA2 RA1 RA0
SSPCON WCOL SSPOV SSPEN CKP SSPM3 SSPM2 SSPM1 SSPM0
T1CON T1GINV TMR1GE T1CKPS1 T1CKPS0 T1OSCEN !T1SYNC TMR1CS TMR1ON
TRISA ------- ------- TRISA5 TRISA4 TRISA3 TRISA2 TRISA1 TRISA0
WPUA ------- ------- WPUA5 WPUA4 ------- WPUA2 WPUA1 WPUA0

3.2.4.2 PORTB and the TRISB Register

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

allow flag bit RABIF to be cleared.

3.2.4.3 PORTC and the TRISC Register

For PIC16F690 microcontroller, PORTC is an 8-bit wide bidirectional port. Its

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.

3.2.5 Timer modules

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:

1) Timer 0 An 8-bit timer 0

2) Timer 2 A 16-bit timer 1

3) Timer 1 An 8-bit timer 2

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,

making it faster and more efficient.

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

external signal. Thus the timer can also be used as a counter.

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

Timer 2 module is an 8-bit timer with a prescaler; a postscaler, an interrupt on TMR2

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.

3.2.6 Analog to Digital Converter module

Many control applications require the measurement of analogue variables, such as

voltage, temperature, pressure, speed and so on. The analogue-to-digital converter

converts continuous signals into discrete signals. The converter registers are used to

control the ADC ports. The analogue-to-digital converter works by successive

approximation method (Bates, 2008) and uses the system clock to drive the converter that

generates the binary equivalent of the input voltage.

The PIC16F690 analog-to-digital converter allows conversion of an analogue input signal

to a 10-bit binary representation of that signal thus giving a resolution of 1 in 1024, or


26

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

peripheral circuit to select between an internal reference of 5V and an external reference

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

PIC16F690 microcontroller ADC peripheral done with the conversion.

3.2.6.1 ADCON1: A/D Control Register 1

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

bits are set to ADCS2=0, ADCS1=1 and ADCS0=1


27

Table 3.3: Registers associated with the PIC16F690 analog to digital converter

Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0

ADCON0 ADFM VCFG CHS3 CHS2 CHS1 CHS0 GO/!DONE ADON


ADCON1 ------- ADCS2 ADCS1 ADCS0 ------ ----- -------- -------
ANSEL ANS7 ANS6 ANS5 ANS4 ANS3 ANS2 ANS1 ANS0
ANSELH ------- ------- ------ ------ ANS11 ANS10 ANS9 ANS8
ADRESH High byte
ADRESL Low byte
INTCON GIE PEIE T0IE INTE RABIE T0IF INTF RABIF
PIE1 ------- ADIE RCIE TXIE SSPIE CCP1IE TMR2IE TMR1IE
PIR1 ------- ADIF RCIF TXIF SSPIF CCP1IF TMR2IF TMR1IF

3.2.7 Oscillator configuration

An oscillator circuit is used to provide the microcontroller with a clock in order to

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

HS modes, an external oscillator can be connected to the OSC1 input of the

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.

A higher C2 can lower the gain if the crystal is being overdriven.

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

resonators, ceramic resonators and Resistor-Capacitor (RC) circuits. In addition, the

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-

frequency oscillator) and LFINTOSC (uncalibrated low frequency oscillator).

3.2.8 Interrupts

An interrupt is an internally or externally generated signal that forces the processor to

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

asynchronously or synchronously. Asynchronous interrupts are usually external events

(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

increases making interrupt servicing via a single vector more complicated.

3.2.9 Watchdog timer

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

appropriate configuration setting during program code downloading, or specifying it in

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

instruction. On enabling the WDT option, an interrupt is generated hence a routine to

restart the processor must be set at the ISR vector address.

3.3 In-Circuit Programming

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.

In-circuit programming is an effective program downloading method since it allows the

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)

output on the host PC.

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

Figure 3.5: Figure illustrating programmer/ debugger connections (Bates, 2011)

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

VPP provides the programming voltage.

3.4 Programme code development

In order to develop a control algorithm for the microcontroller system, the MPLAB

Integrated Development Environment (IDE), PICkit2 programmer and some

microcontroller interface circuitry are used. The host computer contains the MPLAB IDE

and PICkit2 software versions with the programmer being interfaced to this computer

through a USB cable.


32

3.4.1 PICkit2 Demo System

The PICkit2 is a low cost in-circuit programming module that is capable of

programming most of Microchip`s Flash microcontrollers. The PICkit2 starter kit

includes the low pin count board incorporating the PIC16F690 MCU and some minimal

circuitry as shown on Figure 3.6.

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-

pin connections is summarized in Table 3.4.

Table 3.4: The PICkit 2 programmer pin functions

Pin label Function

1 VPP/!MCLR Programming voltage or reset input

2 VDD Target Power supply positive voltage (+5 V)

3 VSS(ground) Power supply reference voltage (+0 V)

4 ICSPDAT/PGD Programming code: bidirectional serial signal

5 ICSPCLK/PGC Programming clock: unidirectional clock signal

6 Auxiliary Connected to T1G/CLKOUT

3.4.2 MPLAB Integrated Development Environment

The MPLAB Integrated Development Environment is used to perform code

development and debugging. It is a free, integrated software development environment

that includes a MPASM macro assembler, MPLAB SIM software simulator with

symbolic debugger, color-coded editor, and project manager with high-level language

debugger. It is a windows Operating system software programme that runs on a personal

computer to develop applications for PIC MCU families and the dsPIC digital signal

controllers. It is termed an Integrated Development Environment (IDE) because it

provides a single integrated environment to develop code for embedded microcontrollers.

The MPLAB IDE provides the ability to:

i) Create and edit source code using the built-in editor

ii) Assemble, compile and link source code


34

iii) Debug the executable logic by watching program flow with the built-in simulator

or in real time with in-circuit emulators or in-circuit debuggers

iv) View variables in watch windows

v) Make timing measurements with the simulator or emulator

vi) Program firmware into devices with device programmers

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

manager controls this process.

3.5 Power supply

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

which performs a particular function. A block diagram of a regulated power supply

system which converts a 240V AC mains supply into a regulated 5 V DC supply is

illustrated in Figure 3.7.

From 230 V AC mains input


(50Hz)

12 V Rectification Smoothing Regulation


Transformer

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 same. According to Faraday`s laws of electromagnetic induction, an emf is induced in

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

low output voltage.

(3.1)

where; VP = primary (input), VS = Secondary Output Voltage, NP = number of turns on

primary coil while NS is the number of turns on the secondary coil.

3.5.2 Rectification

A rectifier converts an AC waveform into a DC waveform. They are of two different

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.

Figure 3.8: schematic illustrating a bridge rectifier (www.kpsec.freeuk.com)

3.5.3 Capacitor filter

In most circuits, smoothing is performed by a large value electrolytic capacitor connected

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

line) and a smoothed DC (solid line) are illustrated in Figure 3.9.


37

Figure 3.9: Smoothed varying Direct Current (www.kpsec.freeuk.com)

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

smoothing capacitor, the equation below is used.

C = 5IO/ (VS F) (3.2)

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

the peak output current to a safe value.

3.6 Relay Control

A relay is an electromechanical switching device that allows a high power circuit to be

controlled by a small input current, using an electromagnetic coil to operate a set of

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

comparison to a relay coil which requires approximately 100 mA to operate, a switching

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

directly to a digital or microcontroller system.


39

3.7 Liquid Crystal Displays (LCDs)

A liquid crystal display (LCD) is a low cost module that can be interfaced to a

microcontroller to show register contents as characters and numerals. Although seven

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:

i) They are economical in that they exhibit low power consumption

ii) Have small foot print and the ability to display both characters and graphics in

contrast to LEDs, which are limited to numbers and a few characters

iii) They possess an internal refreshing controller. This relieves the CPU from

continuously sending data to the display.

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

excitation voltage applied to each segment.

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

of the LCDs printed circuit.

Figure 3.10: Schematic diagram of a 16-pin LCD connection (Lovine, 2011).


The command register stores the command instructions given to the LCD to do a

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:

(i). Enable (E)

(ii). Read/Write (R/W)


41

(iii). Register select (RS)

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

being written to the LCD.

3.8 Passive Infrared motion sensor

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

energy is determined by the temperature and surface condition of an object.


42

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 frequency of the response change by these factors.


43

3.9 555 Timer

The 555 Timer is a monolithic circuit that can produce accurate and highly stable time

delays or oscillations. It operates in two modes namely

(i). Monostable (one-shot) multivibrator

(ii). Astable (free-running) multivibrator

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

the output becomes high. The cycle then repeats.

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.

This research aimed at designing a microcontroller-based light energy control system

where human movement was to be under continuous surveillance. To achieve this,

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

LCD was interfaced to PORTC of the PIC16F690 microcontroller. A complete block

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

motion sensor, relay and LCD connection circuits.

Figure 4.1: Block diagram of the automatic room light controller


4.2 Hardware design

The hardware component of this system is made up of infrared sensors, PIC16F690

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

4.2.1 Relay to microcontroller interface circuit

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

input circuit it can be considered as a form of an electrical amplifier. When 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

mechanically linked to a moving contact. This movement either makes or breaks a

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

approximately half as strong as the magnetic force to its relaxed position.

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:

i. COM Common, is the moving part of the switch

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

Figure 4.2: Schematic illustrating how to interface PIC microcontroller pin to a

relay coil (Bates, 2008).

4.2.2 Liquid Crystal Display to microcontroller interface

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

sending a command otherwise setting it to logic 1 writes a character to the LCD.

Table 4.1: Liquid Crystal Display pins configuration

Pin no. Symbol Function Pin no. Symbol Function

1 VSS Ground 9 DB2 GND

2 VDD Supply 2.7V to 5.5V 10 DB3 GND

3 Vo Display contrast 11 DB4 RC0

4 RS Register Select 12 DB5 RC1

5 R/W Read/Write (GND) 13 DB6 RC2

6 E Enable 14 DB7 RC3

7 DB0 GND 15 N/A Backlight (+5V)

8 DB1 GND 16 N/A Backlight (GND)

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

Figure 4.3: PIC16F690 Microcontroller to LCD interface

4.2.3 Passive Infrared Sensor interface to PIC16F690 microcontroller

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

which is a maximum at a frequency of about 9.4 m. The presence of human beings

creates a sudden change in the surrounding that is sensed by the pyroelectric sensor. The

PIR sensor requires an initial stabilization of about 10 to 60 seconds in order to get

familiar with the surrounding environment and also function properly. Most of the

motion sensor modules have three pins namely:


51

i) VCC which is connected to positive power rail

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

motion is sensed and low if no motion is detected.

iii) Ground connected to the negative power rail

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

the collector drops down to logic low (0.2 V).

4.2.4 Infrared transmitter circuit

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.

In this mode output frequency is obtained as,

F = 1.44/ (R1 + 2R2) C (4.1)

Figure 4.4: Schematic diagram of an Infrared transmitter

Where we have chosen C=0.001 F, R1=15 k, hence R2=11.4 k. Since a resistor of

value 11.4 k is not available we have used a potentiometer of 10 k along with a

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

switch to the TIL38 LEDs.


53

4.2.5 Infrared receiver circuit

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

ii) Pin 2- VDD

iii) Pin 3- Output

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.

The collector output of the transistor is obtained at pin 3 of TSOP1738 module.

+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

Figure 4.5: Schematic diagram illustrating Infrared receiver interface to PIC16F690

Members of TSOP17xx series are sensitive to different centre frequencies of the IR

spectrum. For instance TSOP1738 is sensitive to 38 kHz whereas TSOP1740 to 40 kHz

centre frequency.

4.3 Software design

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

to the system while PORTC was used for output purposes.


55

4.3.1 Flowchart for the system software

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

executed shall be at address 0001h

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

title of the system

iv) Display the Message "BY SHADRACK" who in this case is the designer

v) Display the room occupancy "NO OF PERSONS IN THE ROOM = "

vi) Check if receiver one is cut If not then go to step no. viii, if cut it is interpreted as

someone has passed across the sensor.

vii) check if receiver two is cut If not then go to step no. ix

viii) If yes then check if receiver one is cut. If yes then Decrement the person

counter and display that number on LCD.

ix) Go to step vi
56

Figure 4.6: Flowchart for system software design

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

back to step no.vi of the algorithm.

4.3.2 Code development

The program code was written as text file and converted to a machine code using the

Microchip MPLAB integrated development environment (IDE). It is a comprehensive

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

Toolsuite then selected whose Toolsuite content is the HI-TECH ANSI C

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

necessary files needed for the project are stored.

iii) A summary of the project parameters is then outlined on the next window.

Figure 4.8: Screenshot of MPLAB software illustrating summary of parameters


used for configuring the programme code
iv) The project is then given a name and a project directory selected where the

necessary files needed for the project are stored.


59

Figure 4.9: Screenshot of MPLAB software showing associated development files


and programme code
v) A new file is opened from the file menu where the programme code is then

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

burned to the PIC16F690 memory using the pickit2 programmer.

4.3.3 Simulation Test

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

the PIC16F690 program memory using the PICkit2.


61

CHAPTER FIVE

RESULTS AND DISCUSSION

5.1 Introduction

This chapter discusses the results obtained on testing the designed system.

5.2 System response to person entry/exit

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

greater than one and the motion detector senses motion.

To test the system, two methods were used.

i) Simulation using Proteus virtual system modeling (VSM) whereby the source

code file obtained from the development environment was added to the

PIC16F690 program memory and the simulation initiated. On pressing switch 1


62

followed by switch 2 the status of the counter incremented and this count was

displayed on the liquid crystal display as illustrated on Figure 5.1.

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

integrated development environment using the PICkit2 programmer into the

microcontrollers program memory. On traversing the two sets of transmitter and

receiver simultaneously the status of the counter also incremented indicating an

entry into the controlled room. The number of people in the room was displayed

on the liquid crystal display as shown on Figure 5.2

On both setups when there was no person in the room the liquid crystal display

displayed count as 0 and the lighting loads were switched off.


63

Figure 5.2: System response schematic of the designed system on using actual

sensors

5.3 Pulse generation

The TSOP1738 infra-red receiver module requires the incoming frequency to be

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

percentage of the time the output is high to the time period T.

(5.1)

Whereby the capacitor charging time (TC) is given by equation 5.2 below

TC = O.69 (R1+R2) C (5.2)

According to the relation 5.1, a duty cycle of 50 % which corresponds to a square wave

is achieved only if the value of R1 equals 0 resulting in terminal 7 being directly

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

circuitry on activating the lighting loads.

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

R1 increased the time high but left time low unaffected.

Table 5.1: Table illustrating calculations of a 555 timer connected in astable mode

R1 R2 Capacitor Frequency Duty cycle Time high

(k) (k) (F) (kHz) (%) (s)

15 11.0 0.001 39.00 70.27 18.018

15 11.1 0.001 38.79 70.16 18.087

15 11.2 0.001 38.58 70.05 18.157

15 11.3 0.001 38.37 69.95 18.226

15 11.4 0.001 38.17 69.84 18.295

15 11.5 0.001 37.97 69.74 18.364

5.4 PIR motion sensor response to motion detection

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

the two halves.

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

the collector drops down to logic-0.

Figure 5.4: Motion sensor to microcontroller interface circuit


67

5.5 Power supply load regulation

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.

Table 5.2: Output Voltage against loading of power supply

12 V power supply 5 V power supply

Load Vout Error Load Vout Error


(k) (V) (V) (k) (V) (V)
11.9 0.005 4.99 0.005

1.2 11.9 0.005 1.2 4.99 0.005

2.4 11.9 0.005 2.4 4.99 0.005

3.6 11.9 0.005 3.6 4.99 0.005

4.8 11.9 0.005 4.8 4.99 0.005

8.4 11.9 0.005 8.4 4.99 0.005

9.6 11.9 0.005 9.6 4.99 0.005

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

voltage produced at full loading.

Figure 5.5: Output voltage versus power supply loading

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

under all load conditions.


69

CHAPTER SIX

CONCLUSIONS AND RECOMMENDATIONS

6.1 Conclusions

A simple, cheap, portable and microcontroller-based automatic room light controller

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

about 0 V which is interpreted as a logic-0 by the microcontroller. In this state, the

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

energy control operations to help limit electric energy wastage.

6.2 Recommendations for future work

Though the designed system was able to reduce energy wastage, a few developments can

be made on it to be more robust. These involve;

Extending the system to include a room with multiple exits/entrances by

employing several sensors. This arrangement would require installation of

multiple pairs of transmitter-receiver sensors and a logical combination of the

outputs. In addition motion detectors with a higher resolution can be integrated in

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

evolve a more reliable system.

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

can be achieved by using data loggers or employing PIC16F690 timer registers

and modifying the programme code.


71

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

commercial and residential sectors.CRC Handbook of Energy Efficiency: 41-56.CRC

press.

Bai Y. and Ku Y. (2008). Automatic Room Light Intensity Detection and Control using a

Microprocessor and Light Sensors, IEEE International Symposium on Consumer

Electronics 54: 1173-1176.

Bates M. (2008). Programming 8-bit PIC Microcontrollers in C with Interactive

Hardware Simulation: Newness. London.

Bates M. (2011). PIC microcontrollers; An Introduction to Microelectronics: Newness.

London. pp 331.

Beil J. (1996). Choosing a microcontroller Electronic product design: Newness. Oxford

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.

Chau-shing W. and Changhua N. (2008). Flicker-insensitive Light Dimmer for

incandescent Lamps. IEEE Transactions on Industrial Electronics 55: (2): 78-112.


72

Dermikol, O. (2006). Measurement and Compensation in with Harmonic and unbalanced

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.

Gunturkun, R. (2003). Feedforward and Elman Feedback Harmonics Compensation

Using Artificial Neural Networks. PhD thesis, Graduate School of Natural and Applied

Sciences, Sakarya. Turkey

Hengyu W., Minli T. and Guo H. (2010). Design of multi-functional street light control

system based on AT89S52 single-chip computer, 2nd International Conference on

Robotics & Control Systems, Wuhan, China: IEEE Conference Publications: 134-137.

Horowitz P. and Hill W. (1989). The Art of Electronics. 2nd Edition, Cambridge

University press. Cambridge.

Jinsoo H., Intark H. and Kwang-Roh P. (2008). Zigbee-based IR Remote Control

Repeater and its control Message frame format, Proceedings of the 2008 International

Symposium on Consumer electronics, Algarve, Portugal 57. IEEE Conference

Publications: 1- 4.

Kakuta N. Yokoyama S. Nakumura M. and Mabuchi K. (2001). Estimation of radiative

heat transfer using a geometric human model IEEE Transactions on Biomedical

Engineering, 48 (3) pp. 324-331.

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,

Newness. USA. pp 256.

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,

3316-3321. Glendale. (USA)

Meiklejohn, D. (2008). Introduction to PIC programming lesson 0: 1-19, Newness.

Mohamed F., Mounir B. and Bedda M. (2008). Microcontroller based heart rate monitor.

The International Arab Journal of Information Technology 5 (4): 1-5.

Niu M. and Qin H. (2012). Design of LED street lamps intelligent control system based

on PIC microcontroller International Conference on Image Analysis and Signal

Processing: 1- 4, Hangzou.

PIC16F631/677/685/689/690 Datasheet (2008). Microchip Technology Inc., Reference

no. DS41262; www.microchip.com accessed July 2012.

Ranjit S., Baljit S., Tuani I. and Ahamed F. (2010). Designing Switching System for AC

Powered Appliances Using a Microcontroller, Mathematical/Analytical Modeling and

Computer simulation (AMS), Fourth Asia International Conference, 34: 46 50,

Washington.
74

Reinhardt, S. (2000). Integrating hardware and software concepts in a microprocessor

based system lab. IEEE computers 26: 49-55.Elsevier.

Richard, B. (2002). Energy Management Systems and Digital direct control, 1st Edition,

Marcel Dekker, Inc.

RLW Analytics, Inc (1999). Non-Residential New construction baselines study for the

California Board for Energy Efficiency of the CPU 42 (July): 126-28.

Rubinstein F, Avery D, Jennings J. and Blanc S. (1997). Calibration and commissioning

of lighting controls. Proceedings of the Right light 4 conference, Copenhagen, Denmark:

1- 11.

Rubinstein F, Jennings J, Avery D. and Blanc S. (1999). Preliminary results from an

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

Electronics, 25: 3106-3118.

Thomann A. and Younger J. (2003). The Handbook of Energy Audits, 6th Edition

Fairmount Press. Inc. Georgia, USA.


75

Tien-shang L. and Chun-lin, L. (2011). Proposals for dimming ballast control through

toggle switches. Institute of Electrical and Electronics Engineers. Taiwan.

TSOP1738 Datasheet (2001). Vishay semiconductors, Reference no. 82030;

www.vishay.com accessed October 2012.

Valvano, J. (2000). Embedded microcomputer systems, Real Time Interfacing,

Brooks/Cole Thomson learning, USA.

Wang C. and Devaney M. (2004). Incandescent Lamp flicker mitigation and

measurement, IEEE Transitional Instrument measurement, 53: 1028-1031.

Wayne, C. and Steve, D. (2007). Energy Management Handbook, 6th Edition, Fairmount

press, Inc: USA. 88-104.

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

zigbee communication. Proceedings of the 2008 International symposium on consumer

Electronics, 24: 1- 4.
76

APPENDICES

Appendix A: Circuit diagram


77

Appendix B: Schematic Edit

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

(figure B.1) whose main applications are:

1) Select components from library

2) Place and connect up components

3) Write a test program for the MCU

4) Attach to the MCU and simulate

5) Debug the program if necessary

6) Export netlist to make a PCB

Figure B.1: ISIS Schematic capture screenshot

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.

Figure B.2: Pick Devices dialogue


The components here are organized in in category and the devices are listed in numerical

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

Appendix C: Programme code


/*-------------------------------------------------------------------------------------------------------*/

/* Program Name: AUTOMATIC ROOM LIGHT CONTROLLER */

/* Name of Author: SHADRACK */

/* 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>

__CONFIG(INTIO & WDTDIS & PWRTEN & MCLRDIS & UNPROTECT \

& UNPROTECT & BORDIS & IESODIS & FCMDIS);

// LCD module connections

#define RS RC5;

#define EN RC4;

#define D4 RC0;

#define D5 RC1;

#define D6 RC2;

#define D7 RC3;

// End LCD module connections

#define button_1 RB7;

#define button_2 RB6;

#define LED RB5;


80

#define button_3 RB4;

char MSG1[] ="ROOM LIGHT";

char MSG2[] ="CONTROLLER";

char MSG3[] =" BY ";

char MSG4[] ="SHADRACK";

char MSG5[7];

char MSG6[] =" PERSON IN ";

char MSG7[] =" PERSONS IN ";

unsigned int cnt,cnt2=0;

unsigned int counter=0,m, flip,flip2,temp,temp1;

char flag,i,flag2=1; // Loop variable

void InitTimer0(){

OPTION_REG = 0x88;

TMR0 = 7;

INTCON = 0xA0;

void Interrupt(){

if (T0IF_bit){

T0IF_bit = 0;

TMR0 = 7;

cnt++;

if(cnt==10000) // this is exactly 1 sec.

{cnt=0;cnt2++;}

if(LED >=1)

{flag = 1;}
81

else

{flag =0;}

void wait() { // Function used for text moving

Delay_ms(1); // You can change the moving speed here

void wait2() { // Function used for text moving

Delay_ms(5000); // You can change the moving speed here

void main(){

ANSEL = 0; // Configure AN pins as digital I/O

ANSELH = 0;

C1ON_bit = 0; // Disable comparators

C2ON_bit = 0;

PORTB = 0x00;

TRISB = 0xC0;

PORTC = 0x00;

TRISC = 0x00;

OPTION_REG = 0x83;

TMR0 = 97;

INTCON = 0xA0;
82

Lcd_Init(); // Initialize LCD

Lcd_Cmd(_LCD_CLEAR); // Clear display

Lcd_Cmd(_LCD_CURSOR_OFF); // Cursor off

Lcd_Out(1,4,MSG1); // Write text in first row

Lcd_Out(2,4,MSG2); // Write text in second row

Delay_ms(1000);

Lcd_Cmd(_LCD_CLEAR); // Clear display

Lcd_Cmd(_LCD_CLEAR); // Clear display

Lcd_Cmd(_LCD_CURSOR_OFF); // Cursor off

Lcd_Out(1,4,MSG3); // Write text in first row

Lcd_Out(2,4,MSG4); // Write text in second row

Delay_ms(1000);

Lcd_Cmd(_LCD_CLEAR); // Clear display

InitTimer0();

while(1) { // Endless loop

if(button_3==1){

if(counter>=1)

{LED =1;cnt=0;}

else

{LED =0;}
83

IntToStr(counter,MSG5);

Lcd_Out(1,4,MSG5); // Write text in second row

if(counter==1)

{Lcd_Out(2,3,MSG6);}

else

{Lcd_Out(2,3,MSG7);}

if(button_1)

{flip =1;}

if(button_2)

{flip2 =1; delay_ms(500);}

while(flip==1){

if(button_2)

{counter = counter ++;

delay_ms(500);flip = 0;}

while (flip2==1){

if(button_1)

{counter = counter --;

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

LED =0;} // Write text in second row

}
85

Appendix D: PIC16F690 data sheet


86

Appendix E: PIC16F690 Block diagram


87

Appendix F: Plates showing hardware components of the proposed automatic


room light controller

i) Person counter circuitry


88

ii) Complete light control system

You might also like