Using an AVR microcontroller with Zephyr to read data from an ADC via SPI

Hey guys, I'm using an AVR microcontroller with Zephyr to read data from an ADC via SPI. I've configured the SPI peripheral and device tree, but the data coming back from the ADC just doesn't seem right. So far I have been able to set up the SPI in prj.conf and the device tree (dts). Wrote code to read data from the ADC. Below is the code snippet.
#include <zephyr.h>
#include <device.h>
#include <drivers/spi.h>
#include <logging/log.h>

LOG_MODULE_REGISTER(main);

#define ADC_SPI DT_NODELABEL(adc)

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(ADC_SPI);

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

uint8_t tx_buf[1] = {0x00}; // Dummy data to trigger ADC read
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 adc_value = (rx_buf[0] << 8) | rx_buf[1];
LOG_INF("ADC Value: %d", adc_value);
}
#include <zephyr.h>
#include <device.h>
#include <drivers/spi.h>
#include <logging/log.h>

LOG_MODULE_REGISTER(main);

#define ADC_SPI DT_NODELABEL(adc)

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(ADC_SPI);

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

uint8_t tx_buf[1] = {0x00}; // Dummy data to trigger ADC read
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 adc_value = (rx_buf[0] << 8) | rx_buf[1];
LOG_INF("ADC Value: %d", adc_value);
}
The code seems to be working, but the values I'm getting from the ADC are way off. Is there something wrong with my SPI configuration or how I'm reading the data? Help! @Middleware & OS
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server