#include <stdio.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/spi_master.h"
#include "esp_log.h"
#include "driver/gpio.h"
#define CS_SAMD21 GPIO_NUM_12
#define RADIO_RX_BUF_LEN 32
#define RADIO_TX_BUF_LEN 32
typedef enum{
NONE = 0xF0,
GET_ALL = 0xF1,
GET_RADIO = 0xF2,
GET_LASER = 0xF3,
GET_AUX = 0xF4,
GET_EXT = 0xF5,
TAKE_RADIO = 0xF6,
TAKE_DISCR = 0xF7
}SPI_cmd_t;
#define SPI_CLOCK_SPEED 1000000
#define TAG "M"
spi_device_handle_t SPI_W25Q128;
spi_device_handle_t SPI_SAMD21;
spi_device_handle_t SPI_NANO;
uint8_t tx_buf[RADIO_TX_BUF_LEN] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31
};
void spi_init()
{
esp_err_t ret;
spi_bus_config_t buscfg = {
.miso_io_num = GPIO_NUM_19,
.mosi_io_num = GPIO_NUM_23,
.sclk_io_num = GPIO_NUM_18,
.quadwp_io_num = -1,
.quadhd_io_num = -1,
.max_transfer_sz = 0,
};
spi_device_interface_config_t devcfg = {
.command_bits = 0,
.address_bits = 0,
.dummy_bits = 0,
.mode = 0,
.duty_cycle_pos = 0,
.cs_ena_pretrans = 0,
.cs_ena_posttrans = 0,
.clock_speed_hz = SPI_CLOCK_SPEED,
.input_delay_ns = 0,
.spics_io_num = -1,
.flags = 0,
.queue_size = 1,
.pre_cb = NULL,
.post_cb = NULL,
};
// SPI bus init
ret = spi_bus_initialize(SPI2_HOST, &buscfg, 1);
assert(ret == ESP_OK);
// add slave to the bus
devcfg.spics_io_num = CS_SAMD21;
ret = spi_bus_add_device(SPI2_HOST, &devcfg, &SPI_SAMD21);
assert(ret == ESP_OK);
}
void spi_exchange_data(spi_device_handle_t device, const uint8_t *tx_data, uint8_t *rx_data, size_t len)
{
spi_transaction_t t;
memset(&t, 0, sizeof(t));
t.length = len * 8;
t.rxlength = len * 8;
t.rx_buffer = rx_data;
t.tx_buffer = tx_data;
esp_err_t ret = spi_device_transmit(device, &t);
assert(ret == ESP_OK);
}
void app_main(void)
{
spi_init();
vTaskDelay(1000 / portTICK_PERIOD_MS);
while (1)
{
vTaskDelay(1000 / portTICK_PERIOD_MS);
uint8_t rx_data[RADIO_RX_BUF_LEN] = {0};
spi_exchange_data(SPI_SAMD21, tx_buf, rx_data, RADIO_TX_BUF_LEN);
ESP_LOGI(TAG, "received: ");
for(uint8_t i = 0; i<RADIO_RX_BUF_LEN; i++){
printf("%x ", rx_data[i]);
}
printf("\n");
}
}