C program to capture the frequency of square wave and display it on 2x16 LCD display using PIC 16f877a microcontroller
Program:
#include<htc.h>
#include<stdio.h>
#include<math.h>
#define
rs RB0
#define
rw RB1
#define
en RB2
#define
lcd PORTD
void
lcd_ini();
void
lcd_cmd(unsigned char cmd);
void
lcd_data(unsigned char data);
void
lcd_str(unsigned char *str);
void
delay();
void
main()
{
long
int period1,period2;
long
int period;
int
overflow;
long
int frequency;
char
str[10];
TRISD=0;
TRISB=0;
TRISC=0X04; //capture is
done at RC2 i.e CCP1
//capture mode initializations
lcd_ini();
lcd_cmd(0x80);
lcd_str("frequency");
while(1)
{
period1=0;
period2=0;
period=0;
//capture mode initialization
INTCON=0x00; //GIE, PEIE Enable peripheral interrupts
PIE1=0x00; //CCP1IE disable CCP1 interrupt
PIR1=0x00; //CCP1IF CCP1 interrupt flag(SET TO 0)
CCP1CON=0x05; //CCP1M0-3
Capture mode – every rising edge
TMR1H=0;
TMR1L=0;
overflow=0;
while(!RC2);
//First capture count
T1CON=0x01; //TMR1ON start
timer with internal clock
while(!(PIR1&0x04)); //checking for capture flag to be set on
every rising edge
PIR1=0x00; //clear capture
flag
period1=((CCPR1H<<8)|CCPR1L); //2nd capture count
while(!(PIR1&0x04));
PIR1=0x00;
period2=((CCPR1H<<8)|CCPR1L);
period=period2-period1;
frequency=5000000/(period*2);
sprintf(str,"%ld",frequency);
lcd_cmd(0xC0);
lcd_str(str);
lcd_str("Hertz");
INTCON=0X00;
T1CON=0X00;
CCP1CON=0X00;
}
}
void
lcd_ini()
{
lcd_cmd(0x38);
delay();
lcd_cmd(0x0E);
delay();
lcd_cmd(0x01);
delay();
lcd_cmd(0x06);
delay();
}
void
lcd_cmd(unsigned char cmd)
{
lcd=cmd;
rs=0;
rw=0;
en=1;
delay();
en=0;
}
void
lcd_data(unsigned char data)
{
lcd=data;
rs=1;
rw=0;
en=1;
delay();
en=0;
}
void
delay()
{
unsigned
int i=5000;
while(i--);
}
void
lcd_str(unsigned char *str)
{
unsigned
char i=0;
while(str[i]!=0)
lcd_data(str[i++]);
}