Skip to content

Commit f46d7cc

Browse files
Speed up SPI by not reinitting if the paramters are the same as before (#394)
Leave the SPI port initted after a transaction, and when a new one comes in check if it is the same settings we're already running. If so, do nothing. If not, deinit and reinit. In general the settings will be identical, so this will speed things up massively. Fixes #392
1 parent 5ee7643 commit f46d7cc

File tree

1 file changed

+16
-12
lines changed

1 file changed

+16
-12
lines changed

libraries/SPI/SPI.cpp

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -179,23 +179,22 @@ void SPIClassRP2040::transfer(void *txbuf, void *rxbuf, size_t count) {
179179

180180
void SPIClassRP2040::beginTransaction(SPISettings settings) {
181181
DEBUGSPI("SPI::beginTransaction(clk=%d, bo=%s\n", _spis.getClockFreq(), (_spis.getBitOrder() == MSBFIRST) ? "MSB" : "LSB");
182-
_spis = settings;
183-
if (_initted) {
184-
DEBUGSPI("SPI: deinitting currently active SPI\n");
185-
spi_deinit(_spi);
182+
if (_initted && settings == _spis) {
183+
DEBUGSPI("SPI: Reusing existing initted SPI\n");
184+
} else {
185+
_spis = settings;
186+
if (_initted) {
187+
DEBUGSPI("SPI: deinitting currently active SPI\n");
188+
spi_deinit(_spi);
189+
}
190+
DEBUGSPI("SPI: initting SPI\n");
191+
spi_init(_spi, _spis.getClockFreq());
192+
_initted = true;
186193
}
187-
DEBUGSPI("SPI: initting SPI\n");
188-
spi_init(_spi, _spis.getClockFreq());
189-
_initted = true;
190194
}
191195

192196
void SPIClassRP2040::endTransaction(void) {
193197
DEBUGSPI("SPI::endTransaction()\n");
194-
if (_initted) {
195-
DEBUGSPI("SPI: deinitting currently active SPI\n");
196-
spi_deinit(_spi);
197-
}
198-
_initted = false;
199198
}
200199

201200
bool SPIClassRP2040::setRX(pin_size_t pin) {
@@ -281,6 +280,11 @@ void SPIClassRP2040::begin(bool hwCS) {
281280

282281
void SPIClassRP2040::end() {
283282
DEBUGSPI("SPI::end()\n");
283+
if (_initted) {
284+
DEBUGSPI("SPI: deinitting currently active SPI\n");
285+
_initted = false;
286+
spi_deinit(_spi);
287+
}
284288
gpio_set_function(_RX, GPIO_FUNC_SIO);
285289
if (_hwCS) {
286290
gpio_set_function(_CS, GPIO_FUNC_SIO);

0 commit comments

Comments
 (0)