Go Down

Topic: On one line (Read 1 time) previous topic - next topic

bperrybap


You can also use direct port manipulation without fors or whiles:

Code: [Select]

DDRD = DDRD | B0111111;  // pins 2-7
DDRB = DDRB | B10000000; // pin 8


You can use port manipulation, but as mentioned earlier it isn't portable across MCUs
as it is stepping outside the Arduino core library code.
Even if you are willing to accept that, the above statements still do not do what was requested:
Set D2 to D10 as outputs and set D2 to D10 LOW.

This example shows, how easy it is to accidentally incorrectly set/configure the wrong pins
when using direct port i/o.

The above statements are only setting the direction bits  for 7 pins.
Assuming a mega328/168, the above statements  set the direction bits to "output"
for Arduino pins D0 (Serial RX), D1 (Serial TX), D2, D3, D4, D5, and (XTAL2)

It is not setting the direction bits for pins D6, D7, D8, D9, and D10
and it is trying to set Pins D0 and D1 which are the serial port.
Not sure what happens when you try to set the serial port RX pin or the Crystal XTAL2
pin to output.
It also does not set any of the pin output levels to LOW as was requested.

The correct statements would be:

Code: [Select]

DDRD |= B11111100; // pins 2-7 as output
DDRB |= B00000111; // pins 8-10 as output
PORTD &= ~B11111100; // set pins 2-7 as LOW
PORTB &= ~B00000011; // set pins 8-10 as LOW


--- bill

Nick Gammon


You can also use direct port manipulation without fors or whiles:

Code: [Select]

DDRD = DDRD | B0111111;  // pins 2-7
DDRB = DDRB | B10000000; // pin 8



I'm inclined to agree with bperrybap here. In general, the pins are split between different ports, so you don't necessarily even achieve the aim of doing things "in one line". It is also less portable, and much less easy to verify at a quick glance that you are setting the right pins.

The couple of microseconds you might save are not generally needed to be saved. In particular, it is rarely likely that you need to set ports to inputs or outputs "in a hurry".
http://www.gammon.com.au/electronics

pekkaa

Yes, I totally agree with with you, Nick and  bperrybap. I didn't claim that direct port manipulation (or using "while" instead of "for") was a better way to do it. I just meant to demonstrate that there are several ways to do it.

Nick Gammon

OK, no problem then.
http://www.gammon.com.au/electronics

Go Up