Using port in ATmega 328

Hello everybody.
I just read User Guide about Port : Arduino Reference - Arduino Reference
But it 's so little informations ,how to use Port: turn on ,turn off each pins.
Example:
PORTD = B10101000; // sets digital pins 7,5,3 HIGH
PORTB |= B00000001; // sets digital pins 8 HIGH
I don't know how to set digital pins 8 to LOW ?
Can you explain PORTB | ,PORTB~ ,and give some examples using Port ?

I aslo upload a sample of linking led for everyone

void setup()
{
  DDRD = B11111111; // set PORTD (digital 7~0) to outputs
}

void loop()
{
  PORTD = B11110000; // digital 4~7 HIGH, digital 3~0 LOW
  delay(1000);
  PORTD = B00001111; // digital 4~7 LOW, digital 3~0 HIGH
  delay(1000);
}

I don't know how to set digital pins 8 to LOW

When you set a bit you OR the port with a value. To clear a bit you AND it. So for example

PORTD != B00010000;

Sets bit 4 and

PORTD &= ~B00010000;

clears the same bit. The ~ inverts the value so that is the same as

PORTD &= B11101111;

but usually it's considered easier to read, especially when constants are used.

#define SOME_BIT_VALUE B00010000
PORTD &= ~SOME_BIT_VALUE;

or the very common

#define SOME_BIT_POSITION 4
PORTD &= ~(1 << SOME_BIT_POSITION);


Rob

Thanks, Graynomad Rob
Can you upload a full example.pde ? , because i still not understand clearly :roll_eyes:
Thanks a lots.

Example to do what? I'm not sure I can make it much clearer.

I don't know how to set digital pins 8 to LOW ?

If you want to set pin 8 low then do this after the pin has been set to an output.

PORTB &= ~1;

or

PORTB &= ~B00000001;

if that's clearer.

Your first post indicated a reasonable grasp of the principals of setting bits and I just showed you how to clear a bit so you should be good to go.

If you are going to use these methods you have study the schematic of the board you are using to see which pin is on what port.

What exactly do you want to do? Why is digitalWrite() not suitable?


Rob

taipscode:
Thanks, Graynomad Rob
Can you upload a full example.pde ? , because i still not understand clearly :roll_eyes:
Thanks a lots.

PORTB |= B00000001; // Set pin high
PORTB &= B11111110; // Set pin low

and:

PINB = B00000001; // Flip the state of the pin

That looks right.


Rob

Yes,That's OK.

PORTB |=
only use for turn on Pin ,can not turn off :wink:
If want to turn off ,use to AND PORTB &= , PORTB &= ~1

Thanks Rob and Fungus