Magnetic Switch to Turn on LEDs

Hi there,

I'm pretty new to arduino, and while I can do basic electronics I really don't like it, but I'm working with this for a school project.

I am attempting to turn on an LED when I complete a circuit. Eventually I will also have sound go off, but I'm tackling this one area at a time.

I am using a magnetic reed switch, which is normally closed (NC) when within range. Below is my code:

int MagneticPin=8;
int ledPin=10;

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

void loop() {
int sensorValue = digitalRead(MagneticPin);
if(sensorValue==1)
{
digitalWrite(ledPin,HIGH);
}
else
{
digitalWrite(ledPin,LOW);
}
}

However, when I upload the code, the LED is on when the magnets are not within range of each other, and the LED turns off when the magnet are within range.

So, my questions are:

  1. Did I purchase the right type of switch?
  2. If I did not purchase the right type, is there a way to fix this without purchasing new switches? Or,
  3. If I did purchase the right type of switch, what is wrong with my code?

Thank you in advance.

a quick fix without you touching any of your electronics setup (i figured you don't want to do that) is to just invert the reading from the switch:

  int sensorValue = digitalRead(!MagneticPin);

or you change this line:

  if(sensorValue==0)
  int sensorValue = digitalRead(!MagneticPin);

Whoops - presume this was a braino - and that you meant:

  int sensorValue = !digitalRead(MagneticPin);

whooops - mea culpa, big braino :blush:
could attract some really weird bugs;-)