Challenge

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

Explanation:

  1. Header files and Macro definition:
    • The code starts by defining the microcontroller clock frequency (F_CPU) and includes necessary header files for AVR programming.
    • #define F_CPU 16000000L sets the CPU clock frequency to 16 MHz.
  2. Variable Declaration:
    • volatile int TimerOverflow = 0; declares a volatile integer variable TimerOverflow and initializes it to 0. This variable is used to count timer overflows.
  3. Timer Overflow Interrupt Service Routine (ISR):
    • ISR(TIMER1_OVF_vect) is an interrupt service routine that is executed when Timer1 overflows.
  4. Main Function:
    • int main(void) is the main function where the program execution begins.
  5. Port Configuration:
    • DDRA, DDRB, and DDRD are Data Direction Registers, used to configure the direction of data flow for each port (input or output).
    • PORTD is set to enable pull-up resistors on all pins.
  6. Timer Configuration:
    • TIMSK = (1 << TOIE1); enables Timer1 overflow interrupts.
    • TCCR1A = 0; configures Timer1 for normal operation.
  7. LCD Initialization:
    • LCD_Init(); initializes the LCD module.
  8. Ultrasonic Sensor Measurement Loop:
    • The while(1) loop contains the code for measuring the distance using an ultrasonic sensor.
    • The trigger pin is set high and low to initiate the ultrasonic pulse.
    • Timer1 is configured and used to measure the time it takes for the pulse to return.
  9. Distance Calculation:
    • The count is calculated based on the timer values, and the distance is calculated using a formula (distance = (double)count / 932.944).
  10. LCD Display:
    • The distance value is displayed on an LCD screen.
  11. Delay:
    • _delay_ms(50); introduces a delay of 50 milliseconds.
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.