esp-idf v4.3
代码如下
- void app_main(void)
- {
- //SPI测试代码
- luat_spi_t spi = {
- .id =2,
- .CPHA = 0,
- .CPOL = 0,
- .bit_dict = 8,
- .master = 0,
- .mode = 0,
- .cs = 5,
- .bandrate = 20*1000*1000
- };
- if (luat_spi_setup(&spi) == 0)
- {
- printf("spi setup success\n");
- }
- printf("luat_spi_transfer: %d",luat_spi_transfer(2,"0x9F",recv_buf,1));
- char* recv_buf0 = "";
- printf("luat_spi_transfer: %d",luat_spi_transfer(2,"0x00",recv_buf0,1));
- printf(recv_buf0);
- char* recv_buf1 = "";
- printf("luat_spi_transfer: %d",luat_spi_transfer(2,"0x00",recv_buf1,1));
- printf(recv_buf1);
- char* recv_buf2 = "";
- printf("luat_spi_transfer: %d",luat_spi_transfer(2,"0x00",recv_buf2,1));
- printf(recv_buf2);
- }
- //十六进制字符串转uint8_t
- uint8_t AsciiToHex8(const char * src)
- {
- luat_log_log(1,LUAT_LOG_TAG," hex str: %s\n",src);
- char* src0;
- uint8_t ret;
- ret = strtol(src,&src0,16);
- luat_log_log(1,LUAT_LOG_TAG,"ret: %x\n",ret);
- return ret;
- }
- //SPI收发
- int luat_spi_transfer(int spi_id, const char *send_buf, char *recv_buf, size_t length)
- {
- //判断是否超出32位 超过续开启DMA
- if(length*8 > 32)
- {
- luat_log_error(LUAT_LOG_TAG,"Data exceeds 32 bits");
- return -1;
- }
- //判断长度是否为0 为0则不发送
- if(length == 0)
- {
- luat_log_error(LUAT_LOG_TAG,"Data length can't be 0");
- return -1;
- }
- //判断SPI ID是否合法
- if (spi_id == 1 || spi_id == 2)
- {
- //初始化发送配珠
- printf("init spi_transaction_t");
- uint8_t *hex_recv_buf = NULL;
- spi_transaction_t t;
- memset(&t,0,sizeof(t));
- luat_log_debug(LUAT_LOG_TAG,"Data is %d byte\n",length);
- t.length = length*8;
- //将数据转换成uint8_t
- printf("convert spi_transaction_t");
- uint8_t hex_send_buf = AsciiToHex8(send_buf);
- luat_log_debug(LUAT_LOG_TAG,"AsciiToHex8 %x\n",hex_send_buf);
- t.tx_buffer = hex_send_buf;
- luat_log_debug(LUAT_LOG_TAG,"Recv Hex\n");
- t.rx_buffer = hex_recv_buf;
- printf("send spi_transaction_t");
- esp_err_t ret = spi_device_transmit(spi_h, &t);
- if (ret != ESP_OK)
- return -1;
- HexToAscii(hex_recv_buf,recv_buf,sizeof(hex_recv_buf));
- luat_log_log(1,LUAT_LOG_TAG,"SPI recv error check: %d\n",ret);
- }
- return 0;
- }