esp32c3,esp-idf 4.4.4,与ch623刷卡芯片用spi通信不用dma,给个例程
时间: 2024-03-10 08:49:41 浏览: 114
下面是一个简单的 ESP32-C3 与 CH623 刷卡芯片通过 SPI 通信的例程,不需要使用 DMA:
```c
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/spi_master.h"
#include "driver/gpio.h"
#define PIN_NUM_MISO 13
#define PIN_NUM_MOSI 12
#define PIN_NUM_CLK 14
#define PIN_NUM_CS 15
#define SPI_CLOCK_SPEED_HZ 1000000
spi_device_handle_t spi_handle;
void ch623_spi_init(void)
{
esp_err_t ret;
spi_bus_config_t buscfg = {
.miso_io_num = PIN_NUM_MISO,
.mosi_io_num = PIN_NUM_MOSI,
.sclk_io_num = PIN_NUM_CLK,
.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_HZ,
.input_delay_ns = 0,
.spics_io_num = PIN_NUM_CS,
.flags = 0,
.queue_size = 1,
.pre_cb = NULL,
.post_cb = NULL,
};
ret = spi_bus_initialize(HSPI_HOST, &buscfg, 1);
assert(ret == ESP_OK);
ret = spi_bus_add_device(HSPI_HOST, &devcfg, &spi_handle);
assert(ret == ESP_OK);
}
void ch623_spi_write(uint8_t addr, uint8_t data)
{
esp_err_t ret;
uint8_t tx_data[2] = {addr, data};
spi_transaction_t t = {
.length = 2 * 8,
.tx_buffer = tx_data,
};
ret = spi_device_transmit(spi_handle, &t);
assert(ret == ESP_OK);
}
void ch623_spi_read(uint8_t addr, uint8_t *data)
{
esp_err_t ret;
uint8_t tx_data[2] = {addr, 0};
spi_transaction_t t = {
.length = 2 * 8,
.tx_buffer = tx_data,
.rx_buffer = data,
};
ret = spi_device_transmit(spi_handle, &t);
assert(ret == ESP_OK);
}
void app_main(void)
{
ch623_spi_init();
// 读取 CH623 的芯片 ID
uint8_t id;
ch623_spi_read(0x00, &id);
printf("CH623 ID: 0x%02x\n", id);
// 写入 CH623 密码
ch623_spi_write(0x01, 0x12);
ch623_spi_write(0x02, 0x34);
ch623_spi_write(0x03, 0x56);
ch623_spi_write(0x04, 0x78);
}
```
在这个例程中,我们使用了 ESP32-C3 的 HSPI 接口与 CH623 进行通信,使用了默认的 GPIO 引脚配置。在 `ch623_spi_init()` 函数中,我们初始化了 SPI 总线并添加了一个 SPI 设备,然后在 `ch623_spi_write()` 和 `ch623_spi_read()` 函数中分别实现了写入和读取 CH623 的寄存器值。在 `app_main()` 函数中,我们先读取了 CH623 的芯片 ID,然后写入了 CH623 的密码。这只是一个简单的例程,你可以根据自己的需求进行修改。
阅读全文