1

Final edit: Got it working! Thank you all for your suggestions.

The first issue was that my magnet was broken. I got a multimeter and tested the switch open and closed, and the meter was detecting current regardless of the state.

I bought a new switch and it works as intended. (current stopped, current flowing)

The second issue was in my code. I was reading the GPIO status outside of the while Loop.

In the end, I learned some valuable information. Thank you all!


I'm using a 2.5A Canakit power supply to power the Pi.

Since I need the magnet switch, how can I use an external DC power supply to send power to the magnet?

If I use 3.3v or 5v, like the diagram suggests, my Pi's LEDs dim. This is because I have a Sharp IR sensor and a Pi camera connected already. Not enough juice I guess.

This is how I currently have the magnet switch hooked up: This is how I currently have the magnet hooked up:

Thank you!

EDIT: I'm using a magnet switch. Sorry for calling it a relay. enter image description here

EDIT 2: @Joan suggested using GPIO to NO and GND to COM. I did that but there were no status changes if the switch was on or off according to the Pi.

enter image description here

EDIT 3: Here's my code. Am I enabling the internal resistor?

import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False) 

GPIO.setup(22, GPIO.IN, GPIO.PUD_UP)

read = GPIO.input(22)

while True:
    if read == True:
        print ('Door is True')
    else:
        print ('Door is false')
Entryton
  • 106
  • 1
  • 8

2 Answers2

3

You could use a power supply module, like the one linked here: https://www.amazon.com/JBtek-Breadboard-Supply-Arduino-Solderless/dp/B010UJFVTU (First result on a quick google search, you might want to look further)

If you're adventurous you could cut apart a cable (a USB works well if you're near a computer - just be careful to prevent short circuiting)

EDIT: Just to clarify, you would connect the 3.3v to the RPi GPIO pin, and the 5v/gnd to the power supply.

1

I suspect you are using lower value resistors if the Pi LEDs dim.

I would wire a GPIO direct to NO and connect ground to COM.

Set the GPIO to be an INPUT and enable its internal pull-up to 3V3.

The GPIO will read back as 1 when the switch is open and 0 when the switch is closed. If you connect to NC rather than NO the read values will be reversed.

joan
  • 71,852
  • 5
  • 76
  • 108