The Code

#include <avr /io.h> #include <avr /interrupt.h> #include <util /delay.h> #include <stdlib.h> #define enable PORTD3 #define registerselection PORTD5 void send_a_command(unsigned char command); void send_a_character(unsigned char character); void send_a_string(char *string_of_characters); uint16_t us_measurement(); void set_compare(uint16_t); void set_period(uint16_t); void timer3_init(); static volatile int pulse = 0; static volatile int i = 0; int kalle; int main(void) { DDRB = 0xFF; DDRD = 0xFF; DDRC |=(1<<PORTC0); DDRD &=~(1<<PORTD7); _delay_ms(50); timer3_init(); set_period(58); float COUNTA=0; char SHOWA [16]; send_a_command(0x01); send_a_command(0x38); _delay_ms(50); send_a_command(0b00001111); _delay_ms(50); while(1) { set_compare(us_measurement()); COUNTA=us_measurement()*2.0; send_a_string ("DISTANCE="); itoa(COUNTA,SHOWA,10); send_a_string(SHOWA); send_a_string (" cm "); send_a_command(0x80 + 0); _delay_ms(60); if(COUNTA <= 5){ _delay_ms(60); PORTD |=(1<<PORTD1); _delay_ms(1000); PORTD &=~(1<<PORTD1); } } } void send_a_command(unsigned char command) { PORTB = command; PORTD &= ~ (1<<registerselection); PORTD |= 1<<enable; _delay_ms(8); PORTD &= ~1<<enable; PORTB = 0; } void send_a_character(unsigned char character) { PORTB = character; PORTD |= 1<<registerselection; PORTD |= 1<<enable; _delay_ms(8); PORTD &= ~1<<enable; PORTB = 0; } void send_a_string(char *string_of_characters) { while(*string_of_characters > 0) { send_a_character(*string_of_characters++); } } void timer3_init() { TCCR3A &= ~(1 << COM3A1); TCCR3A &= ~(1 << COM3A0); TCCR3A |= (1 << WGM31); TCCR3B |= (1 << WGM33) | (1 << WGM32) | (1 << CS30) | (1 << CS32); } void set_compare(uint16_t ocr){ OCR3A = ocr; } void set_period(uint16_t icr){ ICR3 = icr; } uint16_t us_measurement(){ _delay_ms(60); TCNT1 = 0; PORTC |= (1 << PORTC0); _delay_us(10); PORTC &= ~(1 << PORTC0); while(!(PIND & (1 << PIND7))); TCCR1B |= (1 << CS12) | (1 << CS10) ; while((PIND & (1 << PIND7))); TCCR1B = 0; kalle = TCNT1; return TCNT1; }