I was having an issue where reading from SPI inside a timer handler always yielded 0xFF instead of the actual values. I tried to reproduce the issue with a simple test program but it shows a different behavior than my actual application - it simply hangs during the second transfer. When I step through it with the debugger it frequently just crashes (reboots).
#include <zephyr.h>
#include <sys/printk.h>
#include <drivers/spi.h>
const struct device * spi_dev = DEVICE_DT_GET(DT_NODELABEL(spi1));
void read_byte_from_spi() {
struct spi_config spi_cfg = {};
spi_cfg.frequency = 1000000;
spi_cfg.operation = SPI_WORD_SET(8);
char buf[1] = {};
struct spi_buf bufs[] = {
{
.buf = buf,
.len = 1
}
};
struct spi_buf_set bufset = {
.buffers = bufs,
.count = 1
};
spi_transceive(spi_dev, &spi_cfg, &bufset, &bufset);
printk("Read: %02x\n", buf[0]);
}
void spi_timer_expired() {
printk("Reading in spi_timer_expired() - ");
read_byte_from_spi();
}
K_TIMER_DEFINE(spi_timer, spi_timer_expired, NULL);
void main(void)
{
printk("Start\n");
k_timer_start(&spi_timer, K_MSEC(3000), K_MSEC(3000));
while(1) {
printk("Reading in main() - ");
read_byte_from_spi();
k_msleep(5000);
}
}
prj.conf:
CONFIG_SPI=y CONFIG_DEBUG_THREAD_INFO=y CONFIG_DEBUG_OPTIMIZATIONS=y
I'm running this on an nRF52-DK with P0.29 connected to GND.