Skip to content

Commit c3e7b54

Browse files
authored
Merge pull request #3842 from anangl/fix_spi_api
TARGET_NRF: corrected spi_init() to properly handle re-initialization…
2 parents 1c4e0d7 + 4213c61 commit c3e7b54

File tree

1 file changed

+26
-7
lines changed

1 file changed

+26
-7
lines changed

targets/TARGET_NORDIC/TARGET_NRF5/spi_api.c

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -90,22 +90,22 @@ void SPI0_TWI0_IRQHandler(void);
9090
void SPI1_TWI1_IRQHandler(void);
9191
void SPIM2_SPIS2_SPI2_IRQHandler(void);
9292

93-
static const peripheral_handler_desc_t spi_hanlder_desc[SPI_COUNT] = {
93+
static const peripheral_handler_desc_t spi_handler_desc[SPI_COUNT] = {
9494
#if SPI0_ENABLED
9595
{
96-
SPIS0_IRQ,
96+
SPI0_IRQ,
9797
(uint32_t) SPI0_TWI0_IRQHandler
9898
},
9999
#endif
100100
#if SPI1_ENABLED
101101
{
102-
SPIS1_IRQ,
102+
SPI1_IRQ,
103103
(uint32_t) SPI1_TWI1_IRQHandler
104104
},
105105
#endif
106106
#if SPI2_ENABLED
107107
{
108-
SPIS2_IRQ,
108+
SPI2_IRQ,
109109
(uint32_t) SPIM2_SPIS2_SPI2_IRQHandler
110110
},
111111
#endif
@@ -254,12 +254,29 @@ void spi_init(spi_t *obj,
254254
PinName mosi, PinName miso, PinName sclk, PinName ssel)
255255
{
256256
int i;
257+
258+
// This block is only a workaround that allows to create SPI object several
259+
// times, what would be otherwise impossible in the current implementation
260+
// of mbed driver that does not call spi_free() from SPI destructor.
261+
// Once this mbed's imperfection is corrected, this block should be removed.
262+
for (i = 0; i < SPI_COUNT; ++i) {
263+
spi_info_t *p_spi_info = &m_spi_info[i];
264+
if (p_spi_info->initialized &&
265+
p_spi_info->mosi_pin == (uint8_t)mosi &&
266+
p_spi_info->miso_pin == (uint8_t)miso &&
267+
p_spi_info->sck_pin == (uint8_t)sclk &&
268+
p_spi_info->ss_pin == (uint8_t)ssel) {
269+
// Reuse the already allocated SPI instance (instead of allocating
270+
// a new one), if it appears to be initialized with exactly the same
271+
// pin assignments.
272+
SPI_IDX(obj) = i;
273+
return;
274+
}
275+
}
276+
257277
for (i = 0; i < SPI_COUNT; ++i) {
258278
spi_info_t *p_spi_info = &m_spi_info[i];
259279
if (!p_spi_info->initialized) {
260-
261-
NVIC_SetVector(spi_hanlder_desc[i].IRQn, spi_hanlder_desc[i].vector);
262-
263280
p_spi_info->sck_pin = (uint8_t)sclk;
264281
p_spi_info->mosi_pin = (mosi != NC) ?
265282
(uint8_t)mosi : NRF_DRV_SPI_PIN_NOT_USED;
@@ -270,6 +287,8 @@ void spi_init(spi_t *obj,
270287
p_spi_info->spi_mode = (uint8_t)NRF_DRV_SPI_MODE_0;
271288
p_spi_info->frequency = NRF_DRV_SPI_FREQ_1M;
272289

290+
NVIC_SetVector(spi_handler_desc[i].IRQn, spi_handler_desc[i].vector);
291+
273292
// By default each SPI instance is initialized to work as a master.
274293
// Should the slave mode be used, the instance will be reconfigured
275294
// appropriately in 'spi_format'.

0 commit comments

Comments
 (0)