MCP23017 examples

Reading

 1#include <chrono>
 2#include <cstdint>
 3#include <iostream>
 4#include <thread>
 5
 6#include "i2c_bus/i2c.hh"
 7#include "mcp23017/mcp23017.hh"
 8
 9int main([[maybe_unused]] int argc, [[maybe_unused]] char* argv[]) {
10    iplo::I2C i2c("/dev/i2c-1");
11    iplo::MCP23017 mcp(i2c, 0x20);
12    if (!mcp.begin()) {
13        std::cout << "Error initializing communication with GPIO expander\n";
14        return -1;
15    }
16
17    for (int pin = 0; pin < iplo::MCP23017::PINS; ++pin) {
18        mcp.pinMode(pin, iplo::PinMode::INPUT);
19        mcp.setPullUp(pin, true);
20        mcp.setPolarity(pin, true);  // reversed polarity because of pull up
21    }
22
23    for (int i = 0; i < 10; ++i) {
24        const auto value = mcp.digitalRead16();
25        for (std::uint8_t pin = 0; pin < iplo::MCP23017::PINS; ++pin) {
26            const auto pinValue = iplo::MCP23017::extractPinValue(value, pin);
27            std::cout << "Value for pin " << +pin << ": " << +pinValue << "\n";
28        }
29
30        std::cout << "==================\n\n";
31        std::this_thread::sleep_for(std::chrono::seconds(1));
32    }
33
34    return 0;
35}

Writing

 1#include <chrono>
 2#include <thread>
 3
 4#include "i2c_bus/i2c.hh"
 5#include "mcp23017/mcp23017.hh"
 6
 7int main([[maybe_unused]] int argc, [[maybe_unused]] char* argv[]) {
 8    iplo::I2C i2c("/dev/i2c-1");
 9    iplo::MCP23017 mcp(i2c, 0x20);
10    if (!mcp.begin()) {
11        return -1;
12    }
13
14    for (int pin = 0; pin < iplo::MCP23017::PINS; ++pin) {
15        mcp.pinMode(pin, iplo::PinMode::OUTPUT);
16        std::this_thread::sleep_for(std::chrono::milliseconds(200));
17    }
18
19    for (int pin = 0; pin < iplo::MCP23017::PINS; ++pin) {
20        mcp.digitalWrite(pin, 1 - pin % 2);
21        std::this_thread::sleep_for(std::chrono::milliseconds(200));
22    }
23
24    return 0;
25}