This is vaguely related to my previous thread, but deals with another matter,
http://forum.arduino.cc/index.php?topic=181325.0
I have this library code [3rd party, not mine], which I'm trying to generalize. It currently hardcodes the CS pin value via conditional compilation, and does not allow the Port-value to be changed by the program, since it uses bitClear() and bitSet() for efficiency.
original header file:
----------------------
#define SS_PORT PORTB
#define SS_BIT 2 // for PORTB: 2 = d.10, 1 = d.9, 0 = d.8
original .ccp file:
---------------------
uint8_t RFM12B::cs_pin = SS_BIT; // CS pin value - modifiable.
// here is the critical function:
void RFM12B::XFER(uint16_t cmd)
{
bitClear(SS_PORT, cs_pin);
// digitalWrite(10, LOW);
// enable_cs();
Byte(cmd >> 8); // Byte() sends a databyte out the SPI port.
Byte(cmd & 0xFF);
bitSet(SS_PORT, cs_pin);
// digitalWrite(10, HIGH);
// disable_cs();
}
In the above, digitalWrite() will work, but is very slow. So, I want to define new functions as follows, which will allow changing the CS pin to any Port.bit, but also be very efficient. I came up with this, after trying several things. Anyone got a slam-dunk better way?
volatile uint8_t *ptr = &PORTB;
void RFM12B::enable_cs()
{
bitClear(*ptr, cs_pin);
}
void RFM12B::disable_cs()
{
bitSet(*ptr, cs_pin);
}
void RFM12B::set_CSpin( volatile uint8_t* porto, uint8_t pin )
{
ptr = porto;
cs_pin = pin;
}
call:
----
// eg, change CS to PORTD.5
radio.setCSpin( &PORTD, 5);
This also works, I guess,
#define enable_cs() bitClear(*ptr, cs_pin)
#define disable_cs() bitSet(*ptr, cs_pin)