#define _XTAL_FREQ 8000000
#include <stdio.h>
#include <string.h>
#include <p18F4520.h>
#include "pic_lcd.h"
#define Trigger PORTCbits.RC0
#define Power PORTBbits.RB0
#define Echo PORTBbits.RB4
// interrupt handling variables
char m10sec;
char timerL, timerH;
// interrupt handling variables
//data types convert
char data_buff[16];
float Height_val;
//data types convert
// Display Related Variables
char disp_ram[2][16];
// Display Related Variables
char sensor_flag = 0;
bit read_flag = 0;
/// Function Prototypes
void Refresh_lcd();
void fill_ram(char y, char x, char str[16]);
void Trigger_Sensor();
/// Function Prototypes
void interrupt Interrupt(void)
{
if ( INTCONbits.TMR0IF == 1 )
{
INTCONbits.TMR0IF = 0;
TMR0H = 0xF8;
TMR0L = 0x20 ;
m10sec ++;
if(m10sec >=10){
Refresh_lcd();
m10sec = 0;
}
INTCONbits.GIE = 1;
}
if(INTCONbits.INT0IF == 1){
Trigger_Sensor();
INTCONbits.INT0IF = 0;
}
if(RBIF == 1)
{
char temp1, temp2;
temp1 = PORTBbits.RB4;
RBIF = 0;
if(Echo == 1){
TMR1ON = 1;
}
if(Echo == 0){
TMR1ON = 0;
timerH = TMR1H;
timerL = TMR1L;
TMR1H = 0;
TMR1H = 0;
read_flag = 1;
}
}
INTCONbits.GIE = 1;
INTCONbits.PEIE = 1;
}
void timer0_init()
{
T0CON = 0x08;
TMR0H = 0xF8;
TMR0L = 0x20;
INTCON = 0x04;
INTCONbits.TMR0IE = 1;
INTCONbits.PEIE = 1;
INTCONbits.GIE = 1;
T0CONbits.TMR0ON = 1;
}
void ftoa(float i)
{
sprintf(data_buff,"Height = %.2f",i);
// return(data_buff);
}
void change_int_init(){
T1CON = 0x10;
TMR1H = 0x00;
TMR1L = 0x00;
T1CONbits.TMR1ON = 0;
INTCONbits.RBIE = 1; //Enable PORTB On-Change Interrupt
}
void Trigger_Sensor(){
Trigger = 1;
__delay_us(10);
Trigger = 0;
}
void Refresh_lcd(){
lcd_goto(1,0);
for(char i = 0; i < 2; i++){
for(char j = 0; j< 16; j++){
lcd_putch(disp_ram[i][j]);
}
lcd_goto(2,0);
}
}
void my_ftoa(float i)
{
int num,dec;
//char b[10];
num=i;
dec=(i-num)*100;
sprintf(data_buff,"Height = %d.%d",num,dec);
}
void find_Height(){
Height_val = (timerL | (timerH <<8 ))/58.82;
timerL = 0;
timerH = 0;
my_ftoa(Height_val);
}
void main()
{
TRISD = 0x00;
TRISB = 0xF0;
TRISC = 0xFF;
PORTC = 0xFF;
//TRISD = 0x00;
PORTD = 0x00;
PORTD = 0x00;
timer0_init();
change_int_init();
lcd_init();
INTCON = 0xF8;
__delay_ms(10);
lcd_goto(1,1);
lcd_putch('A');
fill_ram(0,3,"Indent");
while(1)
{
/*
if(Power == 1 && sensor_flag == 0){
__delay_ms(10);
if(Power == 1){
Trigger_Sensor();
sensor_flag = 1;
}
}
*/
if((sensor_flag == 1) && read_flag == 1){
find_Height();
}
// if(sensor_flag == 1)
}
}
void fill_ram(char y, char x, char str[16]){
char len;
len = strlen(str);
char i =0, j = 0;
for(i =0; i < x && i<16; i++){
disp_ram[y][i] = ' ';
}
for(i = x,j =0; i < len+x && i < 16; i++){
disp_ram[y][i] = str[j++];
}
if(i < 15 )
for(i = len+x; i < 16; i++){
disp_ram[y][i] = ' ';
}
}