I have a problem with HCSR04 ultrasonic distance sensor. I wrote a code that works perfectly in Proteus simulator but when I upload it in real microchip it stop working properly. Looks like it sticks at one while loop and never get a echo signal. Btw when I'm uploading the code with PicKit that few seconds while code is uploading looks like system is working because led is blinking, after few seconds after upload the system stops and only one led shines without blinking.
#define _XTAL_FREQ 8000000
#include <xc.h>
#include <stdlib.h>
#pragma config FOSC = INTIO67
#pragma config WDTEN = OFF
#pragma config LVP = OFF
#define RB0 PORTBbits.RB0
#define RA1 PORTAbits.RA1
#define RA2 PORTAbits.RA2
#define RA6 PORTAbits.RA6
void delay (unsigned int ms)
{
unsigned int i;
while (ms--) {
for (i = 0; i < 398; i++);
}
}
void main(void) {
float time;
float distance;
OSCCONbits.IRCF2 = 1;
OSCCONbits.IRCF1 = 1;
OSCCONbits.IRCF0 = 0;
ANSELA = 0; //RA0,RA1- analoginis iejimas
ANSELB = 0;
ANSELC = 0;
LATA = 0;
TRISA = 0b00010000;
LATB = 0;
TRISB = 0;
LATC = 0;
TRISC = 0;
T0CON = 0x80; // Konfiguruojamas Timer0
while(1){
TMR0H = 0;
TMR0L = 0;
RB0 = 0; //Trigger 0
__delay_us(2);
RB0 = 1; //TRIGGER 1
__delay_us(10);
RB0 = 0; //TRIGGER 0
while(!PORTAbits.RA4); //Waiting for Echo
TMR0ON = 1;
TMR0=0;
while(PORTAbits.RA4); //Waiting for Echo goes LOW
TMR0ON = 0; //Timer Stops
time = TMR0;
distance = ((float)time/58.82);
distance = distance + 1;
RA2 = 0;
RA1 = 1;
delay(distance);
RA1 = 0;
RA2 = 1;
delay(distance);
}
}