Processor

【라즈베리파이】 wiringPi Python : 충격 센서(인터럽트)

작성자 임베디드코리아 작성일26-02-20 00:31 조회135회 댓글0건
충격 센서의 신호핀(S 핀)은 충격이 감지되면 충격 신호를 보내는 핀으로 GPIO 14번과 연결해 주시고
전원 핀은  5V와 연결해 주고  - 핀은는 GND와 연결한다.

--->>> 예제 : Shock_Sensor.py  <<<------------------------
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(14, GPIO.IN)

try:
        while True:
                if GPIO.input(14) == True:
                        print("Shock Detected")
                        time.sleep(1)
                else:
                        print("No Detected")
                        time.sleep(1)
except KeyboardInterrupt:
 pass
GPIO.cleanup()
-------------------------------------------------------------------------------
▶ if GPIO.input(14) == True:  print("Shock Detected")  time.sleep(1)은 충격에 의해 코일 속의 자석이 움직여
  전류가 흐르게 되면 충격이 감지되었다는 안내문이 1초마다 출력한다.
▶ else:  print("No Detected")  time.sleep(1)은 충격이 감지되지 않으면 충격이 없다는 안내문이 1초마다 출력된다.


--->>> 예제 : Shock_Sensor_interrupt.py  <<<-------------
import RPi.GPIO as GPIO
#GPIO 라이브러리 버젼을 출력한다
print GPIO.VERSION
#핀 넘버링을 BCM 방식을 사용한다.
GPIO.setmode(GPIO.BCM)
 
#4번 핀을 입력모드로 설정
GPIO.setup(4, GPIO.IN)
globalCounter = 0
 
#인터럽트 함수가 호출되면 글로벌 변수 globalCounter 값을 1 증가시킨다.
def myInterrupt(channel):
    global globalCounter
    globalCounter += 1
    print " Done. counter:" , globalCounter
 
 
#4번 핀이 OFF될 때 myInterrupt 함수를  통해 인터럽트를 받겠다는 요청
#GPIO.FALLING은 ON 상태에서 OFF로 변경될 때 시그널을 받겠다는 의미
GPIO.add_event_detect(4, GPIO.FALLING, callback=myInterrupt)
 
try:
    raw_input("Press Enter to Exit\n>")
except KeyboardInterrupt:
    GPIO.cleanup() # clean up GPIO on CTRL+C exit
    GPIO.remove_event_detect(4)
 
GPIO.remove_event_detect(4)
GPIO.cleanup() # clean up GPIO on normal exit
-----------------------------------------------------------------------