Port Mapping

I'm trying to read 6 digital inputs to see if their state changes.

I have digital 2 to 7 inclusive held high or low:
2 = high
3 = high
4 = low
5 = low
6 = high
7 = low

My code is very basic at the moment but I do not understand why the state of 7 is not displayed in Serial Monitor.

int val = 0;
int prevState = 0;

void setup() {
DDRD = 0x00;
Serial.begin(9600);
}

void loop(){
prevState = val;
val = PIND;
if (val != prevState) {
Serial.println(val,BIN);
}
delay(1000);
}

I see 1001111 in Serial Monitor. I realise the left most two bits are the RX and TX pins so to me are irrelevant but only 5 data bit are visible.

Why is the bit 7 missing??

Thanks for any help.

DDRD = 0x00;

This is setting all 8 pins on the port. You do not want to be mucking with pins 0 and 1.

I see 1001111 in Serial Monitor. I realise the left most two bits are the RX and TX pins so to me are irrelevant but only 5 data bit are visible.

Not true. The right 6 values are the values of interest, regardless of the actual number of characters displayed. Leading 0s are not printed.

PaulS

Thanks for this.

If I change 7 to a high it shows up, great.

What should 0 & 1 be set to? Would xxxxxx01 setting TX to an output and RX to an input be correct?

Would xxxxxx01 setting TX to an output and RX to an input be correct?

They should not be messed with. You need to learn how to OR in the bits of interest, without changing the other bits.

Here Arduino Reference - Arduino Reference recommends:

DDRD = DDRD | B11111100;  // this is safer as it sets pins 2 to 7 as outputs
	                  // without changing the value of pins 0 & 1, which are RX & TX

I don't understand the difference between DDRD = DDRD | B00000000; and:

DDRD = 0x00;

Thanks again

I don't understand the difference between DDRD = DDRD | B00000000; and DDRD = 0x00;

The DDRD = 0x00; statement sets all bits to 0. The DDRD = DDRD | B00000000; statement changes the bits that are specified (none, in this case).

The DDRD = DDRD | B11111100; changes (sets) bits 2 through 7, because they are non-zero in the value after the |.

This tutorial should explain why they are different:
http://www.arduino.cc/playground/Code/BitMath

Thanks to both of you, now I understand a little better.

To jraskell, I had seen "Bit Math Tutorial" but dismissed it before reading further down thinking it not relevant.

:slight_smile: