ESPHome  2022.11.3
i2c_bus.h
Go to the documentation of this file.
1 #pragma once
2 #include <cstdint>
3 #include <cstddef>
4 #include <utility>
5 #include <vector>
6 
7 namespace esphome {
8 namespace i2c {
9 
10 enum ErrorCode {
11  ERROR_OK = 0,
18  ERROR_CRC = 7,
19 };
20 
21 struct ReadBuffer {
22  uint8_t *data;
23  size_t len;
24 };
25 struct WriteBuffer {
26  const uint8_t *data;
27  size_t len;
28 };
29 
30 class I2CBus {
31  public:
32  virtual ErrorCode read(uint8_t address, uint8_t *buffer, size_t len) {
33  ReadBuffer buf;
34  buf.data = buffer;
35  buf.len = len;
36  return readv(address, &buf, 1);
37  }
38  virtual ErrorCode readv(uint8_t address, ReadBuffer *buffers, size_t cnt) = 0;
39  virtual ErrorCode write(uint8_t address, const uint8_t *buffer, size_t len) {
40  return write(address, buffer, len, true);
41  }
42  virtual ErrorCode write(uint8_t address, const uint8_t *buffer, size_t len, bool stop) {
43  WriteBuffer buf;
44  buf.data = buffer;
45  buf.len = len;
46  return writev(address, &buf, 1, stop);
47  }
48  virtual ErrorCode writev(uint8_t address, WriteBuffer *buffers, size_t cnt) {
49  return writev(address, buffers, cnt, true);
50  }
51  virtual ErrorCode writev(uint8_t address, WriteBuffer *buffers, size_t cnt, bool stop) = 0;
52 
53  protected:
54  void i2c_scan_() {
55  for (uint8_t address = 8; address < 120; address++) {
56  auto err = writev(address, nullptr, 0);
57  if (err == ERROR_OK) {
58  scan_results_.emplace_back(address, true);
59  } else if (err == ERROR_UNKNOWN) {
60  scan_results_.emplace_back(address, false);
61  }
62  }
63  }
64  std::vector<std::pair<uint8_t, bool>> scan_results_;
65  bool scan_{false};
66 };
67 
68 } // namespace i2c
69 } // namespace esphome
std::vector< std::pair< uint8_t, bool > > scan_results_
Definition: i2c_bus.h:64
virtual ErrorCode write(uint8_t address, const uint8_t *buffer, size_t len, bool stop)
Definition: i2c_bus.h:42
virtual ErrorCode writev(uint8_t address, WriteBuffer *buffers, size_t cnt)
Definition: i2c_bus.h:48
virtual ErrorCode read(uint8_t address, uint8_t *buffer, size_t len)
Definition: i2c_bus.h:32
virtual ErrorCode write(uint8_t address, const uint8_t *buffer, size_t len)
Definition: i2c_bus.h:39
const uint8_t * data
Definition: i2c_bus.h:26
Definition: a4988.cpp:4