STANNUM
Open the simulator

Tutorials / Input

Reed switch

A contact that closes near a magnet — the sensor on every door and window alarm.

Parts in the example:
  • Reed sensor
  • LED
The Reed sensor block as it appears on the canvas.

What it is

Inside a reed switch two thin blades sit in a glass capsule; a magnet nearby pulls them together. Glue the magnet to a door and the sensor to the frame: door closed, contact closed. It is a switch nobody touches — the magnet does.

In the simulator

The block is a slider standing for the magnet: click to bring it near (contact closed) or take it away (contact open). The Contact setting picks normally open or normally closed; the position is saved with the project.

Pins

PinWhat it is
Ssignal — to a GPIO configured as an input
3V3power of the sensor module — to a 3V3 symbol
GNDground — to a GND symbol

Wiring

Build this circuit yourself: start a New project, add the parts from the catalog and wire them as in the table.

The wired circuit, as the lab draws it.
Reed sensor pinGoes to
SD27 on the board (GPIO 27)
3V3a 3V3 symbol
GNDa GND symbol

Settings

Double-click the block's title bar to open its card, then the Settings tab. Changes apply to the running simulation right away.

The Settings tab of the Reed sensor.
SettingAcceptsDefaultNotes
ContactNormally open (NA) · Normally closed (NF)Normally open (NA)

Code

sketch.cpp
#include <Arduino.h>

// A reed switch closes when a magnet comes near. Glue the magnet to the door
// and the sensor to the frame: door closed = magnet close = contact closed.
const int REED = 27;
const int LED = 2;

void setup() {
  Serial.begin(115200);
  pinMode(REED, INPUT_PULLUP);
  pinMode(LED, OUTPUT);
}

void loop() {
  static bool before = true;
  bool open = digitalRead(REED) == HIGH;   // contact open = magnet away
  if (open != before) {                    // print only on a CHANGE
    Serial.println(open ? "door OPEN" : "door closed");
    before = open;
  }
  digitalWrite(LED, open ? HIGH : LOW);
  delay(50);
}

The sketch reads the contact with the pull-up on and prints only on a change, keeping the previous reading in a static variable — the pattern for any event-style input. The LED lights while the door is open.

Run it

Press Build and run. The first build of a project takes a while; after that, only what changed is rebuilt.

The simulation running: the canvas reacts and the serial monitor shows what the code prints.

Click the reed block: the serial monitor prints “door OPEN” and the LED lights; click again for “door closed”.

How the simulation models it

Try this

  1. Sound the buzzer for two seconds when the door opens, then stay quiet until it closes and opens again.
  2. Count how many times the door was opened and print the total on every event.

See also