Sunday, March 20, 2016

HC-SR04 with Raspberry Pi - Distance

HC-SR04 (Ultrasonic Module) interfacing with Raspberry Pi for distance calculation.




Will provide the schematics soon.

/*
 * HC-SR04 <> RPi
 * To calculate the distance
 * Using the libbcm2835 library
 * Author : Ahamed EN (ahamed.en@gmail.com)
 * 20-March-2016
 */
#include <bcm2835.h>
#include <stdio.h>
#include <sys/time.h>

/* We will be using
 * Pin#16 (GPIO23) as Trigger
 * Pin#18 (GPIO24) for Echo
 */
#define TRIGGER RPI_GPIO_P1_16
#define ECHO    RPI_GPIO_P1_18

int main(int argc, char **argv)
{

    if (!bcm2835_init())
        return 1;

    struct timeval start, end;
    float duration;

    bcm2835_gpio_fsel(TRIGGER, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_fsel(ECHO, BCM2835_GPIO_FSEL_INPT);

    bcm2835_gpio_write(TRIGGER, LOW);
    bcm2835_gpio_write(ECHO, LOW);
    bcm2835_delay(2);

    bcm2835_gpio_write(TRIGGER, HIGH);
    usleep(10); /* As per the HC-SR04 manual */
    bcm2835_gpio_write(TRIGGER, LOW);

    /* Wait until we get a HIGH */
    while(!bcm2835_gpio_lev(ECHO));
    gettimeofday(&start, NULL);

    /* Wait until we get a LOW */
    while(bcm2835_gpio_lev(ECHO));
    gettimeofday(&end, NULL);

    /*
     * speed = distance/time
     * speed = 340m/s = 34300cm/s (speed of sound)
     *
     * 34300 = distance/time
     *
     * distance = time/2 * 34300 (time/2 because what we got is the time
     *                              for to and fro)
     */

    duration = (end.tv_sec - start.tv_sec) * 1000.0;
    duration += (end.tv_usec - start.tv_usec) / 1000.0;
    duration = duration/1000; /* to seconds */

    float distance = duration/2 * 34300;

    printf("Disatnce : %f cm\n", distance);

    bcm2835_delay(500);
    bcm2835_close();
    return 0;
}

1 comment: