gpio_exp.c 29 KB

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