Challenge

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

#define F_CPU 16000000UL // 16 MHz clock frequency

#include <avr/io.h>

#include <util/delay.h>

#include <avr/interrupt.h>

#include <stdio.h>

// Define pins

#define TRIG_PIN PD2

#define ECHO_PIN PD3

void USART_Init(unsigned int ubrr) {

// Set baud rate

UBRR0H = (unsigned char)(ubrr>>8);

UBRR0L = (unsigned char)ubrr;

// Enable receiver and transmitter

UCSR0B = (1 << RXEN0) | (1 << TXEN0);

// Set frame format: 8 data bits, 1 stop bit

UCSR0C = (1 << UCSZ01) | (1 << UCSZ00);

}

void USART_Transmit(unsigned char data) {

// Wait for empty transmit buffer

while (!(UCSR0A & (1 << UDRE0)));

// Put data into buffer, sends the data

UDR0 = data;

}

void USART_SendString(const char *str) {

while (*str) {

USART_Transmit(*str++);

}

}

unsigned char USART_Receive(void) {

// Wait for data to be received

while (!(UCSR0A & (1 << RXC0)));

// Get and return received data from buffer

return UDR0;

}

void init_hcsr04() {

// Set Trig pin as output and Echo pin as input

DDRD |= (1 << TRIG_PIN);

DDRD &= ~(1 << ECHO_PIN);

}

void send_trigger_pulse() {

// Send 10us pulse on Trig pin

PORTD &= ~(1 << TRIG_PIN); // Set Trig pin low

_delay_us(2);

PORTD |= (1 << TRIG_PIN); // Set Trig pin high

_delay_us(10); // Wait for 10 microseconds

PORTD &= ~(1 << TRIG_PIN); // Set Trig pin low

}

uint16_t measure_distance() {

uint16_t count = 0;

// Wait for Echo pin to go high

while (!(PIND & (1 << ECHO_PIN)));

// Measure the length of the Echo high pulse

while (PIND & (1 << ECHO_PIN)) {

count++;

_delay_us(1);

}

// Calculate distance in cm (speed of sound = 34300 cm/s)

// Distance = (Echo pulse width in us) / 58

return (count / 58);

}

int main(void) {

// Initialize USART with baud rate 9600

USART_Init(103); // 16 MHz / (16 * 9600) - 1 = 103

// Initialize HC-SR04

init_hcsr04();

char buffer[10];

while (1) {

send_trigger_pulse();

_delay_ms(60); // Wait for the echo pulse to complete

uint16_t distance = measure_distance();

// Send distance to serial monitor

snprintf(buffer, sizeof(buffer), "%d cm\r\n", distance);

USART_SendString(buffer);

_delay_ms(500);

}

return 0;

}

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.