Skip to content

Commit cf79dc6

Browse files
feat(SPI): Make SPISettings constructors constexpr
This turns SPISettings into a "literal type" and allows variables using it to be constexpr to guarantee the constructor is executed at compiletime. This requires (with C++11) that all variables are set using initializers instead of assignments and that the regular if cascade is replaced by a ternary if. It also requires explicit initializers for all values (omitted variables were previously initialized to zero anyway).
1 parent aab7d10 commit cf79dc6

File tree

1 file changed

+20
-23
lines changed

1 file changed

+20
-23
lines changed

libraries/SPI/src/SPI.h

+20-23
Original file line numberDiff line numberDiff line change
@@ -74,29 +74,26 @@ enum SPITransferMode {
7474

7575
class SPISettings {
7676
public:
77-
SPISettings(uint32_t clock, BitOrder bitOrder, uint8_t dataMode, bool noRecv = SPI_TRANSMITRECEIVE)
78-
{
79-
clk = clock;
80-
bOrder = bitOrder;
81-
noReceive = noRecv;
82-
83-
if (SPI_MODE0 == dataMode) {
84-
dMode = SPI_MODE_0;
85-
} else if (SPI_MODE1 == dataMode) {
86-
dMode = SPI_MODE_1;
87-
} else if (SPI_MODE2 == dataMode) {
88-
dMode = SPI_MODE_2;
89-
} else if (SPI_MODE3 == dataMode) {
90-
dMode = SPI_MODE_3;
91-
}
92-
}
93-
SPISettings()
94-
{
95-
pinCS = -1;
96-
clk = SPI_SPEED_CLOCK_DEFAULT;
97-
bOrder = MSBFIRST;
98-
dMode = SPI_MODE_0;
99-
}
77+
constexpr SPISettings(uint32_t clock, BitOrder bitOrder, uint8_t dataMode, bool noRecv = SPI_TRANSMITRECEIVE)
78+
: pinCS(-1),
79+
clk(clock),
80+
bOrder(bitOrder),
81+
dMode((spi_mode_e)(
82+
(SPI_MODE0 == dataMode) ? SPI_MODE_0 :
83+
(SPI_MODE1 == dataMode) ? SPI_MODE_1 :
84+
(SPI_MODE2 == dataMode) ? SPI_MODE_2 :
85+
(SPI_MODE3 == dataMode) ? SPI_MODE_3 :
86+
SPI_MODE0
87+
)),
88+
noReceive(noRecv)
89+
{ }
90+
constexpr SPISettings()
91+
: pinCS(-1),
92+
clk(SPI_SPEED_CLOCK_DEFAULT),
93+
bOrder(MSBFIRST),
94+
dMode(SPI_MODE_0),
95+
noReceive(SPI_TRANSMITRECEIVE)
96+
{ }
10097
private:
10198
int16_t pinCS; //CS pin associated to the configuration
10299
uint32_t clk; //specifies the spi bus maximum clock speed

0 commit comments

Comments
 (0)