Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.1 kB
4
Indexable
/*
 * Ultrasonic sensor HC-05 interfacing with AVR ATmega16
 * http://www.electronicwings.com
 */ 

#define F_CPU 16000000UL /* CPU to 16Mhz */
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include <string.h>
#include <stdlib.h>

#define  Trigger_pin	PB3	/* Trigger pin */

int TimerOverflow = 0;

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

int main(void)
{
    init();
	char string[10];
	long count;
	double distance;
	
  
	DDRB = 0x7F;		/* Make trigger pin as output */
	PORTD = 0xFF;		/* Turn on Pull-up */
	
	
	sei();			/* Enable global interrupt */
	TIMSK0 = (1 << TOIE1);	/* Enable Timer1 overflow interrupts */
	TCCR1A = 0;		/* Set all bit to zero Normal operation */
    TCCR1B = 0b00000101;
  
	while(1)
	{   
        Serial.begin(9600);
        Serial.println();
        Serial.print("Distance: ");
        Serial.print(distance); 
		/* Give 10us trigger pulse on trig. pin to HC-SR04 */
		
        PORTB |= (1 << Trigger_pin);
		_delay_us(10);
		PORTB &= (~(1 << Trigger_pin));
		
		TCNT1 = 0;	/* Clear Timer counter */
		TCCR1B = 0x41;	/* Capture on rising edge, No prescaler*/
		EIFR = 1<<ICF1;	/* Clear ICP flag (Input Capture flag) */
		EIFR = 1<<TOV1;	/* Clear Timer Overflow flag */

		/*Calculate width of Echo by Input Capture (ICP) */
		
		while ((EIFR & (1 << ICF1)) == 0);/* Wait for rising edge */
        
		TCNT1 = 0;	/* Clear Timer counter */
		TCCR1B = 0x01;	/* Capture on falling edge, No prescaler */
		EIFR = 1<<ICF1;	/* Clear ICP flag (Input Capture flag) */
		EIFR = 1<<TOV1;	/* Clear Timer Overflow flag */
		TimerOverflow = 0;/* Clear Timer overflow count */ 
        
      
		while ((EIFR & (1 << ICF1)) == 0);/* Wait for falling edge */
        
		count = ICR1 + (65535 * TimerOverflow);	/* Take count */
		/* 16MHz 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 */
	}
}