Mega2560 overriding portB standard functions with alternative functions

Hi all,

I am have developed a new communication method, bit of a mix of SPI, I2C and Serial(I use 4 wires similar to SPI, but no Dedicated SS, flexible addressing, flexible data format, no master and slave but all can transmit and receive). I have it working, I'm using two external interrupts from pins D2 D3 of the Arduino Mega.

I now want to make it compatible with SPI wiring, meaning I want to use pins 51 MISO, 52 MOSI, 53 SCK, 54 SS instead of D2 D3 D4 D5 I am using now.

I have been looking at the ATMEGA2560 datasheet and it seems to be possible to override the standard functions of these pins (MOSI, MISO , SCK, SS) and use their alternative functions which are general digital I/Os pins(Datasheet page 72 chapter "13.3 Alternate Port Functions") which is what I need.

On page 76 chapter "13.3.2 Alternate Functions" of Port B where pins alternative functions are explained and on the next page we get to explanation of SPI pins starting with the MOSI pin:


• MISO/PCINT3 – Port B, Bit 3
MISO: Master Data input, Slave Data output pin for SPI channel. When the SPI is enabled as a master, this pin is
configured as an input regardless of the setting of DDB3. When the SPI is enabled as a slave, the data direction of
this pin is controlled by DDB3. When the pin is forced to be an input, the pull-up can still be controlled by the
PORTB3 bit.
PCINT3, Pin Change Interrupt source 3: The PB3 pin can serve as an external interrupt source.


So as it says, the PB3 pin can be used as an external interrupt source, which is just what I need. But my question is How?? what would the code be to use the alternative function and use the PB3 pin as an input and attach the external interrupt to execute an ISR function?

On the other hand I would also need to use the PB2 pin as an output and make it high or low.

Can anyone please help. I will share the hole code once this is fixed, so there is only one "master" version.

Thanks!

Hi again,

I thought this would be unusual and difficult but it seems there have been many people having this problem before and have written several libraries. I found this one below. Have to test speeds but think it will be ok. Just in case anybody needs more interrupts, or interrupts on different pins, here is the link to the library.

Stay Home!!

Thanks!!

The SPI pins don't do SPI unless you explicitly use an SPI library. They DEFAULT to GPIO.

Almost any of the pins can be Pin Change Interrupts. That's a per-port interrupt - if you enabled more than one pin per port as interrupts, you have figure out which pin interrupted in software (compared to the "external interrupts", which have an entire interrupt per pin.)
As you've discovered, the pin change interrupts aren't included in the core "attachInterrupt" function, but they are supported by many 3rd party libraries.