Challenge

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

Code:

#include 
#define F_CPU 16000000ul
#include 
#include 
#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<
	lcd_command_port|= (1<
	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<

Circuit:

output:

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.