Dtynin
Dtynin
DIIDevHeads IoT Integration Server
Created by Dtynin on 7/2/2024 in #middleware-and-os
Resolving 'SPI Device Not Ready' Error on AVR Microcontroller with Zephyr RTOS
hey guys, I am attempting to set up SPI communication on an AVR microcontroller running Zephyr RTOS to acquire data from an SPI temperature sensor (MCP9808) and send it to an IoT cloud platform, I have configured the SPI peripheral in the prj.conf file, created a Zephyr SPI device binding in the device tree source file (dts), writing an application to read temperature data from the MCP9808 sensor. But am getting the error, what could be wrong?
SPI device not ready
SPI device not ready
I have verified the device tree source configuration to ensure proper SPI peripheral settings, checked the pin configurations to match the hardware setup, made sure the MCP9808 sensor is connected correctly to the SPI pins.
#include <zephyr.h>
#include <device.h>
#include <drivers/spi.h>
#include <logging/log.h>

LOG_MODULE_REGISTER(main);

#define MCP9808_SPI DT_NODELABEL(mcp9808)

static const struct spi_config spi_cfg = {
.frequency = 1000000U,
.operation = SPI_WORD_SET(8) | SPI_TRANSFER_MSB,
.slave = 0,
.cs = NULL,
};

void main(void) {
const struct device *spi_dev = DEVICE_DT_GET(MCP9808_SPI);

if (!device_is_ready(spi_dev)) {
LOG_ERR("SPI device not ready");
return;
}

uint8_t tx_buf[1] = {0x05}; // Register to read temperature
uint8_t rx_buf[2];
struct spi_buf tx = {.buf = tx_buf, .len = sizeof(tx_buf)};
struct spi_buf rx = {.buf = rx_buf, .len = sizeof(rx_buf)};
struct spi_buf_set tx_set = {.buffers = &tx, .count = 1};
struct spi_buf_set rx_set = {.buffers = &rx, .count = 1};

int ret = spi_transceive(spi_dev, &spi_cfg, &tx_set, &rx_set);
if (ret) {
LOG_ERR("SPI transceive failed: %d", ret);
return;
}


int temp = ((rx_buf[0] << 8) | rx_buf[1]) & 0x0FFF;
temp /= 16;

LOG_INF("Temperature: %d C", temp);
}
#include <zephyr.h>
#include <device.h>
#include <drivers/spi.h>
#include <logging/log.h>

LOG_MODULE_REGISTER(main);

#define MCP9808_SPI DT_NODELABEL(mcp9808)

static const struct spi_config spi_cfg = {
.frequency = 1000000U,
.operation = SPI_WORD_SET(8) | SPI_TRANSFER_MSB,
.slave = 0,
.cs = NULL,
};

void main(void) {
const struct device *spi_dev = DEVICE_DT_GET(MCP9808_SPI);

if (!device_is_ready(spi_dev)) {
LOG_ERR("SPI device not ready");
return;
}

uint8_t tx_buf[1] = {0x05}; // Register to read temperature
uint8_t rx_buf[2];
struct spi_buf tx = {.buf = tx_buf, .len = sizeof(tx_buf)};
struct spi_buf rx = {.buf = rx_buf, .len = sizeof(rx_buf)};
struct spi_buf_set tx_set = {.buffers = &tx, .count = 1};
struct spi_buf_set rx_set = {.buffers = &rx, .count = 1};

int ret = spi_transceive(spi_dev, &spi_cfg, &tx_set, &rx_set);
if (ret) {
LOG_ERR("SPI transceive failed: %d", ret);
return;
}


int temp = ((rx_buf[0] << 8) | rx_buf[1]) & 0x0FFF;
temp /= 16;

LOG_INF("Temperature: %d C", temp);
}
9 replies