Very quick question regarding the internal pullup resistor.

Is it possible to enable the pullup resistor using direct port manipulation, or is it a pinMode/digitalWrite exclusive function?

Enabling the pull-up resistor is as simple as writing a HIGH (1) to the PORT bit when it's in input mode.

If you look at the source of pinMode and digitalWrite you'll see that they are implemented in terms of direct port manipulation.

something like this:

  DDRx &= ~b ;
  PORTx |= b ;

For suitable x and b.

A subtle point to note is that digitalWrite() et al are written with critical sections so they work as expected if called from normal code and interrupt routines "simultaneously" - simple port manipulation code such as the above won't be reliable in the face of interrupt routines that call pinMode() and digital/analogWrite() on the same port.

MarkT: A subtle point to note is that digitalWrite() et al are written with critical sections so they work as expected if called from normal code and interrupt routines "simultaneously" - simple port manipulation code such as the above won't be reliable in the face of interrupt routines that call pinMode() and digital/analogWrite() on the same port.

This is interesting. So if I understand correctly, changing DDRx and PORTx multiple times in a say 8khz interrupt routine won't provide reliable results ?

You want to keep interrupt routines as short as possible.

Vinter: This is interesting. So if I understand correctly, changing DDRx and PORTx multiple times in a say 8khz interrupt routine won't provide reliable results ?

I would expect that to be OK, as long as you don't also manipulate either of those ports (or call any code that manipulates those ports) in your main loop() code.

I would set a flag in the IRQ and use it to trigger port manipulation in the regular code.

Make sure the flag is data type "volatile", global between ISR and other stuff. (I think that's the right one)

Vinter: This is interesting. So if I understand correctly, changing DDRx and PORTx multiple times in a say 8khz interrupt routine won't provide reliable results ?

Inside an interrupt routine is fine, as interrupts are off. He is referring to doing it outside an interrupt routine.