---
# System prepended metadata

title: Hall Switch with RPI
tags: [控制組]

---

#  RPI腳位分配與霍爾開關使用
> [name=徐冠東(gordondonghsu.ee10@nycu.edu.tw)]

## Pin-out
![image](https://hackmd.io/_uploads/SJraTG5tp.png)

## Pin-out for 霍爾開關模組

![image](https://hackmd.io/_uploads/ByMwCfqFa.png)

參考網址:https://shopee.tw/product/139069730/6992675519?d_id=9e099&uls_trackid=4urmrl7400b9&utm_content=3QqRUBuoZbM11Zakxo3Mhx9Rb3AX

Connection (霍爾開關 to Rpi):
S -> GPIO17
VCC -> 5V
GND -> Ground
 
### Python code in Rpi:

```=python3
#!/usr/bin/env python3

import rospy
from std_msgs.msg import Bool

import signal
import sys
import time
import RPi.GPIO as GPIO
BUTTON_GPIO = 11


def signal_handler(sig, frame):
    GPIO.cleanup()
    sys.exit(0)
def button_callback(channel):
    global button_state
    button_state = not button_state

if __name__ == '__main__':
    GPIO.setmode(GPIO.BOARD)

    GPIO.setup(BUTTON_GPIO, GPIO.IN, pull_up_down=GPIO.PUD_UP)

    GPIO.add_event_detect(BUTTON_GPIO, GPIO.BOTH,
            callback=button_callback, bouncetime=200)

    signal.signal(signal.SIGINT, signal_handler)

    rospy.init_node("Interrupt_py")
    pub = rospy.Publisher('interrupt', Bool, queue_size = 10)
    data_to_send = Bool()
    button_state = True

    rate = rospy.Rate(10)

    while(not rospy.is_shutdown()):
        if button_state:
            data_to_send.data = True
            pub.publish(data_to_send)
            rate.sleep()
            time.sleep(0.5)
        if not button_state:
            data_to_send.data = False
            pub.publish(data_to_send)
            rate.sleep()
            time.sleep(0.5)
```


參考: https://roboticsbackend.com/raspberry-pi-gpio-interrupts-tutorial/?fbclid=IwAR0Q34iOlTppN5cEjfIM7-_YegNaa22icFjiDiW6AHT0i3cIbAmarBDIEKo