raspberry pi + wiring pi + 초음파 센서

1.회로구성
Cap 2015-07-05 10-47-10-867Cap 2015-07-05 10-50-53-333

2. 코딩

pi@was02 ~/wiringPi $ mkdir ultrasonic
pi@was02 ~/wiringPi/ultrasonic $ vi ultrasonic.c

#include<stdio.h>
#include<wiringPi.h>

#define trigPin 0
#define echoPin 1

int main(void)
{
int distance = 0;
//int pulse = 0;

if(wiringPiSetup () == -1)
{
return 1;
}

pinMode (trigPin, OUTPUT);
pinMode (echoPin, INPUT);

for(;;)
{
digitalWrite (trigPin, LOW);
delay(2);

digitalWrite (trigPin, HIGH);
delay(20);

digitalWrite (trigPin, LOW);

while(digitalRead(echoPin) == LOW);
long startTime = micros();

while(digitalRead(echoPin) == HIGH);
long travelTime = micros() - startTime;

distance = travelTime / 58;

printf("Distance: %d cm\n", distance);
delay(100);
}
}

3. 컴파일

pi@was02 ~/wiringPi/ultrasonic $ gcc -Wall -o ultrasonic ultrasonic.c -lwiringPi
pi@was02 ~/wiringPi/ultrasonic $

4. 테스트

pi@was02 ~/wiringPi/ultrasonic $ sudo ./ultrasonic
Distance: 25 cm
Distance: 25 cm
Distance: 25 cm
Distance: 25 cm
Distance: 25 cm
Distance: 25 cm
Distance: 25 cm
Distance: 25 cm
Distance: 25 cm
^Cpi@was02 ~/wiringPi/ultrasonic $
Cap 2015-07-05 11-04-08-517

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s