From 694010c57bd25c63de31fafd42e0d9864dec7148 Mon Sep 17 00:00:00 2001 From: ladyada Date: Thu, 7 Mar 2019 14:23:42 -0500 Subject: [PATCH] create an i2c device with an address and be able to detect it --- Adafruit_I2CDevice.cpp | 33 +++++++++++++++++++ Adafruit_I2CDevice.h | 15 +++++++++ .../i2c_address_detect/i2c_address_detect.ino | 21 ++++++++++++ 3 files changed, 69 insertions(+) create mode 100644 examples/i2c_address_detect/i2c_address_detect.ino diff --git a/Adafruit_I2CDevice.cpp b/Adafruit_I2CDevice.cpp index e69de29..e0e6afc 100644 --- a/Adafruit_I2CDevice.cpp +++ b/Adafruit_I2CDevice.cpp @@ -0,0 +1,33 @@ +#include +#include + +Adafruit_I2CDevice::Adafruit_I2CDevice(uint8_t addr, TwoWire *theWire) { + _addr = addr; + _wire = theWire; + _begun = false; +} + +bool Adafruit_I2CDevice::begin(void) { + _wire->begin(); + _begun = true; + + return detected(); +} + +bool Adafruit_I2CDevice::detected(void) { + // Init I2C if not done yet + if (!_begun && !begin()) { + return false; + } + + // A basic scanner, see if it ACK's + _wire->beginTransmission(_addr); + if (_wire->endTransmission () == 0) { + return true; + } + return false; +} + +uint8_t Adafruit_I2CDevice::address(void) { + return _addr; +} diff --git a/Adafruit_I2CDevice.h b/Adafruit_I2CDevice.h index e69de29..d353329 100644 --- a/Adafruit_I2CDevice.h +++ b/Adafruit_I2CDevice.h @@ -0,0 +1,15 @@ +#include + +class Adafruit_I2CDevice { + +private: + uint8_t _addr; + TwoWire *_wire; + bool _begun; + +public: + Adafruit_I2CDevice(uint8_t addr, TwoWire *theWire=&Wire); + uint8_t address(void); + bool begin(void); + bool detected(void); +}; diff --git a/examples/i2c_address_detect/i2c_address_detect.ino b/examples/i2c_address_detect/i2c_address_detect.ino new file mode 100644 index 0000000..b150525 --- /dev/null +++ b/examples/i2c_address_detect/i2c_address_detect.ino @@ -0,0 +1,21 @@ +#include + +Adafruit_I2CDevice i2c_dev = Adafruit_I2CDevice(0x10); + +void setup() { + while (!Serial) { delay(10); } + Serial.begin(115200); + Serial.println("I2C address detection test"); + + if (!i2c_dev.begin()) { + Serial.print("Did not find device at 0x"); + Serial.println(i2c_dev.address(), HEX); + while (1); + } + Serial.print("Device found on address 0x"); + Serial.println(i2c_dev.address(), HEX); +} + +void loop() { + +}