====== Ultrasonic distance sensor SRF05 ====== [{{ :examples:sensor:ultrasonic_distance:srf05.jpg?160|Ultrasonic distance sensor SRF05}}] The SRF05 is an evolutionary step from the SRF04, and has been designed to increase flexibility, increase range, and to reduce costs still further. As such, the SRF05 is fully compatible with the SRF04. Range is increased from 3 meters to 4 meters. A new operating mode (tying the mode pin to ground) allows the SRF05 to use a single pin for both trigger and echo. When the mode pin is left unconnected, the SRF05 operates with separate trigger and echo pins, like the SRF04. The SRF05 includes a small delay before the echo pulse. {{ :examples:sensor:ultrasonic_distance:srf05p1.jpg?580 }} {{ :examples:sensor:ultrasonic_distance:srf05tmb.gif?580 }} Following example uses one pin mode of SRF05. Code is based on the slightly modified HomeLab library 1.03 ultrasonic_measure function. Example is intended for the ATmega128 controller module and Sensor module (v5). #include #include #include #include "homelab/common.h" #include "homelab/pin.h" #define ULTRASONIC_SPEED_OF_SOUND 33000 // cm/s //SRF05 1 pin mode pin srf05 = PIN(F,3); //external sensor selection (make sure that the resistor is monted on the RC socket) pin ext_sensors = PIN(G, 0); //////////////////////////// UH measure ////////////// unsigned short ultrasonic_measure(pin srf05) { // Pin setup pin_setup_output(srf05); // Set timer 3 to normal mode // with period of F_CPU / 8 timer3_init_normal(TIMER3_PRESCALE_8); // Create trigger pulse pin_set(srf05); // Reset timer timer3_overflow_flag_clear(); timer3_set_value(0); // Wait ~10 us while (timer3_get_value() < 18) {} // End trigger pulse pin_clear(srf05); //short delay sw_delay_ms(1); //set the pin as input pin_setup_input_with_pullup(srf05); // Wait for echo start while (!pin_get_value(srf05)) { // Timeout ? if (timer3_overflow_flag_is_set()) { return 0; } } // Reset timer again timer3_set_value(0); // Wait for echo end while (pin_get_value(srf05)) { // 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); } ///////////////////////// Main program ///////////////////////////// int main(void) { int dist; char text[16]; //set external sensor pin_setup_output(ext_sensors); pin_set(ext_sensors); // LCD init lcd_gfx_init(); lcd_gfx_clear(); while (true) { //Measure dist = ultrasonic_measure(srf05); //print to LCD sprintf(text,"Distance: %d cm",dist); lcd_gfx_goto_char_xy(0, 0); lcd_gfx_write_string(text); //0,5 s delay sw_delay_ms(50); //Clear LCD lcd_gfx_clear(); } }