Example Code for Arduino-Magnetic Detection Control LED

This article demonstrates how to use Arduino and a magnetic switch to control an LED, including hardware setup, wiring instructions, and sample code to achieve a simple magnetic detection system.

Hardware Preparation

Wiring Diagram

Here we use the I/O9 and 13 ports of Arduino UNO for demonstration

Other Preparation Work

Sample Code

 * @copyright  Copyright (c) 2010 DFRobot Co.Ltd (http://www.dfrobot.com)
 * @licence  The MIT License (MIT)
 * @author  [huyujie]([email protected])
 * @version  V1.0
 * @date  2021-05-13
 */
int ledPin = 13;
int magnet_inputPin = 9;

    void setup() {
      pinMode(ledPin, OUTPUT);
      pinMode(magnet_inputPin, INPUT);
    }

    void loop(){
      int val = digitalRead(magnet_inputPin);
      if (val == HIGH) {
         digitalWrite(ledPin, HIGH);
      } else {
         digitalWrite(ledPin, LOW);
      }
    }

Result

When the magnetic switch is close to the magnet, the LED of UNO 13 pin will light up. And the LED will light off when the magnetic switch moves away from the magnet.

Was this article helpful?

TOP