Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

Unit 5

Real World Interfacing with PIC 18FXX

PORTS

40 pins of PIC18F4550 are divided into 5 ports. Out of which, 35 pins are Input-Output pins
which can be configured for general Input or Output by setting registers associated with them.
Please Refer the Pinout diagram above for a clear idea about location of these pins on the
microcontroller.

Ports Number of pins Pin Name

PORTA 7 RA0-RA6
PORTB 8 RB0-RB7
PORTC 7 RC0-RC2, RC4-RC7 (Check the Pinout Diagram)
PORTD 8 RD0-RD7
PORTE 4 RE0-RE3

Registers Associated with Ports in PIC18F4550

Each port in pic18f4450 is associated with three 8 bit registers for IO operations.

1. TRISX (8 bit)
2. LATx (8 bit)
3. PORTx (8 bit)

TRISx : where X is the name of the ports either of A, B, C, D, E. For example TRISA, TRISB
etc.This register assigns the direction of the pins (Input or Output). For example “TRISB =
0xF0”, will set all the pins in port B to Output.

LATX: The latch registers reds and modifies the write operation on the value of I/O pin and
stored the output data that is to be passed on to the external hardware.

PORTX: Reads the device level, stores the Input level of the pins and reads and registers the
input signal from the external device if the pin is configured as Input.
LED Interfacing with PIC Microcontroller

Circuit Setup:
1. LED Orientation:
 LEDs have a longer lead called the anode (+) and a shorter lead called the cathode (-).
The longer lead is usually the positive side.
 If you're not sure about the polarity, you can identify it by looking at the LED. The shorter
lead is usually flat on the bottom of the LED bulb.
2. Connect the LED to Power:
 Connect the anode of the LED to the positive side of the power source (through a
current-limiting resistor).
 Connect the cathode of the LED to the negative side of the power source (commonly
ground).
3. Limiting Current:
 LEDs are sensitive to current and can burn out if too much current flows through them.
To limit the current, connect a resistor in series with the LED. The resistor value depends
on the supply voltage and the LED's forward voltage and current specifications.

Embedded C code to blink LED

#include <pic18f.h>

// Configuration settings for the PIC 18F microcontroller

#pragma config FOSC = HS // Oscillator Selection bits (HS oscillator)

#pragma config WDTE = OFF // Watchdog Timer Enable bit (WDT disabled)

#pragma config PWRTE = OFF // Power-up Timer Enable bit (PWRT disabled)

#pragma config BOREN = OFF // Brown-out Reset Enable bit (BOR disabled)

#pragma config LVP = OFF // Low-Voltage (Single-Supply) In-Circuit Serial Programming


Enable bit (RB3 is digital I/O, HV on MCLR must be used for programming)

void main()

TRISB = 0x00; // Set all pins of Port B as outputs

while(1)

PORTB = 0x0F; // Turn on all LEDs (RB0 to RB3)

delay_ms(500); // Delay for 500 milliseconds (0.5 seconds)

PORTB = 0x00; // Turn off all LEDs

delay_ms(500); // Delay for 500 milliseconds

}
void delay_ms()

int i,j;

for(i=0,i<500,i++)

for(j=0,j<500,j++)

LCD interfacing

A liquid crystal display or LCD draws its definition from its name itself. It is a combination of
two states of matter, the solid and the liquid. LCD uses a liquid crystal to produce a visible
image. Liquid crystal displays are super-thin technology display screens that are generally used
in laptop computer screens, TVs, cell phones, and portable video games. LCD’s technologies
allow displays to be much thinner when compared to a cathode ray tube (CRT) technology.

Liquid crystal display is composed of several layers which include two polarized
panel filters and electrodes. LCD technology is used for displaying the image in a notebook or
some other electronic devices like mini computers. Light is projected from a lens on a layer of
liquid crystal. This combination of colored light with the gray scale images of the crystal (formed
as electric current flows through the crystal) forms the colored image. This image is then
displayed on the screen.

LCD pin diagram


RS (Register Select)

A 16X2 LCD has two registers, namely, command and data. The register select is used to switch
from one register to other. RS=0 for the command register, whereas RS=1 for the data register.

Command Register: The command register stores the command instructions given to the LCD.
A command is an instruction given to an LCD to do a predefined task. Examples like:

 initializing it
 clearing its screen
 setting the cursor position
 Controlling display etc.
Processing for commands happens in the command register.

Data Register: The data register stores the data to be displayed on the LCD. The data is the
ASCII value of the character to be displayed on the LCD. When we send data to LCD, it goes to
the data register and is processed there. When RS=1, the data register is selected.

LCD Commands
Interfacing of LCD with PIC 18Fxx

LCD Interfacing- 8 bit mode

LCD Interfacing- 4 bit mode


Embedded C code for LCD interfacing

#include <pic18f4550.h>

/*********************Definition of Ports********************************/

#define RS LATB0 /*PIN 0 of PORTB is assigned for register select Pin of LCD*/
#define EN LATB1 /*PIN 1 of PORTB is assigned for enable Pin of LCD */
#define ldata LATB /*PORTB(PB4-PB7) is assigned for LCD Data Output*/
#define LCD_Port TRISB /*define macros for PORTB Direction Register*/

/*********************Proto-Type Declaration*****************************/

void MSdelay(unsigned int ); /*Generate delay in ms*/


void LCD_Init(); /*Initialize LCD*/
void LCD_Command(unsigned char ); /*Send command to LCD*/
void LCD_Char(unsigned char x); /*Send data to LCD*/
void LCD_String(const char *); /*Display data string on LCD*/
void LCD_String_xy(char, char , const char *);
void LCD_Clear(); /*Clear LCD Screen*/

{
set frequency to 8 MHz*/
LCD_Init(); /*Initialize LCD to 5*8 matrix in 4-bit mode*/
LCD_String_xy(1,5,"Hello"); /*Display string on 1st row, 5th location*/
LCD_String_xy(2,1,"ElectronicWings"); /*Display string on 2nd row,1st
location*/
while(1);
}

/****************************Functions********************************/

{
LCD_Port = 0; /*PORT as Output Port*/
MSdelay(15); /*15ms,16x2 LCD Power on delay*/
for nibble (4-bit) mode */
initialize 5*8 matrix in (4-bit mode)*/
LCD_Command(0x01); /*clear display screen*/
LCD_Command(0x0c); /*display on cursor off*/
LCD_Command(0x06); /*increment cursor (shift cursor to right)*/
}

{
ldata = (ldata & 0x0f) |(0xF0 & cmd); /*Send higher nibble of command
first to PORT*/
RS = 0; /*Command Register is selected i.e.RS=0*/
EN = 1; /*High-to-low pulse on Enable pin to latch data*/
NOP();
EN = 0;
MSdelay(1);
ldata = (ldata & 0x0f) | (cmd<<4); /*Send lower nibble of command to
PORT */
EN = 1;
NOP();
EN = 0;
MSdelay(3);
}

{
ldata = (ldata & 0x0f) | (0xF0 & dat); /*Send higher nibble of data
first to PORT*/
RS = 1; /*Data Register is selected*/
EN = 1; /*High-to-low pulse on Enable pin to latch data*/
NOP();
EN = 0;
MSdelay(1);
ldata = (ldata & 0x0f) | (dat<<4); /*Send lower nibble of data to PORT*/
EN = 1; /*High-to-low pulse on Enable pin to latch data*/
NOP();
EN = 0;
MSdelay(3);
}

{
while((*msg)!=0)
{
LCD_Char(*msg);
msg++;
}
}

{
char location=0;
if(row<=1)
{
location=(0x80) | ((pos) & 0x0f); /*Print message on 1st row and
desired location*/
LCD_Command(location);
}
else
{
location=(0xC0) | ((pos) & 0x0f); /*Print message on 2nd row and
desired location*/
LCD_Command(location);
}

LCD_String(msg);
}

{
LCD_Command(0x01); /*clear display screen*/
MSdelay(3);
}

{
unsigned int i,j;
for(i=0;i<val;i++)
for(j=0;j<165;j++); /*This count Provide delay of 1 ms for 8MHz Frequency
*/
}
Keypad

A keypad is a set of buttons arranged in a block or “pad” which usually bear digits, symbols and
usually a complete set of alphabetical letters. If it mostly contains numbers then it can also be
called a numeric keypad. Here we are using 4 X 4 matrix keypad.

Interfacing keypad

Fig. 1 shows how to interface the 4 X 4 matrix keypad to two ports in microcontroller. The rows
are connected to an output port and the columns are connected to an input port.
To detect a pressed key, the microcontroller grounds all rows by providing 0 to the output latch,
and then it reads the columns. If the data read from the columns is D3-D0=1111, no key has been
pressed and the process continues until a key press is detected. However, if one of the column
bits has a zero, this means that a key press has occurred. For example, if D3-D0=1101, this
means that a key in the D1 column has been pressed.

After a key press is detected, the microcontroller will go through the process of identifying the
key. Starting with the top row, the microcontroller grounds it by providing a low to row D0 only;
then it reads the columns.

If the data read is all 1s, no key in that row is activated and the process is moved to the next row.
It grounds the next row, reads the columns, and checks for any zero. This process continues until
the row is identified. After identification of the row in which the key has been pressed, the next
task is to find out which column the pressed key belongs to.
Embedded C Program to 4 X 4 matrix keypad
#include <pic.h>

#define FOSC 10000

#define BAUD_RATE 9.6

unsigned char KeyArray[4][4]= { '1','2','3','4', '5','6','7','8', '9','A','B','C', 'D','E','F','0'};

int Col=0,Row=0,count=0,i,j;

void main()

DelayMs(50);

SerialInit();

nRBPU=0;

//Enable PORTB Pullup values while(1)

TRISB=0x0f;

// Enable the 4 LSB as I/P & 4 MSB as O/P PORTB=0;

while(PORTB==0x0f);

// Get the ROW value ScanRow(); TRISB=0xf0;

// Enable the 4 LSB as O/P & 4 MSB as I/P PORTB=0; while(PORTB==0xf0);

// Get the Column value ScanCol(); DelayMs(150);

Count[Row][Col]++;

void ScanRow()

// Row Scan Function

{
switch(PORTB)

case 0x07: Row=3;

// 4th Row break;

case 0x0b: Row=2;

// 3rd Row break;

case 0x0d: Row=1;

// 2nd Row break;

case 0x0e: Row=0;

// 1st Row break;

void ScanCol()

// Column Scan Function {

switch(PORTB)

case 0x70: Col=3;

// 4th Column break;

case 0xb0: Col=2;

// 3rd Column break;

case 0xd0: Col=1;

// 2nd Column break; case 0xe0: Col=0;

// 1st Column break;

}
void SerialInit()

TRISC=0xc0;

// RC7,RC6 set to usart mode(INPUT) TXSTA=0x24;

//Enable Serial Transmission, Asynchronous mode, High Speed mode SPBRG=BAUD_VAL;

// 9600 Baud rate selection RCSTA=0x90;

// Enable Serial Port & Continuous Receive printf("Press Anyone Key:\n\r");

void putch(unsigned char character)

while(!TXIF);

// Wait for the TXREG register to be empty TXREG=character;

// Display the Character

void DelayMs(unsigned int Ms)

int delay_cnst; while(Ms>0)

Ms--;

for(delay_cnst = 0;

delay_cnst <220;

delay_cnst++);

}
MOTION DETECTOR
What are Motion Sensors And How Do They Work?

The first motion sensor was invented in the year 1950 by Samuel Bango named as a burglar
alarm. He applied the basics of a radar to ultrasonic waves – a frequency to notice fire or robber
and that which human beings cannot listen to. The Samuel motion sensor is based on the
principle of “Doppler Effect”. Currently, most of the motion sensors work on the principle of
Samuel Bango’s detector. Microwave and infrared sensors used to detect motion by the changes
in the frequencies they produce. To understand the working of motion sensor, you first need to
know the working of a camera. The camera uses an image sensor and the lens direct light to –
when the light strikes the image sensor each pixel records how much light it’s getting. That
outline of light and dark areas in the pixels becomes the entire video image.

Motion sensors are applicable for security systems which are used in offices, banks, shopping
malls, and also as intruder alarm at home. The existing motion detectors can stop serious
accidents by detecting the persons who are closest to the sensor. We can monitor motion
detectors in public places. The main part of the motion detector circuit is the dual IR reflective
sensor.

What is a Motion Sensor?

A motion sensor is a device that notices moving objects, mainly people. A motion sensor is
frequently incorporated as a component of a system that routinely performs a task or else alerts a
user of motion in a region. These sensors form a very important component of security, home
control, energy efficiency, automated lighting control, and other helpful systems. The main
principle of motion sensor is to sense a burglar and send an alert to your control panel, which
gives an alert to your monitoring center. Motion sensors react to different situations like
movement in your living room, doors, windows being unbolt or closed and also these sensors can

 Activate a doorbell when someone comes close to the front door.


 These sensors give you an alert whenever kids enter into some restricted areas in the
home such as medicine cabinet, the basement or workout room.
 Conserve energy by using this sensor lighting in empty spaces.

Types of Motion Sensors

There various kinds of motion sensors are available in the market, which has their ups and
downs. They are namely PIR, Ultrasonic, Microwave, Tomographic and combined types.
1. Passive Infrared (PIR) Sensor
All warm blooded animals produce IR radiation. Passive infrared sensors include a thin
Pyro electric film material, that responds to IR radiation by emitting electricity. This
sensor will activate burglar alarm whenever this influx of electricity takes place. These
sensors are economical, don’t use more energy and last forever. These sensors are
commonly used in indoor alarms.

2. Ultrasonic Sensor
Ultrasonic sensor can be active (or) passive, where passive ones pay attention for
particular sounds like metal on metal, glass breaking. These sensors are very sensitive,
but they are frequently expensive and prone to fake alarms. Active ones generate
ultrasonic wave (sound wave) pulses and then determine the reflection of these waves off
a moving object. Animals like cats, dogs, fishes can hear these sound waves, so an active
ultrasonic alarm might unsettle them.
3. Microwave Sensor

These sensors generate microwave pulses and then calculate their reflection off of objects, in
order to know whether objects are moving or not. Microwave sensors are very sensitive, but
sometimes these can be seen in nonmetallic objects which can be detected moving objects on the
outside of the target range. It consumes a lot of power, so these sensors are frequently designed
to cycle ON & OFF. This makes it feasible to acquire past them, if you know the cycles.
Electronic guard dogs utilize microwave sensors.

4. Tomographic Sensor

These sensors generate radio waves and detect when those waves are troubled. They can notice
through walls and objects, and are frequently placed in a way that makes a radio wave net that
cover ups large areas. These sensors are expensive, so they are normally used in warehouses,
storage units and also in other situations that need a commercial level of security.
5. Combined types of Motion Sensors
Some types of motion detectors mix some sensors in order to decrease fake alarms. But,
dual sensors are only activated when both kinds sense motion. For instance, a dual
microwave or PIR sensor will start out on the passive infrared sensor setting, because that
consumes less energy. When the passive infrared sensor is tripped, the microwave
division will turn ON; then, if the remaining sensor also tripped, the alarm will generate
sound. This combined type is great for neglecting fake alarms, but tuns the possibility of
missing real ones.

Embedded C Program for PIR Sensor

#include <xc.h>

#define _XTAL_FREQ 20000000 //Specify the XTAL crystall FREQ

#define PIR RC0

#define Buzzer RB2

void main() //The main function

TRISB=0X00; //Instruct the MCU that the PORTB pins are used as Output.

TRISC=0Xff; //Instruct the MCU that the PORTB pins are used as Input.

PORTB=0X00; //Make all output of RB3 LOW

while(1) //Get into the Infinie While loop

if(PIR ==1){

Buzzer=1;

__delay_ms(1000); //Wait

}
else{

Buzzer=0;

}
void delay_ms()
{
int i,j;
for(i=0,i<500,i++)
for(j=0,j<500,j++)
}

Gas Sensor

Introduction to Gas Sensor


A gas sensor is a device which detects the presence or concentration of gases in the
atmosphere. Based on the concentration of the gas the sensor produces a corresponding
potential difference by changing the resistance of the material inside the sensor, which
can be measured as output voltage. Based on this voltage value the type and
concentration of the gas can be estimated.

The type of gas the sensor could detect depends on the sensing material present inside
the sensor. Normally these sensors are available as modules with comparators as shown
above. These comparators can be set for a particular threshold value of gas concentration.
When the concentration of the gas exceeds this threshold the digital pin goes high. The
analog pin can be used to measure the concentration of the gas.
Different Types of Gas sensors
Gas sensors are typically classified into various types based on the type of the sensing
element it is built with. Below is the classification of the various types of gas sensors
based on the sensing element that are generally used in various applications:

 Metal Oxide based gas Sensor.


 Optical gas Sensor.
 Electrochemical gas Sensor.
 Capacitance-based gas Sensor.
 Calorimetric gas Sensor.
 Acoustic based gas Sensor.

Applications of Gas Sensors

 Used in industries to monitor the concentration of the toxic gases.


 Used in households to detect an emergency incidents.
 Used at oil rig locations to monitor the concentration of the gases those are released.
 Used at hotels to avoid customers from smoking.
 Used in air quality check at offices.
 Used in air conditioners to monitor the CO2 levels.
 Used in detecting fire.
 Used to check concentration of gases in mines.
 Breath analyzer.
Gas sensor interfacing with PIC microcontroller

IR Sensor
What is an IR Sensor : Circuit Diagram & Its Working

IR technology is used in daily life and also in industries for different purposes. For example, TVs
use an IR sensor to understand the signals which are transmitted from a remote control. The main
benefits of IR sensors are low power usage, their simple design & their convenient features. IR
signals are not noticeable by the human eye. The IR radiation in the electromagnetic
spectrum can be found in the regions of the visible & microwave. Usually, the wavelengths of
these waves range from 0.7 µm 5 to 1000µm. The IR spectrum can be divided into three regions
like near-infrared, mid, and far-infrared. The near IR region’s wavelength ranges from 0.75 –
3µm, the mid-infrared region’s wavelength ranges from 3 to 6µm & the far IR region’s infrared
radiation’s wavelength is higher than 6µm.
An infrared sensor is an electronic device that emits in order to sense some aspects of the
surroundings. An IR sensor can measure the heat of an object as well as detects the motion.
These types of sensors measure only infrared radiation, rather than emitting it that is called a
passive IR sensor. Usually, in the infrared spectrum, all the objects radiate some form of thermal
radiation
IR Sensor Circuit Diagram

An infrared sensor circuit is one of the basic and popular sensor modules in an electronic device.
This sensor is analogous to human’s visionary senses, which can be used to detect obstacles and
it is one of the common applications in real-time. This circuit comprises the following
components
 LM358 IC 2 IR transmitter and receiver pair
 Resistors of the range of kilo-ohms.
 Variable resistors.
 LED (Light Emitting Diode).

Applications IR Sensor

 Climatology
 Meteorology
 Photobiomodulation
 Flame Monitors
 Gas detectors
 Water analysis
 Moisture Analyzers
 Anesthesiology testing
 Petroleum exploration
 Rail safety
 Gas Analyzers
Interfacing of IR sensor with pic microcontroller

Embedded C program for Interfacing of IR sensor with pic microcontroller

#include<pic.h>

#define IR RD0 //IR Output is connected at PORTD.0

#define rs RC0
#define rw RC1
#define en RC2
#define delay for(i=0;i<1000;i++)

int i;

void lcd_init();
void cmd(unsigned char a);
void dat(unsigned char b);
void show(unsigned char *s);
void main()
{
TRISB=TRISC0=TRISC1=TRISC2=0;
TRISD=0xff; //Port D act as Input
lcd_init();
cmd(0x80);
show(" EmbeTronicX ");
while(1) {
if(IR == 0) {
cmd(0xc0);
show("Obstacle Detcted");
delay;
}
else
{
cmd(0xc0);
show(" ");
}
}
}

void lcd_init()
{
cmd(0x38);
cmd(0x0c);
cmd(0x06);
cmd(0x80);
}

void cmd(unsigned char a)


{
PORTB=a;
rs=0;
rw=0;
en=1;
delay;
en=0;
}
void dat(unsigned char b)
{
PORTB=b;
rs=1;
rw=0;
en=1;
delay;
en=0;
}

void show(unsigned char *s)


{
while(*s)
{
dat(*s++);
}
}
HOME PROTECTION SYSTEM

You might also like