This is an old revision of the document!
This example uses one pin mode of SRF05. Code is based on the slightly modifyed HomeLab library 1.03 ultrasonic_measure function. Example is intented for the ATmega128 controller module and Sensor module (v5).
#include <homelab/delay.h> #include <homelab/module/lcd_gfx.h> #include <homelab/timer.h> #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(); } }