Challenge

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

PROJECT 2 OUTPUT SCREEN SHOTS 

OUTPUT SCREEN SHOT 2

CODE FOR PROJECT 2 

#define F_CPU 16000000

#include

#include

#include

#define BAUD_RATE 9600

void USART_Init(unsigned int baud);

void USART_Transmit(unsigned char data);

unsigned char USART_Receive(void);

void initHC_SR04(void);

unsigned int getDistance(void);

int main(void) {

USART_Init(BAUD_RATE);

initHC_SR04();

sei(); // Enable global interrupts

while (1) {

unsigned int distance = getDistance();

// Print distance to serial monitor

char buffer[10];

sprintf(buffer, "%u cm\r\n", distance);

for (int i = 0; buffer[i] != '\0'; i++) {

USART_Transmit(buffer[i]);

}

_delay_ms(1000);  // Wait for 1 second

}

return 0;

}

void USART_Init(unsigned int baud) {

// Set baud rate

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

UBRR0L = (unsigned char)baud;

// Enable receiver and transmitter

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

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

UCSR0C = (3 << 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;

}

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 initHC_SR04(void) {

// Set PB0 as input for Echo

DDRB &= ~(1 << PB0);

// Set PB1 as output for Trigger

DDRB |= (1 << PB1);

}

unsigned int getDistance(void) {

unsigned int duration;

// Trigger pulse

PORTB |= (1 << PB1);  // Set PB1 high

_delay_us(10);        // Wait for 10 microseconds

PORTB &= ~(1 << PB1); // Set PB1 low

// Measure pulse duration

while (!(PINB & (1 << PB0))) // Wait for Echo to go high

;

TCNT1 = 0;  // Clear Timer1 counter

TCCR1B |= (1 << CS11); // Start Timer1 with prescaler 8

while (PINB & (1 << PB0)) // Wait for Echo to go low

;

TCCR1B = 0; // Stop Timer1

// Calculate distance in centimeters

duration = (unsigned int)(TCNT1 * 0.034 / 2);

return duration;

}

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.