You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
101 lines
3.5 KiB
101 lines
3.5 KiB
#include "sx127x_driver.h" |
|
|
|
#include <string.h> |
|
#include <freertos/task.h> |
|
#include <esp_log.h> |
|
|
|
const char *SX127X_TAG = "sx127x"; |
|
|
|
#define SX127X_CHECK(check, str, ret_val, ...) \ |
|
if (!(check)) \ |
|
{ \ |
|
ESP_LOGE(SX127X_TAG, "%s(%d): " str, __FUNCTION__, __LINE__, ##__VA_ARGS__); \ |
|
return (ret_val); \ |
|
} |
|
|
|
#ifdef NODEBUG |
|
#define SX127X_ERROR_CHECK(ret, fun) \ |
|
{ \ |
|
esp_err_t _error_code = (ret); \ |
|
if (_error_code != ESP_OK) \ |
|
{ \ |
|
return _error_code; \ |
|
} \ |
|
} |
|
#else |
|
#define SX127X_ERROR_CHECK(ret, fun) \ |
|
{ \ |
|
esp_err_t _error_code = (ret); \ |
|
if (_error_code != ESP_OK) \ |
|
{ \ |
|
const char *_error_name = esp_err_to_name(_error_code); \ |
|
ESP_LOGE(SX127X_TAG, "%s(%d): " fun ": %s (%d)", \ |
|
__FUNCTION__, __LINE__, _error_name, _error_code); \ |
|
return _error_code; \ |
|
} \ |
|
} |
|
#endif |
|
|
|
esp_err_t sx127x_init(sx127x_config_t *config, sx127x_t *handle) |
|
{ |
|
esp_err_t ret; |
|
|
|
memcpy(&handle->config, config, sizeof(sx127x_config_t)); |
|
|
|
ret = gpio_set_direction(config->rst_io_num, GPIO_MODE_OUTPUT); |
|
SX127X_ERROR_CHECK(ret, "gpio_set_direction") |
|
ret = gpio_set_direction(config->irq_io_num, GPIO_MODE_OUTPUT); |
|
SX127X_ERROR_CHECK(ret, "gpio_set_direction") |
|
|
|
gpio_set_level(config->cs_io_num, 1); |
|
|
|
// perform reset |
|
gpio_set_level(config->rst_io_num, 0); |
|
vTaskDelay(pdMS_TO_TICKS(10)); |
|
gpio_set_level(config->rst_io_num, 1); |
|
vTaskDelay(pdMS_TO_TICKS(10)); |
|
|
|
spi_bus_config_t bus_config = { |
|
.mosi_io_num = config->mosi_io_num, |
|
.miso_io_num = config->miso_io_num, |
|
.sclk_io_num = config->sck_io_num, |
|
.quadhd_io_num = -1, |
|
.quadwp_io_num = -1, |
|
.max_transfer_sz = SX127X_MAX_TRANSFER}; |
|
ret = spi_bus_initialize(config->spi_host, &bus_config, 1); |
|
SX127X_ERROR_CHECK(ret, "spi_bus_initialize") |
|
|
|
spi_device_interface_config_t device_config = { |
|
.command_bits = 0, |
|
.address_bits = 8, |
|
.dummy_bits = 0, |
|
.mode = 0, |
|
.duty_cycle_pos = 0, |
|
.cs_ena_pretrans = 2, |
|
.cs_ena_posttrans = 2, |
|
.clock_speed_hz = 8, // 80mhz / 8 = 10mhz |
|
.input_delay_ns = 0, |
|
.spics_io_num = config->cs_io_num, |
|
.flags = 0, |
|
.queue_size = 8, |
|
.pre_cb = NULL, |
|
.post_cb = NULL, |
|
}; |
|
ret = spi_bus_add_device(config->spi_host, &device_config, &handle->device_handle); |
|
SX127X_ERROR_CHECK(ret, "spi_bus_add_device") |
|
|
|
return ESP_OK; |
|
} |
|
|
|
esp_err_t sx127x_free(sx127x_t *handle) |
|
{ |
|
esp_err_t ret; |
|
|
|
ret = spi_bus_remove_device(handle->device_handle); |
|
SX127X_ERROR_CHECK(ret, "spi_bus_remove_device") |
|
|
|
ret = spi_bus_free(handle->config.spi_host); |
|
SX127X_ERROR_CHECK(ret, "spi_bus_free") |
|
|
|
return ESP_OK; |
|
}
|
|
|