and here is my code: sure there is a better way, I just want to have a try
Code: Select all
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/spi_master.h"
#include "driver/gpio.h"
#include "unistd.h"
#include "sdkconfig.h"
#include "esp_log.h"
#define DMA_CHAN 2
#define PIN_NUM_MISO 41
#define PIN_NUM_MOSI 48
#define PIN_NUM_CLK 37
#define PIN_NUM_CS 41
#define CODE0 0xC0
#define CODE1 0xF1
static const char TAG[] = "main";
esp_err_t spi_write(spi_device_handle_t spi)
{
esp_err_t ret;
spi_transaction_t t;
memset(&t, 0, sizeof(t)); // Zero out the transaction
gpio_set_level(PIN_NUM_CS, 0);
unsigned char Rbuffer = 0;
unsigned char Gbuffer = 255;
unsigned char Bbuffer = 255;
unsigned char Data_buffer[24];
unsigned char *p_data = Data_buffer;
unsigned char mask = 0x80;
unsigned char byte = Gbuffer;
while (mask)
{
if (mask & byte)
{
*p_data = CODE1;
}
else
{
*p_data = CODE1;
}
mask >>= 1;
p_data++;
}
mask = 0x80;
byte = Rbuffer;
while (mask)
{
if (mask & byte)
{
*p_data = CODE1;
}
else
{
*p_data = CODE1;
}
mask >>= 1;
p_data++;
}
mask = 0x80;
byte = Bbuffer;
while (mask)
{
if (mask & byte)
{
*p_data = CODE1;
}
else
{
*p_data = CODE1;
}
mask >>= 1;
p_data++;
}
t.length = 24 * 8; // Len is in bytes, transaction length is in bits.
t.tx_buffer = Data_buffer; // Data
t.user = (void *)1; // D/C needs to be set to 1
ret = spi_device_polling_transmit(spi, &t); // Transmit!
assert(ret == ESP_OK); // Should have had no issues.
gpio_set_level(PIN_NUM_CS, 1);
// gpio_reset_pin(PIN_NUM_MOSI);
// gpio_pullup_dis(PIN_NUM_MOSI);
// gpio_set_pull_mode(PIN_NUM_MOSI, GPIO_PULLDOWN_ONLY);
// gpio_pulldown_en(PIN_NUM_MOSI);
// gpio_set_level(PIN_NUM_MOSI, 0);
// printf("Pin is %d\n",gpio_get_level(PIN_NUM_MOSI));
return ret;
}
void app_main(void)
{
esp_err_t ret;
spi_device_handle_t spi;
ESP_LOGI(TAG, "Initializing bus SPI%d...", SPI2_HOST + 1);
spi_bus_config_t buscfg = {
.miso_io_num = PIN_NUM_MISO, // MISO信号线
.mosi_io_num = PIN_NUM_MOSI, // MOSI信号线
.sclk_io_num = PIN_NUM_CLK, // SCLK信号线
.quadwp_io_num = -1, // WP信号线,专用于QSPI的D2
.quadhd_io_num = -1, // HD信号线,专用于QSPI的D3
.max_transfer_sz = 64 * 8, // 最大传输数据大小
};
spi_device_interface_config_t devcfg = {
.clock_speed_hz = APB_CLK_FREQ / 996, // Clock out at 10 MHz,
.mode = 2, // SPI mode 0
/*
* The timing requirements to read the busy signal from the EEPROM cannot be easily emulated
* by SPI transactions. We need to control CS pin by SW to check the busy signal manually.
*/
.spics_io_num = -1,
.queue_size = 7, // 传输队列大小,决定了等待传输数据的数量
};
// Initialize the SPI bus
ret = spi_bus_initialize(SPI2_HOST, &buscfg, SPI_DMA_CH_AUTO);
ESP_ERROR_CHECK(ret);
ret = spi_bus_add_device(SPI2_HOST, &devcfg, &spi);
ESP_ERROR_CHECK(ret);
gpio_pad_select_gpio(PIN_NUM_CS); // 选择一个GPIO
gpio_set_direction(PIN_NUM_CS, GPIO_MODE_OUTPUT); // 把这个GPIO作为输出
while (1)
{
spi_write(spi);
}
}