Ultrasonic 센서 이용하기
https://bit.ly/2GCKpCN를 참고하여 Ultrasonic 센서로 거리를 측정하였습니다. https://tutorials-raspberrypi.com/raspberry-pi-ultrasonic-sensor-hc-sr04/ 를 참고하시면 됩니다.
import RPi.GPIO as GPIO
import time
instrument = 0
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
trig = 20
echo = 21
GPIO.setup(trig, GPIO.OUT) # for light shooting
GPIO.setup(echo, GPIO.IN) # for light receiving
DISTANCE = 10 # 10cm
before = 0
now = 0
def measure_distance():
time.sleep(1)
GPIO.output(trig, GPIO.HIGH)
time.sleep(0.001)
GPIO.output(trig, GPIO.LOW)
## shoot for 0.001 second(output)
start = 0
end = 0
# until there is no input
while GPIO.input(echo) == GPIO.LOW:
start = time.time()
# if there is input
while GPIO.input(echo) == GPIO.HIGH:
end = time.time()
duration = end - start
distance = (duration * 340 * 100) / 2
print("distance: %dcm" %distance)
return distance
def state(distance):
global now
if distance <= DISTANCE:
now = 1
else:
now = 0
def change():
distance = measure_distance()
before = now
state(distance)
if before != now:
return 1
else:
return 0
def sense():
if change() == 0:
print("stay")
return 0 #stay
elif now == 1:
print("on")
return 1 #on
else:
print("off")
return -1 #off
#---
try:
while True:
sns = sense()
if sns == 0:
pass
elif sns == 1:
print("on")
else:
print("off")
except KeyboardInterrupt:
GPIO.cleanup()
Sharp IR 센서 이용하기
Sharp IR 센서를 사용하기 위해
https://tutorials-raspberrypi.com/infrared-distance-measurement-with-the-raspberry-pi-sharp-gp2y0a02yk0f/
사이트를 참고하였습니다. 주어진 회로와 같이 연결하고, 아래와 같이 코드를 작성하였습니다.
아래 코드는 SPI 객체를 사용하기 위해 spidev library를 import 합니다. SPI는 Serial Peripheral Interface의 약자로, 두 장치간 양방향 통신을 위해 사용되는 프로토콜입니다. Raspberry pi의 경우, 아날로그 신호를 디지털 신호로 변환하는 GPIO 핀이 없기 때문에 별도의 ADC(analog to digital converter)를 사용해야 합니다. spidev library는 adc를 통해 생성된 digital 값을 raspberry pi 내부로 받아오기 위해 사용됩니다. SPI 객체는 raspberry pi에 있는 값과 adc를 통해 변환된 digital 값 3 byte를 교환합니다. raspberry pi에서 전송되는 3 byte는 adc에게 의미 없는 값이지만, adc를 통해 받아온 거리 값은 raspberry pi에게 의미 있는 값이므로 이를 받아 사용합니다.
# 해당 경우, ADC는 MCP8008입니다.
import spidev
import time
spi = spidev.SpiDev() # create spi object
spi.open(0,0) # open spi port 0, device (CS) 0, for the MCP8008
spi.max_speed_hz = 1000000 # set transfer speed
DISTANCE = 10 # 10cm
before = 0
now = 0
def readChannel(channel):
val = spi.xfer2([1,(8+channel)<<4,0])
# 3 바이트의 데이터 1, (8+channel)<<4, 0을 순차적으로 보내고 3바이트를 받습니다.
data = ((val[1]&3) << 8) + val[2]
return data
def measure_distance():
v = (readChannel(0)/1023.0)*3.3
dist = 16.2537 * v**4 - 129.893 * v**3 + 382.268 * v**2 - 512.611 * v + 301.439
print("distance: %dcm" %dist)
return dist
def state(distance):
global now
if distance <= DISTANCE:
now = 1
else:
now = 0
def change():
global before
distance = measure_distance()
before = now
state(distance)
if before != now:
return 1
else:
return 0
def sense():
if change() == 0:
print("stay")
return 0 #stay
elif now == 1:
print("on")
return 1 #on
else:
print("off")
return -1 #off
#---
try:
while True:
time.sleep(0.5)
sns = sense()
if sns == 0:
pass
elif sns == 1:
print("on")
else:
print("off")
except KeyboardInterrupt:
pass
참고 문헌
- https://mintnlatte.tistory.com/199
- http://esos.hanyang.ac.kr/tc/kims/i/entry//spi%EC%97%90-%EB%8C%80%ED%95%9C-%EC%A0%95%EB%A6%AC#_post_48
- https://m.blog.naver.com/PostView.nhn?blogId=22wowow22&logNo=220830021150&proxyReferer=https%3A%2F%2Fwww.google.com%2F
- https://raoh.tistory.com/3
- https://m.blog.naver.com/yuyyulee/220301424499