Direct reading of a PORTD bit

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()
{
Serial.begin(9600);
// 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" :slight_smile: 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.

1 Like

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

PIND = BV(5);

Cheers, Udo

Aha! Thanks Condemned! PIND instead of PORTD.

Does that stand for Port INput D ?

Yes. (my shortest post ever :slight_smile: )

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.

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.

Lefty