Skip to content

Commit a17bb65

Browse files
committed
Fix spi loopback example to work with any pin
1 parent 0d54450 commit a17bb65

File tree

2 files changed

+11
-9
lines changed

2 files changed

+11
-9
lines changed

pio/spi/pio_spi.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ typedef struct pio_spi_inst {
1313
PIO pio;
1414
uint sm;
1515
uint cs_pin;
16+
uint offset;
1617
} pio_spi_inst_t;
1718

1819
void pio_spi_write8_blocking(const pio_spi_inst_t *spi, const uint8_t *src, size_t len);

pio/spi/spi_loopback.c

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -49,19 +49,20 @@ void test(const pio_spi_inst_t *spi) {
4949
int main() {
5050
stdio_init_all();
5151

52-
pio_spi_inst_t spi = {
53-
.pio = pio0,
54-
.sm = 0
55-
};
52+
pio_spi_inst_t spi[2];
5653
float clkdiv = 31.25f; // 1 MHz @ 125 clk_sys
57-
uint cpha0_prog_offs = pio_add_program(spi.pio, &spi_cpha0_program);
58-
uint cpha1_prog_offs = pio_add_program(spi.pio, &spi_cpha1_program);
54+
55+
// pio_claim_free_sm_and_add_program_for_gpio_range finds a free pio and state machine for a program and sets the gpio base correctly
56+
const uint pin_base = MIN(PIN_SCK, MIN(PIN_MOSI, PIN_MISO));
57+
const uint pin_count = MAX(PIN_SCK, MAX(PIN_MOSI, PIN_MISO)) - pin_base + 1;
58+
hard_assert(pio_claim_free_sm_and_add_program_for_gpio_range(&spi_cpha0_program, &spi[0].pio, &spi[0].sm, &spi[0].offset, pin_base, pin_count, true));
59+
hard_assert(pio_claim_free_sm_and_add_program_for_gpio_range(&spi_cpha1_program, &spi[1].pio, &spi[1].sm, &spi[1].offset, pin_base, pin_count, true));
5960

6061
for (int cpha = 0; cpha <= 1; ++cpha) {
6162
for (int cpol = 0; cpol <= 1; ++cpol) {
6263
printf("CPHA = %d, CPOL = %d\n", cpha, cpol);
63-
pio_spi_init(spi.pio, spi.sm,
64-
cpha ? cpha1_prog_offs : cpha0_prog_offs,
64+
pio_spi_init(spi[cpha].pio, spi[cpha].sm,
65+
spi[cpha].offset,
6566
8, // 8 bits per SPI frame
6667
clkdiv,
6768
cpha,
@@ -70,7 +71,7 @@ int main() {
7071
PIN_MOSI,
7172
PIN_MISO
7273
);
73-
test(&spi);
74+
test(&spi[cpha]);
7475
sleep_ms(10);
7576
}
7677
}

0 commit comments

Comments
 (0)