Pages: [1]   Go Down
Author Topic: Magnetic Switch to Turn on LEDs  (Read 559 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 1
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

sweden
Offline Offline
Newbie
*
Karma: 0
Posts: 4
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
 int sensorValue = digitalRead(!MagneticPin);

or you change this line:
Code:
  if(sensorValue==0)
« Last Edit: May 16, 2011, 03:02:59 am by forest » Logged

0
Offline Offline
Shannon Member
****
Karma: 215
Posts: 12489
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Code:
  int sensorValue = digitalRead(!MagneticPin);

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

Code:
  int sensorValue = !digitalRead(MagneticPin);
Logged

[ I won't respond to messages, use the forum please ]

sweden
Offline Offline
Newbie
*
Karma: 0
Posts: 4
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Pages: [1]   Go Up
Jump to: