Code: Select all
#include <16F877A.h>
#fuses XT, NOWDT, NOPROTECT, NOBROWNOUT, NOLVP, NOPUT, NOWRT, NODEBUG, NOCPD
#use fast_io(A)
#use delay(clock = 4 MHz)
#define DT1 pin_c0
#define SCK pin_c1
//LCD module connections
#define LCD_RS_PIN PIN_B0
#define LCD_RW_PIN PIN_B1
#define LCD_ENABLE_PIN PIN_B2
#define LCD_DATA4 PIN_B3
#define LCD_DATA5 PIN_B4
#define LCD_DATA6 PIN_B5
#define LCD_DATA7 PIN_B6
//End LCD module connections
#include <lcd.c> // lcd.c dosyası tanıtılıyor
//
//double SCALE = 72118.4;
double SCALE = 36;
unsigned int32 readCount(void) {
unsigned int32 data;
unsigned int8 j;
output_bit(DT1, 1);
output_bit(SCK, 0);
data = 0;
while (input(DT1));
for (j = 0; j < 24; j++) {
output_bit(SCK, 1);
data = data << 1;
output_bit(SCK, 0);
if (input(DT1)) {
data++;
}
}
output_bit(SCK, 1);
data = data ^ 0x800000;
output_bit(SCK, 0);
return data;
}
int32 readAverage(void) {
unsigned int32 sum = 0;
for (int k = 0; k < 20; k++) {
sum = sum + readCount();
}
sum = sum / 20;
return sum;
}
unsigned int8 count;
unsigned int16 i, distance;
#INT_TIMER0
void timer0_isr(){
count++;
clear_interrupt(INT_TIMER0);
}
int1 wait_sensor(){
i = 0;
set_timer0(0);
count = 0; // Reset Timer0
while(!input(PIN_A1) && (i < 1000))
i = count * 256 + get_timer0();
if(i > 990)
return 0;
else
return 1;
}
unsigned int16 get_distance(){
i = 0;
set_timer0(0);
count = 0;
while(input(PIN_A1) && (i < 25000))
i = count * 256 + get_timer0();
return i;
}
void main() {
lcd_init(); // LCD'yi hazırla
delay_ms(100);
output_a(0);
set_tris_a(2);
clear_interrupt(INT_TIMER0);
enable_interrupts(GLOBAL);
setup_timer_0 (T0_INTERNAL | T0_DIV_2);
unsigned int32 read1 = 0, offset = 0;
float gram = 0;
offset = readAverage();
while (TRUE) {
// Send 10us pulse to HC-SR04 Trigger pin
enable_interrupts(INT_TIMER0);
output_high(PIN_A0);
delay_us(10);
output_low(PIN_A0);
// Read pulse comes from HC-SR04 Echo pin
if(wait_sensor()) {
distance = get_distance();
if(distance > 24990) {
lcd_gotoxy(3, 2); // Go to column 3 row 2
lcd_putc("Out Of Range");
}
else {
distance = i/58; // Calculate the distance
lcd_gotoxy(3, 1); // Go to column 3 row 2
lcd_putc(" cm ");
lcd_gotoxy(6, 1); // Go to column 6 row 2
printf(lcd_putc,"%3Lu",(distance+1)*2);
}
}
delay_ms(100);
disable_interrupts(INT_TIMER0);
read1 = readAverage();
if (offset >= read1) {
float val1 = (offset - read1);
gram = val1;
} else {
float val2 = (read1 - offset);
gram = val2;
}
printf(lcd_putc,"\n%f",gram / SCALE);
// printf(lcd_putc, "\f%f", gram / SCALE);
// printf(lcd_putc, "\f%f", gram);
delay_ms(500);
}
}
its link for download proteus, code and hex
https://easyupload.io/j9b1of