raspberrypi/gpio/ultrasound.c

72 lines
1.5 KiB
C
Raw Normal View History

2020-09-10 13:23:23 +08:00
/*
*
*
*/
#include <wiringPi.h>
#include <sys/time.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
2023-12-31 10:47:49 +08:00
#include <ctype.h>
2020-09-10 13:23:23 +08:00
2023-03-25 09:01:17 +08:00
static int is_num(char *str)
2020-09-10 13:23:23 +08:00
{
2023-03-25 09:01:17 +08:00
int i, len;
for (i = 0, len = strlen(str); i < len; i++) {
if (isdigit(str[i]) == 0) {
printf("不是数字\n");
return 1;
2020-09-10 13:23:23 +08:00
}
}
2023-03-25 09:01:17 +08:00
return 0;
2020-09-10 13:23:23 +08:00
}
2023-03-25 09:01:17 +08:00
2020-09-10 13:23:23 +08:00
int main(int argc, char *argv[])
{
if (argc != 3) {
printf("Parameter error.\n");
exit(1);
}
2023-03-25 09:01:17 +08:00
if (is_num(argv[1]) == 1) {
printf("Parameter error, parameter 1 is PIN pin value\n");
2020-09-10 13:23:23 +08:00
exit(1);
}
2023-03-25 09:01:17 +08:00
if (is_num(argv[2]) == 1) {
printf("Parameter error, parameter 1 is PIN pin value\n");
2020-09-10 13:23:23 +08:00
exit(1);
2023-03-25 09:01:17 +08:00
}
2020-09-10 13:23:23 +08:00
int pin_tring = atol(argv[1]);
int pin_echo = atol(argv[2]);
struct timeval tv1;
struct timeval tv2;
long start_time, stop_time;
float distance;
if (wiringPiSetup() == -1) {
exit(0);
return 0;
}
digitalWrite(pin_tring, LOW);
digitalWrite(pin_tring, HIGH);
delayMicroseconds(10);
digitalWrite(pin_tring, LOW);
while (!(digitalRead(pin_echo) == 1)) ;
gettimeofday(&tv1, NULL);
while (!(digitalRead(pin_echo) == 0)) ;
gettimeofday(&tv2, NULL);
start_time = tv1.tv_sec * 1000000 + tv1.tv_usec;
stop_time = tv2.tv_sec * 1000000 + tv2.tv_usec;
distance = (float)(stop_time - start_time) / 1000000 * 34000 / 2;
printf("%0.0f\n", distance);
return distance;
}