(Reference) Magnetic Switch

Magnetic Switch

Wiring

Screenshot 2024-07-04 at 12.35.08 AM

Operation

  • Switch is “normally open” (open circuit) - HIGH
  • Switch is closed when placed near a magnet - LOW

Code

const int PIN_SWITCH = D2;

void setup() {
   pinMode(PIN_SWITCH, INPUT);  //configure
   Serial.begin(9600);
}

void loop() {
	//read button state
   int switchVal = digitalRead(PIN_SWITCH); 
   
    if (switchVal == HIGH) {
     Serial.write("Switch open");
   }
   else {
     Serial.write("Switch closed");
   }
 }

Credit

Updated: