Project 2 - Measuring distance of an object using ultrasonic sensor (HC-SR04)
Program:
#include <avr/io.h>
#include "avr/interrupt.h"
#define F_CPU 16000000
#include <util/delay.h>
#define Baudrate 9600
#define UBRR ((F_CPU / (16 * Baudrate)) - 1)
enum status {
ON,
OFF
};
enum status counterStatus = OFF;
uint16_t counterValue = 65000;
void initTriggerPulse()
{
DDRB |= (1<<DDB1);
PORTB |= (1<<PORTB1);
_delay_us(10);
PORTB &= ~(1<<PORTB1);
}
void initTimerSettings()
{
// timer/counter normal mode and ICES1 set to zero to set falling edge as trigger
TCCR1B = 0;
TIFR1 |= (1<<ICF1);
TIMSK1 |= (1 << ICIE1);
sei();
}
void startTimer()
{
TCCR1B |= (1 << CS12);
counterStatus = ON;
}
void stopTimer()
{
TCNT1 = 0;
TCCR1B &= ~(1 << CS12);
counterStatus = OFF;
}
void calculateAndPrintDistance()
{
// pre scale value 256
// speed of sound 343 * 100 cm/s
// ((1 / (F_CPU / 256)) * 343 * 100) / 2 = 0.2744
float distanceInCM = 0.2744 * counterValue;
char str[25];
sprintf(str, "distance: %.2f cm", distanceInCM);
//sprintf(str, "u: %" PRIu16 " ", counterValue);
uartPrintString(str);
}
void Uart_Init()
{
UBRR0H = UBRR >> 8;
UBRR0L = UBRR;
UCSR0B = 1 << TXEN0;
UCSR0C = (1 << UCSZ01) | (1 << UCSZ00);
}
void UartSend(uint8_t data)
{
while (!( UCSR0A & (1<<UDRE0)));
UDR0 = data;
_delay_ms(500);
}
void uartPrintString(char *str)
{
int i = 0;
while (str[i] != '\0') {
UartSend(str[i++]);
}
}
int main(void)
{
initTimerSettings();
initTriggerPulse();
startTimer();
while(1) {
if (counterStatus == OFF) {
calculateAndPrintDistance();
_delay_ms(1000);
initTriggerPulse();
startTimer();
}
}
}
ISR(TIMER1_CAPT_vect) {
counterValue = ICR1;
stopTimer();
}
Output:
