Medición ultrasonica con sensor SRF-05.

SRF05 es un nuevo sensor de distancias pensado para ser una actualización del clásico SRF04 con el que es compatible, pero además añadiendo nuevas funciones y características. En el modo estándar, el SRF05 se comporta igual que el SRF04 con la diferencia de que el rango de trabajo se ha aumentado de 3 a 4 metros. Esto significa que todo el software que funciona con el SRF04, funciona con el SRF05. Por otro lado, el SRF05 cuenta con un nuevo modo de trabajo que emplea un solo pin para controlar el sensor y hacer la lectura de la medida. Lo que se hace es mandar un impulso para iniciar la lectura y luego poner el pin en modo entrada. Después basta con leer la longitud del pulso devuelto por el sensor, que es proporcional a la distancia medida por el sensor. El SRF05 es mecánicamente igual al SRF04, por lo que puede ser un sustituto de este.

El sensor SRF05 incluye un breve retardo después del pulso de eco para dar a los controladores más lentos como Basic Stamp y Picaxe el tiempo necesario para ejecutar sus pulsos en los comandos. El sensor SRF05 tiene dos modos de funcionamiento, según se realicen las conexiones.

 

 Programa principal

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/***********************************************************************
*   Proyecto con KEIL 5 para la medición de distancia con el
*   sensor ultrasónico SRF-05
*   Controlador STM32F407vg Cortex M4
*    www.firtec.com.ar
*    
************************************************************************/
#include "stm32f4xx.h"
#include "delay.h"
#include "SRF_05.h"
#include <stdio.h>
#include "hd44780.h"
 
char floatStr[14];    
 
int main(void) {
  float distancia;   
   HD44780_Init(16, 2); // Configura el LCD
   DELAY_Init();                // Configura los retardos
   HD44780_Puts(2, 0, "CENTIMETROS"); // Cartel inicial
  if (!HCSR04_Init()) { // Inicializa el sensor
       HD44780_Puts(0, 0, "Sensor EEROR!!!!");
        while (1);     
    }
  while (1) {
   distancia = HCSR04_Read(); // Lee la distancia en Centimetros
   if (distancia < 0) { // La distancia no puede ser menor que cero
       HD44780_Puts(0, 0, "Sistema EEROR!!");
   } else if (distancia > 50) {
   HD44780_Puts(0, 0, "Fuera de rango!!"); // No debe ser mayor a 50cmts.
    } else {
        HD44780_Puts(0, 0, "Dentro del rango"); // Distancia en Rango
     }
        sprintf(floatStr,"Centim:%3.2f  ",distancia);
      HD44780_Puts(0, 1, floatStr);
    Delayms(100);
    }
}

Archivo SRF_05.C

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include "SRF_05.h"
 
uint8_t HCSR04_Init(void) {
    GPIO_InitTypeDef GPIO_InitStruct;
    
    TM_DELAY_Init(); // Configura los timer para retardos
    
    // Configura pines y reloj
    RCC_AHB1PeriphClockCmd(HCSR04_TRIGGER_RCC | HCSR04_ECHO_RCC, ENABLE);
    GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_DOWN;
    GPIO_InitStruct.GPIO_Speed = GPIO_Speed_100MHz;
    
    // Configura pin Trigger
    GPIO_InitStruct.GPIO_Mode = GPIO_Mode_OUT;
    GPIO_InitStruct.GPIO_Pin = HCSR04_TRIGGER_PIN;
    GPIO_Init(HCSR04_TRIGGER_PORT, &GPIO_InitStruct);
    
    // Configura pin Echo
    GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN;
    GPIO_InitStruct.GPIO_Pin = HCSR04_ECHO_PIN;
    GPIO_Init(HCSR04_ECHO_PORT, &GPIO_InitStruct);
    
    // El Trigger inicia en nivel bajo
    HCSR04_TRIGGER_LOW;
    
    // Inicia la medición, interroga si el sensor está trabajando
    if (HCSR04_Read() >= 0) {
        return 1;  // Sensor OK
    }
    return 0; // Problemas con el sensor !!!
}
 
float HCSR04_Read(void) {
    uint32_t time, timeout;
    float dis;
    HCSR04_TRIGGER_LOW;     // Baja pin Trigger
    Delay(2);                         // Espera 2 us
    HCSR04_TRIGGER_HIGH;     // Pin Trigger sube 10 us
    Delay(10);                      // Espera 10 us
    HCSR04_TRIGGER_LOW;        // Trigger baja
    timeout = HCSR04_TIMEOUT; // Espera para verificar el resultado
    while (HCSR04_ECHO_CHECK == Bit_RESET) {
        if (timeout-- == 0x00) {
            return -1;
        }
    }
    time = 0;
    // Espera hasta que el pin baje
    while (HCSR04_ECHO_CHECK == Bit_SET) {
    time++;
    Delay(1);
    }
    // Convierte los us en centimetros
    dis = (float)time * SFR05_AJUSTE;
    return dis;  // Retorna la distancia.
}

Archivo SRF_05.H

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include "stm32f4xx.h"
#include "stm32f4xx_rcc.h"
#include "stm32f4xx_gpio.h"
#include "delay.h"
 
// PIN Trigger
#ifndef HCSR04_TRIGGER_PIN
#define HCSR04_TRIGGER_RCC        RCC_AHB1Periph_GPIOB
#define HCSR04_TRIGGER_PORT        GPIOB
#define HCSR04_TRIGGER_PIN        GPIO_Pin_4
#endif
 
// PIN Echo PIN
#ifndef HCSR04_ECHO_PIN
#define HCSR04_ECHO_RCC            RCC_AHB1Periph_GPIOB
#define HCSR04_ECHO_PORT        GPIOB
#define HCSR04_ECHO_PIN            GPIO_Pin_5
#endif
 
// Pulsos de retardo
#ifndef HCSR04_TIMEOUT
#define HCSR04_TIMEOUT            1000000
#endif
 
// Pines
#define HCSR04_TRIGGER_LOW        HCSR04_TRIGGER_PORT->BSRRH = HCSR04_TRIGGER_PIN
#define HCSR04_TRIGGER_HIGH        HCSR04_TRIGGER_PORT->BSRRL = HCSR04_TRIGGER_PIN
#define HCSR04_ECHO_CHECK        GPIO_ReadInputDataBit(HCSR04_ECHO_PORT, HCSR04_ECHO_PIN)
 
#define SFR05_AJUSTE            ((float)0.0183000)    
    
/**
  * Retorna 1 si el sensor está listo para usar y 0 si error
 */
extern uint8_t TM_HCSR04_Init(void);
 
/**
 * Inicia la medición de distancia
 *
 * Esta función devuelve -1 si hubo un error, o si la distancia en cm si todo está bien
 */
extern float TM_HCSR04_Read(void);