Go Down

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

oransen

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);    

programmer

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


condemned

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

Udo Klein

#3
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

oransen

Aha! Thanks Condemned! PIND instead of PORTD.

Does that stand for Port INput D ?


Pumbaa

#5
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.

retrolefty

#6
Feb 26, 2010, 12:28 am Last Edit: Feb 26, 2010, 12:29 am by retrolefty Reason: 1
Quote
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

Go Up
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy