Reed switch not reading

I have a reed switch with a 10k resistor (see attached). I am using this code:

#define reed A0

int reedVal;

void setup(){
  Serial.begin(9600);
  /* the part that I forgot
  pinMode(reed,INPUT);
  digitalWrite(reed,HIGH);
  */
}

void loop(){
  reedVal = analogRead(reed);
  Serial.println(reedVal);
  delay(500);
}

When I open the serial monitor, it just spits out constant zeros. Putting a magnet next to it does nothing. If I pull the A0 pin out while serial monitor is open, I see numbers all over the place. Measuring the resistance of the reed/resistor setup with a multimeter yields results when I pass a magnet past it, yet not with the Arduino.

How have I messed up this time?

EDIT: Solved. Forgot to put the digitalWrite in the setup.

majhi:
How have I messed up this time?

Yep!

Twice.

Firstly, the reed switch should go to ground, but the resistor should go to Vcc. In fact, as long as the connections are short and not in proximity to other cabling, you do not need the resistor at all, but use the INPUT_PULLUP function for that pin.

Secondly, you are using analogRead() for a digital function - that is inappropriate.


pinMode(reed,INPUT);
digitalWrite(reed,HIGH);

OK, that is in fact the equivalent of INPUT_PULLUP.

On the ATmega based Arduinos you can analogRead() simulataneously to using the
pin as a digital pin, there is nothing wrong with that - unusual, but perfectly valid,
however this will not necessarily work on other microcontrollers (The Due doesn't
allow this AFAIK).

pinMode (pin, INPUT_PULLUP); is the new and portable way to set up
internal pullups, and obviously more readable.

Hi,
Mahji, you can use ExpressSch to draw your schematics, and under FILES, Export Schematic Images, this makes a jpg image of your schematic.

Tom... :slight_smile: