gpio_exp.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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/queue.h"
  12. #include "esp_task.h"
  13. #include "esp_log.h"
  14. #include "driver/gpio.h"
  15. #include "driver/i2c.h"
  16. #include "gpio_exp.h"
  17. static const char TAG[] = "gpio expander";
  18. static void IRAM_ATTR intr_isr_handler(void* arg);
  19. static struct gpio_exp_s* find_expander(struct gpio_exp_s *expander, int *gpio);
  20. static void pca9535_set_direction(union gpio_exp_phy_u*, uint32_t, uint32_t);
  21. static int pca9535_read(union gpio_exp_phy_u*);
  22. static void pca9535_write(union gpio_exp_phy_u*, uint32_t, uint32_t);
  23. static void pca85xx_set_direction(union gpio_exp_phy_u*, uint32_t, uint32_t);
  24. static int pca85xx_read(union gpio_exp_phy_u*);
  25. static void pca85xx_write(union gpio_exp_phy_u*, uint32_t, uint32_t);
  26. static void async_handler(void *arg);
  27. static esp_err_t i2c_write_byte(uint8_t i2c_port, uint8_t i2c_addr, uint8_t reg, uint8_t val);
  28. static uint8_t i2c_read_byte(uint8_t i2c_port, uint8_t i2c_addr, uint8_t reg);
  29. static uint16_t i2c_read_word(uint8_t i2c_port, uint8_t i2c_addr, uint8_t reg);
  30. static esp_err_t i2c_write_word(uint8_t i2c_port, uint8_t i2c_addr, uint8_t reg, uint16_t data);
  31. typedef struct {
  32. enum { ASYNC_WRITE } type;
  33. int gpio;
  34. int level;
  35. struct gpio_exp_s *expander;
  36. } async_request_t;
  37. static const struct gpio_exp_model_s {
  38. char *model;
  39. gpio_int_type_t trigger;
  40. void (*init)(union gpio_exp_phy_u*);
  41. int (*read)(union gpio_exp_phy_u*);
  42. void (*write)(union gpio_exp_phy_u*, uint32_t r_mask, uint32_t shadow);
  43. void (*set_direction)(union gpio_exp_phy_u*, uint32_t r_mask, uint32_t w_mask);
  44. void (*set_pull_mode)(int, gpio_pull_mode_t);
  45. } registered[] = {
  46. { .model = "pca9535",
  47. .trigger = GPIO_INTR_NEGEDGE,
  48. .set_direction = pca9535_set_direction,
  49. .read = pca9535_read,
  50. .write = pca9535_write, },
  51. { .model = "pca85xx",
  52. .trigger = GPIO_INTR_NEGEDGE,
  53. .set_direction = pca85xx_set_direction,
  54. .read = pca85xx_read,
  55. .write = pca85xx_write, }
  56. };
  57. static EXT_RAM_ATTR uint8_t n_expanders;
  58. static EXT_RAM_ATTR QueueHandle_t async_queue;
  59. static EXT_RAM_ATTR struct gpio_exp_s {
  60. uint32_t first, last;
  61. union gpio_exp_phy_u phy;
  62. uint32_t shadow;
  63. TickType_t age;
  64. SemaphoreHandle_t mutex;
  65. uint32_t r_mask, w_mask;
  66. struct {
  67. gpio_exp_isr handler;
  68. void *arg;
  69. } isr[4];
  70. struct gpio_exp_model_s const *model;
  71. } expanders[4];
  72. /******************************************************************************
  73. * Retrieve base from an expander reference
  74. */
  75. uint32_t gpio_exp_get_base(struct gpio_exp_s *expander) {
  76. return expander->first;
  77. }
  78. /******************************************************************************
  79. * Retrieve reference from a GPIO
  80. */
  81. struct gpio_exp_s *gpio_exp_get_expander(int gpio) {
  82. int _gpio = gpio;
  83. return find_expander(NULL, &_gpio);
  84. }
  85. /******************************************************************************
  86. * Create an I2C expander
  87. */
  88. struct gpio_exp_s* gpio_exp_create(const gpio_exp_config_t *config) {
  89. struct gpio_exp_s *expander = expanders + n_expanders;
  90. if (config->base < GPIO_NUM_MAX || n_expanders == sizeof(expanders)/sizeof(struct gpio_exp_s)) {
  91. 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);
  92. return NULL;
  93. }
  94. // See if we know that model (expanders is zero-initialized)
  95. for (int i = 0; !expander->model && i < sizeof(registered)/sizeof(struct gpio_exp_model_s); i++) {
  96. if (strcasestr(config->model, registered[i].model)) expander->model = registered + i;
  97. }
  98. // well... try again
  99. if (!expander->model) {
  100. ESP_LOGE(TAG,"Unknown GPIO expansion chip %s", config->model);
  101. return NULL;
  102. }
  103. n_expanders++;
  104. expander->first = config->base;
  105. expander->last = config->base + config->count - 1;
  106. expander->mutex = xSemaphoreCreateMutex();
  107. memcpy(&expander->phy, &config->phy, sizeof(union gpio_exp_phy_u));
  108. if (expander->model->init) expander->model->init(&expander->phy);
  109. // create a task to handle asynchronous requests (only write at this time)
  110. if (!async_queue) {
  111. // we allocate TCB but stack is staic to avoid SPIRAM fragmentation
  112. StaticTask_t* xTaskBuffer = (StaticTask_t*) heap_caps_malloc(sizeof(StaticTask_t), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
  113. static EXT_RAM_ATTR StackType_t xStack[2*1024] __attribute__ ((aligned (4)));
  114. async_queue = xQueueCreate(4, sizeof(async_request_t));
  115. xTaskCreateStatic(async_handler, "gpio_expander", sizeof(xStack), NULL, ESP_TASK_PRIO_MIN + 1, xStack, xTaskBuffer);
  116. }
  117. // set interrupt if possible
  118. if (config->intr > 0) {
  119. gpio_pad_select_gpio(config->intr);
  120. gpio_set_direction(config->intr, GPIO_MODE_INPUT);
  121. switch (expander->model->trigger) {
  122. case GPIO_INTR_NEGEDGE:
  123. case GPIO_INTR_LOW_LEVEL:
  124. gpio_set_pull_mode(config->intr, GPIO_PULLUP_ONLY);
  125. break;
  126. case GPIO_INTR_POSEDGE:
  127. case GPIO_INTR_HIGH_LEVEL:
  128. gpio_set_pull_mode(config->intr, GPIO_PULLDOWN_ONLY);
  129. break;
  130. default:
  131. gpio_set_pull_mode(config->intr, GPIO_PULLUP_PULLDOWN);
  132. break;
  133. }
  134. gpio_set_intr_type(config->intr, expander->model->trigger);
  135. gpio_isr_handler_add(config->intr, intr_isr_handler, expander);
  136. gpio_intr_enable(config->intr);
  137. }
  138. ESP_LOGI(TAG, "Create GPIO expander at base %u with INT %u at @%x on port %d", config->base, config->intr, config->phy.addr, config->phy.port);
  139. return expander;
  140. }
  141. /******************************************************************************
  142. * Add ISR handler
  143. */
  144. bool gpio_exp_add_isr(gpio_exp_isr isr, void *arg, struct gpio_exp_s *expander) {
  145. xSemaphoreTake(expander->mutex, pdMS_TO_TICKS(portMAX_DELAY));
  146. for (int i = 0; i < sizeof(expander->isr)/sizeof(*expander->isr); i++) {
  147. if (!expander->isr[i].handler) {
  148. expander->isr[i].handler = isr;
  149. expander->isr[i].arg = arg;
  150. ESP_LOGI(TAG, "Added new ISR for expander base %d", expander->first);
  151. xSemaphoreGive(expander->mutex);
  152. return true;
  153. }
  154. }
  155. xSemaphoreGive(expander->mutex);
  156. ESP_LOGE(TAG, "No room left to add new ISR");
  157. return false;
  158. }
  159. /******************************************************************************
  160. * Set GPIO direction
  161. */
  162. esp_err_t gpio_exp_set_direction(int gpio, gpio_mode_t mode, struct gpio_exp_s *expander) {
  163. if ((expander = find_expander(expander, &gpio)) == NULL) return ESP_ERR_INVALID_ARG;
  164. xSemaphoreTake(expander->mutex, pdMS_TO_TICKS(portMAX_DELAY));
  165. if (mode == GPIO_MODE_INPUT) {
  166. expander->r_mask |= 1 << gpio;
  167. expander->age = ~xTaskGetTickCount();
  168. } else {
  169. expander->w_mask |= 1 << gpio;
  170. }
  171. if (expander->r_mask & expander->w_mask) {
  172. xSemaphoreGive(expander->mutex);
  173. ESP_LOGE(TAG, "GPIO %d on expander base %u can't be r/w", gpio, expander->first);
  174. return ESP_ERR_INVALID_ARG;
  175. }
  176. // most expanders want unconfigured GPIO to be set to output
  177. if (expander->model->set_direction) expander->model->set_direction(&expander->phy, expander->r_mask, expander->w_mask);
  178. xSemaphoreGive(expander->mutex);
  179. return ESP_OK;
  180. }
  181. /******************************************************************************
  182. * Get GPIO level with cache
  183. */
  184. int gpio_exp_get_level(int gpio, uint32_t age, struct gpio_exp_s *expander) {
  185. if ((expander = find_expander(expander, &gpio)) == NULL) return -1;
  186. uint32_t now = xTaskGetTickCount();
  187. // this is a little risk here but that avoids calling scheduler if we are cached
  188. if (now - expander->age >= pdMS_TO_TICKS(age)) {
  189. if (xSemaphoreTake(expander->mutex, pdMS_TO_TICKS(50)) == pdFALSE) return -1;
  190. expander->shadow = expander->model->read(&expander->phy);
  191. expander->age = now;
  192. xSemaphoreGive(expander->mutex);
  193. }
  194. ESP_LOGD(TAG, "Get level for GPIO %u => read %x", expander->first + gpio, expander->shadow);
  195. return (expander->shadow >> gpio) & 0x01;
  196. }
  197. /******************************************************************************
  198. * Set GPIO level with cache
  199. */
  200. esp_err_t gpio_exp_set_level(int gpio, int level, bool direct, struct gpio_exp_s *expander) {
  201. if ((expander = find_expander(expander, &gpio)) == NULL) return ESP_ERR_INVALID_ARG;
  202. uint32_t mask = 1 << gpio;
  203. // limited risk with lack of semaphore here
  204. if ((expander->w_mask & mask) == 0) {
  205. ESP_LOGW(TAG, "GPIO %d is not set for output", expander->first + gpio);
  206. return ESP_ERR_INVALID_ARG;
  207. }
  208. if (direct) {
  209. xSemaphoreTake(expander->mutex, pdMS_TO_TICKS(portMAX_DELAY));
  210. level = level ? mask : 0;
  211. mask &= expander->shadow;
  212. // only write if shadow not up to date
  213. if ((mask ^ level) && expander->model->write) {
  214. expander->shadow = (expander->shadow & ~(mask | level)) | level;
  215. expander->model->write(&expander->phy, expander->r_mask, expander->shadow);
  216. }
  217. xSemaphoreGive(expander->mutex);
  218. ESP_LOGD(TAG, "Set level %x for GPIO %u => wrote %x", level, expander->first + gpio, expander->shadow);
  219. } else {
  220. async_request_t request = { .gpio = gpio, .level = level, .type = ASYNC_WRITE, .expander = expander };
  221. if (xQueueSend(async_queue, &request, 0) == pdFALSE) return ESP_ERR_INVALID_RESPONSE;
  222. }
  223. return ESP_OK;
  224. }
  225. /******************************************************************************
  226. * Set GPIO pullmode
  227. */
  228. esp_err_t gpio_exp_set_pull_mode(int gpio, gpio_pull_mode_t mode, struct gpio_exp_s *expander) {
  229. if ((expander = find_expander(expander, &gpio)) != NULL && expander->model->set_pull_mode) {
  230. expander->model->set_pull_mode(gpio, mode);
  231. return ESP_OK;
  232. }
  233. return ESP_ERR_INVALID_ARG;
  234. }
  235. /******************************************************************************
  236. * Enumerate modified GPIO
  237. */
  238. void gpio_exp_enumerate(gpio_exp_enumerator enumerator, struct gpio_exp_s *expander) {
  239. uint32_t value = expander->model->read(&expander->phy) ^ expander->shadow;
  240. uint8_t clz;
  241. // memorize newly read value and just update if requested
  242. xSemaphoreTake(expander->mutex, pdMS_TO_TICKS(50));
  243. expander->shadow ^= value;
  244. xSemaphoreGive(expander->mutex);
  245. if (!enumerator) return;
  246. // now we have a bitmap of all modified GPIO sinnce last call
  247. for (int gpio = 0; value; value <<= (clz + 1)) {
  248. clz = __builtin_clz(value);
  249. gpio += clz;
  250. enumerator(expander->first + 31 - gpio, (expander->shadow >> (31 - gpio)) & 0x01, expander);
  251. }
  252. }
  253. /******************************************************************************
  254. * Wrapper function
  255. */
  256. esp_err_t gpio_set_pull_mode_u(int gpio, gpio_pull_mode_t mode) {
  257. if (gpio < GPIO_NUM_MAX) return gpio_set_pull_mode(gpio, mode);
  258. return gpio_exp_set_pull_mode(gpio, mode, NULL);
  259. }
  260. esp_err_t gpio_set_direction_u(int gpio, gpio_mode_t mode) {
  261. if (gpio < GPIO_NUM_MAX) return gpio_set_direction(gpio, mode);
  262. return gpio_exp_set_direction(gpio, mode, NULL);
  263. }
  264. int gpio_get_level_u(int gpio) {
  265. if (gpio < GPIO_NUM_MAX) return gpio_get_level(gpio);
  266. return gpio_exp_get_level(gpio, 50, NULL);
  267. }
  268. esp_err_t gpio_set_level_u(int gpio, int level) {
  269. if (gpio < GPIO_NUM_MAX) return gpio_set_level(gpio, level);
  270. return gpio_exp_set_level(gpio, level, false, NULL);
  271. }
  272. /****************************************************************************************
  273. * Find the expander related to base
  274. */
  275. static struct gpio_exp_s* find_expander(struct gpio_exp_s *expander, int *gpio) {
  276. for (int i = 0; !expander && i < n_expanders; i++) {
  277. if (*gpio >= expanders[i].first && *gpio <= expanders[i].last) expander = expanders + i;
  278. }
  279. // normalize GPIO number
  280. if (expander && *gpio >= expanders->first) *gpio -= expanders->first;
  281. return expander;
  282. }
  283. /****************************************************************************************
  284. * PCA9535 family : direction, read and write
  285. */
  286. static void pca9535_set_direction(union gpio_exp_phy_u *phy, uint32_t r_mask, uint32_t w_mask) {
  287. i2c_write_word(phy->port, phy->addr, 0x06, r_mask);
  288. }
  289. static int pca9535_read(union gpio_exp_phy_u *phy) {
  290. return i2c_read_word(phy->port, phy->addr, 0x00);
  291. }
  292. static void pca9535_write(union gpio_exp_phy_u *phy, uint32_t r_mask, uint32_t shadow) {
  293. i2c_write_word(phy->port, phy->addr, 0x02, shadow);
  294. }
  295. /****************************************************************************************
  296. * PCA85xx family : read and write
  297. */
  298. static void pca85xx_set_direction(union gpio_exp_phy_u *phy, uint32_t r_mask, uint32_t w_mask) {
  299. // all inputs must be set to 1 (open drain) and output are left open as well
  300. i2c_write_word(phy->port, phy->addr, 0xff, r_mask | w_mask);
  301. }
  302. static int pca85xx_read(union gpio_exp_phy_u *phy) {
  303. return i2c_read_word(phy->port, phy->addr, 0xff);
  304. }
  305. static void pca85xx_write(union gpio_exp_phy_u *phy, uint32_t r_mask, uint32_t shadow) {
  306. // all input must be set to 1 (open drain)
  307. i2c_write_word(phy->port, phy->addr, 0xff, shadow | r_mask);
  308. }
  309. /****************************************************************************************
  310. * INTR low-level handler
  311. */
  312. static void IRAM_ATTR intr_isr_handler(void* arg)
  313. {
  314. struct gpio_exp_s *expander = (struct gpio_exp_s*) arg;
  315. BaseType_t woken = pdFALSE;
  316. for (int i = 0; i < sizeof(expander->isr)/sizeof(*expander->isr); i++) {
  317. if (expander->isr[i].handler) woken |= expander->isr[i].handler(expander->isr[i].arg);
  318. }
  319. if (woken) portYIELD_FROM_ISR();
  320. ESP_EARLY_LOGD(TAG, "INTR for expander %u", expander->first);
  321. }
  322. /****************************************************************************************
  323. * Async task
  324. */
  325. void async_handler(void *arg) {
  326. while (1) {
  327. esp_err_t err;
  328. async_request_t request;
  329. if (!xQueueReceive(async_queue, &request, portMAX_DELAY)) continue;
  330. switch (request.type) {
  331. case ASYNC_WRITE:
  332. err = gpio_exp_set_level(request.gpio, request.level, true, request.expander);
  333. if (err != ESP_OK) ESP_LOGW(TAG, "Can't execute async GPIO %d write request (%d)", request.gpio, err);
  334. break;
  335. default:
  336. break;
  337. }
  338. }
  339. }
  340. /****************************************************************************************
  341. *
  342. */
  343. static esp_err_t i2c_write_byte(uint8_t i2c_port, uint8_t i2c_addr, uint8_t reg, uint8_t val) {
  344. i2c_cmd_handle_t cmd = i2c_cmd_link_create();
  345. i2c_master_start(cmd);
  346. i2c_master_write_byte(cmd, (i2c_addr << 1) | I2C_MASTER_WRITE, I2C_MASTER_NACK);
  347. i2c_master_write_byte(cmd, reg, I2C_MASTER_NACK);
  348. i2c_master_write_byte(cmd, val, I2C_MASTER_NACK);
  349. i2c_master_stop(cmd);
  350. esp_err_t ret = i2c_master_cmd_begin(i2c_port, cmd, 100 / portTICK_RATE_MS);
  351. i2c_cmd_link_delete(cmd);
  352. if (ret != ESP_OK) {
  353. ESP_LOGW(TAG, "I2C write failed");
  354. }
  355. return ret;
  356. }
  357. /****************************************************************************************
  358. * I2C read one byte
  359. */
  360. static uint8_t i2c_read_byte(uint8_t i2c_port, uint8_t i2c_addr, uint8_t reg) {
  361. uint8_t data = 0xff;
  362. i2c_cmd_handle_t cmd = i2c_cmd_link_create();
  363. i2c_master_start(cmd);
  364. i2c_master_write_byte(cmd, (i2c_addr << 1) | I2C_MASTER_WRITE, I2C_MASTER_NACK);
  365. i2c_master_write_byte(cmd, reg, I2C_MASTER_NACK);
  366. i2c_master_start(cmd);
  367. i2c_master_write_byte(cmd, (i2c_addr << 1) | I2C_MASTER_READ, I2C_MASTER_NACK);
  368. i2c_master_read_byte(cmd, &data, I2C_MASTER_NACK);
  369. i2c_master_stop(cmd);
  370. esp_err_t ret = i2c_master_cmd_begin(i2c_port, cmd, 100 / portTICK_RATE_MS);
  371. i2c_cmd_link_delete(cmd);
  372. if (ret != ESP_OK) {
  373. ESP_LOGW(TAG, "I2C read failed");
  374. }
  375. return data;
  376. }
  377. /****************************************************************************************
  378. * I2C read 16 bits word
  379. */
  380. static uint16_t i2c_read_word(uint8_t i2c_port, uint8_t i2c_addr, uint8_t reg) {
  381. uint16_t data = 0xffff;
  382. i2c_cmd_handle_t cmd = i2c_cmd_link_create();
  383. i2c_master_start(cmd);
  384. i2c_master_write_byte(cmd, (i2c_addr << 1) | I2C_MASTER_WRITE, I2C_MASTER_NACK);
  385. // when using a register, write it's value then the device address again
  386. if (reg != 0xff) {
  387. i2c_master_write_byte(cmd, reg, I2C_MASTER_NACK);
  388. i2c_master_start(cmd);
  389. i2c_master_write_byte(cmd, (i2c_addr << 1) | I2C_MASTER_READ, I2C_MASTER_NACK);
  390. }
  391. i2c_master_read(cmd, (uint8_t*) &data, 2, I2C_MASTER_NACK);
  392. i2c_master_stop(cmd);
  393. esp_err_t ret = i2c_master_cmd_begin(i2c_port, cmd, 100 / portTICK_RATE_MS);
  394. i2c_cmd_link_delete(cmd);
  395. if (ret != ESP_OK) {
  396. ESP_LOGW(TAG, "I2C read failed");
  397. }
  398. return data;
  399. }
  400. /****************************************************************************************
  401. * I2C write 16 bits word
  402. */
  403. static esp_err_t i2c_write_word(uint8_t i2c_port, uint8_t i2c_addr, uint8_t reg, uint16_t data) {
  404. i2c_cmd_handle_t cmd = i2c_cmd_link_create();
  405. i2c_master_start(cmd);
  406. i2c_master_write_byte(cmd, (i2c_addr << 1) | I2C_MASTER_WRITE, I2C_MASTER_NACK);
  407. if (reg != 0xff) i2c_master_write_byte(cmd, reg, I2C_MASTER_NACK);
  408. i2c_master_write(cmd, (uint8_t*) &data, 2, I2C_MASTER_NACK);
  409. i2c_master_stop(cmd);
  410. esp_err_t ret = i2c_master_cmd_begin(i2c_port, cmd, 100 / portTICK_RATE_MS);
  411. i2c_cmd_link_delete(cmd);
  412. if (ret != ESP_OK) {
  413. ESP_LOGW(TAG, "I2C write failed");
  414. }
  415. return ret;
  416. }