Code: Select all
// Configure SPI bus
spi_bus.flags = SPICOMMON_BUSFLAG_MASTER;
spi_bus.sclk_io_num = SPI_PIN_NUM_CLK;
spi_bus.mosi_io_num = SPI_PIN_NUM_MOSI;
spi_bus.miso_io_num = SPI_PIN_NUM_MISO;
spi_bus.quadwp_io_num = -1;
spi_bus.quadhd_io_num = -1;
spi_bus.max_transfer_sz = 32;
esp_err_t ret = spi_bus_initialize(HSPI_HOST, &spi_bus, 0);
ESP_ERROR_CHECK(ret);
// Configure SPI device for MCP23S08
spi_mcp23S08.address_bits = 0;
spi_mcp23S08.command_bits = 0;
spi_mcp23S08.dummy_bits = 0;
spi_mcp23S08.mode = 0;
spi_mcp23S08.duty_cycle_pos = 0;
spi_mcp23S08.cs_ena_posttrans = 0;
spi_mcp23S08.cs_ena_pretrans = 0;
spi_mcp23S08.clock_speed_hz = SPI_PORT_EXP_SPEED_MHZ * 1000 * 1000;
spi_mcp23S08.spics_io_num = SPI_PIN_NUM_CS_MCP23S08;
spi_mcp23S08.flags = 0;
spi_mcp23S08.queue_size = 1;
spi_mcp23S08.pre_cb = NULL;
spi_mcp23S08.post_cb = NULL;
ret = spi_bus_add_device(HSPI_HOST, &spi_mcp23S08, &spi_mcp23S08_h);
ESP_ERROR_CHECK(ret);
Code: Select all
void writePortExpander(spi_device_handle_t dev, uint8_t cmd, uint8_t data)
{
spi_transaction_t trans;
memset(&trans, 0, sizeof(spi_transaction_t));
trans.flags = SPI_TRANS_USE_TXDATA;
trans.length = 3 * 8; // 3 bytes
trans.tx_data[0] = MCP23S_CHIP_ADDRESS | MCP23S_WRITE;
trans.tx_data[1] = cmd;
trans.tx_data[2] = data;
esp_err_t ret = spi_device_transmit(dev, &trans);
ESP_ERROR_CHECK(ret);
}
uint8_t readPortExpander(spi_device_handle_t dev, uint8_t reg)
{
spi_transaction_t trans;
memset(&trans, 0, sizeof(spi_transaction_t));
trans.flags = SPI_TRANS_USE_TXDATA | SPI_TRANS_USE_RXDATA;
trans.length = 3 * 8; // 2 bytes
trans.rxlength = 0;
trans.tx_data[0] = MCP23S_CHIP_ADDRESS | MCP23S_READ;
trans.tx_data[1] = reg;
trans.tx_data[2] = 0;
esp_err_t ret = spi_device_transmit(dev, &trans);
ESP_ERROR_CHECK(ret);
return trans.rx_data[2];
}
Code: Select all
// Configure INT as open drain
writePortExpander(MCP23S08, MCP23S08_IOCON, MCP23S08_ODR);
// Generate interrupt on pin change
writePortExpander(MCP23S08, MCP23S08_INTCON, 0);
// Enable interrupt-on-change
writePortExpander(MCP23S08, MCP23S08_GPINTEN, 0xff);
// Dummy read to clear INT
readPortExpander(MCP23S08, MCP23S08_INTCAP);