gpio_exp.c 26 KB

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