c - HC - SR04 raspberry pi -


i have raspberry pi b , trying write code in c allow me use hc-sr04 ultrasonic ranging module. used bcm2835 library control gpio pins. have connected according this website. here attempt:

# include <bcm2835.h> # include <stdio.h> # include <time.h> # include <stdlib.h>  # define echo rpi_v2_gpio_p1_03 # define trig rpi_v2_gpio_p1_05  int main(int argc, char **argv) { if (!bcm2835_init())     return 1;  bcm2835_gpio_fsel(echo, bcm2835_gpio_fsel_inpt); bcm2835_gpio_fsel(trig, bcm2835_gpio_fsel_outp);  time_t clockstart = 0; time_t clockstop = 0;  bcm2835_gpio_write(echo, low); delay(2);  printf("trigger\n");  bcm2835_gpio_write(trig, high); usleep(10); bcm2835_gpio_write(trig, low);  printf("measure\n");   while (bcm2835_gpio_lev(echo) == 0) {     clockstart = time(null); }  printf("b: %i\n", (int)clockstart);  while (bcm2835_gpio_lev(echo) == 1) {     clockstop = time(null); }  printf("e: %i\n", (int)clockstop);  time_t delta = clockstop - clockstart;  printf("d: %i\n", delta);  double distance = (delta * 340) / 2;  printf("distance: %i\n", distance);  bcm2835_close(); return 0; } 

two problems exist:

  1. my method reading time accurate 1 sec,- looked better way of doing found 2 methods , no definitive answer 1 better (clock_gettime() or gettimeofday()).
  2. even when pointed far away, loops finish instantaneously leading exact same value of both time() calls. due crappy method of getting current time, i"m not sure.

i'm pretty sure i'm missing obvious here, need finding it.

edit: better solution use gpio interrupts time echo interval

one suggestion (must comment, don't have enough reputation)

use gettimeofday() instead of time() -- provides greater resolution in timing.

also, i'd change while loops way:

struct timeval start, end;  while (!bcm2835_gpio_lev(echo));   // although gcc may smart gettimeofday(&start, null);        // enough optimisation while (bcm2835_gpio_lev(echo));    // on own gettimeofday(&end, null);  double delta = (end.tv_sec - start.tv_sec) * 1000.0;     // s ms        delta += (end.tv_usec - start.tv_usec) / 1000.0;  // ms  printf("d: %f ms\n", delta); 

Comments

Popular posts from this blog

Android : Making Listview full screen -

javascript - Parse JSON from the body of the POST -

javascript - Chrome Extension: Interacting with iframe embedded within popup -