gpio_exp.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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 "gpio_exp.h"
  18. #define GPIO_EXP_INTR 0x100
  19. #define GPIO_EXP_WRITE 0x200
  20. /*
  21. shadow register is both output and input, so we assume that reading to the
  22. ports also reads the value set on output
  23. */
  24. typedef struct gpio_exp_s {
  25. uint32_t first, last;
  26. union gpio_exp_phy_u phy;
  27. uint32_t shadow, pending;
  28. TickType_t age;
  29. SemaphoreHandle_t mutex;
  30. uint32_t r_mask, w_mask;
  31. uint32_t pullup, pulldown;
  32. struct gpio_exp_isr_s {
  33. gpio_isr_t handler;
  34. void *arg;
  35. TimerHandle_t timer;
  36. } isr[32];
  37. struct gpio_exp_model_s const *model;
  38. } gpio_exp_t;
  39. typedef struct {
  40. enum { ASYNC_WRITE } type;
  41. int gpio;
  42. int level;
  43. gpio_exp_t *expander;
  44. } queue_request_t;
  45. static const char TAG[] = "gpio expander";
  46. static void IRAM_ATTR intr_isr_handler(void* arg);
  47. static gpio_exp_t* find_expander(gpio_exp_t *expander, int *gpio);
  48. static void pca9535_set_direction(gpio_exp_t* self);
  49. static int pca9535_read(gpio_exp_t* self);
  50. static void pca9535_write(gpio_exp_t* self);
  51. static void pca85xx_set_direction(gpio_exp_t* self);
  52. static int pca85xx_read(gpio_exp_t* self);
  53. static void pca85xx_write(gpio_exp_t* self);
  54. static void mcp23017_init(gpio_exp_t* self);
  55. static void mcp23017_set_pull_mode(gpio_exp_t* self);
  56. static void mcp23017_set_direction(gpio_exp_t* self);
  57. static int mcp23017_read(gpio_exp_t* self);
  58. static void mcp23017_write(gpio_exp_t* self);
  59. static void service_handler(void *arg);
  60. static void debounce_handler( TimerHandle_t xTimer );
  61. static esp_err_t i2c_write_byte(uint8_t i2c_port, uint8_t i2c_addr, uint8_t reg, uint8_t val);
  62. static uint16_t i2c_read(uint8_t i2c_port, uint8_t i2c_addr, uint8_t reg, bool word);
  63. static esp_err_t i2c_write_word(uint8_t i2c_port, uint8_t i2c_addr, uint8_t reg, uint16_t data);
  64. static const struct gpio_exp_model_s {
  65. char *model;
  66. gpio_int_type_t trigger;
  67. void (*init)(gpio_exp_t* self);
  68. int (*read)(gpio_exp_t* self);
  69. void (*write)(gpio_exp_t* self);
  70. void (*set_direction)(gpio_exp_t* self);
  71. void (*set_pull_mode)(gpio_exp_t* self);
  72. } registered[] = {
  73. { .model = "pca9535",
  74. .trigger = GPIO_INTR_NEGEDGE,
  75. .set_direction = pca9535_set_direction,
  76. .read = pca9535_read,
  77. .write = pca9535_write, },
  78. { .model = "pca85xx",
  79. .trigger = GPIO_INTR_NEGEDGE,
  80. .set_direction = pca85xx_set_direction,
  81. .read = pca85xx_read,
  82. .write = pca85xx_write, },
  83. { .model = "mcp23017",
  84. .trigger = GPIO_INTR_NEGEDGE,
  85. .init = mcp23017_init,
  86. .set_direction = mcp23017_set_direction,
  87. .set_pull_mode = mcp23017_set_pull_mode,
  88. .read = mcp23017_read,
  89. .write = mcp23017_write, },
  90. };
  91. static EXT_RAM_ATTR uint8_t n_expanders;
  92. static EXT_RAM_ATTR QueueHandle_t message_queue;
  93. static EXT_RAM_ATTR gpio_exp_t expanders[4];
  94. static EXT_RAM_ATTR TaskHandle_t service_task;
  95. /******************************************************************************
  96. * Retrieve base from an expander reference
  97. */
  98. uint32_t gpio_exp_get_base(gpio_exp_t *expander) {
  99. return expander->first;
  100. }
  101. /******************************************************************************
  102. * Retrieve reference from a GPIO
  103. */
  104. gpio_exp_t *gpio_exp_get_expander(int gpio) {
  105. int _gpio = gpio;
  106. return find_expander(NULL, &_gpio);
  107. }
  108. /******************************************************************************
  109. * Create an I2C expander
  110. */
  111. gpio_exp_t* gpio_exp_create(const gpio_exp_config_t *config) {
  112. gpio_exp_t *expander = expanders + n_expanders;
  113. if (config->base < GPIO_NUM_MAX || n_expanders == sizeof(expanders)/sizeof(gpio_exp_t)) {
  114. 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);
  115. return NULL;
  116. }
  117. // See if we know that model (expanders is zero-initialized)
  118. for (int i = 0; !expander->model && i < sizeof(registered)/sizeof(struct gpio_exp_model_s); i++) {
  119. if (strcasestr(config->model, registered[i].model)) expander->model = registered + i;
  120. }
  121. // well... try again
  122. if (!expander->model) {
  123. ESP_LOGE(TAG,"Unknown GPIO expansion chip %s", config->model);
  124. return NULL;
  125. }
  126. n_expanders++;
  127. expander->first = config->base;
  128. expander->last = config->base + config->count - 1;
  129. expander->mutex = xSemaphoreCreateMutex();
  130. memcpy(&expander->phy, &config->phy, sizeof(union gpio_exp_phy_u));
  131. if (expander->model->init) expander->model->init(expander);
  132. // create a task to handle asynchronous requests (only write at this time)
  133. if (!message_queue) {
  134. // we allocate TCB but stack is static to avoid SPIRAM fragmentation
  135. StaticTask_t* xTaskBuffer = (StaticTask_t*) heap_caps_malloc(sizeof(StaticTask_t), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
  136. static EXT_RAM_ATTR StackType_t xStack[4*1024] __attribute__ ((aligned (4)));
  137. message_queue = xQueueCreate(4, sizeof(queue_request_t));
  138. service_task = xTaskCreateStatic(service_handler, "gpio_expander", sizeof(xStack), NULL, ESP_TASK_PRIO_MIN + 1, xStack, xTaskBuffer);
  139. }
  140. // set interrupt if possible
  141. if (config->intr > 0) {
  142. gpio_pad_select_gpio(config->intr);
  143. gpio_set_direction(config->intr, GPIO_MODE_INPUT);
  144. switch (expander->model->trigger) {
  145. case GPIO_INTR_NEGEDGE:
  146. case GPIO_INTR_LOW_LEVEL:
  147. gpio_set_pull_mode(config->intr, GPIO_PULLUP_ONLY);
  148. break;
  149. case GPIO_INTR_POSEDGE:
  150. case GPIO_INTR_HIGH_LEVEL:
  151. gpio_set_pull_mode(config->intr, GPIO_PULLDOWN_ONLY);
  152. break;
  153. default:
  154. gpio_set_pull_mode(config->intr, GPIO_PULLUP_PULLDOWN);
  155. break;
  156. }
  157. gpio_set_intr_type(config->intr, expander->model->trigger);
  158. gpio_isr_handler_add(config->intr, intr_isr_handler, expander);
  159. gpio_intr_enable(config->intr);
  160. }
  161. 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);
  162. return expander;
  163. }
  164. /******************************************************************************
  165. * Add ISR handler for a GPIO
  166. */
  167. 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) {
  168. if (gpio < GPIO_NUM_MAX && !expander) return gpio_isr_handler_add(gpio, isr_handler, arg);
  169. if ((expander = find_expander(expander, &gpio)) == NULL) return ESP_ERR_INVALID_ARG;
  170. expander->isr[gpio].handler = isr_handler;
  171. expander->isr[gpio].arg = arg;
  172. if (debounce) expander->isr[gpio].timer = xTimerCreate("gpioExpDebounce", pdMS_TO_TICKS(debounce),
  173. pdFALSE, expander->isr + gpio, debounce_handler );
  174. return ESP_OK;
  175. }
  176. /******************************************************************************
  177. * Remove ISR handler for a GPIO
  178. */
  179. esp_err_t gpio_exp_isr_handler_remove(int gpio, struct gpio_exp_s *expander) {
  180. if (gpio < GPIO_NUM_MAX && !expander) return gpio_isr_handler_remove(gpio);
  181. if ((expander = find_expander(expander, &gpio)) == NULL) return ESP_ERR_INVALID_ARG;
  182. if (expander->isr[gpio].timer) xTimerDelete(expander->isr[gpio].timer, portMAX_DELAY);
  183. memset(expander->isr + gpio, 0, sizeof(struct gpio_exp_isr_s));
  184. return ESP_OK;
  185. }
  186. /******************************************************************************
  187. * Set GPIO direction
  188. */
  189. esp_err_t gpio_exp_set_direction(int gpio, gpio_mode_t mode, gpio_exp_t *expander) {
  190. if (gpio < GPIO_NUM_MAX && !expander) return gpio_set_direction(gpio, mode);
  191. if ((expander = find_expander(expander, &gpio)) == NULL) return ESP_ERR_INVALID_ARG;
  192. xSemaphoreTake(expander->mutex, pdMS_TO_TICKS(portMAX_DELAY));
  193. if (mode == GPIO_MODE_INPUT) {
  194. expander->r_mask |= 1 << gpio;
  195. expander->shadow = expander->model->read(expander);
  196. expander->age = ~xTaskGetTickCount();
  197. } else {
  198. expander->w_mask |= 1 << gpio;
  199. }
  200. if (expander->r_mask & expander->w_mask) {
  201. xSemaphoreGive(expander->mutex);
  202. ESP_LOGE(TAG, "GPIO %d on expander base %u can't be r/w", gpio, expander->first);
  203. return ESP_ERR_INVALID_ARG;
  204. }
  205. // most expanders want unconfigured GPIO to be set to output
  206. if (expander->model->set_direction) expander->model->set_direction(expander);
  207. xSemaphoreGive(expander->mutex);
  208. return ESP_OK;
  209. }
  210. /******************************************************************************
  211. * Get GPIO level with cache
  212. */
  213. int gpio_exp_get_level(int gpio, int age, gpio_exp_t *expander) {
  214. if (gpio < GPIO_NUM_MAX && !expander) return gpio_get_level(gpio);
  215. if ((expander = find_expander(expander, &gpio)) == NULL) return -1;
  216. uint32_t now = xTaskGetTickCount();
  217. // return last thing we had if we can't get the mutex
  218. if (xSemaphoreTake(expander->mutex, pdMS_TO_TICKS(50)) == pdFALSE) {
  219. ESP_LOGW(TAG, "Can't get mutex for GPIO %d", expander->first + gpio);
  220. return (expander->shadow >> gpio) & 0x01;
  221. }
  222. // re-read the expander if data is too old
  223. if (age >= 0 && now - expander->age >= pdMS_TO_TICKS(age)) {
  224. uint32_t value = expander->model->read(expander);
  225. expander->pending |= (expander->shadow ^ value) & expander->r_mask;
  226. expander->shadow = value;
  227. expander->age = now;
  228. }
  229. // clear pending bit
  230. expander->pending &= ~(1 << gpio);
  231. xSemaphoreGive(expander->mutex);
  232. ESP_LOGD(TAG, "Get level for GPIO %u => read %x", expander->first + gpio, expander->shadow);
  233. return (expander->shadow >> gpio) & 0x01;
  234. }
  235. /******************************************************************************
  236. * Set GPIO level with cache
  237. */
  238. esp_err_t gpio_exp_set_level(int gpio, int level, bool direct, gpio_exp_t *expander) {
  239. if (gpio < GPIO_NUM_MAX && !expander) return gpio_set_level(gpio, level);
  240. if ((expander = find_expander(expander, &gpio)) == NULL) return ESP_ERR_INVALID_ARG;
  241. uint32_t mask = 1 << gpio;
  242. // very limited risk with lack of semaphore here
  243. if ((expander->w_mask & mask) == 0) {
  244. ESP_LOGW(TAG, "GPIO %d is not set for output", expander->first + gpio);
  245. return ESP_ERR_INVALID_ARG;
  246. }
  247. if (direct) {
  248. xSemaphoreTake(expander->mutex, pdMS_TO_TICKS(portMAX_DELAY));
  249. level = level ? mask : 0;
  250. mask &= expander->shadow;
  251. // only write if shadow not up to date
  252. if ((mask ^ level) && expander->model->write) {
  253. expander->shadow = (expander->shadow & ~(mask | level)) | level;
  254. expander->model->write(expander);
  255. }
  256. xSemaphoreGive(expander->mutex);
  257. ESP_LOGD(TAG, "Set level %x for GPIO %u => wrote %x", level, expander->first + gpio, expander->shadow);
  258. } else {
  259. queue_request_t request = { .gpio = gpio, .level = level, .type = ASYNC_WRITE, .expander = expander };
  260. if (xQueueSend(message_queue, &request, 0) == pdFALSE) return ESP_ERR_INVALID_RESPONSE;
  261. // notify service task that will write it when it can
  262. xTaskNotify(service_task, GPIO_EXP_WRITE, eSetValueWithoutOverwrite);
  263. }
  264. return ESP_OK;
  265. }
  266. /******************************************************************************
  267. * Set GPIO pullmode
  268. */
  269. esp_err_t gpio_exp_set_pull_mode(int gpio, gpio_pull_mode_t mode, gpio_exp_t *expander) {
  270. if (gpio < GPIO_NUM_MAX && !expander) return gpio_set_pull_mode(gpio, mode);
  271. if ((expander = find_expander(expander, &gpio)) != NULL && expander->model->set_pull_mode) {
  272. expander->pullup &= ~(1 << gpio);
  273. expander->pulldown &= ~(1 << gpio);
  274. if (mode == GPIO_PULLUP_ONLY || mode == GPIO_PULLUP_PULLDOWN) expander->pullup |= 1 << gpio;
  275. if (mode == GPIO_PULLDOWN_ONLY || mode == GPIO_PULLUP_PULLDOWN) expander->pulldown |= 1 << gpio;
  276. expander->model->set_pull_mode(expander);
  277. return ESP_OK;
  278. }
  279. return ESP_ERR_INVALID_ARG;
  280. }
  281. /******************************************************************************
  282. * Wrapper function
  283. */
  284. esp_err_t gpio_set_pull_mode_x(int gpio, gpio_pull_mode_t mode) {
  285. if (gpio < GPIO_NUM_MAX) return gpio_set_pull_mode(gpio, mode);
  286. return gpio_exp_set_pull_mode(gpio, mode, NULL);
  287. }
  288. esp_err_t gpio_set_direction_x(int gpio, gpio_mode_t mode) {
  289. if (gpio < GPIO_NUM_MAX) return gpio_set_direction(gpio, mode);
  290. return gpio_exp_set_direction(gpio, mode, NULL);
  291. }
  292. int gpio_get_level_x(int gpio) {
  293. if (gpio < GPIO_NUM_MAX) return gpio_get_level(gpio);
  294. return gpio_exp_get_level(gpio, 10, NULL);
  295. }
  296. esp_err_t gpio_set_level_x(int gpio, int level) {
  297. if (gpio < GPIO_NUM_MAX) return gpio_set_level(gpio, level);
  298. return gpio_exp_set_level(gpio, level, false, NULL);
  299. }
  300. esp_err_t gpio_isr_handler_add_x(int gpio, gpio_isr_t isr_handler, void* args) {
  301. if (gpio < GPIO_NUM_MAX) return gpio_isr_handler_add(gpio, isr_handler, args);
  302. return gpio_exp_isr_handler_add(gpio, isr_handler, 0, args, NULL);
  303. }
  304. esp_err_t gpio_isr_handler_remove_x(int gpio) {
  305. if (gpio < GPIO_NUM_MAX) return gpio_isr_handler_remove(gpio);
  306. return gpio_exp_isr_handler_remove(gpio, NULL);
  307. }
  308. /****************************************************************************************
  309. * Find the expander related to base
  310. */
  311. static gpio_exp_t* find_expander(gpio_exp_t *expander, int *gpio) {
  312. // a mutex would be better, but risk is so small...
  313. for (int i = 0; !expander && i < n_expanders; i++) {
  314. if (*gpio >= expanders[i].first && *gpio <= expanders[i].last) expander = expanders + i;
  315. }
  316. // normalize GPIO number
  317. if (expander && *gpio >= expanders->first) *gpio -= expanders->first;
  318. return expander;
  319. }
  320. /****************************************************************************************
  321. * PCA9535 family : direction, read and write
  322. */
  323. static void pca9535_set_direction(gpio_exp_t* self) {
  324. i2c_write_word(self->phy.port, self->phy.addr, 0x06, self->r_mask);
  325. }
  326. static int pca9535_read(gpio_exp_t* self) {
  327. return i2c_read(self->phy.port, self->phy.addr, 0x00, true);
  328. }
  329. static void pca9535_write(gpio_exp_t* self) {
  330. i2c_write_word(self->phy.port, self->phy.addr, 0x02, self->shadow);
  331. }
  332. /****************************************************************************************
  333. * PCA85xx family : read and write
  334. */
  335. static void pca85xx_set_direction(gpio_exp_t* self) {
  336. // all inputs must be set to 1 (open drain) and output are left open as well
  337. i2c_write_word(self->phy.port, self->phy.addr, 0xff, self->r_mask | self->w_mask);
  338. }
  339. static int pca85xx_read(gpio_exp_t* self) {
  340. return i2c_read(self->phy.port, self->phy.addr, 0xff, true);
  341. }
  342. static void pca85xx_write(gpio_exp_t* self) {
  343. // all input must be set to 1 (open drain)
  344. i2c_write_word(self->phy.port, self->phy.addr, 0xff, self->shadow | self->r_mask);
  345. }
  346. /****************************************************************************************
  347. * MCP23017 family : init, direction, read and write
  348. */
  349. static void mcp23017_init(gpio_exp_t* self) {
  350. /*
  351. 0111 x10x = same bank, mirrot single int, no sequentµial, open drain, active low
  352. not sure about this funny change of mapping of the control register itself, really?
  353. */
  354. i2c_write_byte(self->phy.port, self->phy.addr, 0x05, 0x74);
  355. i2c_write_byte(self->phy.port, self->phy.addr, 0x0a, 0x74);
  356. // no interrupt on comparison or on change
  357. i2c_write_word(self->phy.port, self->phy.addr, 0x04, 0x00);
  358. i2c_write_word(self->phy.port, self->phy.addr, 0x08, 0x00);
  359. }
  360. static void mcp23017_set_direction(gpio_exp_t* self) {
  361. // default to input and set real input to generate interrupt
  362. i2c_write_word(self->phy.port, self->phy.addr, 0x00, ~self->w_mask);
  363. i2c_write_word(self->phy.port, self->phy.addr, 0x04, self->r_mask);
  364. }
  365. static void mcp23017_set_pull_mode(gpio_exp_t* self) {
  366. i2c_write_word(self->phy.port, self->phy.addr, 0x0c, self->pullup);
  367. }
  368. static int mcp23017_read(gpio_exp_t* self) {
  369. // read the pin value, not the stored one @interrupt
  370. return i2c_read(self->phy.port, self->phy.addr, 0x12, true);
  371. }
  372. static void mcp23017_write(gpio_exp_t* self) {
  373. i2c_write_word(self->phy.port, self->phy.addr, 0x12, self->shadow);
  374. }
  375. /****************************************************************************************
  376. * INTR low-level handler
  377. */
  378. static void IRAM_ATTR intr_isr_handler(void* arg) {
  379. BaseType_t woken = pdFALSE;
  380. xTaskNotifyFromISR(service_task, GPIO_EXP_INTR, eSetValueWithOverwrite, &woken);
  381. if (woken) portYIELD_FROM_ISR();
  382. ESP_EARLY_LOGD(TAG, "INTR for expander base", gpio_exp_get_base(arg));
  383. }
  384. /****************************************************************************************
  385. * INTR debounce handler
  386. */
  387. static void debounce_handler( TimerHandle_t xTimer ) {
  388. struct gpio_exp_isr_s *isr = (struct gpio_exp_isr_s*) pvTimerGetTimerID (xTimer);
  389. isr->handler(isr->arg);
  390. }
  391. /****************************************************************************************
  392. * Service task
  393. */
  394. void service_handler(void *arg) {
  395. while (1) {
  396. queue_request_t request;
  397. uint32_t notif = ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
  398. // we have been notified of an interrupt
  399. if (notif == GPIO_EXP_INTR) {
  400. /* If we want a smarter bitmap of expanders with a pending interrupt
  401. we'll have to disable interrupts while clearing that bitmap. For
  402. now, a loop will do */
  403. for (int i = 0; i < n_expanders; i++) {
  404. gpio_exp_t *expander = expanders + i;
  405. xSemaphoreTake(expander->mutex, pdMS_TO_TICKS(50));
  406. // read GPIOs and clear all pending status
  407. uint32_t value = expander->model->read(expander);
  408. uint32_t pending = expander->pending | ((expander->shadow ^ value) & expander->r_mask);
  409. expander->shadow = value;
  410. expander->pending = 0;
  411. expander->age = xTaskGetTickCount();
  412. xSemaphoreGive(expander->mutex);
  413. ESP_LOGD(TAG, "Handling GPIO %d reads 0x%04x and has 0x%04x pending", expander->first, expander->shadow, pending);
  414. for (int gpio = 31, clz; pending; pending <<= (clz + 1)) {
  415. clz = __builtin_clz(pending);
  416. gpio -= clz;
  417. if (expander->isr[gpio].timer) xTimerReset(expander->isr[gpio].timer, 1); // todo 0
  418. else if (expander->isr[gpio].handler) expander->isr[gpio].handler(expander->isr[gpio].arg);
  419. }
  420. }
  421. }
  422. // check if we have some other pending requests
  423. if (xQueueReceive(message_queue, &request, 0) == pdTRUE) {
  424. esp_err_t err = gpio_exp_set_level(request.gpio, request.level, true, request.expander);
  425. if (err != ESP_OK) ESP_LOGW(TAG, "Can't execute async GPIO %d write request (%d)", request.gpio, err);
  426. }
  427. }
  428. }
  429. /****************************************************************************************
  430. *
  431. */
  432. static esp_err_t i2c_write_byte(uint8_t i2c_port, uint8_t i2c_addr, uint8_t reg, uint8_t val) {
  433. i2c_cmd_handle_t cmd = i2c_cmd_link_create();
  434. i2c_master_start(cmd);
  435. i2c_master_write_byte(cmd, (i2c_addr << 1) | I2C_MASTER_WRITE, I2C_MASTER_NACK);
  436. i2c_master_write_byte(cmd, reg, I2C_MASTER_NACK);
  437. i2c_master_write_byte(cmd, val, I2C_MASTER_NACK);
  438. i2c_master_stop(cmd);
  439. esp_err_t ret = i2c_master_cmd_begin(i2c_port, cmd, 100 / portTICK_RATE_MS);
  440. i2c_cmd_link_delete(cmd);
  441. if (ret != ESP_OK) {
  442. ESP_LOGW(TAG, "I2C write failed");
  443. }
  444. return ret;
  445. }
  446. /****************************************************************************************
  447. * I2C read 8 or 16 bits word
  448. */
  449. static uint16_t i2c_read(uint8_t i2c_port, uint8_t i2c_addr, uint8_t reg, bool word) {
  450. uint8_t data[2];
  451. i2c_cmd_handle_t cmd = i2c_cmd_link_create();
  452. i2c_master_start(cmd);
  453. i2c_master_write_byte(cmd, (i2c_addr << 1) | I2C_MASTER_WRITE, I2C_MASTER_NACK);
  454. // when using a register, write it's value then the device address again
  455. if (reg != 0xff) {
  456. i2c_master_write_byte(cmd, reg, I2C_MASTER_NACK);
  457. i2c_master_start(cmd);
  458. i2c_master_write_byte(cmd, (i2c_addr << 1) | I2C_MASTER_READ, I2C_MASTER_NACK);
  459. }
  460. if (word) {
  461. i2c_master_read_byte(cmd, data, I2C_MASTER_ACK);
  462. i2c_master_read_byte(cmd, data + 1, I2C_MASTER_NACK);
  463. } else {
  464. i2c_master_read_byte(cmd, data, I2C_MASTER_NACK);
  465. }
  466. i2c_master_stop(cmd);
  467. esp_err_t ret = i2c_master_cmd_begin(i2c_port, cmd, 100 / portTICK_RATE_MS);
  468. i2c_cmd_link_delete(cmd);
  469. if (ret != ESP_OK) {
  470. ESP_LOGW(TAG, "I2C read failed");
  471. }
  472. return *(uint16_t*) data;
  473. }
  474. /****************************************************************************************
  475. * I2C write 16 bits word
  476. */
  477. static esp_err_t i2c_write_word(uint8_t i2c_port, uint8_t i2c_addr, uint8_t reg, uint16_t data) {
  478. i2c_cmd_handle_t cmd = i2c_cmd_link_create();
  479. i2c_master_start(cmd);
  480. i2c_master_write_byte(cmd, (i2c_addr << 1) | I2C_MASTER_WRITE, I2C_MASTER_NACK);
  481. if (reg != 0xff) i2c_master_write_byte(cmd, reg, I2C_MASTER_NACK);
  482. i2c_master_write(cmd, (uint8_t*) &data, 2, I2C_MASTER_NACK);
  483. i2c_master_stop(cmd);
  484. esp_err_t ret = i2c_master_cmd_begin(i2c_port, cmd, 100 / portTICK_RATE_MS);
  485. i2c_cmd_link_delete(cmd);
  486. if (ret != ESP_OK) {
  487. ESP_LOGW(TAG, "I2C write failed");
  488. }
  489. return ret;
  490. }