Вернуться на страницу библиотеки модулей
const int ledPin = 13; // on-board LED
const int reedPin = 2; // KY-021 signal (S) pin
int reedState = HIGH; // debounced reed state (HIGH = no magnet)
int lastReading = HIGH; // previous raw reading
unsigned long lastChange = 0;
const unsigned long debounceMs = 20;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(reedPin, INPUT); // the KY-021 has an on-board pull-up resistor
}
void loop() {
int reading = digitalRead(reedPin);
// restart the debounce timer whenever the raw reading changes
if (reading != lastReading) {
lastChange = millis();
lastReading = reading;
}
// accept the reading once it has stayed stable long enough
if (millis() - lastChange > debounceMs) {
reedState = reading;
}
// the KY-021 reads LOW when a magnet closes the reed switch
if (reedState == LOW) {
digitalWrite(ledPin, HIGH); // magnet detected -> LED on
} else {
digitalWrite(ledPin, LOW); // no magnet -> LED off
}
}
Рекомендуемые ссылки:
Arduino Mini Reed Switch KY-021 (HW-497) — Wiring & Code
KY-021 Mini reed magnet – SensorKit
Using the Mini Magnetic Reed Module KY-021 with Arduino – Phipps Electronics
Mini Reed Switch Module KY-021 on Arduino – Hackster.io
Arduino – Magnetic Reed Switch KY-021 – Instructables