PIND Questions

I I continue to struggle with PIND.

I I wrote a simple sketch as an attempt to better understand PIND. In the sketch below, PIND reads my NANO's pin D4 state which is connected to a KY40 SW pin. I have independently confirmed this KY40 DOES have the switch button and it does work.

Question 1 :The PIND read correctly reads a button press as "0". But with no button press, PIND reads pinD4 as 16.
Where in the 16 coming from?

Question 2: Will PIND reads (with masking)affect subsequent PIND reads in the same sketch? I.e, are PIND reads i ndependent?

int pinSW=4;
int val;
void setup() {
pinMode(pinSW, INPUT_PULLUP);
Serial.begin(115200);
}

void loop() {
delay(1000);
val = PIND & 0b00010000;//read the button state (NANO pin D4)
//When no button push,the val read is 16 ??
//When Button pushed, val read is 0.                                                                                                                                 
Serial.println(val);
}

ardocman:
I I continue to struggle with PIND.

Then you haven't had a good sit down and read the AVR data sheet and avr/portpins.h.

1
2631 
8426 8421
0001 0000  = 16 

0001 0001  = 17
etc.

Try:

val = (PIND & 0b00010000) >> 4;
Serial.println(val);

If you just want to get a 1 or a 0 back you can use the bitRead function
You can read up on it in the Reference section of this website.

result=bitRead(PIND,4);

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.