Bits and bytes

Using the port F as digital I/O in Teensy++

I wanted to use the port F in Teensy++ board as ordinary digital inputs/outputs and it turned out that there is an extra step involved to ordinary DDR stuff. I’m coding using the Teensy port of core Arduino libraries to AT90USB646 chip. After checking the chip datasheet, I found that the proper port initialization includes setting the DIDR0 register (setting desired pins of port F to digital instead of analogue). So the full initialization should look like

#define IO_MASK B00000111  // three pins used (0, 1 and 2)
#define IO_DDR  B00000100    // pins 0 and 1 inputs, 2 output
#define IO_PINS B11111100

// Setting the three pins as digital:
DIDR0  &=   (~IO_MASK);

// Setting the direction of pins:
DDRF   |=   (IO_MASK  & IO_DDR);
DDRF   &=   (~IO_MASK | IO_DDR);

// Setting the initial state of the pins:
PORTF  |=   (IO_MASK  & IO_PINS);
PORTF  &=   (~IO_MASK | IO_PINS);

Now the three pins on port F can be used as normal digital inputs/outputs with usual Arduino digitalRead/digitalWrite functions or PORTF/PINF registers. Perhaps I explain the DIDR0 register more in details in the future. Until then, don’t fear to check the datasheet.