ESPHome 2026.5.0-dev
Loading...
Searching...
No Matches
mcp23s17.cpp
Go to the documentation of this file.
1#include "mcp23s17.h"
2#include "esphome/core/log.h"
3
4namespace esphome {
5namespace mcp23s17 {
6
7static const char *const TAG = "mcp23s17";
8
9// IOCON register bits
10static constexpr uint8_t IOCON_SEQOP = 0x20; // Sequential operation mode
11static constexpr uint8_t IOCON_MIRROR = 0x40; // Mirror INTA/INTB pins
12static constexpr uint8_t IOCON_HAEN = 0x08; // Hardware address enable
13static constexpr uint8_t IOCON_ODR = 0x04; // Open-drain output for INT pin
14
15void MCP23S17::set_device_address(uint8_t device_addr) {
16 if (device_addr != 0) {
17 this->device_opcode_ |= ((device_addr & 0b111) << 1);
18 }
19}
20
22 this->spi_setup();
23
24 // Enable HAEN (broadcast to addresses 0 and 4 since HAEN isn't active yet)
25 this->enable();
26 this->transfer_byte(0b01000000);
28 this->transfer_byte(IOCON_SEQOP | IOCON_HAEN);
29 this->disable();
30
31 this->enable();
32 this->transfer_byte(0b01001000);
34 this->transfer_byte(IOCON_SEQOP | IOCON_HAEN);
35 this->disable();
36
37 // Read current output register state
40
41 uint8_t iocon_flags = IOCON_SEQOP | IOCON_HAEN;
42 if (this->open_drain_ints_) {
43 iocon_flags |= IOCON_ODR;
44 }
45 if (this->interrupt_pin_ != nullptr) {
46 // Mirror INTA/INTB so either pin fires for changes on any port
47 iocon_flags |= IOCON_MIRROR;
48 }
49 if (this->open_drain_ints_ || this->interrupt_pin_ != nullptr) {
50 this->write_reg(mcp23x17_base::MCP23X17_IOCONA, iocon_flags);
51 this->write_reg(mcp23x17_base::MCP23X17_IOCONB, iocon_flags);
52 }
53
55}
56
58 ESP_LOGCONFIG(TAG, "MCP23S17:");
59 LOG_PIN(" CS Pin: ", this->cs_);
60 LOG_PIN(" Interrupt Pin: ", this->interrupt_pin_);
61}
62
63bool MCP23S17::read_reg(uint8_t reg, uint8_t *value) {
64 this->enable();
65 this->transfer_byte(this->device_opcode_ | 1);
66 this->transfer_byte(reg);
67 *value = this->transfer_byte(0xFF);
68 this->disable();
69 return true;
70}
71
72bool MCP23S17::write_reg(uint8_t reg, uint8_t value) {
73 this->enable();
74 this->transfer_byte(this->device_opcode_);
75 this->transfer_byte(reg);
76 this->transfer_byte(value);
77
78 this->disable();
79 return true;
80}
81
82} // namespace mcp23s17
83} // namespace esphome
void dump_config() override
Definition mcp23s17.cpp:57
void set_device_address(uint8_t device_addr)
Definition mcp23s17.cpp:15
bool read_reg(uint8_t reg, uint8_t *value) override
Definition mcp23s17.cpp:63
bool write_reg(uint8_t reg, uint8_t value) override
Definition mcp23s17.cpp:72
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7