diff --git a/src/rp2_common/hardware_pio/pio.c b/src/rp2_common/hardware_pio/pio.c index 7182cfff5..a379e20b3 100644 --- a/src/rp2_common/hardware_pio/pio.c +++ b/src/rp2_common/hardware_pio/pio.c @@ -433,27 +433,29 @@ bool pio_claim_free_sm_and_add_program_for_gpio_range(const pio_program_t *progr sm_index[num_claimed] = (int8_t)pio_claim_unused_sm(*pio, false); if (sm_index[num_claimed] < 0) break; } - if (num_claimed && (!pass || num_claimed == NUM_PIO_STATE_MACHINES)) { + // rc = 0 if we claimed all the required state machines for the pass, <0 otherwise + int rc = num_claimed - (pass ? NUM_PIO_STATE_MACHINES : 1); + if (rc >= 0) { uint32_t save = hw_claim_lock(); if (pass) { pio_set_gpio_base_unsafe(*pio, required_gpio_ranges & 4 ? 16 : 0); } - int rc = is_gpio_compatible(*pio, required_gpio_ranges) ? PICO_OK : PICO_ERROR_BAD_ALIGNMENT; - if (rc == PICO_OK) rc = find_offset_for_program(*pio, program); + rc = is_gpio_compatible(*pio, required_gpio_ranges) ? 0 : -1; + if (rc >= 0) rc = find_offset_for_program(*pio, program); if (rc >= 0) rc = add_program_at_offset(*pio, program, (uint)rc); if (rc >= 0) { *sm = (uint) sm_index[0]; *offset = (uint) rc; } hw_claim_unlock(save); - // always un-claim all SMs other than the one we need (array index 0), - // or all of them if we had an error - for (uint i = (rc >= 0); i < num_claimed; i++) { - pio_sm_unclaim(*pio, (uint) sm_index[i]); - } - if (rc >= 0) { - return true; - } + } + // always un-claim all SMs other than the one we need (array index 0), + // or all of them if we had an error + for (uint i = (rc >= 0); i < num_claimed; i++) { + pio_sm_unclaim(*pio, (uint) sm_index[i]); + } + if (rc >= 0) { + return true; } } }