Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

Help with sonar sensor and 8051

Status
Not open for further replies.

NerdyRocker54

Newbie level 4
Joined
Jan 26, 2010
Messages
5
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,281
Activity points
1,326
Hi I'm having trouble interfacing a sonar sensor and the 8051. I've searched around online and read the datasheet and have some code. I understand what needs to be done to implement the sensor but having a hard time getting it to work. It's a 3 pin sonar sensor. I have the signal pin connected to pin 3.2 as it uses interrupt timers that I use to capture the distance. (this is my problem) It is not capturing the distance at all. I created a main to test out the distance (if distance is less than 2 feet turn on LED 1, 2 feet - 4 feet turn on LED 2, etc..)

I've tried connecting it to an O-Scope to see if my input signal is correct and that is also not working. attached is a link to the sensor I'm using as well as code as I have.

Any help would be greatly appreciated. Thank you.

https://www.seeedstudio.com/depot/ultra-sonic-range-measurement-module-p-626.html?cPath=144_149

Code:
	/*
	* sonartest.c
	* When the sonsar function is called, a short pulse of 
	* 8 us is sent to the sonar sensor to trigger it through
	* P3.2, the the UC waits for the sonar to use the provided
	* echo to send an ultrasonic signal that hits the objects
	* within its range and bounces back to the sonar's reciever
	* indicating some object at a certain distance was detected

	* P3.2 which is an interrupt  controlled pin that allows the
	* timers to capture the time when an interrupt happens. 
	* We use such feature along with Timer0 to capture the time
	* from when the sonar sends the ultrasonic signal until it 
	* recieves the boucned back signal
	* then we convert the time captured to distance to find
	* how close is the object from the fan
	*/

#include <reg51rd2.h>
#include <intrins.h>

void delay(unsigned int NumMillisecs);
void sonar();
void InitISR();

// get high order byte from word
#define High(X) ((unsigned char)((X&0xFF00)>>8))
// get low order byte from word
#define Low(X) ((unsigned char)(X&0x00FF))
// 1 millisecond
#define Msec1 64536

// counter for T1 interrupt
volatile unsigned long Ticker;
unsigned int time;
unsigned int distance;
unsigned int temp;
unsigned int d;

sbit sonarO = P3^2;
sbit LED = P1^0;
sbit LED2 = P1^1;
sbit LED3 = P1^2;

void main()
{
	//init the variables once
	distance = 0;
	time = 0;
	temp = 0;
	LED = 0;
	LED2=0;
	LED3=0;
	
	//init the timers
	InitISR();
	
	//loop forever
	while(1)
	{
		//measure the distance
		sonar();

		//if distance is less than or equal 61 cm (2 feet) turn on led 1.
		if (distance <= 61 && distance !=38)
		{
			LED = 1;
			LED2 =0;
			LED3 = 0;
		}
		
		//if distance is less than 122 cm (4 feet) but greater than 61 cm (2ft).
		else if (distance <=122 && distance >61)
		{
			LED =0;
			LED2 = 1;
			LED3 =0;
		}
		
		//if distance is less than 183cm (6ft) bu greater than 122(4ft)
		else if (distance <=183 && distance >122)
		{
			LED = 0;
			LED2 = 0;
			LED3=1;
		}
	}  // end while

}//end main
	
	 void sonar()
	{
		//make the pin as an output to send a short pulse
        sonarO = 0; 
        sonarO = 1;
        
		//wait 10 uS to complete the pulse signal
		//_nop_() when called provies a delay of 1us

        _nop_(); // 1 us
		_nop_(); // 2 us
		_nop_(); // 3 us
		_nop_(); // 4 us
		_nop_(); // 5 us
		_nop_(); // 6 us
		_nop_(); // 7 us
		_nop_(); // 8 us
		_nop_(); // 9 us
		_nop_(); // 10 us
 
		// pulse complete L-H-L
		sonarO = 0;
		//make it input pin to read the pulse width
		sonarO = 1;
		
		//TMOD is set to be gate controlled through P3.2 meaning
		//it starts the timer when it reads an input from the sonar
		
		//Timer0, 16bit gate controlled(P3.2)
        TMOD = 0x09;
		//Reset the timers
		TH0 = 0;
		TL0 = 0;
		//Timer will only run when Pin becomes high.
        TR0 = 1;
        
		//wait till pin is low
		while(!sonarO);
		//when the pin becomes High again
		//means we detected something
		//wait for pulse to finish
        while(sonarO);
        //timer stopped automatically as soon as P3.2 goes low
        //completely stop timer.
		TR0 = 0;
        //the time is caputred in TH0 and TL0
        //convert it to 16 bit in temp then multiply temp by 1.08uS to get the total time traveled
        //divide it by 2 to get the time from sensor to object
        //then convert it to distance
		
        temp = TH0;
		temp = (temp<<8) | TL0;
		time = temp;
				
		/*We first calculate the max distance can be detected by the sonar sensor:
		  max distance = (18.5ms * 340 m/s)/2 = 3.145 m
		  then we use a prescalar in the calculation of the distance we measure... 
		  8 is a good prescalar for those who uses a crystal of 11.059 MHZ ...
		  x = 1 / [(prescalar * max distance)/(frequency * 18.5 ms)] 
		  so distance = time / x ( the 16-bit time capatured from TH0 and TL0)
		  this will give us the distance in meters so to get them in cm, 
		  we divide x by 100 to equal 81.
		  */
		distance = (time / 58); // in centimeter
}
	
	void InitISR()
	{
		Ticker = 0;
		EA = 0;
		TH1 = High(Msec1);
		TL1 = Low(Msec1); // load initial values for timer
		TMOD = (TMOD & 0x0F) | 0x19; // sets timer1 to Mode 1, a 16-bit non-
		//reload, and timer 0 to be gate controlled
		//through P3.2
		ET1 = 1; // enable timer 1 interrupt
		TR1 = 1; // turns on timer 1
		EA = 1; // enable interrupts
	}

	// Programmable Timer 1 Interrupt Service Routine
	void ProgrammableTimer1_ISR() interrupt 3 using 1
	{
		TH1 = High(Msec1); // Reset the clock for next interrupt
		TL1 = Low(Msec1);
		Ticker++; // bump ticker count...
	}

	// delay routine...
	void delay( unsigned int NumMillisecs )
	{
		unsigned long DelayTickValue;
		DelayTickValue = Ticker + NumMillisecs;
		while( Ticker < DelayTickValue );
	}
 

Hello,
I'm not familiar to 8051 ways... ( I just got stunned that you don't need to define pin direction)

this is demo code for arduino at **broken link removed**


Code C - [expand]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/* Ping))) Sensor
 
   This sketch reads a PING))) ultrasonic rangefinder and returns the
   distance to the closest object in range. To do this, it sends a pulse
   to the sensor to initiate a reading, then listens for a pulse 
   to return.  The length of the returning pulse is proportional to 
   the distance of the object from the sensor.
 
   The circuit:
    * +V connection of the PING))) attached to +5V
    * GND connection of the PING))) attached to ground
    * SIG connection of the PING))) attached to digital pin 7
 
   [url]https://www.arduino.cc/en/Tutorial/Ping[/url]
 
   created 3 Nov 2008
   by David A. Mellis
   modified 30 Jun 2009
   by Tom Igoe
 
   This example code is in the public domain.
 
 */
 
// this constant won't change.  It's the pin number
// of the sensor's output:
const int pingPin = 7;
 
void setup() {
  // initialize serial communication:
  Serial.begin(9600);
}
 
void loop()
{
  // establish variables for duration of the ping, 
  // and the distance result in inches and centimeters:
  long duration, inches, cm;
 
  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);
 
  // The same pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);
 
  // convert the time into a distance
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);
 
  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
 
  delay(100);
}
 
long microsecondsToInches(long microseconds)
{
  // According to Parallax's datasheet for the PING))), there are
  // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
  // second).  This gives the distance travelled by the ping, outbound
  // and return, so we divide by 2 to get the distance of the obstacle.
  // See: **broken link removed**
  return microseconds / 74 / 2;
}
 
long microsecondsToCentimeters(long microseconds)
{
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the
  // object we take half of the distance travelled.
  return microseconds / 29 / 2;
}





Any way, my attention goes here...

Code:
//make the pin as an output to send a short pulse
        sonarO = 0; 

[B]        //a delay between transitions as in the 2 micro seconds example in sparkfun wiki
        _nop_(); // 1 us
        _nop_(); // 2 us[/B]
        sonarO = 1;
        
		//wait 10 uS to complete the pulse signal
		//_nop_() when called provies a delay of 1us

                _nop_(); // 1 us
		_nop_(); // 2 us
		_nop_(); // 3 us
		_nop_(); // 4 us
		_nop_(); // 5 us
		_nop_(); // 6 us
		_nop_(); // 7 us
		_nop_(); // 8 us
		_nop_(); // 9 us
		_nop_(); // 10 us
 
		// pulse complete L-H-L
		sonarO = 0;
[B]		//make it input pin to read the pulse width
		sonarO = 1; // -I don't understand this line... I would remove it if not needed because i think that it is interacting with the while loop[/B]
		
		//TMOD is set to be gate controlled through P3.2 meaning
		//it starts the timer when it reads an input from the sonar
		
		//Timer0, 16bit gate controlled(P3.2)
        TMOD = 0x09;
		//Reset the timers
		TH0 = 0;
		TL0 = 0;
		//Timer will only run when Pin becomes high.
        TR0 = 1;
        
        
         
[B]		//wait till pin is low
		while(!sonarO);
		//when the pin becomes High again
		//means we detected something
		//wait for pulse to finish
        while(sonarO);[/B]
 

Ok so I got it working as it should. Only thing is now it's not always reading. I have it in the while(1) loop but every time i want to recapture new distance data I have to hit the reset button on the 8051. In other words it's not always reading data, only when the program starts. attached below is the revised code.

I need to get it always reading the sensor data. Thank you in advanced.

Code:
	/*
	* sonartest.c
	* When the sonsar function is called, a short pulse of 
	* 8 us is sent to the sonar sensor to trigger it through
	* P3.2, the the UC waits for the sonar to use the provided
	* echo to send an ultrasonic signal that hits the objects
	* within its range and bounces back to the sonar's reciever
	* indicating some object at a certain distance was detected

	* P3.2 which is an interrupt  controlled pin that allows the
	* timers to capture the time when an interrupt happens. 
	* We use such feature along with Timer0 to capture the time
	* from when the sonar sends the ultrasonic signal until it 
	* recieves the boucned back signal
	* then we convert the time captured to distance to find
	* how close is the object from the fan
	*/

#include <reg51rd2.h>

//function declarations
void sonar();
void initT();

unsigned int time;
unsigned int distance;
unsigned int temp;
unsigned int d;

sbit LED = P1^0;
sbit LED2 = P1^1;
sbit LED3 = P1^2;

void main()
{
	//init the variables once
	distance = 0;
	time = 0;
	temp = 0;
	//d=0;
	LED=0;
	LED2=0;
	LED3=0;
	
	//init the timers
	initT();
	
	//loop forever
	while(1)
	{	  
		//measure the distance
		sonar();

		//if distance is less than or equal 61 cm (2 feet) turn on led 1.
		if (distance <= 61 && distance !=38)
		{
			LED = 1;
			LED2 =0;
			LED3 = 0;
		}
		
		//if distance is less than 122 cm (4 feet) but greater than 61 cm (2ft).
		else if (distance <=122 && distance >61)
		{
			LED =0;
			LED2 = 1;
			LED3 =0;
		}
		
		//if distance is less than 183cm (6ft) bu greater than 122(4ft)
		else if (distance <=183 && distance >122)
		{
			LED = 0;
			LED2 = 0;
			LED3=1;
		}
	}  // end while

}//end main

void initT()
{	// sets timer1 to Mode 1, a 16-bit non-
	//reload, and timer 0 to be gate controlled
	//through P3.2
	TMOD = (TMOD & 0x0F) | 0x19; 

}



	/*
	* ultrasonic.c
	* When the sonsar function is called, a short pulse of 
	* 8 us is sent to the sonar sensor to trigger it through
	* P3.2, the the UC waits for the sonar to use the provided
	* echo to send an ultrasonic signal that hits the objects
	* within its range and bounces back to the sonar's reciever
	* indicating some object at a certain distance was detected

	* P3.2 which is an interrupt  controlled pin that allows the
	* timers to capture the time when an interrupt happens. 
	* We use such feature along with Timer0 to capture the time
	* from when the sonar sends the ultrasonic signal until it 
	* recieves the boucned back signal
	* then we convert the time captured to distance to find
	* how close is the object from the fan
	*/

	#include <reg51rd2.h>
	#include <intrins.h>

	//INT0 P3.2	 0xB2
	sbit sonarO = 0xB2;

	//variables used
	
	extern unsigned int distance;
	extern unsigned int temp;
	extern unsigned int time;
	extern unsigned int d;

	void sonar()
	{
		// make the pin as an output to send a short pulse
		// for 2us to give a clean 0
		sonarO = 0;
		_nop_(); // 1 us
		_nop_(); // 2 us
		
		//wait 10uS to complete the pulse signal
		//_nop_() when called provies a delay of 1us
		sonarO = 1;
		_nop_(); // 1 us
		_nop_(); // 2 us
		_nop_(); // 3 us
		_nop_(); // 4 us
		_nop_(); // 5 us
		_nop_(); // 6 us
		_nop_(); // 7 us
		_nop_(); // 8 us
		_nop_(); // 9 us
		_nop_(); // 10 us

		// pulse complete L-H-L  ___|----------|_____
		sonarO = 0;
		_nop_();
		
		//make it input pin to read the pulse width
		sonarO = 1;
			
		//TMOD is set to be gate controlled through P3.2 meaning
		//it starts the timer when it reads an input from the sonar
			
		//Timer0, 16bit gate controlled(P3.2)
		//TMOD = 0x09;
		//Reset the timers
		TH0 = 0;
		TL0 = 0;
		//Timer will only run when Pin becomes high.
		TR0 = 1;
		   
		//wait till pin is low
		while(!sonarO);
		
		//when the pin becomes High again
		//means we detected something
		//wait for pulse to finish
		while(sonarO);
		
		//timer stopped automatically as soon as P3.2 goes low
		//completely stop timer.
		TR0 = 0;
		//the time is caputred in TH0 and TL0
		//convert it to 16 bit in temp 
		//then convert it to distance
			
		   temp = TH0;
		   time = (temp<<8) | TL0;
			
			/*We first calculate the max distance can be detected by the sonar sensor:
			  max distance = (18.5ms * 340 m/s)/2 = 3.145 m
			  then we use a prescalar in the calculation of the distance we measure... 
			  8 is a good prescalar for those who uses a crystal of 11.059 MHZ ...
			  x = 1 / [(prescalar * max distance)/(frequency * 18.5 ms)] 
			  so distance = time / x ( the 16-bit time capatured from TH0 and TL0)
			  this will give us the distance in meters so to get them in cm, 
			  we divide x by 100 to equal 81.
			  then in our code
			  */
			distance = (time / 58); // in centimeter
	}
 

The recommend cycle period should be no less than 50ms.. add a delay at the end of the reading so that you can wait enough before next cycle
 

thanks to mgate and again after re-reading the data sheet I have added a 50 ms delay after it captures the distance data. But it's still not looping.
Again i think it might be that I'm using timer0mode1 gate controlled (for the time counter for the sonar) and now timer1mode1 for the 50 ms delay. I added a toggle to LED7 to see it if gets in the delay function. it toggles but then it crashes... Please help. thank you for your time. attached is current code.

Code:
   /*
	* sonar.c
	* When the sonsar function is called, a short pulse of 
	* 8 us is sent to the sonar sensor to trigger it through
	* P3.2, the the UC waits for the sonar to use the provided
	* echo to send an ultrasonic signal that hits the objects
	* within its range and bounces back to the sonar's reciever
	* indicating some object at a certain distance was detected

	* P3.2 which is an interrupt  controlled pin that allows the
	* timers to capture the time when an interrupt happens. 
	* We use such feature along with Timer0 to capture the time
	* from when the sonar sends the ultrasonic signal until it 
	* recieves the boucned back signal
	* then we convert the time captured to distance to find
	* how close is the object from the fan
	*/

	#include <reg51rd2.h>
	#include <intrins.h>

	void delay();
//	voidISR();

	//INT0 P3.2	 0xB2
	sbit sonar0 = 0xB2;

	sbit LED0 = P1^0;
	sbit LED1 = P1^1;
	sbit LED2 = P1^2;


	//variables used
	
	 extern unsigned int distance;
	 extern unsigned int temp;
	 extern unsigned int time;
	 int i;

	void sonar()
	{	 
		// make the pin as an output to send a short pulse
		// for 10us to give a clean 0
		sonar0 = 0;
		_nop_(); // 1 us
		_nop_(); // 2 us
		_nop_();
		_nop_(); 
		_nop_(); 
		_nop_();
		_nop_(); 
		_nop_(); 
		_nop_();
		_nop_(); 
				
		//wait 10uS to complete the pulse signal
		//_nop_() when called provies a delay of 1us
		sonar0 = 1;
		_nop_(); // 1 us
		_nop_(); // 2 us
		_nop_(); // 3 us
		_nop_(); // 4 us
		_nop_(); // 5 us
		_nop_(); // 6 us
		_nop_(); // 7 us
		_nop_(); // 8 us
		_nop_(); // 9 us
		_nop_(); // 10 us


		// pulse complete L-H-L  ___|----------|_____
		sonar0 = 0;
		
		//make it input pin to read the pulse width
		sonar0 = 1;

		//TMOD is set to be gate controlled through P3.2 meaning
		//it starts the timer when it reads an input from the sonar
		TMOD = 0x09;
		//Reset the timers
		TH0 = 0x00;
		TL0 = 0x00;
		//Timer will only run when Pin becomes high.
		TR0 = 1;
		   
		//wait till pin is low
		while(!sonar0);
		
		//when the pin becomes High again
		//means we detected something
		//wait for pulse to finish
		while(sonar0);
		
		//timer stopped automatically as soon as P3.2 goes low
		//completely stop timer.
		TR0 = 0;
		//the time is caputred in TH0 and TL0
		//convert it to 16 bit in temp 
		//then convert it to distance
			
		   temp = TH0;
		   time = (temp<<8) | TL0;
			
			/*We first calculate the max distance can be detected by the sonar sensor:
			  max distance = (18.5ms * 340 m/s)/2 = 3.145 m
			  then we use a prescalar in the calculation of the distance we measure... 
			  8 is a good prescalar for those who uses a crystal of 11.059 MHZ ...
			  x = 1 / [(prescalar * max distance)/(frequency * 18.5 ms)] 
			  so distance = time / x ( the 16-bit time capatured from TH0 and TL0)
			  this will give us the distance in meters so to get them in cm, 
			  we divide x by 100 to equal 81.
			  then in our code
			  */
			distance = (time / 58); // in centimeter


	}


	void delay()
	{  /* To calculate the bucket 50/1.085 = 4608
		* 65536-4608 = 60928 in decimal = EE00H
		* TL=00 & TH=EE
		* in case 50 ms delay doesnt work use 51 ms
		* TL=A4 & TH=ED

		* book values
		TL=FD TH=4B
		
		*/
		LED7=~LED7;
	   	TMOD=0x10;      //Timer 1, mode 1 (16 bit) 
	   	TL1=0xFD;		//load TL1
	   	TH1=0x4B;		//load TH1
	   	TR1=1;			//turn on T1
	   	while(TF1==0);	//wait for TF1 to roll over
	   	TR1=0;			//turn off T1;
	   	TF1=0;
	}

//	void initISR()
//	{
//		EA = 0;
//		//TMOD = 0x09; //timer 0 to be gate controlled
//		//through P3.2
//		ET0 = 1; // enable timer 1 interrupt
//	//	TR0 = 1; // turns on timer 1
//		EA = 1; // enable interrupts
//	}

//main.c

#include <reg51rd2.h>


 void delay();
 void sonar();
 void initISR();

 unsigned int time;
 unsigned int distance;
 unsigned int temp;

 sbit LED0=P1^0;
 sbit LED1=P1^1;
 sbit LED2=P1^2;

 void main()
 {
 	//init the variables once
	distance =0;
	time =0;
	temp = 0;

	//init the timers
//	initISR();

	//loop forever
	while(1)
	{
		sonar();

		//if distance is less than or equal 61 cm (2 feet) turn on led 1.
			if (distance <= 61 && distance !=38)
			{
				LED0 = 1;
				LED1 = 0;
				LED2 = 0;
			}
			
			//if distance is less than 122 cm (4 feet) but greater than 61 cm (2ft).
			else if (distance <=122 && distance >61)
			{
				LED0 = 0;
				LED1 = 1;
				LED2 = 0;
			}
			
						//if distance is less than 183cm (6ft) bu greater than 122(4ft)
			else if (distance <=183 && distance >122)
			{
				LED0 = 0;
				LED1 = 0;
				LED2 = 1;
			}
			//nothing found
			else
			{ 
				LED0=1;
				LED1=0;
				LED2=1;
			}
		}  // end while

}//end main
 

I think your code is messy, you should post the files on different code tags (looks like two files)...

.... also I don't see any call to the sub delay()... and I'm surprised that you can see the Led toging as it should be toggling really fast (about 80ms if the program is running well)...

You need method... I can give a few suggestions

You need to Isolate the problem in order to know it. Only then you will be able to solve it! So:
Make sure that the timer delay function is working properly.. in order to do that, reduce the complexity by no calling the sonar() sub... Also you need to make sure that the led toggling speed will not interfere in your validation process of the delay sub. I suggest something like:
Code:
while(1)
{
       for(int i=0; i<200;i++) delay();
        
       LED7=~LED7;
}
.....................
.....................
void delay()
	{  /* To calculate the bucket 50/1.085 = 4608
		* 65536-4608 = 60928 in decimal = EE00H
		* TL=00 & TH=EE
		* in case 50 ms delay doesnt work use 51 ms
		* TL=A4 & TH=ED

		* book values
		TL=FD TH=4B
		
		*/
		//LED7=~LED7;
	   	TMOD=0x10;      //Timer 1, mode 1 (16 bit) 
	   	TL1=0xFD;		//load TL1
	   	TH1=0x4B;		//load TH1
	   	TR1=1;			//turn on T1
	   	while(TF1==0);	//wait for TF1 to roll over
	   	TR1=0;			//turn off T1;
	   	TF1=0;
	}

this way the led will be toggling close to 1 second interval... after check this, you will have sure that the delay sub is not the problem, and you can use it carefully

next, use the led7 toggling to check if your code is running, i mean if is not getting stuck at sonar(),... so use 1 second delay before calling sonar an toggle the led ... you can easily do that in your code...
Code:
while(1)
{
   .....
       for(int i=0; i<200;i++) delay();
       LED7=~LED7;

       sonar();

...................
}

if sonar() is not crashing then you will only need to check the communication protocol..

whatever the problem is, after isolated is possible to work on it ...

I hope it helps..
 

I think your code is messy, you should post the files on different code tags (looks like two files)...

.... also I don't see any call to the sub delay()... and I'm surprised that you can see the Led toging as it should be toggling really fast (about 80ms if the program is running well)...

You need method... I can give a few suggestions

You need to Isolate the problem in order to know it. Only then you will be able to solve it! So:
Make sure that the timer delay function is working properly.. in order to do that, reduce the complexity by no calling the sonar() sub... Also you need to make sure that the led toggling speed will not interfere in your validation process of the delay sub. I suggest something like:
Code:
while(1)
{
       for(int i=0; i<200;i++) delay();
        
       LED7=~LED7;
}
.....................
.....................
void delay()
	{  /* To calculate the bucket 50/1.085 = 4608
		* 65536-4608 = 60928 in decimal = EE00H
		* TL=00 & TH=EE
		* in case 50 ms delay doesnt work use 51 ms
		* TL=A4 & TH=ED

		* book values
		TL=FD TH=4B
		
		*/
		//LED7=~LED7;
	   	TMOD=0x10;      //Timer 1, mode 1 (16 bit) 
	   	TL1=0xFD;		//load TL1
	   	TH1=0x4B;		//load TH1
	   	TR1=1;			//turn on T1
	   	while(TF1==0);	//wait for TF1 to roll over
	   	TR1=0;			//turn off T1;
	   	TF1=0;
	}

this way the led will be toggling close to 1 second interval... after check this, you will have sure that the delay sub is not the problem, and you can use it carefully

next, use the led7 toggling to check if your code is running, i mean if is not getting stuck at sonar(),... so use 1 second delay before calling sonar an toggle the led ... you can easily do that in your code...
Code:
while(1)
{
   .....
       for(int i=0; i<200;i++) delay();
       LED7=~LED7;

       sonar();

...................
}

if sonar() is not crashing then you will only need to check the communication protocol..

whatever the problem is, after isolated is possible to work on it ...

I hope it helps..

I tested the delay with the LED and the delay works. I than added the sonar() function and after 1 second the LED doesnt go back on. So the error has to be in the sonar function.
 

So its getting stuck at one of those whiles... I suggest you Put a activation between those two whiles to see on witch is getting stuck

Code:
........................................................
 	        _nop_(); // 10 us
 
		// pulse complete L-H-L
		sonarO = 0;
		//make it input pin to read the pulse width
		sonarO = 1;
		
		//TMOD is set to be gate controlled through P3.2 meaning
		//it starts the timer when it reads an input from the sonar
		
		//Timer0, 16bit gate controlled(P3.2)
        TMOD = 0x09;
		//Reset the timers
		TH0 = 0;
		TL0 = 0;
		//Timer will only run when Pin becomes high.
        TR0 = 1;
        
		//wait till pin is low
	[B]	while(!sonarO);[/B]
		//when the pin becomes High again
		//means we detected something
		//wait for pulse to finish
        [B]while(sonarO);[/B]
 

Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top