Limit Switch Arduino: NO/NC Wiring, Debounce and Motor Stop Code
Limit switch Arduino guide: NO, NC and COM pins, pull-up wiring, debounce, stopping door and curtain motors, CNC endstops, ESP32 homing and Pico code.
In limit switch Arduino projects, this small but vital switch reports that a moving part has reached the end of its travel. It is also called a micro switch or an end switch. When a door or curtain motor is fully open, when a CNC axis reaches the end of its rail, or when a 3D printer bed arrives at its zero point, the lever or roller is pushed and the contact inside changes state. The Arduino reads this change and stops the motor, so the mechanism isn't strained, the motor doesn't burn out and the belt doesn't snap.
In this article you'll learn the NO, NC and COM terminals of a limit switch, its types and current ratings, how to wire it with a pull-up resistor and why NC wiring is preferred for safety. Then you'll find reading code that removes contact bounce (debounce), a complete program that stops a door or curtain motor with two end switches, GRBL settings for CNC limit switches, homing a stepper motor axis with an ESP32 and MicroPython code for the Raspberry Pi Pico.
What is a limit switch and how does it work?
Inside a limit switch there is a spring-loaded metal blade. When the lever or button is pushed past a certain point, the blade suddenly "jumps" to the other position; that's why these are called snap-action switches. Snap action makes the contact change in one go instead of slowly and reduces sparking. The switch has three terminals: COM is the common terminal, NC (normally closed) is connected to COM while the switch is untouched, and NO (normally open) is connected to COM only while the switch is pressed. Depending on the mechanism you choose a plain button, a straight lever or a roller lever model: the roller lever detects a part that slides past it (such as the edge of a door) without friction.
| Terminal | Meaning | Switch released | Switch pressed |
|---|---|---|---|
| COM | Common terminal | Connected to NC | Connected to NO |
| NC | Normally closed | Shorted to COM | Open circuit |
| NO | Normally open | Open circuit | Shorted to COM |
Limit switch types and current ratings
| Type | Example | Contact rating (typical) | Where is it used? |
|---|---|---|---|
| Mini micro switch | KW11-3Z, KW12 | 5 A, 125/250 V AC | Doors, curtains, toys, 3D printers |
| Subminiature switch | SS-5, KW10 | 3–5 A, 125 V AC | Tight spaces, endstop modules |
| Standard basic switch | V-15, Z-15 | 15 A, 250 V AC | Machines, household appliances |
| Industrial limit switch | ME-8108, TZ-8108 | 5 A, 250 V AC, metal housing | Garage doors, conveyors, outdoors |
| Mechanical endstop module | KW10 + board with LED, 3 pins | Signal only (a few mA) | 3D printer and CNC boards |
| Optical endstop | Slotted optical sensor | Signal only, contactless | Fast axes that must not bounce |
The current rating printed on the body is usually for AC; the DC rating of the same switch is noticeably lower, because the arc that forms when direct current is interrupted doesn't extinguish by itself. If you'll run a motor directly through the switch, check the DC rating in the datasheet and the motor's stall current. Micro switches have a mechanical life of 1 to 10 million operations, while their electrical life at full load is far lower. With an Arduino only a few milliamps of signal current flow through the switch, so even the smallest model lasts for years. The three-pin mechanical endstop modules common on 3D printers carry a pull-up resistor and a status LED next to the switch; you connect their S, GND and VCC pins straight to the board.
Wiring: NO or NC with a pull-up?
The cleanest way to connect a limit switch to an Arduino is to wire COM to GND and the other terminal to a digital pin set to INPUT_PULLUP. The internal pull-up resistor keeps the pin HIGH when idle, and when the switch connects the pin to GND it reads LOW. You'll find the pull-up logic explained in detail in the pull-up resistor article. The real decision is whether to use NO or NC. With NC wiring, the pin sits at GND and reads LOW while the switch is released; when the switch is pressed or the wire breaks, the pin goes HIGH. So a broken wire looks like "end reached" and the motor never runs in that direction. With NO wiring, a broken wire means "switch never pressed"; the motor overruns the end and strains the mechanism. That's why CNC machines, 3D printers and all safety stops prefer NC wiring. All the code in this article is written for NC wiring: HIGH = triggered.
| Wiring | Released | Pressed | If the wire breaks | When? |
|---|---|---|---|---|
| NC + INPUT_PULLUP | LOW | HIGH | HIGH (safe: stops) | End positions and safety stops |
| NO + INPUT_PULLUP | HIGH | LOW | HIGH (dangerous: looks unpressed) | Counters, menus, non-critical detection |
| NO + external pull-down | LOW | HIGH | LOW (dangerous) | Special cases where a pull-up can't be used |
| Connection | Arduino Uno | ESP32 | Raspberry Pi Pico |
|---|---|---|---|
| End switch 1 (open / home), NC terminal | D2 | GPIO 32 | GP14 |
| End switch 2 (closed / far end), NC terminal | D3 | GPIO 33 | GP15 |
| COM terminal of the switches | GND | GND | GND |
| Open / close button | D4 | - | GP13 |
| Motor driver | L298N: IN1 D8, IN2 D9, ENA D10 | A4988: STEP 26, DIR 27 | IN1 GP16, IN2 GP17 |
| Logic level | 5 V | 3.3 V | 3.3 V |
Step by step: reading a limit switch with Arduino and debounce
- Connect the limit switch's COM terminal to the Arduino's GND and the NC terminal to D2. Leave NO unconnected.
- Upload the code below and open the Serial Monitor at 115200 baud.
- While the switch is released, the L LED on the board should be off. Press the lever: the LED lights and the counter goes up by one.
- Pull the wire out of D2: the LED lights and "triggered" is printed. This shows you that a broken wire falls on the safe side.
- Press and release the lever slowly and check that the counter rises by only one per press.
1// Limit switch okuma: NC bağlantı + INPUT_PULLUP + debounce
2// Reading a limit switch: NC wiring + INPUT_PULLUP + debounce
3const int LIMIT_PIN = 2; // NC ucu -> D2, COM -> GND / NC -> D2, COM -> GND
4const unsigned long DEBOUNCE_MS = 20; // sıçrama süresi / bounce time
5
6int stableState; // kararlı durum / stable state
7int lastReading; // son ham okuma / last raw reading
8unsigned long lastChange = 0;
9unsigned int pressCount = 0;
10
11void setup() {
12 Serial.begin(115200);
13 pinMode(LIMIT_PIN, INPUT_PULLUP); // dahili pull-up / internal pull-up
14 pinMode(LED_BUILTIN, OUTPUT);
15 stableState = lastReading = digitalRead(LIMIT_PIN);
16}
17
18void loop() {
19 int reading = digitalRead(LIMIT_PIN);
20 if (reading != lastReading) { // ham değer değişti, sayacı yeniden başlat / raw value changed, restart timer
21 lastChange = millis();
22 lastReading = reading;
23 }
24 if (millis() - lastChange > DEBOUNCE_MS && reading != stableState) {
25 stableState = reading; // 20 ms boyunca aynı kaldı / stayed the same for 20 ms
26 // NC + pull-up: HIGH = basıldı ya da kablo koptu / HIGH = pressed or wire broken
27 if (stableState == HIGH) {
28 pressCount++;
29 Serial.print("Tetiklendi / triggered: ");
30 Serial.println(pressCount);
31 } else {
32 Serial.println("Serbest / released");
33 }
34 }
35 digitalWrite(LED_BUILTIN, stableState); // L LED'i anahtarı gösterir / L LED shows the switch
36}
37When a mechanical contact closes or opens, the metal parts vibrate for a few milliseconds and the Arduino reads LOW and HIGH dozens of times during that period. This is called bounce. The code stores the time the raw reading last changed and accepts the value as the new stable state once it has stayed the same for 20 ms, so one press becomes one count. There's an important distinction here: debounce is needed to count presses. To stop a motor there's no need to wait; you should stop the motor on the very first HIGH reading, because the second reading in a bounce also means "end". On long cables you can add a hardware filter to reduce noise: a 100 nF capacitor between signal and GND and a 1–10 kΩ resistor in series. 10 kΩ and 100 nF give a time constant of about 1 ms; you can change the values with the RC time constant calculator. We cover the same problem for buttons in the button wiring article.
Stopping a door or curtain motor at the end position
For two-ended movements such as a door, curtain, chicken coop door or sliding hatch, a limit switch is placed at each end. The program below turns a DC motor in both directions with an L298N driver. When the button is pressed it opens the door if it's closed, closes it if it's open, and goes opposite to the last direction if it's stopped in the middle; pressing the button while moving stops the motor. The end switches are checked on every loop pass without any delay. There's also a timeout: if the motor doesn't reach the end within 15 seconds (broken belt, failed switch or an obstacle), the program stops the motor and enters a fault state. If both switches appear triggered at once, with NC wiring that most likely means a broken wire, and the motor isn't started. For the motor driver itself, see the DC motor with L298N article.

1// İki limit switch ile kapı / perde motoru (L298N)
2// Door / curtain motor with two limit switches (L298N)
3const int LIMIT_OPEN = 2; // açık uç anahtarı (NC) / open end switch (NC)
4const int LIMIT_CLOSED = 3; // kapalı uç anahtarı (NC) / closed end switch (NC)
5const int BUTTON_PIN = 4; // aç/kapa butonu, GND'ye / open/close button to GND
6const int IN1 = 8, IN2 = 9, ENA = 10; // L298N yön ve hız / L298N direction and speed
7const int MOTOR_SPEED = 200; // 0-255
8const unsigned long MAX_RUN_MS = 15000; // en uzun hareket süresi / longest allowed travel
9
10enum State { STOPPED, OPENING, CLOSING, FAULT };
11State state = STOPPED;
12bool lastDirOpen = false; // son hareket yönü / last direction of travel
13unsigned long moveStart = 0;
14int lastButton = HIGH;
15unsigned long lastButtonTime = 0;
16
17// NC + pull-up: HIGH = uca ulaşıldı ya da kablo koptu / HIGH = end reached or wire broken
18bool atOpen() { return digitalRead(LIMIT_OPEN) == HIGH; }
19bool atClosed() { return digitalRead(LIMIT_CLOSED) == HIGH; }
20
21void motorStop() { analogWrite(ENA, 0); digitalWrite(IN1, LOW); digitalWrite(IN2, LOW); }
22void motorOpen() { digitalWrite(IN1, HIGH); digitalWrite(IN2, LOW); analogWrite(ENA, MOTOR_SPEED); }
23void motorClose() { digitalWrite(IN1, LOW); digitalWrite(IN2, HIGH); analogWrite(ENA, MOTOR_SPEED); }
24
25void startMove(bool open) {
26 if (open && atOpen()) return; // zaten açık / already open
27 if (!open && atClosed()) return; // zaten kapalı / already closed
28 lastDirOpen = open;
29 moveStart = millis();
30 state = open ? OPENING : CLOSING;
31 if (open) motorOpen(); else motorClose();
32 Serial.println(open ? "Aciliyor / opening" : "Kapaniyor / closing");
33}
34
35void setup() {
36 Serial.begin(115200);
37 pinMode(LIMIT_OPEN, INPUT_PULLUP);
38 pinMode(LIMIT_CLOSED, INPUT_PULLUP);
39 pinMode(BUTTON_PIN, INPUT_PULLUP);
40 pinMode(IN1, OUTPUT);
41 pinMode(IN2, OUTPUT);
42 pinMode(ENA, OUTPUT);
43 motorStop();
44}
45
46void loop() {
47 // 1) Uç konum: her turda, gecikmesiz kontrol / end position: checked every pass, no delay
48 if (state == OPENING && atOpen()) { motorStop(); state = STOPPED; Serial.println("Acik / open"); }
49 if (state == CLOSING && atClosed()) { motorStop(); state = STOPPED; Serial.println("Kapali / closed"); }
50
51 // 2) Zaman aşımı: anahtar hiç tetiklenmezse dur / timeout: stop if the switch never trips
52 if ((state == OPENING || state == CLOSING) && millis() - moveStart > MAX_RUN_MS) {
53 motorStop();
54 state = FAULT;
55 Serial.println("HATA: zaman asimi / FAULT: timeout");
56 }
57
58 // 3) Buton: kenar algılama + 50 ms debounce / button: edge detection + 50 ms debounce
59 int b = digitalRead(BUTTON_PIN);
60 if (b != lastButton && millis() - lastButtonTime > 50) {
61 lastButtonTime = millis();
62 lastButton = b;
63 if (b == LOW) {
64 if (state == OPENING || state == CLOSING) {
65 motorStop(); // hareket halindeyse dur / stop if moving
66 state = STOPPED;
67 } else if (state == FAULT) {
68 state = STOPPED; // hatayı onayla / acknowledge the fault
69 Serial.println("Hata sifirlandi / fault cleared");
70 } else if (atOpen() && atClosed()) {
71 state = FAULT; // iki uç birden: kablo koptu / both ends: broken wire
72 Serial.println("HATA: iki anahtar birden / FAULT: both switches");
73 } else if (atClosed()) {
74 startMove(true);
75 } else if (atOpen()) {
76 startMove(false);
77 } else {
78 startMove(!lastDirOpen); // ortadaysa ters yöne / in the middle: reverse
79 }
80 }
81 }
82}
83The program uses a simple state machine: STOPPED, OPENING, CLOSING and FAULT. The motor turns only in the OPENING or CLOSING state, and in each state only the switch in that direction is considered, so releasing the closed-end switch when leaving it doesn't stop the motor by mistake. In addition to software, you can add safety in hardware: an old but very robust method is to wire each end switch's NC contact in series with the motor line and place a diode across the switch terminals in the reverse direction. When the motor reaches the end, the contact opens and the current is cut; to run in the opposite direction, current flows through the diode and the motor can move back off the end. With this method the switch's DC current rating must be higher than the motor's stall current, and the diode must carry at least that current. You'll find a complete curtain example in the automatic curtain article.
CNC and 3D printer limit switches (endstops)
CNC machines and 3D printers don't know where their axes are at power-up. In a process called homing, each axis moves slowly towards its end switch and treats the point where the switch triggers as zero. In GRBL running on an Arduino Uno, the limit switches connect to D9 for X, D10 for Y and D12 for Z; in GRBL 1.1, with variable spindle enabled, the Z limit moves from D11 to D12, so on a CNC Shield V3 you need to connect the Z switch to the pin labelled "SpnEn". GRBL uses the pins with internal pull-ups and expects NO switches by default; with NC wiring you invert the logic with $5=1. In Marlin firmware the same setting is the endstop hit state in Configuration.h. For the full setup, see the Arduino CNC and GRBL article.
| GRBL setting | Function | Recommended value |
|---|---|---|
| $5 | Inverts the limit switch logic | 1 for NC wiring, 0 for NO wiring |
| $20 | Soft limits (prevent leaving the work area) | 1 if homing works |
| $21 | Hard limits (stop everything when a switch triggers) | 1 |
| $22 | Enables the homing cycle | 1 |
| $24 / $25 | Homing slow feed and fast seek rate (mm/min) | Around 25 / 500 |
| $27 | Pull-off distance from the switch after homing (mm) | 1–2 |
Homing and emergency stop with ESP32
The ESP32 code below shows on a small scale what GRBL does, on a stepper motor axis driven by an A4988. There's a switch at each end of the axis: the home switch on GPIO 32 and the safety switch on GPIO 33. At start-up the motor moves quickly to the home switch, backs off 200 steps, then approaches very slowly to find the trigger point precisely, backs off 50 steps and calls that point zero. This two-stage approach stops the switch lever from flexing on a fast approach and shifting the point. During motion two limits work together: the soft limit keeps the target between 0 and 8000 steps, and the hard limit is an interrupt connected to the safety switch. The interrupt function only raises a flag; the main loop checks this flag before every step and stops. For details on interrupts, see the Arduino interrupt article; A4988 wiring is in the A4988 guide.
1// ESP32 + A4988: limit switch ile sıfırlama (homing) ve donanım sınırı
2// ESP32 + A4988: homing with a limit switch and a hardware limit
3const int STEP_PIN = 26;
4const int DIR_PIN = 27;
5const int HOME_SWITCH = 32; // NC, COM -> GND (sıfır ucu / home end)
6const int MAX_SWITCH = 33; // NC, COM -> GND (güvenlik ucu / safety end)
7const long MAX_STEPS = 8000; // eksen boyu, adım / axis length in steps
8
9volatile bool limitHit = false;
10long position = 0;
11
12void IRAM_ATTR onMaxSwitch() {
13 limitHit = true; // kesmede yalnız bayrak / only a flag inside the ISR
14}
15
16bool homeTriggered() { return digitalRead(HOME_SWITCH) == HIGH; }
17
18void stepOnce(int pauseUs) {
19 digitalWrite(STEP_PIN, HIGH);
20 delayMicroseconds(5);
21 digitalWrite(STEP_PIN, LOW);
22 delayMicroseconds(pauseUs); // büyük = yavaş / larger = slower
23}
24
25bool homeAxis() {
26 long n = 0;
27 digitalWrite(DIR_PIN, LOW); // sıfıra doğru / towards home
28 while (!homeTriggered()) { // hızlı yaklaşma / fast approach
29 stepOnce(800);
30 if (++n > MAX_STEPS + 1000) return false; // anahtar bulunamadı / switch not found
31 }
32 digitalWrite(DIR_PIN, HIGH); // geri çekil / back off
33 for (int i = 0; i < 200; i++) stepOnce(800);
34 digitalWrite(DIR_PIN, LOW); // yavaş ve hassas yaklaşma / slow, precise approach
35 n = 0;
36 while (!homeTriggered()) {
37 stepOnce(3000);
38 if (++n > 400) return false;
39 }
40 digitalWrite(DIR_PIN, HIGH); // anahtarı bırak / release the switch
41 for (int i = 0; i < 50; i++) stepOnce(1500);
42 position = 0; // yeni sıfır noktası / new zero point
43 return true;
44}
45
46bool moveTo(long target) {
47 target = constrain(target, 0, MAX_STEPS); // yazılım sınırı / soft limit
48 bool forward = target > position;
49 digitalWrite(DIR_PIN, forward ? HIGH : LOW);
50 while (position != target) {
51 if (limitHit) return false; // donanım sınırı / hard limit
52 if (!forward && homeTriggered()) return false; // beklenmedik sıfır / unexpected home hit
53 stepOnce(800);
54 position += forward ? 1 : -1;
55 }
56 return true;
57}
58
59void setup() {
60 Serial.begin(115200);
61 pinMode(STEP_PIN, OUTPUT);
62 pinMode(DIR_PIN, OUTPUT);
63 pinMode(HOME_SWITCH, INPUT_PULLUP); // GPIO 32/33 dahili pull-up'lı / have internal pull-ups
64 pinMode(MAX_SWITCH, INPUT_PULLUP);
65 // NC + pull-up: tetiklenince LOW -> HIGH / goes LOW -> HIGH when triggered
66 attachInterrupt(digitalPinToInterrupt(MAX_SWITCH), onMaxSwitch, RISING);
67
68 if (!homeAxis()) {
69 Serial.println("HATA: sifir anahtari yok / FAULT: no home switch");
70 while (true) delay(1000);
71 }
72 Serial.println("Sifirlandi / homed");
73}
74
75void loop() {
76 if (!moveTo(6000) || !moveTo(500)) {
77 Serial.println("DUR: sinir anahtari / STOP: limit switch");
78 while (true) delay(1000); // yeniden başlatana kadar bekle / wait until reset
79 }
80 Serial.print("Konum / position: ");
81 Serial.println(position);
82 delay(1000);
83}
84Limit switch with MicroPython on the Raspberry Pi Pico
On the Pico you build the same door logic with MicroPython. The switches connect to GP14 and GP15 with Pin.PULL_UP, and each one gets an interrupt (irq) that fires on the rising edge. The interrupt function stops the motor only if it is moving in that direction at that moment, so bounce while releasing the closed-end switch can't stop the motor by mistake. The main loop repeats the same check and applies a 15-second timeout; the double check is a cheap safeguard for the rare case where an interrupt is missed for some reason. As a motor driver you can use a module that accepts 3.3 V logic, such as the L298N, L9110S or TB6612FNG.
1# Raspberry Pi Pico (MicroPython): iki limit switch ile motor durdurma
2# Raspberry Pi Pico (MicroPython): stopping a motor with two limit switches
3from machine import Pin
4import time
5
6limit_open = Pin(14, Pin.IN, Pin.PULL_UP) # NC, COM -> GND
7limit_closed = Pin(15, Pin.IN, Pin.PULL_UP) # NC, COM -> GND
8button = Pin(13, Pin.IN, Pin.PULL_UP) # buton GND'ye / button to GND
9in1 = Pin(16, Pin.OUT) # motor sürücü IN1 / motor driver IN1
10in2 = Pin(17, Pin.OUT) # motor sürücü IN2 / motor driver IN2
11
12MAX_RUN_MS = 15000
13direction = 0 # 1 = açılıyor / opening, -1 = kapanıyor / closing, 0 = duruyor / stopped
14last_dir = -1
15move_start = 0
16
17def motor(d):
18 global direction
19 direction = d
20 in1.value(1 if d == 1 else 0)
21 in2.value(1 if d == -1 else 0)
22
23# Yalnız gidilen yöndeki anahtar durdurur / only the switch in the travel direction stops
24def on_open(pin):
25 if direction == 1:
26 motor(0)
27
28def on_closed(pin):
29 if direction == -1:
30 motor(0)
31
32limit_open.irq(trigger=Pin.IRQ_RISING, handler=on_open)
33limit_closed.irq(trigger=Pin.IRQ_RISING, handler=on_closed)
34
35def start(d):
36 global last_dir, move_start
37 if d == 1 and limit_open.value():
38 return # zaten açık / already open
39 if d == -1 and limit_closed.value():
40 return # zaten kapalı / already closed
41 last_dir = d
42 move_start = time.ticks_ms()
43 motor(d)
44
45last_button = 1
46while True:
47 # Yedek kontrol: kesme kaçarsa / backup check in case an interrupt is missed
48 if direction == 1 and limit_open.value():
49 motor(0)
50 if direction == -1 and limit_closed.value():
51 motor(0)
52 if direction != 0 and time.ticks_diff(time.ticks_ms(), move_start) > MAX_RUN_MS:
53 motor(0)
54 print("HATA: zaman asimi / FAULT: timeout")
55
56 b = button.value()
57 if b == 0 and last_button == 1:
58 if direction != 0:
59 motor(0)
60 elif limit_closed.value():
61 start(1)
62 elif limit_open.value():
63 start(-1)
64 else:
65 start(-last_dir) # ortadaysa ters yöne / in the middle: reverse
66 time.sleep_ms(50) # buton debounce / button debounce
67 last_button = b
68 time.sleep_ms(5)
69Limit switch project ideas
- Automatic chicken coop door: on a door that opens in the morning and closes in the evening, two end switches stop the motor; details in the automatic chicken coop door article.
- Motorised curtain or blind: one switch at the top and one at the bottom, with timeout protection in between.
- Mini CNC and laser engraver: homing and hard limits for X, Y and Z.
- Door and drawer detection: a simple circuit that turns on an LED strip when a cupboard door opens; NO wiring is fine here.
- Camera slider: repeatable time-lapse shots on a stepper-driven rail with two end switches and homing.
- Conveyor and part counter: count boxes passing on a belt with a roller-lever switch.
Common mistakes and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| Counter rises several times per press | Contact bounce | Add a 20 ms software debounce or a 10 kΩ + 100 nF RC filter |
| Motor doesn't stop at the end | delay() in the code, the switch isn't read | Don't use delay() in the loop, check the end on every pass |
| Motor never runs, both ends triggered | NC wire broken or COM not connected | Check the wires with a multimeter, there should be continuity between NC and COM |
| Motor stops right away when leaving the closed end | Bounce of the released switch counts as a stop | Only consider the switch in the direction of travel |
| Motor stops randomly while running | Motor noise couples into a long cable | Use twisted or shielded cable, add a 1–4.7 kΩ external pull-up and 100 nF |
| On the ESP32 the switch is always HIGH or random | No internal pull-up on GPIO 34–39 | Add an external 10 kΩ pull-up or move to a pin with a pull-up |
| Homing point is slightly different each time | The switch is hit too fast | Two-stage homing: approach fast, back off, approach slowly |
A limit switch is the cheapest and most reliable way to know exactly where a mechanism is with a single digital pin: with NC wiring and INPUT_PULLUP you're safe even against a broken wire. In the BlueGrays app you can explore projects with buttons, reed switches and stepper motors, each with a step-by-step circuit diagram and ready-made code, and apply the end-position logic you learned here to your own door, curtain or CNC project.
Frequently asked questions
What do NO and NC mean on a limit switch?
NO means normally open and NC means normally closed. While the switch is untouched, COM is connected to NC; when it's pressed, the COM–NC path opens and the COM–NO path closes.
How do you connect a limit switch to an Arduino?
Connect COM to GND and NC to a digital pin, and set the pin with pinMode(pin, INPUT_PULLUP). With this wiring the pin reads LOW when the switch is released and HIGH when pressed; since a broken wire also reads HIGH, the system stays on the safe side.
Does a limit switch need a resistor?
Arduino, ESP32 and Pico have internal pull-up resistors, so in most cases no external resistor is needed. On long or noisy cables a 1–10 kΩ external pull-up and a 100 nF capacitor give more stable readings; on the ESP32's GPIO 34–39 an external pull-up is required.
How do you debounce a limit switch?
In software by waiting until the reading stays unchanged for 10–20 ms, or in hardware with an RC filter. To stop a motor you don't need to wait for debounce; the motor should be stopped on the very first trigger reading.
Can a limit switch stop a motor directly?
Yes, if you wire the NC contact in series with the motor, the current is cut when the switch opens; a diode across the switch terminals lets the motor run in reverse. With this method the switch's DC rating must exceed the motor's stall current, otherwise the contacts burn out quickly.
Should a 3D printer endstop be wired NC or NO?
NC wiring is recommended for safety, because a broken wire looks like a triggered switch and the axis doesn't crash into the end. On three-pin endstop modules this wiring is already done on the board; in GRBL you match the software logic with $5, and in Marlin with the endstop hit state setting.
Projects to build after reading this
See all projects
LED Control with a Push Button (Push)
Just like a doorbell: the light stays on as long as you press, and goes off when you let go.

Toggle an LED with a Button (On/Off)
Press the button once and the light comes on, press it again and it goes off, just like the light switch in your room.

ESP32 LED Control with Push Button (Push)
The LED lights up when the button is pressed and turns off when released. Shows how the ESP32's digital input pin and internal pull-up resistor are used. The INPUT_PULLUP mode eliminates the need for an external resistor.

Raspberry Pi Pico Button Controlled LED (Push)
First input project with Pico — button read! LED lights while button is pressed, off when released. This is the big step after LED animations: signal input from the world to Pico. Learn Pin.IN (input mode), Pin.PULL_UP (internal pull-up resistor — standard for buttons), button.value() reading. GP14 LED, GP2 button (internal PULL_UP). Pressed = LOW (0), released = HIGH (1) — reverse logic seems confusing at first but is industry standard.

Raspberry Pi Pico Button Debounce: IRQ vs Software Polling
If one press of a button made your code count 3-4 times, the culprit is contact bounce: the button's metal contacts open and close many times within microseconds as they touch! In this project we count the same button in 2 different ways and compare them side by side in Serial: RAW polling (catches the bounce and miscounts) and IRQ + software debounce (counts correctly).

Using a Stepper Motor
A motor that turns step by step, exactly as far as you want, like the hand of a clock.

Reading a Reed Switch
Ever wondered about the magnetic switch inside door and window alarms? When a magnet comes near the reed relay module, the tiny switch inside it closes; the Arduino reads it once a second and prints…

Reed Switch Door Sensor
Tell whether your door is open or closed just by looking at a light. You attach a small magnet to the door and a magnet-sensing switch to the frame; when the door is closed they sit side by side and…
More articles
BlueGrays app
Build this circuit step by step on your phone
Wiring diagram, code and parts list on one screen. 500+ Arduino, ESP32, ESP8266, Pico, mBot and micro:bit projects ready to build.
Scan with your phone
Point your camera at the code and your phone's app store opens.
or open the store

