Skip to content

Instantly share code, notes, and snippets.

@Park-Developer
Created February 5, 2022 18:38
Show Gist options
  • Save Park-Developer/5ec5b53e8e37e8344a6fe7125de2765d to your computer and use it in GitHub Desktop.
Save Park-Developer/5ec5b53e8e37e8344a6fe7125de2765d to your computer and use it in GitHub Desktop.
ultrasonic sensor with C
#include<stdio.h>
#include<wiringPi.h>
#define TRIG 21 // trig GPIO 5
#define ECHO 22 // echo GPIO 6
int main(void){
long startTime;
long travelTime;
int distance=0;
if(wiringPiSetup()==-1) return 1;
pinMode (TRIG, OUTPUT);
pinMode (ECHO, INPUT);
while(1){
//초음파 발생코드
digitalWrite (TRIG, LOW);
delayMicroseconds(2);
digitalWrite (TRIG, HIGH);
delayMicroseconds(20);
digitalWrite (TRIG, LOW);
//거리측정코드
while(digitalRead(ECHO) == LOW);
startTime = micros();
while(digitalRead(ECHO) == HIGH);
travelTime = micros() - startTime;
distance = travelTime / 58;
if(distance < 400) printf( "Distance: %dcm\n", distance);
delay(500);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment