You are on page 1of 1

#define ULTRASONIC_SPEED_OF_SOUND 33000 // cm/s // // Instant ultrasonic distance measuring // unsigned short ultrasonic_instant_measure(pin trigger, pin echo) { // Pin

setup pin_setup_output(trigger); pin_setup_input_with_pullup(echo); // Set timer 3 to normal mode // with period of F_CPU / 8 timer3_init_normal(TIMER3_PRESCALE_8); // Create trigger pulse pin_set(trigger); // Reset timer timer3_overflow_flag_clear(); timer3_set_value(0); // Wait ~10 us while (timer3_get_value() < 18) {} // End trigger pulse pin_clear(trigger); // Wait for echo start while (!pin_get_value(echo)) { // Timeout ? if (timer3_overflow_flag_is_set()) { return 0; } } // Reset timer again timer3_set_value(0); // Wait for echo end while (pin_get_value(echo)) { // Timeout ? if (timer3_overflow_flag_is_set()) { return 0; } } // Convert time to distance: // distance = timer * (1 / (F_CPU / 8)) * speed / 2 return (unsigned long)timer3_get_value() * ULTRASONIC_SPEED_OF_SOUND / (F_CPU / 4); }

You might also like