Go Down

Topic: Direct reading of a PORTD bit (Read 4752 times) previous topic - next topic


In the code below if I use digitalRead(6) I can read the logic level on my PortD Pin6. If I use the Led = PORTD & B11000000 statement I do not get bit6 wiggling as I'd expect.

What am I doing wrong?

void setup()
   // prints title with ending line break
   Serial.println("Setup starting");
   // The Data Direction Register of Port D, don't touch the
   // lower two bits which are serial IO
   DDRD = DDRD | B00111100 ;


void loop()
   int i = 0 ;
   int iLed = 0 ;
   while (true) {

       // iLed = digitalRead (6) ;
       iLed = PORTD & B11000000 ;
       Serial.println("iLed =");
       Serial.print(iLed, OCT);    


I take it by "wiggling" you mean "toggling"  :) ie 1 becomes 0 and 0 becomes 1

You can do this with an AND operation, because only 1 and 1 = 1 , so as soon as you get a 0 in there, the output will always be 0, it will never flip back to 1 again.

You need an XOR operation eg

PORTD ^= BV(5);

Will flip Bit 5


You need to use PIND to read the port, rather than PORTD.

Udo Klein

Feb 23, 2010, 10:00 pm Last Edit: Feb 23, 2010, 10:01 pm by udoklein Reason: 1
If you just want to toggle the port you can write PIND. The Atmel datasheet says:

Toggling the Pin
              Writing a logic one to PINxn toggles the value of PORTxn, independent on the value of DDRxn.
              Note that the SBI instruction can be used to toggle one single bit in a port.

Hence you can just write a logical one into the desired bit and it will toggle. So you may write

Code: [Select]

PIND = BV(5);

Cheers, Udo
Check out my experiments http://blog.blinkenlight.net


Aha! Thanks Condemned! PIND instead of PORTD.

Does that stand for Port INput D ?


Feb 25, 2010, 08:42 pm Last Edit: Feb 25, 2010, 08:45 pm by willich Reason: 1
Yes. (my shortest post ever :) )

EDIT: i screwed it: Every Port has 3 Registers: DDRx, PINx and PORTx.

PIN to read, PORT to write, and DDR to clarify the "DataDirection (Register)"

But, as seen in Post before: you can write to PIN, and the Bits which are written to "1" change their state.


Feb 26, 2010, 12:28 am Last Edit: Feb 26, 2010, 12:29 am by retrolefty Reason: 1
But, as seen in Post before: you can write to PIN, and the Bits which are written to "1" change their state.

Also you can write with a PORTx pin command, and if the pin is in the input mode (via DDRx pin) and it will turn on (if 1) or off (if 0) the internal pull-up for that pin.


Go Up