Project 2 - Measuring distance of an object using ultrasonic sensor (HC-SR04)
Explanation:
- 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.
- 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.
- Timer Overflow Interrupt Service Routine (ISR):
- ISR(TIMER1_OVF_vect) is an interrupt service routine that is executed when Timer1 overflows.
- Main Function:
- int main(void) is the main function where the program execution begins.
- 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.
- Timer Configuration:
- TIMSK = (1 << TOIE1); enables Timer1 overflow interrupts.
- TCCR1A = 0; configures Timer1 for normal operation.
- LCD Initialization:
- LCD_Init(); initializes the LCD module.
- 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.
- Distance Calculation:
- The count is calculated based on the timer values, and the distance is calculated using a formula (distance = (double)count / 932.944).
- LCD Display:
- The distance value is displayed on an LCD screen.
- Delay:
- _delay_ms(50); introduces a delay of 50 milliseconds.