Project 2 - Measuring distance of an object using ultrasonic sensor (HC-SR04)
Project 2 - Measuring distance of an object using ultrasonic sensor (HC-SR04)
- Overview of the Project:
In this project, the implementation of code for “Measuring distance of an object using ultrasonic distance sensor (HC-SR04)
- Goals:
- Measuring the distance of an object using Ultrasonic Distance Sensor (HC-SR04)
- Usage of Input Capture Mode
- Key Highlights of the Project:
- Measuring the distance travelled by the wave to the object and gets bounced back from the object to sensor.
- Measuring Pulse width using Input Capture Mode
- Deliverables of this project:
- The distance travelled by a wave to the object for which we want to measure the distance using Ultrasonic Distance Sensor (HC-SR04).
- Measuring Pulse width using Input Capture Mode of Timer 1
- Expected Outcomes:
The students will get the Knowledge on Ultrasonic sensor (HC-SR04) to measure the distance travelled by wave to the object, the hardware connection of Atmega328p and HC-SR04 and how to use input capture mode of Timer1
Title: Measuring Distance Using Ultrasonic Distance Sensor (HC-SR04) with AVR Microcontroller and UART Communication
Aim:
The aim of this project is to measure the distance of an object using an Ultrasonic Distance Sensor (HC-SR04) interfaced with an AVR microcontroller (Atmega328) and communicate the distance measurements via UART.
Ultrasonic Sensor Working:
Ultrasonic sensors work based on the principle of sound waves. They emit ultrasonic pulses and measure the time it takes for the pulses to bounce back after hitting an object.

The sensor's transmitter emits high-frequency sound waves (typically ultrasonic pulses in the range of 40 kHz).
The waves travel through the air until they encounter an object. The waves then reflect back to the sensor's receiver, and the sensor measures the time taken for the waves to return. By knowing the speed of sound in the medium (air), the sensor calculates the distance to the object using the time-of-flight method.
Short Explanation of UART:
UART (Universal Asynchronous Receiver/Transmitter) is a serial communication protocol used to transfer data between devices asynchronously.
In this project, we utilize UART to transmit distance measurements from the microcontroller to an external device, such as a computer, via a UART-to-USB converter. UART uses two pins - TX (Transmit) and RX (Receive) - to establish communication between devices.

UART Frame is a unit of data transmission in UART communication, consisting of a start bit, data bits (usually 8 bits), an optional parity bit for error checking, and one or more stop bits.
The frame format ensures synchronized data transfer between devices, with the start bit indicating the beginning of the frame and stop bit(s) indicating the end, while data bits carry the actual information.
Components Used:
- AVR microcontroller (Atmega328)
- Ultrasonic Distance Sensor (HC-SR04)
- 5V fixed power supply
- 1K ohm resistor
- Oscilacope
Circuit Diagram:
Code:
#include <avr/io.h>
#define F_CPU 16000000
#include <util/delay.h>
#include
// Ultrasonic sensor connections
#define TRIG_PIN PD3
#define ECHO_PIN PD2
// Function prototypes
void initUART();
void sendUART(uint8_t data);
void sendPulse();
uint16_t measureEchoPulse();
void initUART() {
// Set the UART Baud Rate
UBRR0H = 0;
UBRR0L = 103; // Baud rate of 9600 (for 16MHz clock)
// Enable Transmitter
UCSR0B = (1 << TXEN0);
// Set frame format: 8 data bits, no parity, 1 stop bit
UCSR0C = (1 << UCSZ01) | (1 << UCSZ00);
}
void sendPulse() {
// Set the trigger pin as output
DDRD |= (1 << TRIG_PIN);
// Generate a 10us pulse on the trigger pin to start the measurement
PORTD |= (1 << TRIG_PIN);
_delay_us(10);
PORTD &= ~(1 << TRIG_PIN);
// Set the echo pin as input
DDRD &= ~(1 << ECHO_PIN);
}
void sendUART(uint8_t data) {
// Wait for the transmit buffer to be empty
while (!(UCSR0A & (1 << UDRE0)));
UDR0 = data; // Send the data byte
}
uint16_t measureEchoPulse() {
// Measure the echo pulse width in microseconds
uint32_t pulse_width_us = 0;
while (!(PIND & (1 << ECHO_PIN)));
while (PIND & (1 << ECHO_PIN)) {
_delay_us(1);
pulse_width_us++;
}
// Calculate the distance in centimeters (speed of sound: 343m/s)
// Divide by 58 instead of 2 to account for the two-way travel of the sound wave
uint16_t distance_cm = pulse_width_us / 58;
return distance_cm;
}
int main() {
// Initialize UART for serial communication
initUART();
while (1) {
// Trigger the ultrasonic sensor to start measurement
sendPulse();
// Measure the echo pulse and calculate the distance
uint16_t distance_cm = measureEchoPulse();
// Send the distance value as ASCII characters via UART
sendUART('D');
sendUART('i');
sendUART('s');
sendUART('t');
sendUART('a');
sendUART('n');
sendUART('c');
sendUART('e');
sendUART(':');
char numberString[5];
// Convert the distance to a string
itoa(distance_cm, numberString, 10);
for (uint8_t i = 0; numberString[i] != '�'; i++) {
sendUART(numberString[i]);
}
sendUART(' ');
sendUART('c');
sendUART('m');
sendUART('n');
// Wait for a short delay before starting the next measurement
_delay_ms(500);
}
return 0;
}
Code Explanation:
- The code initializes UART communication to send distance measurements.
- It triggers the ultrasonic sensor to initiate a distance measurement using a 10μs pulse.
- The code measures the echo pulse width using Input Capture Mode of Timer 1.
- It calculates the distance based on the pulse width and communicates the measurement via UART.
Registers Used in the Program:
- `UBRR0H` and `UBRR0L`: Baud rate registers for setting the communication speed.
- `UCSR0B`: Control register for enabling the UART transmitter (`TXEN0`).
- `UCSR0C`: Control register for setting the frame format (8 data bits, no parity, 1 stop bit).
- `DDRD`: Data Direction Register for setting pins as input or output.
- `PORTD`: Port D register for setting output pin states (high/low).
Output Console:
The output console displays the measured distance in centimetres received through UART communication. For example:

Result:
The project successfully measures the distance of an object using the HC-SR04 ultrasonic sensor and communicates the measured distance via UART.

Conclusion:
The project demonstrates an effective way to measure distances using an ultrasonic distance sensor interfaced with an AVR microcontroller. Utilizing Input Capture Mode of Timer 1, accurate pulse width measurements are made to calculate distances. The UART communication enables data transmission, making it suitable for various applications, such as robotics, automation, and distance sensing systems. This project provides valuable insights into hardware interfacing, sensor integration, and serial communication, allowing for further exploration and development of distance measurement applications.
For verification purposes here I have attached the execution video link to access:
https://drive.google.com/file/d/18bC4YG6_n-v70t5uM5avnqhgb6Umq5Ej/view?usp=sharing
For all project files link to access:
https://drive.google.com/drive/folders/10u4MSZNbkZdbea0DXwrtXKN0oCS20_pc?usp=sharing