ESPHome  2024.11.0
mcp23x08_base.cpp
Go to the documentation of this file.
1 #include "mcp23x08_base.h"
2 #include "esphome/core/log.h"
3 
4 namespace esphome {
5 namespace mcp23x08_base {
6 
7 static const char *const TAG = "mcp23x08_base";
8 
9 bool MCP23X08Base::digital_read(uint8_t pin) {
10  uint8_t bit = pin % 8;
11  uint8_t reg_addr = mcp23x08_base::MCP23X08_GPIO;
12  uint8_t value = 0;
13  this->read_reg(reg_addr, &value);
14  return value & (1 << bit);
15 }
16 
17 void MCP23X08Base::digital_write(uint8_t pin, bool value) {
18  uint8_t reg_addr = mcp23x08_base::MCP23X08_OLAT;
19  this->update_reg(pin, value, reg_addr);
20 }
21 
23  uint8_t iodir = mcp23x08_base::MCP23X08_IODIR;
24  uint8_t gppu = mcp23x08_base::MCP23X08_GPPU;
25  if (flags == gpio::FLAG_INPUT) {
26  this->update_reg(pin, true, iodir);
27  } else if (flags == (gpio::FLAG_INPUT | gpio::FLAG_PULLUP)) {
28  this->update_reg(pin, true, iodir);
29  this->update_reg(pin, true, gppu);
30  } else if (flags == gpio::FLAG_OUTPUT) {
31  this->update_reg(pin, false, iodir);
32  }
33 }
34 
36  uint8_t gpinten = mcp23x08_base::MCP23X08_GPINTEN;
37  uint8_t intcon = mcp23x08_base::MCP23X08_INTCON;
38  uint8_t defval = mcp23x08_base::MCP23X08_DEFVAL;
39 
40  switch (interrupt_mode) {
42  this->update_reg(pin, true, gpinten);
43  this->update_reg(pin, false, intcon);
44  break;
46  this->update_reg(pin, true, gpinten);
47  this->update_reg(pin, true, intcon);
48  this->update_reg(pin, true, defval);
49  break;
51  this->update_reg(pin, true, gpinten);
52  this->update_reg(pin, true, intcon);
53  this->update_reg(pin, false, defval);
54  break;
56  this->update_reg(pin, false, gpinten);
57  break;
58  }
59 }
60 
61 void MCP23X08Base::update_reg(uint8_t pin, bool pin_value, uint8_t reg_addr) {
62  uint8_t bit = pin % 8;
63  uint8_t reg_value = 0;
64  if (reg_addr == mcp23x08_base::MCP23X08_OLAT) {
65  reg_value = this->olat_;
66  } else {
67  this->read_reg(reg_addr, &reg_value);
68  }
69 
70  if (pin_value) {
71  reg_value |= 1 << bit;
72  } else {
73  reg_value &= ~(1 << bit);
74  }
75 
76  this->write_reg(reg_addr, reg_value);
77 
78  if (reg_addr == mcp23x08_base::MCP23X08_OLAT) {
79  this->olat_ = reg_value;
80  }
81 }
82 
83 } // namespace mcp23x08_base
84 } // namespace esphome
void pin_mode(uint8_t pin, gpio::Flags flags) 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
void digital_write(uint8_t pin, bool value) override
virtual bool read_reg(uint8_t reg, uint8_t *value)
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
void update_reg(uint8_t pin, bool pin_value, uint8_t reg_a) override
void pin_interrupt_mode(uint8_t pin, mcp23xxx_base::MCP23XXXInterruptMode interrupt_mode) override