用C写一个hcsr04测距
时间: 2023-04-09 17:03:13 浏览: 79
器的代码。
以下是使用C语言编写HCSR04测距器的代码:
#include <stdio.h>
#include <wiringPi.h>
#define TRIG_PIN 4
#define ECHO_PIN 5
int main(void) {
if (wiringPiSetup() == -1) {
printf("wiringPi setup failed!\n");
return 1;
}
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
while (1) {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
while (digitalRead(ECHO_PIN) == LOW);
long startTime = micros();
while (digitalRead(ECHO_PIN) == HIGH);
long travelTime = micros() - startTime;
int distance = travelTime / 58;
printf("Distance: %d cm\n", distance);
delay(500);
}
return 0;
}
阅读全文