Go Down

Topic: Magnetic Switch to Turn on LEDs (Read 987 times) previous topic - next topic


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);

void loop() {
  int sensorValue = digitalRead(MagneticPin);

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.


May 16, 2011, 10:00 am Last Edit: May 16, 2011, 10:02 am by forest Reason: 1
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:
Code: [Select]

 int sensorValue = digitalRead(!MagneticPin);

or you change this line:
Code: [Select]


Code: [Select]
  int sensorValue = digitalRead(!MagneticPin);

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

Code: [Select]
  int sensorValue = !digitalRead(MagneticPin);
[ I will NOT respond to personal messages, I WILL delete them, use the forum please ]


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

Go Up