라즈베리파이 Python [초음파센서, LED. 접근하면 Right On]

Posted by PeEn
2019. 9. 5. 21:08 Programing/Raspberry Pi)

라즈베리파이 Python 코딩.

초음파센서에 접근하면 LED ON

CNDI 보드, LED, 초음파 센서

 

GPIO 라이브러리 설치!

1. 라즈베리파이에서 파일 다운

https://sourceforge.net/projects/raspberry-gpio-python/

 

raspberry-gpio-python

Download raspberry-gpio-python for free. A Python module to control the GPIO on a Raspberry Pi. To get started with RPi.GPIO, it would be worthwhile reading the examples in the project wiki (link above). Note that this module is unsuitable for real-time or

sourceforge.net

 

2. 터미널 실행

3. cd /home/pi/Downloads

4. tar zxvf RPi.GPIO-0.7.0.tar.gz

5. cd / RPi.GPIO-0.7.0

6. sudo apt-get install python-dev

7. sudo python setup.py install

초음파 연결 도면

 

LED 연결 도면

 

LED GPIO 4번

Tring =24

ECHO = 23

 

Python 코드

import RPi.GPIO as gpio
import time
import sys
import warnings
warnings.filterwarnings('ignore')
LED = 4
TRIGER = 24
ECHO = 23

gpio.setmode(gpio.BCM)
gpio.setup(TRIGER, gpio.OUT)
gpio.setup(ECHO,gpio.IN)
gpio.setup(LED, gpio.OUT)
startTime = time.time()

try:
    while True:
        gpio.output(TRIGER,gpio.LOW)
        time.sleep(0.1)
        gpio.output(TRIGER,gpio.HIGH)
        time.sleep(0.00002)
        gpio.output(TRIGER,gpio.LOW)

        while gpio.input(ECHO) == gpio.LOW:
            startTime = time.time()

        while gpio.input(ECHO) == gpio.HIGH:
            endTime = time.time()

        period = endTime - startTime
        dist1 = round(period * 1000000 / 58, 2)
        dist2 = round(period * 17241, 2)
        try:
            if dist2 <= 20:
                print('error124')
                gpio.output(LED, gpio.HIGH)
                time.sleep(1)
                gpio.output(LED, gpio.LOW)
                time.sleep(1)
        except KeyboardInterrupt:
            print("error")
        print('Dist1', dist1, 'cm', ', Dist2', dist2, 'cm')
except KeyboardInterrupt:
    gpio.cleanup()
    sys.exit()