gpio_exp.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  1. /* GDS Example
  2. This example code is in the Public Domain (or CC0 licensed, at your option.)
  3. Unless required by applicable law or agreed to in writing, this
  4. software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  5. CONDITIONS OF ANY KIND, either express or implied.
  6. */
  7. #include <string.h>
  8. #include <stdlib.h>
  9. #include "freertos/FreeRTOS.h"
  10. #include "freertos/task.h"
  11. #include "freertos/timers.h"
  12. #include "freertos/queue.h"
  13. #include "esp_task.h"
  14. #include "esp_log.h"
  15. #include "driver/gpio.h"
  16. #include "driver/i2c.h"
  17. #include "driver/spi_master.h"
  18. #include "gpio_exp.h"
  19. #include "GPIO.pb.h"
  20. #define GPIO_EXP_INTR 0x100
  21. #define GPIO_EXP_WRITE 0x200
  22. /*
  23. shadow register is both output and input, so we assume that reading to the
  24. ports also reads the value set on output
  25. */
  26. typedef struct gpio_exp_s {
  27. uint32_t first, last;
  28. int intr;
  29. bool intr_pending;
  30. struct {
  31. struct gpio_exp_phy_s phy;
  32. spi_device_handle_t spi_handle;
  33. };
  34. uint32_t shadow, pending;
  35. TickType_t age;
  36. SemaphoreHandle_t mutex;
  37. uint32_t r_mask, w_mask;
  38. uint32_t pullup, pulldown;
  39. struct gpio_exp_isr_s {
  40. gpio_isr_t handler;
  41. void *arg;
  42. TimerHandle_t timer;
  43. } isr[32];
  44. struct gpio_exp_model_s const *model;
  45. } gpio_exp_t;
  46. typedef struct {
  47. enum { ASYNC_WRITE } type;
  48. int gpio;
  49. int level;
  50. gpio_exp_t *expander;
  51. } queue_request_t;
  52. static const char TAG[] = "gpio expander";
  53. static void IRAM_ATTR intr_isr_handler(void* arg);
  54. static gpio_exp_t* find_expander(gpio_exp_t *expander, int *gpio);
  55. static esp_err_t mpr121_init(gpio_exp_t* self);
  56. static uint32_t mpr121_read(gpio_exp_t* self);
  57. static void mpr121_write(gpio_exp_t* self);
  58. static void pca9535_set_direction(gpio_exp_t* self);
  59. static uint32_t pca9535_read(gpio_exp_t* self);
  60. static void pca9535_write(gpio_exp_t* self);
  61. static uint32_t pca85xx_read(gpio_exp_t* self);
  62. static void pca85xx_write(gpio_exp_t* self);
  63. static esp_err_t mcp23017_init(gpio_exp_t* self);
  64. static void mcp23017_set_pull_mode(gpio_exp_t* self);
  65. static void mcp23017_set_direction(gpio_exp_t* self);
  66. static uint32_t mcp23017_read(gpio_exp_t* self);
  67. static void mcp23017_write(gpio_exp_t* self);
  68. static esp_err_t mcp23s17_init(gpio_exp_t* self);
  69. static void mcp23s17_set_pull_mode(gpio_exp_t* self);
  70. static void mcp23s17_set_direction(gpio_exp_t* self);
  71. static uint32_t mcp23s17_read(gpio_exp_t* self);
  72. static void mcp23s17_write(gpio_exp_t* self);
  73. static void service_handler(void *arg);
  74. static void debounce_handler( TimerHandle_t xTimer );
  75. static esp_err_t i2c_write(uint8_t port, uint8_t addr, uint8_t reg, uint32_t data, int len);
  76. static uint32_t i2c_read(uint8_t port, uint8_t addr, uint8_t reg, int len);
  77. static spi_device_handle_t spi_config(struct gpio_exp_phy_s *phy);
  78. static esp_err_t spi_write(spi_device_handle_t handle, uint8_t addr, uint8_t reg, uint32_t data, int len);
  79. static uint32_t spi_read(spi_device_handle_t handle, uint8_t addr, uint8_t reg, int len);
  80. static const struct gpio_exp_model_s {
  81. char *model;
  82. gpio_int_type_t trigger;
  83. esp_err_t (*init)(gpio_exp_t* self);
  84. uint32_t (*read)(gpio_exp_t* self);
  85. void (*write)(gpio_exp_t* self);
  86. void (*set_direction)(gpio_exp_t* self);
  87. void (*set_pull_mode)(gpio_exp_t* self);
  88. } registered[] = {
  89. { .model = "mpr121",
  90. .trigger = GPIO_INTR_LOW_LEVEL,
  91. .init = mpr121_init,
  92. .read = mpr121_read,
  93. .write = mpr121_write, },
  94. { .model = "pca9535",
  95. .trigger = GPIO_INTR_LOW_LEVEL,
  96. .set_direction = pca9535_set_direction,
  97. .read = pca9535_read,
  98. .write = pca9535_write, },
  99. { .model = "pca85xx",
  100. .trigger = GPIO_INTR_LOW_LEVEL,
  101. .read = pca85xx_read,
  102. .write = pca85xx_write, },
  103. { .model = "mcp23017",
  104. .trigger = GPIO_INTR_LOW_LEVEL,
  105. .init = mcp23017_init,
  106. .set_direction = mcp23017_set_direction,
  107. .set_pull_mode = mcp23017_set_pull_mode,
  108. .read = mcp23017_read,
  109. .write = mcp23017_write, },
  110. { .model = "mcp23s17",
  111. .trigger = GPIO_INTR_LOW_LEVEL,
  112. .init = mcp23s17_init,
  113. .set_direction = mcp23s17_set_direction,
  114. .set_pull_mode = mcp23s17_set_pull_mode,
  115. .read = mcp23s17_read,
  116. .write = mcp23s17_write, },
  117. };
  118. static EXT_RAM_ATTR uint8_t n_expanders;
  119. static EXT_RAM_ATTR QueueHandle_t message_queue;
  120. static EXT_RAM_ATTR gpio_exp_t expanders[4];
  121. static EXT_RAM_ATTR TaskHandle_t service_task;
  122. /******************************************************************************
  123. * Retrieve base from an expander reference
  124. */
  125. uint32_t gpio_exp_get_base(gpio_exp_t *expander) {
  126. return expander->first;
  127. }
  128. /******************************************************************************
  129. * Retrieve reference from a GPIO
  130. */
  131. gpio_exp_t *gpio_exp_get_expander(int gpio) {
  132. int _gpio = gpio;
  133. return find_expander(NULL, &_gpio);
  134. }
  135. /******************************************************************************
  136. * Create an I2C expander
  137. */
  138. gpio_exp_t* gpio_exp_create(const gpio_exp_config_t *config) {
  139. gpio_exp_t *expander = expanders + n_expanders;
  140. if (config->base < GPIO_NUM_MAX || n_expanders == sizeof(expanders)/sizeof(gpio_exp_t)) {
  141. ESP_LOGE(TAG, "Base %d GPIO must be at least %d for %s or too many expanders %d", config->base, GPIO_NUM_MAX, config->model, n_expanders);
  142. return NULL;
  143. }
  144. // See if we know that model (expanders is zero-initialized)
  145. for (int i = 0; !expander->model && i < sizeof(registered)/sizeof(struct gpio_exp_model_s); i++) {
  146. if (strcasestr(config->model, registered[i].model)) expander->model = registered + i;
  147. }
  148. // well... try again
  149. if (!expander->model) {
  150. ESP_LOGE(TAG, "Unknown GPIO expansion chip %s", config->model);
  151. return NULL;
  152. }
  153. memcpy(&expander->phy, &config->phy, sizeof(struct gpio_exp_phy_s));
  154. // try to initialize the expander if required
  155. if (expander->model->init && expander->model->init(expander) != ESP_OK) {
  156. ESP_LOGE(TAG, "Cannot create GPIO expander %s, check i2c/spi configuration", config->model);
  157. return NULL;
  158. }
  159. n_expanders++;
  160. expander->first = config->base;
  161. expander->last = config->base + config->count - 1;
  162. expander->intr = config->intr;
  163. expander->mutex = xSemaphoreCreateMutex();
  164. // create a task to handle asynchronous requests (only write at this time)
  165. if (!message_queue) {
  166. // we allocate TCB but stack is static to avoid SPIRAM fragmentation
  167. StaticTask_t* xTaskBuffer = (StaticTask_t*) heap_caps_malloc(sizeof(StaticTask_t), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
  168. static EXT_RAM_ATTR StackType_t xStack[4*1024] __attribute__ ((aligned (4)));
  169. message_queue = xQueueCreate(4, sizeof(queue_request_t));
  170. service_task = xTaskCreateStatic(service_handler, "gpio_expander", sizeof(xStack), NULL, ESP_TASK_PRIO_MIN + 1, xStack, xTaskBuffer);
  171. }
  172. if(config->phy.ena_pin>=0){
  173. ESP_LOGD(TAG,"Enabling expander with pin %d level %d",config->phy.ena_pin,config->phy.ena_lvl);
  174. gpio_pad_select_gpio(config->phy.ena_pin);
  175. gpio_set_direction(config->phy.ena_pin, GPIO_MODE_DEF_OUTPUT);
  176. gpio_set_level(config->phy.ena_pin, config->phy.ena_lvl);
  177. }
  178. // set interrupt if possible
  179. if (config->intr >= 0) {
  180. gpio_pad_select_gpio(config->intr);
  181. gpio_set_direction(config->intr, GPIO_MODE_INPUT);
  182. switch (expander->model->trigger) {
  183. case GPIO_INTR_NEGEDGE:
  184. case GPIO_INTR_LOW_LEVEL:
  185. gpio_set_pull_mode(config->intr, GPIO_PULLUP_ONLY);
  186. break;
  187. case GPIO_INTR_POSEDGE:
  188. case GPIO_INTR_HIGH_LEVEL:
  189. gpio_set_pull_mode(config->intr, GPIO_PULLDOWN_ONLY);
  190. break;
  191. default:
  192. gpio_set_pull_mode(config->intr, GPIO_PULLUP_PULLDOWN);
  193. break;
  194. }
  195. gpio_set_intr_type(config->intr, expander->model->trigger);
  196. gpio_isr_handler_add(config->intr, intr_isr_handler, expander);
  197. gpio_intr_enable(config->intr);
  198. }
  199. ESP_LOGI(TAG, "Create GPIO expander %s at base %u with intr %d at @%x on port/host %d/%d, enable pin: %d:%d", config->model, config->base, config->intr, config->phy.addr, config->phy.port, config->phy.host,config->phy.ena_pin,config->phy.ena_lvl);
  200. return expander;
  201. }
  202. /******************************************************************************
  203. * Add ISR handler for a GPIO
  204. */
  205. esp_err_t gpio_exp_isr_handler_add(int gpio, gpio_isr_t isr_handler, uint32_t debounce, void *arg, struct gpio_exp_s *expander) {
  206. if (gpio < GPIO_NUM_MAX && !expander) return gpio_isr_handler_add(gpio, isr_handler, arg);
  207. if ((expander = find_expander(expander, &gpio)) == NULL) return ESP_ERR_INVALID_ARG;
  208. expander->isr[gpio].handler = isr_handler;
  209. expander->isr[gpio].arg = arg;
  210. if (debounce) expander->isr[gpio].timer = xTimerCreate("gpioExpDebounce", pdMS_TO_TICKS(debounce),
  211. pdFALSE, expander->isr + gpio, debounce_handler );
  212. return ESP_OK;
  213. }
  214. /******************************************************************************
  215. * Remove ISR handler for a GPIO
  216. */
  217. esp_err_t gpio_exp_isr_handler_remove(int gpio, struct gpio_exp_s *expander) {
  218. if (gpio < GPIO_NUM_MAX && !expander) return gpio_isr_handler_remove(gpio);
  219. if ((expander = find_expander(expander, &gpio)) == NULL) return ESP_ERR_INVALID_ARG;
  220. if (expander->isr[gpio].timer) xTimerDelete(expander->isr[gpio].timer, portMAX_DELAY);
  221. memset(expander->isr + gpio, 0, sizeof(struct gpio_exp_isr_s));
  222. return ESP_OK;
  223. }
  224. /******************************************************************************
  225. * Set GPIO direction
  226. */
  227. esp_err_t gpio_exp_set_direction(int gpio, gpio_mode_t mode, gpio_exp_t *expander) {
  228. if (gpio < GPIO_NUM_MAX && !expander) return gpio_set_direction(gpio, mode);
  229. if ((expander = find_expander(expander, &gpio)) == NULL) return ESP_ERR_INVALID_ARG;
  230. xSemaphoreTake(expander->mutex, pdMS_TO_TICKS(portMAX_DELAY));
  231. if (mode == GPIO_MODE_INPUT) {
  232. expander->r_mask |= 1 << gpio;
  233. expander->shadow = expander->model->read(expander);
  234. expander->age = ~xTaskGetTickCount();
  235. } else {
  236. expander->w_mask |= 1 << gpio;
  237. }
  238. if (expander->r_mask & expander->w_mask) {
  239. xSemaphoreGive(expander->mutex);
  240. ESP_LOGE(TAG, "GPIO %d on expander base %u can't be r/w", gpio, expander->first);
  241. return ESP_ERR_INVALID_ARG;
  242. }
  243. // most expanders want unconfigured GPIO to be set to output
  244. if (expander->model->set_direction) expander->model->set_direction(expander);
  245. xSemaphoreGive(expander->mutex);
  246. return ESP_OK;
  247. }
  248. /******************************************************************************
  249. * Get GPIO level with cache
  250. */
  251. int gpio_exp_get_level(int gpio, int age, gpio_exp_t *expander) {
  252. if (gpio < GPIO_NUM_MAX && !expander) return gpio_get_level(gpio);
  253. if ((expander = find_expander(expander, &gpio)) == NULL) return -1;
  254. uint32_t now = xTaskGetTickCount();
  255. // return last thing we had if we can't get the mutex
  256. if (xSemaphoreTake(expander->mutex, pdMS_TO_TICKS(50)) == pdFALSE) {
  257. ESP_LOGW(TAG, "Can't get mutex for GPIO %d", expander->first + gpio);
  258. return (expander->shadow >> gpio) & 0x01;
  259. }
  260. // re-read the expander if data is too old
  261. if (age >= 0 && now - expander->age >= pdMS_TO_TICKS(age)) {
  262. uint32_t value = expander->model->read(expander);
  263. expander->pending |= (expander->shadow ^ value) & expander->r_mask;
  264. expander->shadow = value;
  265. expander->age = now;
  266. }
  267. // clear pending bit
  268. expander->pending &= ~(1 << gpio);
  269. xSemaphoreGive(expander->mutex);
  270. ESP_LOGD(TAG, "Get level for GPIO %u => read %x", expander->first + gpio, expander->shadow);
  271. return (expander->shadow >> gpio) & 0x01;
  272. }
  273. /******************************************************************************
  274. * Set GPIO level with cache
  275. */
  276. esp_err_t gpio_exp_set_level(int gpio, int level, bool direct, gpio_exp_t *expander) {
  277. if (gpio < GPIO_NUM_MAX && !expander) return gpio_set_level(gpio, level);
  278. if ((expander = find_expander(expander, &gpio)) == NULL) return ESP_ERR_INVALID_ARG;
  279. uint32_t mask = 1 << gpio;
  280. // very limited risk with lack of semaphore here
  281. if ((expander->w_mask & mask) == 0) {
  282. ESP_LOGW(TAG, "GPIO %d is not set for output", expander->first + gpio);
  283. return ESP_ERR_INVALID_ARG;
  284. }
  285. if (direct) {
  286. xSemaphoreTake(expander->mutex, pdMS_TO_TICKS(portMAX_DELAY));
  287. level = level ? mask : 0;
  288. mask &= expander->shadow;
  289. // only write if shadow not up to date
  290. if ((mask ^ level) && expander->model->write) {
  291. expander->shadow = (expander->shadow & ~(mask | level)) | level;
  292. expander->model->write(expander);
  293. }
  294. xSemaphoreGive(expander->mutex);
  295. ESP_LOGD(TAG, "Set level %x for GPIO %u => wrote %x", level, expander->first + gpio, expander->shadow);
  296. } else {
  297. queue_request_t request = { .gpio = gpio, .level = level, .type = ASYNC_WRITE, .expander = expander };
  298. if (xQueueSend(message_queue, &request, 0) == pdFALSE) return ESP_ERR_INVALID_RESPONSE;
  299. // notify service task that will write it when it can
  300. xTaskNotify(service_task, GPIO_EXP_WRITE, eSetValueWithoutOverwrite);
  301. }
  302. return ESP_OK;
  303. }
  304. /******************************************************************************
  305. * Set GPIO pullmode
  306. */
  307. esp_err_t gpio_exp_set_pull_mode(int gpio, gpio_pull_mode_t mode, gpio_exp_t *expander) {
  308. if (gpio < GPIO_NUM_MAX && !expander) return gpio_set_pull_mode(gpio, mode);
  309. if ((expander = find_expander(expander, &gpio)) != NULL && expander->model->set_pull_mode) {
  310. expander->pullup &= ~(1 << gpio);
  311. expander->pulldown &= ~(1 << gpio);
  312. if (mode == GPIO_PULLUP_ONLY || mode == GPIO_PULLUP_PULLDOWN) expander->pullup |= 1 << gpio;
  313. if (mode == GPIO_PULLDOWN_ONLY || mode == GPIO_PULLUP_PULLDOWN) expander->pulldown |= 1 << gpio;
  314. expander->model->set_pull_mode(expander);
  315. return ESP_OK;
  316. }
  317. return ESP_ERR_INVALID_ARG;
  318. }
  319. /******************************************************************************
  320. * Wrapper function
  321. */
  322. void esp_rom_gpio_pad_select_gpio_x(uint32_t gpio){
  323. if (gpio < GPIO_NUM_MAX) {
  324. esp_rom_gpio_pad_select_gpio(gpio);
  325. }
  326. }
  327. esp_err_t gpio_set_pull_mode_x(int gpio, gpio_pull_mode_t mode) {
  328. if (gpio < GPIO_NUM_MAX) return gpio_set_pull_mode(gpio, mode);
  329. return gpio_exp_set_pull_mode(gpio, mode, NULL);
  330. }
  331. esp_err_t gpio_set_direction_x(int gpio, gpio_mode_t mode) {
  332. if (gpio < GPIO_NUM_MAX) return gpio_set_direction(gpio, mode);
  333. return gpio_exp_set_direction(gpio, mode, NULL);
  334. }
  335. int gpio_get_level_x(int gpio) {
  336. if (gpio < GPIO_NUM_MAX) return gpio_get_level(gpio);
  337. return gpio_exp_get_level(gpio, 10, NULL);
  338. }
  339. esp_err_t gpio_set_level_x(int gpio, int level) {
  340. if (gpio < GPIO_NUM_MAX) return gpio_set_level(gpio, level);
  341. return gpio_exp_set_level(gpio, level, false, NULL);
  342. }
  343. esp_err_t gpio_isr_handler_add_x(int gpio, gpio_isr_t isr_handler, void* args) {
  344. if (gpio < GPIO_NUM_MAX) return gpio_isr_handler_add(gpio, isr_handler, args);
  345. return gpio_exp_isr_handler_add(gpio, isr_handler, 0, args, NULL);
  346. }
  347. esp_err_t gpio_isr_handler_remove_x(int gpio) {
  348. if (gpio < GPIO_NUM_MAX) return gpio_isr_handler_remove(gpio);
  349. return gpio_exp_isr_handler_remove(gpio, NULL);
  350. }
  351. /****************************************************************************************
  352. * INTR low-level handler
  353. */
  354. static void IRAM_ATTR intr_isr_handler(void* arg) {
  355. gpio_exp_t *self = (gpio_exp_t*) arg;
  356. BaseType_t woken = pdFALSE;
  357. // edge interrupts do not work because of read/clear = potential short pulse
  358. gpio_intr_disable(self->intr);
  359. // activate all, including ourselves
  360. for (int i = 0; i < n_expanders; i++) if (expanders[i].intr == self->intr) expanders[i].intr_pending = true;
  361. xTaskNotifyFromISR(service_task, GPIO_EXP_INTR, eSetValueWithOverwrite, &woken);
  362. if (woken) portYIELD_FROM_ISR();
  363. ESP_EARLY_LOGD(TAG, "INTR for expander base %d", gpio_exp_get_base(self));
  364. }
  365. /****************************************************************************************
  366. * INTR debounce handler
  367. */
  368. static void debounce_handler( TimerHandle_t xTimer ) {
  369. struct gpio_exp_isr_s *isr = (struct gpio_exp_isr_s*) pvTimerGetTimerID (xTimer);
  370. isr->handler(isr->arg);
  371. }
  372. /****************************************************************************************
  373. * Service task
  374. */
  375. void service_handler(void *arg) {
  376. while (1) {
  377. queue_request_t request;
  378. uint32_t notif = ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
  379. // we have been notified of an interrupt
  380. if (notif == GPIO_EXP_INTR) {
  381. /* If we want a smarter bitmap of expanders with a pending interrupt
  382. we'll have to disable interrupts while clearing that bitmap. For
  383. now, a loop will do */
  384. for (int i = 0; i < n_expanders; i++) {
  385. gpio_exp_t *expander = expanders + i;
  386. // no interrupt for that gpio or not pending (safe as interrupt is disabled)
  387. if (expander->intr < 0 || !expander->intr_pending) continue;
  388. xSemaphoreTake(expander->mutex, pdMS_TO_TICKS(50));
  389. // read GPIOs and clear all pending status
  390. uint32_t value = expander->model->read(expander);
  391. expander->age = xTaskGetTickCount();
  392. // re-enable interrupt now that it has been cleared
  393. expander->intr_pending = false;
  394. gpio_intr_enable(expander->intr);
  395. uint32_t pending = expander->pending | ((expander->shadow ^ value) & expander->r_mask);
  396. expander->shadow = value;
  397. expander->pending = 0;
  398. xSemaphoreGive(expander->mutex);
  399. ESP_LOGD(TAG, "Handling GPIO %d reads 0x%04x and has 0x%04x pending", expander->first, expander->shadow, pending);
  400. for (int gpio = 31, clz = 0; pending && clz < 31; pending <<= (clz + 1)) {
  401. clz = __builtin_clz(pending);
  402. gpio -= clz;
  403. if (expander->isr[gpio].timer) xTimerReset(expander->isr[gpio].timer, 1); // todo 0
  404. else if (expander->isr[gpio].handler) expander->isr[gpio].handler(expander->isr[gpio].arg);
  405. }
  406. }
  407. }
  408. // check if we have some other pending requests
  409. while (xQueueReceive(message_queue, &request, 0) == pdTRUE) {
  410. esp_err_t err = gpio_exp_set_level(request.gpio, request.level, true, request.expander);
  411. if (err != ESP_OK) ESP_LOGW(TAG, "Can't execute async GPIO %d write request (%d)", request.gpio, err);
  412. }
  413. }
  414. }
  415. /****************************************************************************************
  416. * Find the expander related to base
  417. */
  418. static gpio_exp_t* find_expander(gpio_exp_t *expander, int *gpio) {
  419. // a mutex would be better, but risk is so small...
  420. for (int i = 0; !expander && i < n_expanders; i++) {
  421. if (*gpio >= expanders[i].first && *gpio <= expanders[i].last) expander = expanders + i;
  422. }
  423. // normalize GPIO number
  424. if (expander && *gpio >= expander->first) *gpio -= expander->first;
  425. return expander;
  426. }
  427. /****************************************************************************************
  428. DRIVERS
  429. ****************************************************************************************/
  430. /****************************************************************************************
  431. * MPR121 family : init, direction, read and write
  432. */
  433. static esp_err_t mpr121_init(gpio_exp_t* self) {
  434. static const struct {
  435. uint8_t addr;
  436. uint8_t data;
  437. } mpr121_init_table[] = {
  438. { 0x80, 0x63 }, /* Soft reset */
  439. { 0x2b, 0x01 }, { 0x2c, 0x01 }, { 0x2d, 0x10 }, { 0x2e, 0x20 }, /* MHDR, NHDR, NCLR, FDLR */
  440. { 0x2f, 0x01 }, { 0x30, 0x01 }, { 0x31, 0x10 }, { 0x32, 0x20 }, /* MHDF, NHDF, NCLF, FDLF */
  441. { 0x33, 0x01 }, { 0x34, 0x10 }, { 0x35, 0xff }, /* NHDT, NCLT, FDLT */
  442. { 0x5b, 0x11 }, { 0x5c, 0xff }, { 0x5d, 0x30 }, /* DTR, AFE1, AFE2 */
  443. { 0x7b, 0x00 }, { 0x7c, 0x00 }, { 0x7d, 0x00 }, { 0x7e, 0x00 }, { 0x7f, 0x00 },/* ACCR0, ACCR1, USL, LSL, TL */
  444. { 0x41, 0x28 }, { 0x42, 0x14 }, /* ELE0: Touch Threshold, Release Threshold */
  445. { 0x43, 0x28 }, { 0x44, 0x14 }, /* ELE1: Touch Threshold, Release Threshold */
  446. { 0x45, 0x28 }, { 0x46, 0x14 }, /* ELE2: Touch Threshold, Release Threshold */
  447. { 0x47, 0x28 }, { 0x48, 0x14 }, /* ELE3: Touch Threshold, Release Threshold */
  448. { 0x49, 0x28 }, { 0x4a, 0x14 }, /* ELE4: Touch Threshold, Release Threshold */
  449. { 0x4b, 0x28 }, { 0x4c, 0x14 }, /* ELE5: Touch Threshold, Release Threshold */
  450. { 0x4d, 0x28 }, { 0x4e, 0x14 }, /* ELE6: Touch Threshold, Release Threshold */
  451. { 0x4f, 0x28 }, { 0x50, 0x14 }, /* ELE7: Touch Threshold, Release Threshold */
  452. { 0x51, 0x28 }, { 0x52, 0x14 }, /* ELE8: Touch Threshold, Release Threshold */
  453. { 0x53, 0x28 }, { 0x54, 0x14 }, /* ELE9: Touch Threshold, Release Threshold */
  454. { 0x55, 0x28 }, { 0x56, 0x14 }, /* ELE10: Touch Threshold, Release Threshold */
  455. { 0x57, 0x28 }, { 0x58, 0x14 }, /* ELE11: Touch Threshold, Release Threshold */
  456. { 0x5e, 0xcc }, /* ECR - must be set last */
  457. { 0, 0 }
  458. };
  459. esp_err_t err = 0;
  460. for (int i = 0; mpr121_init_table[i].addr; i++) {
  461. err |= i2c_write(self->phy.port, self->phy.addr, mpr121_init_table[i].addr, mpr121_init_table[i].data, 1);
  462. }
  463. return err;
  464. }
  465. static uint32_t mpr121_read(gpio_exp_t* self) {
  466. // only return the lower 12 bits of the pin status registers
  467. return i2c_read(self->phy.port, self->phy.addr, 0x00, 2) & 0x0fff;
  468. }
  469. static void mpr121_write(gpio_exp_t* self) {
  470. ESP_LOGE(TAG, "MPR121 GPIO write not implemented");
  471. }
  472. /****************************************************************************************
  473. * PCA9535 family : direction, read and write
  474. */
  475. static void pca9535_set_direction(gpio_exp_t* self) {
  476. i2c_write(self->phy.port, self->phy.addr, 0x06, self->r_mask, 2);
  477. }
  478. static uint32_t pca9535_read(gpio_exp_t* self) {
  479. return i2c_read(self->phy.port, self->phy.addr, 0x00, 2);
  480. }
  481. static void pca9535_write(gpio_exp_t* self) {
  482. i2c_write(self->phy.port, self->phy.addr, 0x02, self->shadow, 2);
  483. }
  484. /****************************************************************************************
  485. * PCA85xx family : read and write
  486. */
  487. static uint32_t pca85xx_read(gpio_exp_t* self) {
  488. // must return the full set of pins, not just inputs
  489. uint32_t data = i2c_read(self->phy.port, self->phy.addr, 0xff, 2);
  490. return (data & self->r_mask) | (self->shadow & ~self->r_mask);
  491. }
  492. static void pca85xx_write(gpio_exp_t* self) {
  493. /*
  494. There is no good option with this chip: normally, unused pin should be set to input
  495. to avoid any conflict but then they float and create tons of suprious. So option 1 is
  496. to le tthem float and option 2 is to set them as output to 0.
  497. In addition, setting an output pin to 1 equals is making it an input and if this is
  498. use to short a led (e.g.) instead of being the sink, the it generates a spurious
  499. */
  500. // option 1
  501. // i2c_write(self->phy.port, self->phy.addr, 0xff, (self->shadow & self->w_mask) | ~self->w_mask, 2);
  502. // option 2
  503. i2c_write(self->phy.port, self->phy.addr, 0xff, (self->shadow & self->w_mask) | self->r_mask, 2);
  504. }
  505. /****************************************************************************************
  506. * MCP23017 family : init, direction, read and write
  507. */
  508. static esp_err_t mcp23017_init(gpio_exp_t* self) {
  509. /*
  510. 0111 x10x = same bank, mirrot single int, no sequentµial, open drain, active low
  511. not sure about this funny change of mapping of the control register itself, really?
  512. */
  513. esp_err_t err = i2c_write(self->phy.port, self->phy.addr, 0x05, 0x74, 1);
  514. err |= i2c_write(self->phy.port, self->phy.addr, 0x0a, 0x74, 1);
  515. // no interrupt on comparison or on change
  516. err |= i2c_write(self->phy.port, self->phy.addr, 0x04, 0x00, 2);
  517. err |= i2c_write(self->phy.port, self->phy.addr, 0x08, 0x00, 2);
  518. return err;
  519. }
  520. static void mcp23017_set_direction(gpio_exp_t* self) {
  521. // default to input and set real input to generate interrupt
  522. i2c_write(self->phy.port, self->phy.addr, 0x00, ~self->w_mask, 2);
  523. i2c_write(self->phy.port, self->phy.addr, 0x04, self->r_mask, 2);
  524. }
  525. static void mcp23017_set_pull_mode(gpio_exp_t* self) {
  526. i2c_write(self->phy.port, self->phy.addr, 0x0c, self->pullup, 2);
  527. }
  528. static uint32_t mcp23017_read(gpio_exp_t* self) {
  529. // read the pins value, not the stored one @interrupt
  530. return i2c_read(self->phy.port, self->phy.addr, 0x12, 2);
  531. }
  532. static void mcp23017_write(gpio_exp_t* self) {
  533. i2c_write(self->phy.port, self->phy.addr, 0x12, self->shadow, 2);
  534. }
  535. /****************************************************************************************
  536. * MCP23s17 family : init, direction, read and write
  537. */
  538. static esp_err_t mcp23s17_init(gpio_exp_t* self) {
  539. if ((self->spi_handle = spi_config(&self->phy)) == NULL) return ESP_ERR_INVALID_ARG;
  540. /*
  541. 0111 x10x = same bank, mirrot single int, no sequentµial, open drain, active low
  542. not sure about this funny change of mapping of the control register itself, really?
  543. */
  544. esp_err_t err = spi_write(self->spi_handle, self->phy.addr, 0x05, 0x74, 1);
  545. err |= spi_write(self->spi_handle, self->phy.addr, 0x0a, 0x74, 1);
  546. // no interrupt on comparison or on change
  547. err |= spi_write(self->spi_handle, self->phy.addr, 0x04, 0x00, 2);
  548. err |= spi_write(self->spi_handle, self->phy.addr, 0x08, 0x00, 2);
  549. return err;
  550. }
  551. static void mcp23s17_set_direction(gpio_exp_t* self) {
  552. // default to input and set real input to generate interrupt
  553. spi_write(self->spi_handle, self->phy.addr, 0x00, ~self->w_mask, 2);
  554. spi_write(self->spi_handle, self->phy.addr, 0x04, self->r_mask, 2);
  555. }
  556. static void mcp23s17_set_pull_mode(gpio_exp_t* self) {
  557. spi_write(self->spi_handle, self->phy.addr, 0x0c, self->pullup, 2);
  558. }
  559. static uint32_t mcp23s17_read(gpio_exp_t* self) {
  560. // read the pins value, not the stored one @interrupt
  561. return spi_read(self->spi_handle, self->phy.addr, 0x12, 2);
  562. }
  563. static void mcp23s17_write(gpio_exp_t* self) {
  564. spi_write(self->spi_handle, self->phy.addr, 0x12, self->shadow, 2);
  565. }
  566. /***************************************************************************************
  567. I2C low level
  568. ***************************************************************************************/
  569. /****************************************************************************************
  570. * I2C write up to 32 bits
  571. */
  572. static esp_err_t i2c_write(uint8_t port, uint8_t addr, uint8_t reg, uint32_t data, int len) {
  573. i2c_cmd_handle_t cmd = i2c_cmd_link_create();
  574. i2c_master_start(cmd);
  575. i2c_master_write_byte(cmd, (addr << 1) | I2C_MASTER_WRITE, I2C_MASTER_NACK);
  576. if (reg != 0xff) i2c_master_write_byte(cmd, reg, I2C_MASTER_NACK);
  577. // works with our endianness
  578. if (len > 1) i2c_master_write(cmd, (uint8_t*) &data, len, I2C_MASTER_NACK);
  579. else i2c_master_write_byte(cmd, data, I2C_MASTER_NACK);
  580. i2c_master_stop(cmd);
  581. esp_err_t ret = i2c_master_cmd_begin(port, cmd, 100 / portTICK_RATE_MS);
  582. i2c_cmd_link_delete(cmd);
  583. if (ret != ESP_OK) {
  584. ESP_LOGW(TAG, "I2C write failed");
  585. }
  586. return ret;
  587. }
  588. /****************************************************************************************
  589. * I2C read up to 32 bits
  590. */
  591. static uint32_t i2c_read(uint8_t port, uint8_t addr, uint8_t reg, int len) {
  592. uint32_t data = 0;
  593. i2c_cmd_handle_t cmd = i2c_cmd_link_create();
  594. i2c_master_start(cmd);
  595. // when using a register, write it's value then the device address again
  596. if (reg != 0xff) {
  597. i2c_master_write_byte(cmd, (addr << 1) | I2C_MASTER_WRITE, I2C_MASTER_NACK);
  598. i2c_master_write_byte(cmd, reg, I2C_MASTER_NACK);
  599. i2c_master_start(cmd);
  600. i2c_master_write_byte(cmd, (addr << 1) | I2C_MASTER_READ, I2C_MASTER_NACK);
  601. } else {
  602. i2c_master_write_byte(cmd, (addr << 1) | I2C_MASTER_READ, I2C_MASTER_NACK);
  603. }
  604. // works with our endianness
  605. if (len > 1) i2c_master_read(cmd, (uint8_t*) &data, len, I2C_MASTER_LAST_NACK);
  606. else i2c_master_read_byte(cmd, (uint8_t*) &data, I2C_MASTER_NACK);
  607. i2c_master_stop(cmd);
  608. esp_err_t ret = i2c_master_cmd_begin(port, cmd, 100 / portTICK_RATE_MS);
  609. i2c_cmd_link_delete(cmd);
  610. if (ret != ESP_OK) {
  611. ESP_LOGW(TAG, "I2C read failed");
  612. }
  613. return data;
  614. }
  615. /***************************************************************************************
  616. SPI low level
  617. ***************************************************************************************/
  618. /****************************************************************************************
  619. * SPI device addition
  620. */
  621. static spi_device_handle_t spi_config(struct gpio_exp_phy_s *phy) {
  622. spi_device_interface_config_t config = { };
  623. spi_device_handle_t handle = NULL;
  624. config.command_bits = config.address_bits = 8;
  625. config.clock_speed_hz = phy->speed ? phy->speed : SPI_MASTER_FREQ_8M;
  626. config.spics_io_num = phy->cs_pin;
  627. config.queue_size = 1;
  628. config.flags = SPI_DEVICE_NO_DUMMY;
  629. spi_bus_add_device( phy->host, &config, &handle );
  630. ESP_LOGI(TAG, "SPI expander initialized on host:%d with cs:%d and speed:%dHz", phy->host, phy->cs_pin, config.clock_speed_hz);
  631. return handle;
  632. }
  633. /****************************************************************************************
  634. * SPI write up to 32 bits
  635. */
  636. static esp_err_t spi_write(spi_device_handle_t handle, uint8_t addr, uint8_t reg, uint32_t data, int len) {
  637. spi_transaction_t transaction = { };
  638. // rx_buffer is NULL, nothing to receive
  639. transaction.flags = SPI_TRANS_USE_TXDATA;
  640. transaction.cmd = addr << 1;
  641. transaction.addr = reg;
  642. transaction.tx_data[0] = data; transaction.tx_data[1] = data >> 8;
  643. transaction.length = len * 8;
  644. // only do polling as we don't have contention on SPI (otherwise DMA for transfers > 16 bytes)
  645. return spi_device_polling_transmit(handle, &transaction);
  646. }
  647. /****************************************************************************************
  648. * SPI read up to 32 bits
  649. */
  650. static uint32_t spi_read(spi_device_handle_t handle, uint8_t addr, uint8_t reg, int len) {
  651. spi_transaction_t *transaction = heap_caps_calloc(1, sizeof(spi_transaction_t), MALLOC_CAP_DMA);
  652. // tx_buffer is NULL, nothing to transmit except cmd/addr
  653. transaction->flags = SPI_TRANS_USE_RXDATA;
  654. transaction->cmd = (addr << 1) | 0x01;
  655. transaction->addr = reg;
  656. transaction->length = len * 8;
  657. // only do polling as we don't have contention on SPI (otherwise DMA for transfers > 16 bytes)
  658. spi_device_polling_transmit(handle, transaction);
  659. uint32_t data = *(uint32_t*) transaction->rx_data;
  660. free(transaction);
  661. return data;
  662. }