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