gpio_exp.c 26 KB

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