-
Notifications
You must be signed in to change notification settings - Fork 0
/
temp.c
60 lines (59 loc) · 2 KB
/
temp.c
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
/*
* Ultrasonic sensor HC-05 interfacing with AVR ATmega16
* http://www.electronicwings.com
*/
#dene F_CPU 8000000UL
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include <string.h>
#include <stdlib.h>
#include "LCD_16x2_H_le.h" /* Include LCD header le */
#dene Trigger_pin PA0 /* Trigger pin */
int TimerOverflow = 0;
ISR(TIMER1_OVF_vect)
{
TimerOverflow++; /* Increment Timer Overow count */
}
int main(void)
{
char string[10];
long count;
double distance;
DDRA = 0x01; /* Make trigger pin as output */
PORTD = 0xFF; /* Turn on Pull-up */
LCD_Init();
LCD_String_xy(1, 0, "Ultrasonic");
sei(); /* Enable global interrupt */
TIMSK = (1 << TOIE1); /* Enable Timer1 overow 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 ag (Input Capture ag) */
TIFR = 1 << TOV1; /* Clear Timer Overow ag */
/*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 ag (Input Capture ag) */
TIFR = 1 << TOV1; /* Clear Timer Overow ag */
TimerOverflow = 0; /* Clear Timer overow 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);
}
}