# quick question abt digitalRead in a circuit

Hi, I have a circuit/sensor that kinda looks like this

Each number corresponds with the digital pin number on the arduino decimilia board. I'm using the USB connection (and powered by USB) on a windows xp laptop. Here is the code that i'm using on this board:

``````int val = 0;

void setup() {
pinMode(7,OUTPUT);

pinMode(6,INPUT);
pinMode(5,INPUT);
pinMode(4,INPUT);
pinMode(3,INPUT);

Serial.begin(9600);
Serial.println("starting...");
}

void loop() {
digitalWrite(7,HIGH);

Serial.print(" 6 : ");
Serial.println(val);

Serial.print(" 5 : ");
Serial.println(val);

Serial.print(" 4 : ");
Serial.println(val);

Serial.print(" 3 : ");
Serial.println(val);

delay(1000);
}
``````

Now when everything is turned off, the serial monitor reports it back as randomly 1 or 0, but when I switch one of the switch to on, it reports 1 correctly. What am I doing wrong here? Why doesn't it say 0 when the switch is off?

I don't understand from that pic or code what you're trying to do, but I think your problem is because those input pins will be floating - so you'll need a pull-down resistor to get a 0 when nothing connected.

G.

What am I doing wrong here?

Apart from not being able to draw a circuit to save your life nothing.

Why doesn't it say 0 when the switch is off

Because as mentioned the inputs are floating. That is not connected to anything so they pick up electrical noise in the air. Zero is just as solid a state as a one. Zero is not the absence of a one it is a state every bit as defined as a one. When it is off these is nothing defined so the input floats between the two states.

Okay, so the code like this (using pullup resistor) seem to work. Only thing is that 1 means that its not connected and 0 is connected. I didn't have to change the hardware config at all:

``````int val = 0;

void setup() {
pinMode(7,OUTPUT);

pinMode(6,INPUT);
digitalWrite(6,HIGH);
pinMode(5,INPUT);
digitalWrite(5,HIGH);
pinMode(4,INPUT);
digitalWrite(4,HIGH);
pinMode(3,INPUT);
digitalWrite(3,HIGH);

Serial.begin(9600);
Serial.println("starting...");
}

void loop() {
digitalWrite(7,LOW);

Serial.print(" 6 : ");
Serial.println(val);

Serial.print(" 5 : ");
Serial.println(val);

Serial.print(" 4 : ");
Serial.println(val);