#include #include #include #include #include "gpio-event-drv.h" #include #include #define MICRO_PER_SECOND 1000000 /* Pinos GPIO */ #define TRIG 146 //Pino 27 #define ECHO 147 //Pino 29 FILE *fs_event; //Detecção do pulso int fd_event; //Detecção do pulso FILE *fs_trig; //Trigger int fd_trig; //Trigger struct timeval start; struct timeval stop; void wait_us(int micro){ usleep(micro); } void wait_ms(int mili){ usleep(1000*mili); } void config_pins(){ /* Detecção do pulso (ECHO) */ system("insmod gpio-event-drv.ko"); if (( fs_event = fopen( "/dev/gpio-event","r")) < 0 ) { perror( "Unable to open /dev/gpio-event" ); exit( 1 ); } GPIO_EventMonitor_t monitor; monitor.gpio = ECHO; monitor.onOff = 1; monitor.edgeType = GPIO_EventBothEdges; monitor.debounceMilliSec = 0.001; if ( ioctl( fileno(fs_event), GPIO_EVENT_IOCTL_MONITOR_GPIO, &monitor ) != 0 ) { perror( "ioctl GPIO_EVENT_IOCTL_MONITOR_GPIO failed" ); } /* Controle do trigger */ char s[50]; sprintf(s, "echo %d > /sys/class/gpio/export", TRIG); system(s); sprintf(s, "echo out > /sys/class/gpio/gpio%d/direction",TRIG); system(s); sprintf(s, "/sys/class/gpio/gpio%d/value",TRIG); if ((fs_trig = fopen(s, "w")) < 0 ) { perror( "Unable to open TRIG" ); exit( 1 ); } fd_trig = fileno(fs_trig); } int main(void) { int value; char eventStr[50]; float tempo; config_pins(); write(fd_trig, "0", 1); wait_ms(100); printf("Monitorando...\n"); while(1){ /* TRIGGER */ write(fd_trig, "1", 1); wait_us(10); write(fd_trig,"0",1); /* ECHO: borda de subida */ fgets(eventStr, sizeof(eventStr),fs_event); if (memchr(eventStr,'F', sizeof(eventStr))) { printf("Invertido!\n"); wait_ms(200); continue; } gettimeofday(&start, NULL); printf("%s", eventStr); /* ECHO: borda de descida */ fgets(eventStr, sizeof(eventStr),fs_event); gettimeofday(&stop, NULL); printf("%s", eventStr); tempo = (float)(stop.tv_sec - start.tv_sec); tempo += (float)(stop.tv_usec - start.tv_usec)/(float)MICRO_PER_SECOND; if (tempo > 0.020) printf("Tempo: %.6fs -- Fora de alcance! \n",tempo); else printf ("Tempo: %.6fs -- Distancia: %.2fcm \n", tempo, (float)1000000*(tempo/58.0)); wait_ms(200); } }