I2C address auto-detection example added.

Rene 'Renne' Bartsch 2018-09-29 01:57:13 +02:00
parent 32bfffb605
commit f1202c6d04
1 changed files with 49 additions and 0 deletions

@ -118,6 +118,55 @@ When writing your function responsible for detecting an externally connected I2C
Unless your driver is specifically going to use the entire array of addresses provisioned by the manufacturer please consider using a #define USE_MYCHIPNAME_ADDR in the user_config.h so that the user may specify the address on which to expect the device. This is of course only applicable to drivers that are not enabled by default in any of the pre-built binaries.
**I2C address auto-detection example**
```
#define MPR121_I2C_ADDR_1ST 0x5A /** 1st I2C address of sensor model **/
#define MPR121_I2C_ADDR_NUM 4 /** Number of sensors/I2C addresses **/
#define MPR121_I2C_ID_REG 0x5D /** Sensor model specific ID register **/
#define MPR121_I2C_ID_VAL 0x24 /** Sensor model specific ID register value **/
/* Sensor data struct type declaration/default definition */
typedef struct {
bool connected = false; /** Status if sensor is connected at I2C address */
bool running = false; /** Running state of sensor */
.
.
.
} mpr121;
// Declare array of sensor data structs
mpr121 mpr121[MPR121_I2C_ADDR_NUM];
// Sensor specific init function
void mpr121_init() {
// Loop through I2C addresses
for (uint8_t i = 0; i < MPR121_I2C_ADDR_NUM); i++) {
// Check if sensor is connected on I2C address
mpr121[i].connected = (MPR121_I2C_ID_VAL == I2cRead8(MPR121_I2C_ADDR_1ST + i, MPR121_I2C_ID_REG);
if(mpr121[i].connected) {
// Log sensor found
snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_I2C "MPR121-%d " D_FOUND_AT " 0x%X"), i, MPR121_I2C_ADDR_1ST + i);
AddLog(LOG_LEVEL_INFO);
// Initialize sensor
.
.
.
// Set running to true
mpr121[i].running = true;
}
}
if(!(mpr121[0].connected || mpr121[1].connected || mpr121[2].connected || mpr121[3].connected)){
snprintf_P(log_data, sizeof(log_data), PSTR(D_LOG_I2C "MPR121: No sensors found"));
AddLog(LOG_LEVEL_INFO);
}
}
```
**Four advanced methods to use FUNC_EVERY_SECOND (Food for thought) :**
* If a sensor needs an action which takes a long time, like more than 100mS, the action will be started here for a future follow-up. Using the uptime variable for testing like (uptime &1) will happen every 2 seconds. An example is the DS18B20 driver where readings (conversions they call it) can take up to 800mS from the initial request.
* If a sensor needed the previous action it is now time to gather the information and store it in a safe place to be used by FUNC_JSON_APPEND and/or FUNC_WEB_APPEND. Using the else function of the previous test (uptime &1) will happen every 2 seconds too but just 1 second later than the previous action.