Challenge

Measuring distance of an object using ultrasonic sensor (HC-SR04)

Aim:

To implement code for “Measuring distance of an object using ultrasonic distance sensor (HC-SR04).

Objective:

  • Measuring the distance of an object using Ultrasonic Distance Sensor (HC-SR04)
  • Usage of Input Capture Mode

Highlights:

  • Measuring the distance travelled by the wave to the object and gets bounced back from the object to sensor.
  • Measuring Pulse width using Input Capture Mode

Deliverables:

  • The distance travelled by a wave to the object for which we want to measure the distance using Ultrasonic Distance Sensor (HC-SR04).
  • Measuring Pulse width using Input Capture Mode of Timer 1

Code:

#include <avr/io.h>
#define F_CPU 16000000ul
#include <util/delay.h>
#include <avr/interrupt.h>
#include 
#include 


#define lcd_data_dir DDRD         
#define lcd_command_dir DDRC      
#define lcd_data_port PORTD       
#define lcd_command_port PORTC      
#define EN PC2                      
#define RW PC3                       
#define RS PC4                      

void lcd_command(char);                     
void lcd_char(char);                        
void lcd_init(void);                         
void lcd_string(char*);                   
void lcd_string_xy (char,char,char*);          

void lcd_command (char cmd)                    
{
	lcd_data_port = cmd;                          
	lcd_command_port&=~((1<<RS)|(1<<RW));                   
	lcd_command_port|= (1<<EN);                         
	_delay_ms(1);
	lcd_command_port&=~(1<<EN);
	_delay_ms(2);                                   
	
}
void lcd_char(char char_data)                     
{
	lcd_data_port= char_data;                       
	lcd_command_port&=~(1<<RW);                     
	lcd_command_port|=((1<<EN)|(1<<RS));            
	_delay_ms(1);
	lcd_command_port&=~(1<<EN);
	_delay_ms(1);
}
void lcd_init(void)                               
{
	lcd_command_dir|= (1<<RS)|(1<<RW)|(1<<EN);              
	lcd_data_dir = 0xff;                                     
	
	_delay_ms(20);                            
	lcd_command(0x38);                        
	lcd_command(0x0C);                      
	lcd_command(0x06);                      
	lcd_command(0x01);                      
	lcd_command(0x80);                     
}
void lcd_string(char *str)             

	int i;
	for(i=0;str[i]!=0;i++)            
	{
		lcd_char (str[i]);               
	}
	
}
void lcd_string_xy(char row,char pos,char *str)             
{
	if (row == 1)
	lcd_command((pos & 0x0f)|0x80);
	else if (row == 2)
	lcd_command((pos & 0x0f)|(0xC0));
	lcd_string(str);                        
}
#define trigger_pin PA0                     
int TimerOverFlow = 0;
ISR(TIMER1_OVF_vect)
{
	TimerOverFlow++;                      
}
int main (void)
{
	char string[10];
	long count;
	double distance;
	
	DDRA = 0x01;                           
	PORTB = 0xff;                         
	
	lcd_init();
	lcd_string_xy(1,0,"ultrasonic");
	
	sei();                                
	TIMSK = (1<< TOIE1);                 
	TCCR1A = 0;                           
	
	while(1)
	{
		PORTA |= (1<< trigger_pin);
		_delay_ms(10);
		PORTA &=(~(1<< trigger_pin));
		
		TCNT1 = 0;                             
		TCCR1B = 0x41;                          
		TIFR = 1<<ICF1;                           
		TIFR = 1<<TOV1;                          
		
		
		while ((TIFR & (1<<ICF1)) == 0);                
		TCNT1 = 0;                                     
		TCCR1B = 0x01;                                 
		TIFR = 1<<ICF1;                               
		TIFR = 1<<TOV1;                                
		TimerOverFlow = 0;                               
		
		while ((TIFR & (1<< ICF1))== 0);                         
		count = ICR1 +(65535 * TimerOverFlow);              
		distance = (double)count/466.47;
		
		dtostrf(distance,2,2,string);                      
		strcat(string,"cm");                             
		lcd_string_xy(2,0,"dist= ");
		lcd_string_xy(2,7,string);                     
		_delay_ms(200);
	}
}

Program:

#define F_CPU 8000000UL
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include 
#include 

#define LCD_Data_Dir DDRD /* Define LCD data port direction */
#define LCD_Command_Dir DDRC /* Define LCD command port direction register */
#define LCD_Data_Port PORTD /* Define LCD data port */
#define LCD_Command_Port PORTC /* Define LCD data port */
#define EN PC2 /* Define Enable signal pin */
#define RW PC3 /* Define Read/Write signal pin */
#define RS PC4 /* Define Register Select (data reg./command reg.) signal pin */

void LCD_Command (char); /* LCD command write function */
void LCD_Char (char); /* LCD data write function */
void LCD_Init (void); /* LCD Initialize function */
void LCD_String (char*); /* Send string to LCD function */
void LCD_String_xy (char,char,char*); /* Send row, position and string to LCD function */

void LCD_Command (char cmd) /* LCD command write function */
{
LCD_Data_Port = cmd; /* Write command data to LCD data port */
LCD_Command_Port &= ~((1<<RS)|(1<<RW)); /* Make RS LOW (command reg.), RW LOW (Write) */
LCD_Command_Port |= (1<<EN); /* High to Low transition on EN (Enable) */
_delay_us(1);
LCD_Command_Port &= ~(1<<EN);
_delay_ms(3); /* Wait little bit */
}

void LCD_Char (char char_data) /* LCD data write function */
{
LCD_Data_Port = char_data; /* Write data to LCD data port */
LCD_Command_Port &= ~(1<<RW); /* Make RW LOW (Write) */
LCD_Command_Port |= (1<<EN)|(1<<RS); /* Make RS HIGH (data reg.) and High to Low transition on EN (Enable) */
_delay_us(1);
LCD_Command_Port &= ~(1<<EN);
_delay_ms(1); /* Wait little bit */
}

void LCD_Init (void) /* LCD Initialize function */
{
LCD_Command_Dir |= (1<<RS)|(1<<RW)|(1<<EN); /* Make LCD command port direction as o/p */
LCD_Data_Dir = 0xFF; /* Make LCD data port direction as o/p */

_delay_ms(20); /* LCD power up time to get things ready, it should always >15ms */
LCD_Command (0x38); /* Initialize 16X2 LCD in 8bit mode */
LCD_Command (0x0C); /* Display ON, Cursor OFF command */
LCD_Command (0x06); /* Auto Increment cursor */
LCD_Command (0x01); /* Clear LCD command */
LCD_Command (0x80); /* 8 is for first line and 0 is for 0th position */
}

void LCD_String (char *str) /* Send string to LCD function */
{
int i;
for(i=0;str[i]!=0;i++) /* Send each char of string till the NULL */
{
LCD_Char (str[i]); /* Call LCD data write */
}
}

void LCD_String_xy (char row, char pos, char *str) /* Send string to LCD function */
{
if (row == 1)
LCD_Command((pos & 0x0F)|0x80); /* Command of first row and required position<16 */
else if (row == 2)
LCD_Command((pos & 0x0F)|0xC0); /* Command of Second row and required position<16 */
LCD_String(str); /* Call LCD string function */
}
#define Trigger_pin PA0 /* Trigger pin */

int TimerOverflow = 0;

ISR(TIMER1_OVF_vect)
{
TimerOverflow++; /* Increment Timer Overflow count */
}

int main(void)
{
char string[10];
long count;
double distance;

DDRA = 0x01; /* Make trigger pin as output */
PORTB = 0xFF; /* Turn on Pull-up */

LCD_Init();
LCD_String_xy(1, 0, "Ultrasonic");

sei(); /* Enable global interrupt */
TIMSK = (1 << TOIE1); /* Enable Timer1 overflow interrupts */
TCCR1A = 0; /* Set all bit to zero Normal operation */

while(1)
{
/* Give 10us trigger pulse on trig. pin to HC-SR04 */
PORTA |= (1 << Trigger_pin);
_delay_us(10);
PORTA &= (~(1 << Trigger_pin));

TCNT1 = 0; /* Clear Timer counter */
TCCR1B = 0x41; /* Capture on rising edge, No prescaler*/
TIFR = 1<<ICF1; /* Clear ICP flag (Input Capture flag) */
TIFR = 1<<TOV1; /* Clear Timer Overflow flag */

/*Calculate width of Echo by Input Capture (ICP) */

while ((TIFR & (1 << ICF1)) == 0);/* Wait for rising edge */
TCNT1 = 0; /* Clear Timer counter */
TCCR1B = 0x01; /* Capture on falling edge, No prescaler */
TIFR = 1<<ICF1; /* Clear ICP flag (Input Capture flag) */
TIFR = 1<<TOV1; /* Clear Timer Overflow flag */
TimerOverflow = 0; /* Clear Timer overflow count */

while ((TIFR & (1 << ICF1)) == 0); /* Wait for falling edge */
count = ICR1 + (65535 * TimerOverflow); /* Take count */
/* 8MHz Timer freq, sound speed =343 m/s */
distance = (double)count / 466.47;

dtostrf(distance, 2, 2, string);/* distance to string */
strcat(string, " cm "); /* Concat unit i.e.cm */
LCD_String_xy(2, 0, "Dist = ");
LCD_String_xy(2, 7, string); /* Print distance */
_delay_ms(200);
}
}

Circuit:

  • The program is loaded in the Atmega 32 chip.
  • LCD pins are connected to the Atmega32 as shown above.
  • Osillocope and ultrasonic sensors are connected to view the output.

Output:

OUTPUT:

1.Input Pulse: High , Time Delay : 10 micro seconds , Distance :85.12 cm

2.

  • 60.38 cm is the distance of an object obtained.

Result:

Thus the implementation of code for “Measuring distance of an object using ultrasonic distance sensor (HC-SR04) is done.

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.