Refactor main.

Only create sensors once, then loop over them with do_si7021() and
do_sht31().
This commit is contained in:
Pim van Pelt
2018-04-02 21:46:54 +02:00
parent 37838f0062
commit 97310e3e03

View File

@ -39,42 +39,34 @@ bool i2c_dumpregs(struct mgos_i2c *i2c, uint8_t i2caddr) {
return true;
}
bool sht31(struct mgos_i2c *i2c, uint8_t i2caddr) {
struct mgos_sht31 *sht31;
bool do_sht31(struct mgos_sht31 *sensor) {
float temp, humid;
if (!(sht31 = mgos_sht31_create(i2c, i2caddr))) {
LOG(LL_ERROR, ("Cannot create SHT31 device"));
return false;
}
if (!sensor) return false;
temp=mgos_sht31_getTemperature(sht31);
humid=mgos_sht31_getHumidity(sht31);
LOG(LL_INFO, ("SHT31: temperature=%.2fC humidity=%.1f%%", temp, humid));
temp=mgos_sht31_getTemperature(sensor);
humid=mgos_sht31_getHumidity(sensor);
LOG(LL_INFO, ("temperature=%.2fC humidity=%.1f%%", temp, humid));
mgos_sht31_destroy(&sht31);
return true;
}
bool si7021(struct mgos_i2c *i2c, uint8_t i2caddr) {
struct mgos_si7021 *si7021;
bool do_si7021(struct mgos_si7021 *sensor) {
float temp, humid;
if (!(si7021 = mgos_si7021_create(i2c, i2caddr))) {
LOG(LL_ERROR, ("Cannot create SI7021 device"));
return false;
}
if (!sensor) return false;
temp=mgos_si7021_getTemperature(si7021);
humid=mgos_si7021_getHumidity(si7021);
LOG(LL_INFO, ("SI7021: temperature=%.2fC humidity=%.1f%%", temp, humid));
temp=mgos_si7021_getTemperature(sensor);
humid=mgos_si7021_getHumidity(sensor);
LOG(LL_INFO, ("temperature=%.2fC humidity=%.1f%%", temp, humid));
mgos_si7021_destroy(&si7021);
return true;
}
int main() {
struct mgos_i2c *i2c;
struct mgos_si7021 *si7021;
struct mgos_sht31 *sht31;
if (!mgos_i2c_open(I2CBUSNR)) {
LOG(LL_ERROR, ("Cannot open I2C bus %u", I2CBUSNR));
@ -86,14 +78,23 @@ int main() {
}
i2c_scanner(i2c);
// i2c_dumpregs(i2c, 0x76);
for (;;) {
sht31(i2c, 0x44);
// i2c_dumpregs(i2c, 0x40);
si7021(i2c, 0x40);
if (!(sht31 = mgos_sht31_create(i2c, 0x44))) {
LOG(LL_ERROR, ("Cannot create SHT31 device"));
}
if (!(si7021 = mgos_si7021_create(i2c, 0x40))) {
LOG(LL_ERROR, ("Cannot create SI7021 device"));
}
for (;;) {
do_sht31(sht31);
do_si7021(si7021);
sleep(1);
}
mgos_sht31_destroy(&sht31);
mgos_si7021_destroy(&si7021);
return 0;
}