ESPHome  2024.10.2
mcp23x17_base.cpp
Go to the documentation of this file.
1 #include "mcp23x17_base.h"
2 #include "esphome/core/log.h"
3 
4 namespace esphome {
5 namespace mcp23x17_base {
6 
7 static const char *const TAG = "mcp23x17_base";
8 
9 bool MCP23X17Base::digital_read(uint8_t pin) {
10  uint8_t bit = pin % 8;
11  uint8_t reg_addr = pin < 8 ? mcp23x17_base::MCP23X17_GPIOA : mcp23x17_base::MCP23X17_GPIOB;
12  uint8_t value = 0;
13  this->read_reg(reg_addr, &value);
14  return value & (1 << bit);
15 }
16 
17 void MCP23X17Base::digital_write(uint8_t pin, bool value) {
18  uint8_t reg_addr = pin < 8 ? mcp23x17_base::MCP23X17_OLATA : mcp23x17_base::MCP23X17_OLATB;
19  this->update_reg(pin, value, reg_addr);
20 }
21 
25  if (flags == gpio::FLAG_INPUT) {
26  this->update_reg(pin, true, iodir);
27  this->update_reg(pin, false, gppu);
28  } else if (flags == (gpio::FLAG_INPUT | gpio::FLAG_PULLUP)) {
29  this->update_reg(pin, true, iodir);
30  this->update_reg(pin, true, gppu);
31  } else if (flags == gpio::FLAG_OUTPUT) {
32  this->update_reg(pin, false, iodir);
33  }
34 }
35 
40 
41  switch (interrupt_mode) {
43  this->update_reg(pin, true, gpinten);
44  this->update_reg(pin, false, intcon);
45  break;
47  this->update_reg(pin, true, gpinten);
48  this->update_reg(pin, true, intcon);
49  this->update_reg(pin, true, defval);
50  break;
52  this->update_reg(pin, true, gpinten);
53  this->update_reg(pin, true, intcon);
54  this->update_reg(pin, false, defval);
55  break;
57  this->update_reg(pin, false, gpinten);
58  break;
59  }
60 }
61 
62 void MCP23X17Base::update_reg(uint8_t pin, bool pin_value, uint8_t reg_addr) {
63  uint8_t bit = pin % 8;
64  uint8_t reg_value = 0;
65  if (reg_addr == mcp23x17_base::MCP23X17_OLATA) {
66  reg_value = this->olat_a_;
67  } else if (reg_addr == mcp23x17_base::MCP23X17_OLATB) {
68  reg_value = this->olat_b_;
69  } else {
70  this->read_reg(reg_addr, &reg_value);
71  }
72 
73  if (pin_value) {
74  reg_value |= 1 << bit;
75  } else {
76  reg_value &= ~(1 << bit);
77  }
78 
79  this->write_reg(reg_addr, reg_value);
80 
81  if (reg_addr == mcp23x17_base::MCP23X17_OLATA) {
82  this->olat_a_ = reg_value;
83  } else if (reg_addr == mcp23x17_base::MCP23X17_OLATB) {
84  this->olat_b_ = reg_value;
85  }
86 }
87 
88 } // namespace mcp23x17_base
89 } // namespace esphome
void digital_write(uint8_t pin, bool value) override
void update_reg(uint8_t pin, bool pin_value, uint8_t reg_a) override
virtual bool write_reg(uint8_t reg, uint8_t value)
bool digital_read(uint8_t pin) override
const uint32_t flags
Definition: stm32flash.h:85
virtual bool read_reg(uint8_t reg, uint8_t *value)
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
void pin_interrupt_mode(uint8_t pin, mcp23xxx_base::MCP23XXXInterruptMode interrupt_mode) override
void pin_mode(uint8_t pin, gpio::Flags flags) override