Example Code for Raspberry Pi – Digital SMD Magnetic Induction Sensor

Last revision 2026/01/20

This article explains how to use a Digital SMD Magnetic Induction Sensor with a Raspberry Pi by providing example code and instructions for hardware setup and programming, focusing on creating efficient magnetic interaction projects.

Introduction

This is a magnetic sensor based on high-quality reed tube that can sense the magnetic force within 3cm (the detection distance varies with the magnitude of the magnetic force).
With our IO sensor expansion board V7, it can quickly build magnetic interaction projects.

The reed switch is disconnected in an environment without a magnetic field.
When the magnetic force is strong enough, the reeds can be contacted and conducted.
This process is very fast, making it a highly efficient and reliable switching element.

Hardware Preparation

Wiring Diagram

  • Connect the Raspberry Pi correctly to devices such as the screen, power, keyboard and mouse.

  • Connect the LED to pin 12 on the expansion board, and the sensor to pin 8.

Sample Code

  • Open Thonny Python IDE to copy the following program into it

import RPi.GPIO as GPIO    #Import the python module provided by the Raspberry Pi
import time    #Import time package to detect induction time

LED = 12          #Define the pin number to which the LED is connected
magnetic_key = 8           #Define the pin number to which the sensor is connected

GPIO.setmode(GPIO.BCM)      #Set GPIO mode, BCM mode is common to all Raspberry Pi
GPIO.setup(LED,GPIO.OUT)    #Set GPIO12 to output mode
GPIO.setup(magnetic_key ,GPIO.IN)    #设Set GPIO8 to input mode

while True:        #Execute the following commands in an infinite loop
    if GPIO.input(magnetic_key ):        #GPIO.input(magnetic_key )
      GPIO.output(LED,GPIO.HIGH)         #Set the LED signal high (Turn off LED)
    else :          #If GPIO8 is low (The sensor didn't reiceive signal)
      GPIO.output(LED,GPIO.LOW)          #Set LED signal low (Turn on LED)
time.sleep(0.1)   #Delay one second, here is to control the frequency of the query key

Was this article helpful?

TOP