[SOLVED] Something's wrong with my while loops

General discussion on mikroC PRO for PIC.
Post Reply
Author
Message
Kitsune_W
Posts: 3
Joined: 25 Jun 2022 04:45

[SOLVED] Something's wrong with my while loops

#1 Post by Kitsune_W » 25 Jun 2022 04:57

Excuse my english in advance. So I'm trying to interface an ultrasonic sensor with a PIC16F873A using mikroC, for which I have to use Timer1 module to measure the time it takes the sound to return to the sensor since it gets triggered, I wrote this code, I commented the lines that makes the math to covert the time to a distance in centimeters but I noticed the while loops make the PIC freeze, so the trigger pulses only once and then does nothing until I reset my simulation, I hope someone can help me.

Code: Select all

sbit ECHO at PORTA.B2;
sbit TR at PORTA.B3; //Declare bits
sbit LED at PORTA.B4;

unsigned int E_dist_us; //Distance variable

void main() {

INTCON = 0;
TRISA = 0x27;
TRISB = 0;
T1CON = 0;
PORTA = 0;
PORTB = 0;

E_dist_us = 0;

TMR1L = 0;
TMR1H = 0;
LED = 1;
delay_ms(100);

while(1){

TR = 1;
delay_us(100);
TR = 0;

while(ECHO == 0);     //Wait for the ECHO pin go high
TMR1ON_bit = 1;       //Start TIMER1
while(ECHO == 1);     // Wait for the ECHO pin go low
TMR1ON_bit = 0;       //Stop TIMER1

/*E_dist_us = (TMR1L + (TMR1H << 8));

E_dist_us = E_dist_us / 58.82;   */

/*if(E_dist_us <= 10) {
LED = 0;
}

else {
LED = 1;
}   */

PORTB = TMR1L;

delay_ms(1000);

TMR1L = 0;      //Reset the count of the timer
TMR1H = 0;

}
}
Last edited by Kitsune_W on 30 Jun 2022 04:25, edited 1 time in total.

User avatar
filip
mikroElektronika team
Posts: 11874
Joined: 25 Jan 2008 09:56

Re: Something's wrong with my while loops

#2 Post by filip » 28 Jun 2022 12:56

Hi,

Can you debug the code step by step and see where the issue is ?

Regards,
Filip.

Kitsune_W
Posts: 3
Joined: 25 Jun 2022 04:45

Re: Something's wrong with my while loops

#3 Post by Kitsune_W » 30 Jun 2022 04:13

Ji,

I debugged it and code seems just fine, "while(!ECHO);" waits till the pin goes high and then jumps into the next line as expected, and then "while(ECHO);" waits for the pin going high. The thing is when I compile the code and load the hex file to my circuit or even in simulation it doesn't work at all. All it does it fires the trigger pin once and then stays forever doing nothing else. As a matter of fact I wrote same main function on XC8 and worked just fine, so I'm thinking this is a compiler issue.

Regards.

Kitsune_W
Posts: 3
Joined: 25 Jun 2022 04:45

Re: Something's wrong with my while loops

#4 Post by Kitsune_W » 30 Jun 2022 04:24

Hi again,

This is bery embarassing, but somehow after debbuging, compiling and loading it works now. Anyways, I appreciate the time and help, I feel so sorry about this lol.

Regards

Post Reply

Return to “mikroC PRO for PIC General”