From 3e5e8480f3f2f0af56731471cc967404efe0c921 Mon Sep 17 00:00:00 2001 From: Steven Date: Wed, 6 Oct 2021 00:52:14 -0400 Subject: andy cleanup --- CCS811.cpp | 154 ++++++++++++++++++++++++++++++++++++ CCS811.h | 224 ++++++++++++++++++++++++++++++++++++++++++++++++++++ Makefile | 60 ++++++++++++++ mush.ino | 126 +++++++++++++++++++++++++++++ ota.h | 98 +++++++++++++++++++++++ src/main/CCS811.cpp | 154 ------------------------------------ src/main/CCS811.h | 224 ---------------------------------------------------- src/main/Makefile | 58 -------------- src/main/main.ino | 126 ----------------------------- src/main/ota.h | 98 ----------------------- src/main/wifiinfo.h | 6 -- wifiinfo.h | 6 ++ 12 files changed, 668 insertions(+), 666 deletions(-) create mode 100644 CCS811.cpp create mode 100644 CCS811.h create mode 100644 Makefile create mode 100644 mush.ino create mode 100644 ota.h delete mode 100644 src/main/CCS811.cpp delete mode 100644 src/main/CCS811.h delete mode 100644 src/main/Makefile delete mode 100644 src/main/main.ino delete mode 100644 src/main/ota.h delete mode 100644 src/main/wifiinfo.h create mode 100644 wifiinfo.h diff --git a/CCS811.cpp b/CCS811.cpp new file mode 100644 index 0000000..05b71c0 --- /dev/null +++ b/CCS811.cpp @@ -0,0 +1,154 @@ +#include "CCS811.h" + +int CCS811::begin(void) +{ + uint8_t id=0; + Wire.begin(); + softReset(); + delay(100); + if(readReg(CCS811_REG_HW_ID,&id,1) != 1){DBG(""); + DBG("bus data access error");DBG(""); + return ERR_DATA_BUS;DBG(""); + } + + DBG("real sensor id=");DBG(id); + if(id != CCS811_HW_ID){DBG(""); + delay(1); + return ERR_IC_VERSION; + } + writeReg(CCS811_BOOTLOADER_APP_START, NULL, 0); + setMeasurementMode(0,0,eMode4); + setInTempHum(25, 50); + return ERR_OK; +} + +void CCS811::softReset(){ + uint8_t value[4] = {0x11, 0xE5, 0x72, 0x8A}; + writeReg(CCS811_REG_SW_RESET, value, 4); +} + +bool CCS811::checkDataReady() +{ + int8_t status[1] = {0}; + readReg(CCS811_REG_STATUS, status, 1); + DBG(status[0],HEX); + if(!((status[0] >> 3) & 0x01)) + return false; + else + return true; +} + +uint16_t CCS811::readBaseLine(){ + uint8_t buffer[2]; + readReg(CCS811_REG_BASELINE, buffer, 2); + return buffer[0]<<8|buffer[1]; +} + +void CCS811::writeBaseLine(uint16_t baseLine){ + uint8_t buffer[2]; + + buffer[0] = baseLine>>8; + buffer[1] = baseLine; + writeReg(CCS811_REG_BASELINE, buffer, 2); +} + +void CCS811::setMeasurementMode(uint8_t thresh, uint8_t interrupt, eDRIVE_MODE_t mode){ + uint8_t measurement[1] = {0}; + measurement[0] = (thresh << 2) | (interrupt << 3) | (mode << 4); + writeReg(CCS811_REG_MEAS_MODE, measurement, 1); +} + +void CCS811::setMeasCycle(eCycle_t cycle){ + uint8_t measurement[1] = {0}; + measurement[0] = cycle << 4; + writeReg(CCS811_REG_MEAS_MODE, measurement, 1); +} + +uint8_t CCS811::getMeasurementMode(){ + uint8_t meas[1] = {0}; + readReg(CCS811_REG_MEAS_MODE, meas, 1); + return meas[0]; +} + +void CCS811::setThresholds(uint16_t lowToMed, uint16_t medToHigh) +{ + uint8_t buffer[] = {(uint8_t)((lowToMed >> 8) & 0xF), + (uint8_t)(lowToMed & 0xF), + (uint8_t)((medToHigh >> 8) & 0xF), + (uint8_t)(medToHigh & 0xF)}; + + writeReg(CCS811_REG_THRESHOLDS, buffer, 5); + uint8_t buf[1]; + readReg(CCS811_REG_THRESHOLDS, buf, 1); + Serial.println(buf[0],HEX); +} + +uint16_t CCS811::getCO2PPM(){ + uint8_t buffer[8]; + readReg(CCS811_REG_ALG_RESULT_DATA, buffer, 8); + eCO2 = (((uint16_t)buffer[0] << 8) | (uint16_t)buffer[1]); + return eCO2; +} + +uint16_t CCS811::getTVOCPPB(){ + uint8_t buffer[8]; + readReg(CCS811_REG_ALG_RESULT_DATA, buffer, 8); + eTVOC = (((uint16_t)buffer[2] << 8) | (uint16_t)buffer[3]); + return eTVOC; +} + +void CCS811::setInTempHum(float temperature, float humidity) // compensate for temperature and relative humidity +{ + int _temp, _rh; + if(temperature>0) + _temp = (int)temperature + 0.5; // this will round off the floating point to the nearest integer value + else if(temperature<0) // account for negative temperatures + _temp = (int)temperature - 0.5; + _temp = _temp + 25; // temperature high byte is stored as T+25°C in the sensor's memory so the value of byte is positive + _rh = (int)humidity + 0.5; // this will round off the floating point to the nearest integer value + + uint8_t envData[4]; + + envData[0] = _rh << 1; // shift the binary number to left by 1. This is stored as a 7-bit value + envData[1] = 0; // most significant fractional bit. Using 0 here - gives us accuracy of +/-1%. Current firmware (2016) only supports fractional increments of 0.5 + envData[2] = _temp << 1; + envData[3] = 0; + + writeReg(CCS811_REG_ENV_DATA, &envData, 4); +} + +void CCS811::writeReg(uint8_t reg, const void* pBuf, size_t size) +{ + if(pBuf == NULL){ + DBG("pBuf ERROR!! : null pointer"); + } + uint8_t * _pBuf = (uint8_t *)pBuf; + _pWire->beginTransmission(_deviceAddr); + _pWire->write(®, 1); + + for(uint16_t i = 0; i < size; i++){ + _pWire->write(_pBuf[i]); + } + _pWire->endTransmission(); +} + +uint8_t CCS811::readReg(uint8_t reg, const void* pBuf, size_t size) +{ + if(pBuf == NULL){ + DBG("pBuf ERROR!! : null pointer"); + } + uint8_t * _pBuf = (uint8_t *)pBuf; + _pWire->beginTransmission(_deviceAddr); + _pWire->write(®, 1); + + if( _pWire->endTransmission() != 0){ + return 0; + } + + _pWire->requestFrom(_deviceAddr, (uint8_t) size); + for(uint16_t i = 0; i < size; i++){ + _pBuf[i] = _pWire->read(); + } + _pWire->endTransmission(); + return size; +} diff --git a/CCS811.h b/CCS811.h new file mode 100644 index 0000000..2640535 --- /dev/null +++ b/CCS811.h @@ -0,0 +1,224 @@ +#ifndef _CCS811_H +#define _CCS811_H + +#if ARDUINO >= 100 +#include "Arduino.h" +#else +#include "WProgram.h" +#endif +#include + + +/*I2C ADDRESS*/ +#define CCS811_I2C_ADDRESS1 0x5A +#define CCS811_I2C_ADDRESS2 0x5B + +#define CCS811_REG_STATUS 0x00 +#define CCS811_REG_MEAS_MODE 0x01 +#define CCS811_REG_ALG_RESULT_DATA 0x02 +#define CCS811_REG_RAW_DATA 0x03 +#define CCS811_REG_ENV_DATA 0x05 +#define CCS811_REG_NTC 0x06 +#define CCS811_REG_THRESHOLDS 0x10 +#define CCS811_REG_BASELINE 0x11 +#define CCS811_REG_HW_ID 0x20 +#define CCS811_REG_HW_VERSION 0x21 +#define CCS811_REG_FW_BOOT_VERSION 0x23 +#define CCS811_REG_FW_APP_VERSION 0x24 +#define CCS811_REG_INTERNAL_STATE 0xA0 +#define CCS811_REG_ERROR_ID 0xE0 +#define CCS811_REG_SW_RESET 0xFF + +#define CCS811_BOOTLOADER_APP_ERASE 0xF1 +#define CCS811_BOOTLOADER_APP_DATA 0xF2 +#define CCS811_BOOTLOADER_APP_VERIFY 0xF3 +#define CCS811_BOOTLOADER_APP_START 0xF4 + +#define CCS811_HW_ID 0x81 +//Open the macro to see the detailed program execution process. +//#define ENABLE_DBG + +#ifdef ENABLE_DBG +#define DBG(...) {Serial.print("[");Serial.print(__FUNCTION__); Serial.print("(): "); Serial.print(__LINE__); Serial.print(" ] "); Serial.println(__VA_ARGS__);} +#else +#define DBG(...) +#endif + +class CCS811 +{ +public: + #define ERR_OK 0 //OK + #define ERR_DATA_BUS -1 //error in data bus + #define ERR_IC_VERSION -2 //chip version mismatch + + uint8_t _deviceAddr; + typedef enum{ + eMode0, //Idle (Measurements are disabled in this mode) + eMode1, //Constant power mode, IAQ measurement every second + eMode2, //Pulse heating mode IAQ measurement every 10 seconds + eMode3, //Low power pulse heating mode IAQ measurement every 60 seconds + eMode4 //Constant power mode, sensor measurement every 250ms 1xx: Reserved modes (For future use) + }eDRIVE_MODE_t; + + typedef enum{ + eClosed, //Idle (Measurements are disabled in this mode) + eCycle_1s, //Constant power mode, IAQ measurement every second + eCycle_10s, //Pulse heating mode IAQ measurement every 10 seconds + eCycle_60s, //Low power pulse heating mode IAQ measurement every 60 seconds + eCycle_250ms //Constant power mode, sensor measurement every 250ms 1xx: Reserved modes (For future use) + }eCycle_t; + /** + * @brief Constructor + * @param Input in Wire address + */ + CCS811(TwoWire *pWire = &Wire, uint8_t deviceAddr = 0x5A){_pWire = pWire; _deviceAddr = deviceAddr;}; + + /** + * @brief Constructor + * @return Return 0 if initialization succeeds, otherwise return non-zero. + */ + int begin(); + /** + * @brief Judge if there is data to read + * @return Return 1 if there is, otherwise return 0. + */ + bool checkDataReady(); + /** + * @brief Reset sensor, clear all configured data. + */ + void softReset(), + /** + * @brief Set environment parameter + * @param temperature Set temperature value, unit: centigrade, range (-40~85℃) + * @param humidity Set humidity value, unit: RH, range (0~100) + */ + setInTempHum(float temperature, float humidity), + /** + * @brief Measurement parameter configuration + * @param thresh:0 for Interrupt mode operates normally; 1 for interrupt mode only asserts the nINT signal (driven low) if the new + * @param interrupt:0 for Interrupt generation is disabled; 1 for the nINT signal is asserted (driven low) when a new sample is ready in + * @param mode:in typedef enum eDRIVE_MODE_t + */ + setMeasurementMode(uint8_t thresh, uint8_t interrupt, eDRIVE_MODE_t mode), + /** + * @brief Measurement parameter configuration + * @param mode:in typedef enum eDRIVE_MODE_t + */ + setMeasCycle(eCycle_t cycle), + /** + * @brief Set interrupt thresholds + * @param lowToMed: interrupt triggered value in range low to middle + * @param medToHigh: interrupt triggered value in range middle to high + */ + setThresholds(uint16_t lowToMed, uint16_t medToHigh); + /** + * @brief Get current configured parameter + * @return configuration code, needs to be converted into binary code to analyze + * The 2nd: Interrupt mode (if enabled) operates normally,1: Interrupt mode (if enabled) only asserts the nINT signal (driven low) if the new + * The 3rd: Interrupt generation is disabled,1: The nINT signal is asserted (driven low) when a new sample is ready in + * The 4th: 6th: in typedef enum eDRIVE_MODE_t + */ + uint8_t getMeasurementMode(); + + /** + * @brief Get the current carbon dioxide concentration + * @return current carbon dioxide concentration, unit:ppm + */ + uint16_t getCO2PPM(), + /** + * @brief Get current TVOC concentration + * @return Return current TVOC concentration, unit: ppb + */ + getTVOCPPB(); + uint16_t readBaseLine(); + void writeBaseLine(uint16_t baseLine); + +protected: + + typedef struct{ + /* + * The CCS811 received an I²C write request addressed to this station but with invalid register address ID + */ + uint8_t sWRITE_REG_INVALID: 1; + /* + * The CCS811 received an I²C read request to a mailbox ID that is invalid + */ + uint8_t sREAD_REG_INVALID: 1; + /* + * The CCS811 received an I²C request to write an unsupported mode to MEAS_MODE + */ + uint8_t sMEASMODE_INVALID: 1; + /* + * The sensor resistance measurement has reached or exceeded the maximum range + */ + uint8_t sMAX_RESISTANCE: 1; + /* + * The The Heater current in the CCS811 is not in range + */ + uint8_t sHEATER_FAULT: 1; + /* + * The Heater voltage is not being applied correctly + */ + uint8_t sHEATER_SUPPLY: 1; + } __attribute__ ((packed))sError_id; + + typedef struct{ + /* + * ALG_RESULT_DATA crosses one of the thresholds set in the THRESHOLDS register + * by more than the hysteresis value (also in the THRESHOLDS register) + */ + uint8_t sINT_THRESH: 1; + /* + * At the end of each measurement cycle (250ms, 1s, 10s, 60s) a flag is set in the + * STATUS register regardless of the setting of this bit. + */ + uint8_t sINT_DATARDY: 1; + /* + * A new sample is placed in ALG_RESULT_DATA and RAW_DATA registers and the + * DATA_READY bit in the STATUS register is set at the defined measurement interval. + */ + uint8_t sDRIVE_MODE: 3; + } __attribute__ ((packed))sMeas_mode; + + typedef struct{ + /* + * This bit is cleared by reading ERROR_ID + * It is not sufficient to read the ERROR field of ALG_RESULT_DATA and STATUS + */ + uint8_t sERROR: 1; + /* + * ALG_RESULT_DATA is read on the I²C interface + */ + uint8_t sDATA_READY: 1; + uint8_t sAPP_VALID: 1; + /* + * After issuing a VERIFY command the application software must wait 70ms before + * issuing any transactions to CCS811 over the I²C interface + */ + uint8_t sAPP_VERIFY: 1; + /* + * After issuing the ERASE command the application software must wait 500ms + * before issuing any transactions to the CCS811 over the I2C interface. + */ + uint8_t sAPP_ERASE: 1; + uint8_t sFW_MODE: 1; + } __attribute__ ((packed))sStatus; + + + void getData(void); + + void writeConfig(); + + virtual void writeReg(uint8_t reg, const void* pBuf, size_t size); + virtual uint8_t readReg(uint8_t reg, const void* pBuf, size_t size); + + + +private: + TwoWire *_pWire; + + uint16_t eCO2; + uint16_t eTVOC; +}; + +#endif diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..481382a --- /dev/null +++ b/Makefile @@ -0,0 +1,60 @@ +# Optionally some environment variables can be set: +# +# FQBN Fully Qualified Board Name; if not set in the environment +# it will be assigned a value in this makefile +# +# SERIAL_DEV Serial device to upload the sketch; if not set in the +# environment it will be assigned: +# /dev/ttyUSB0 if it exists, or +# /dev/ttyACM0 if it exists, or +# unknown +# +# MDNS_NAME Hostname of the Arduino; if not set in the environment +# it will be assigned a value in this makefile. This is +# needed for OTA update, the device will be searched +# on the local subnet using this name +# +# OTA_PORT Port used by OTA update; if not set in the environment +# it will be assigned the default value of 8266 in this +# makefile +# +# OTA_PASS Password used for OTA update; if not set in the environment +# it will be assigned the default value of an empty string + +PROGNAME = mush + +FQBN = esp8266:esp8266:espmxdevkit +MDNS_NAME = $(PROGNAME) +OTA_PORT = 8266 +OTA_PASS = + +SERIAL_DEV = $(firstword $(wildcard /dev/ttyUSB* /dev/ttyACM*)) + +cli = arduino-cli -b "$(FQBN)" + +BUILD_DIR != $(cli) compile --show-properties | sed -ne 's/^build.path=//p' + +SRC := CCS811.cpp $(PROGNAME).ino +HDRS := CCS811.h ota.h wifiinfo.h +BIN := $(BUILD_DIR)/$(PROGNAME).ino.bin +ELF := $(BUILD_DIR)/$(PROGNAME).ino.elf + +all: $(ELF) +.PHONY: all + +compile: $(ELF) +.PHONY: compile + +$(BIN) $(ELF): $(SRC) $(HDRS) + $(cli) compile --warnings all + +upload: + $(cli) upload -p "$(SERIAL_DEV)" + +PLAT_PATH != $(cli) compile --show-properties | sed -ne 's/^runtime.platform.path=//p' +PY_PATH != $(cli) compile --show-properties | sed -ne 's/^runtime.tools.python3.path=//p' +MDNS_IP != getent ahostsv4 $(MDNS_NAME).local | (read ip _; echo $$ip) + +ota: $(BIN) + "$(PY_PATH)/python3" "$(PLAT_PATH)/tools/espota.py" -i "$(MDNS_IP)" -p "$(OTA_PORT)" --auth="$(OTA_PASS)" -f "$(BIN)" + diff --git a/mush.ino b/mush.ino new file mode 100644 index 0000000..6c2688f --- /dev/null +++ b/mush.ino @@ -0,0 +1,126 @@ +#include +#include "ota.h" +#include +#include "CCS811.h" + +#define TEMP_SENSOR_PIN 12 +#define HUMIDITY_SENSOR_PIN 12 +#define FAN_PIN 15 +#define CO2_PIN 16 +#define ULTRASONIC_PIN 12 + +#define PHOTORESISTOR 0 // pin 0 is analog + +#define CHECK_FREQUENCY 2 // check sensors every 2 seconds +#define HUMIDITY_DESIRED 75 +#define HUMIDITY_VARIATION 3 // ultrasonic turns on at (75 - 3 = 72) and off + // at (75 + 3 = 78) +WiFiClient *wific = 0; + +// Tempature + Humidity Sensor +#define DHTPIN 12 +#define DHTTYPE DHT11 +DHT dht(DHTPIN, DHTTYPE); + +/* + * IIC address default 0x5A, the address becomes 0x5B if the ADDR_SEL is soldered. + */ +//CCS811 sensor(&Wire, /*IIC_ADDRESS=*/0x5A); +CCS811 sensor; + +void setup(void) +{ + setupWifi((char *) hostname); + setupOTA((char *) hostname); + + dht.begin(); // temp+humidity sensor + pinMode(PHOTORESISTOR, INPUT); // photo resistor + wific = new WiFiClient(); + + + Serial.begin(115200); + /*Wait for the chip to be initialized completely, and then exit*/ + while (sensor.begin()) { + Serial.println("failed to init chip, please check if the chip connection is fine"); + delay(1000); + } + /** + * @brief Set measurement cycle + * @param cycle:in typedef enum{ + * eClosed, //Idle (Measurements are disabled in this mode) + * eCycle_1s, //Constant power mode, IAQ measurement every second + * Ecycle_10s, //Pulse heating mode IAQ measurement every 10 seconds + * eCycle_60s, //Low power pulse heating mode IAQ measurement every 60 seconds + * eCycle_250ms //Constant power mode, sensor measurement every 250ms + * }eCycle_t; + */ + sensor.setMeasCycle(sensor.eCycle_250ms); +} + +void writeBoth(char *buf) +{ + Serial.print(buf); + if (wific->connected()) { + wific->write(buf); + } +} + +void log_reading (float temp_c, float humidity, int photons, uint16_t co2, uint16_t tvoc) +{ + auto fmt = "T: %.2f H: %.2f HI: %.2f Light: %d CO2: %d TVOC: %d\r\n"; + char buf[500]; + + float heat_index_c = dht.computeHeatIndex(temp_c, humidity, false); + + snprintf(buf, sizeof(buf), fmt, temp_c, humidity, heat_index_c, photons, co2, tvoc); + writeBoth(buf); +} + +struct SensorState +{ + float last_reading; + virtual void sense() = 0; +}; + +struct TemperatureSensor : public SensorState { virtual void sense() { last_reading = dht.readTemperature(); } }; +struct HumiditySensor : public SensorState { virtual void sense() { last_reading = dht.readHumidity(); } }; +struct PhotoSensor : public SensorState { virtual void sense() { last_reading = analogRead(PHOTORESISTOR); } }; +struct CO2Sensor : public SensorState { virtual void sense() { last_reading = sensor.getCO2PPM(); } }; +struct TVOCSensor : public SensorState { virtual void sense() { last_reading = sensor.getTVOCPPB(); } }; + +TemperatureSensor temperatureSensor; +HumiditySensor humiditySensor; +PhotoSensor photoSensor; +CO2Sensor cO2Sensor; +TVOCSensor tVOCSensor; + +SensorState *sensors[] = { &temperatureSensor, &humiditySensor, &photoSensor, &cO2Sensor, &tVOCSensor }; + +void sensor_loop() +{ + for (int i=0; isense(); + } + sensor.writeBaseLine(0x847B); +} + +void loop() +{ + ArduinoOTA.handle(); + + auto ip = IPAddress(192,168,1,2); + auto port = 3141; + if (!wific->connected()) { + Serial.println("Attempting to connect"); + wific->connect(ip, port); + } + + sensor_loop(); + + log_reading(temperatureSensor.last_reading, humiditySensor.last_reading, photoSensor.last_reading, cO2Sensor.last_reading, tVOCSensor.last_reading); + + delay(1000); +} + + diff --git a/ota.h b/ota.h new file mode 100644 index 0000000..28fb37b --- /dev/null +++ b/ota.h @@ -0,0 +1,98 @@ +// Include what is needed to implement Over The Air Update +// The WiFi connection is not done on this include file, so must be done +// in the main program file +// +// This include file provides the functions +// setupWifi(hostname) +// hostname can be an empty string; this function will +// establish the wifi connections, WiFi credentials are supplied +// in the file "wifiinfo.h", see "wifiinfo.h.sample" +// setupOTA(hostname) +// hostname can be an empty string; will be used to retrieve the +// correct board to upgrade Over The Air. +// If an empty string the default name is esp8266-[ChipID] +// The above 2 functions must be called in the setup() function +// +// in the loop function the function +// ArduinoOTA.handle() +// must be called + +#ifndef ota_h +#define ota_h +// needed include files +#include +#include +#include +#include + +// include our Network SSID and PASSWORD +#include "wifiinfo.h" + +// ================================================================== +// Establish WiFi connection +// ================================================================== +void setupWifi(char hostname[]) { + int i = 0; + WiFi.mode(WIFI_STA); + if (sizeof(hostname) > 0) { + WiFi.hostname(hostname); + } + if (Serial) {Serial.println("Connecting ");} + WiFi.begin(ssid, password); + while (WiFi.status() != WL_CONNECTED) { + if (Serial) {Serial.print(".");} + delay(500); + } + if (Serial) { + Serial.println("."); + Serial.print("Connected! IP: "); + Serial.println(WiFi.localIP()); + } +} + + +// ================================================================== +// Setup for OTA update +// ================================================================== + +void setupOTA(char hostname[]) { + // Port defaults to 8266 + // ArduinoOTA.setPort(8266); + + // Hostname defaults to esp8266-[ChipID] + if (sizeof(hostname) > 0) { + ArduinoOTA.setHostname(hostname); + } + + // No authentication by default + // ArduinoOTA.setPassword((const char *)"123"); + + ArduinoOTA.onStart([]() { + if (Serial) {Serial.println("Start");} + }); + ArduinoOTA.onEnd([]() { + if (Serial) {Serial.println("\nEnd");} + }); + ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { + if (Serial) {Serial.printf("Progress: %u%%\r", (progress / (total / 100)));} + }); + ArduinoOTA.onError([](ota_error_t error) { + if (Serial) { + Serial.printf("Error[%u]: ", error); + if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); + else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); + else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); + else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); + else if (error == OTA_END_ERROR) Serial.println("End Failed"); + } + }); + ArduinoOTA.begin(); + if (Serial) { + Serial.println("Ready"); + Serial.print("IP address: "); + Serial.println(WiFi.localIP()); + } +} + + +#endif diff --git a/src/main/CCS811.cpp b/src/main/CCS811.cpp deleted file mode 100644 index 05b71c0..0000000 --- a/src/main/CCS811.cpp +++ /dev/null @@ -1,154 +0,0 @@ -#include "CCS811.h" - -int CCS811::begin(void) -{ - uint8_t id=0; - Wire.begin(); - softReset(); - delay(100); - if(readReg(CCS811_REG_HW_ID,&id,1) != 1){DBG(""); - DBG("bus data access error");DBG(""); - return ERR_DATA_BUS;DBG(""); - } - - DBG("real sensor id=");DBG(id); - if(id != CCS811_HW_ID){DBG(""); - delay(1); - return ERR_IC_VERSION; - } - writeReg(CCS811_BOOTLOADER_APP_START, NULL, 0); - setMeasurementMode(0,0,eMode4); - setInTempHum(25, 50); - return ERR_OK; -} - -void CCS811::softReset(){ - uint8_t value[4] = {0x11, 0xE5, 0x72, 0x8A}; - writeReg(CCS811_REG_SW_RESET, value, 4); -} - -bool CCS811::checkDataReady() -{ - int8_t status[1] = {0}; - readReg(CCS811_REG_STATUS, status, 1); - DBG(status[0],HEX); - if(!((status[0] >> 3) & 0x01)) - return false; - else - return true; -} - -uint16_t CCS811::readBaseLine(){ - uint8_t buffer[2]; - readReg(CCS811_REG_BASELINE, buffer, 2); - return buffer[0]<<8|buffer[1]; -} - -void CCS811::writeBaseLine(uint16_t baseLine){ - uint8_t buffer[2]; - - buffer[0] = baseLine>>8; - buffer[1] = baseLine; - writeReg(CCS811_REG_BASELINE, buffer, 2); -} - -void CCS811::setMeasurementMode(uint8_t thresh, uint8_t interrupt, eDRIVE_MODE_t mode){ - uint8_t measurement[1] = {0}; - measurement[0] = (thresh << 2) | (interrupt << 3) | (mode << 4); - writeReg(CCS811_REG_MEAS_MODE, measurement, 1); -} - -void CCS811::setMeasCycle(eCycle_t cycle){ - uint8_t measurement[1] = {0}; - measurement[0] = cycle << 4; - writeReg(CCS811_REG_MEAS_MODE, measurement, 1); -} - -uint8_t CCS811::getMeasurementMode(){ - uint8_t meas[1] = {0}; - readReg(CCS811_REG_MEAS_MODE, meas, 1); - return meas[0]; -} - -void CCS811::setThresholds(uint16_t lowToMed, uint16_t medToHigh) -{ - uint8_t buffer[] = {(uint8_t)((lowToMed >> 8) & 0xF), - (uint8_t)(lowToMed & 0xF), - (uint8_t)((medToHigh >> 8) & 0xF), - (uint8_t)(medToHigh & 0xF)}; - - writeReg(CCS811_REG_THRESHOLDS, buffer, 5); - uint8_t buf[1]; - readReg(CCS811_REG_THRESHOLDS, buf, 1); - Serial.println(buf[0],HEX); -} - -uint16_t CCS811::getCO2PPM(){ - uint8_t buffer[8]; - readReg(CCS811_REG_ALG_RESULT_DATA, buffer, 8); - eCO2 = (((uint16_t)buffer[0] << 8) | (uint16_t)buffer[1]); - return eCO2; -} - -uint16_t CCS811::getTVOCPPB(){ - uint8_t buffer[8]; - readReg(CCS811_REG_ALG_RESULT_DATA, buffer, 8); - eTVOC = (((uint16_t)buffer[2] << 8) | (uint16_t)buffer[3]); - return eTVOC; -} - -void CCS811::setInTempHum(float temperature, float humidity) // compensate for temperature and relative humidity -{ - int _temp, _rh; - if(temperature>0) - _temp = (int)temperature + 0.5; // this will round off the floating point to the nearest integer value - else if(temperature<0) // account for negative temperatures - _temp = (int)temperature - 0.5; - _temp = _temp + 25; // temperature high byte is stored as T+25°C in the sensor's memory so the value of byte is positive - _rh = (int)humidity + 0.5; // this will round off the floating point to the nearest integer value - - uint8_t envData[4]; - - envData[0] = _rh << 1; // shift the binary number to left by 1. This is stored as a 7-bit value - envData[1] = 0; // most significant fractional bit. Using 0 here - gives us accuracy of +/-1%. Current firmware (2016) only supports fractional increments of 0.5 - envData[2] = _temp << 1; - envData[3] = 0; - - writeReg(CCS811_REG_ENV_DATA, &envData, 4); -} - -void CCS811::writeReg(uint8_t reg, const void* pBuf, size_t size) -{ - if(pBuf == NULL){ - DBG("pBuf ERROR!! : null pointer"); - } - uint8_t * _pBuf = (uint8_t *)pBuf; - _pWire->beginTransmission(_deviceAddr); - _pWire->write(®, 1); - - for(uint16_t i = 0; i < size; i++){ - _pWire->write(_pBuf[i]); - } - _pWire->endTransmission(); -} - -uint8_t CCS811::readReg(uint8_t reg, const void* pBuf, size_t size) -{ - if(pBuf == NULL){ - DBG("pBuf ERROR!! : null pointer"); - } - uint8_t * _pBuf = (uint8_t *)pBuf; - _pWire->beginTransmission(_deviceAddr); - _pWire->write(®, 1); - - if( _pWire->endTransmission() != 0){ - return 0; - } - - _pWire->requestFrom(_deviceAddr, (uint8_t) size); - for(uint16_t i = 0; i < size; i++){ - _pBuf[i] = _pWire->read(); - } - _pWire->endTransmission(); - return size; -} diff --git a/src/main/CCS811.h b/src/main/CCS811.h deleted file mode 100644 index 2640535..0000000 --- a/src/main/CCS811.h +++ /dev/null @@ -1,224 +0,0 @@ -#ifndef _CCS811_H -#define _CCS811_H - -#if ARDUINO >= 100 -#include "Arduino.h" -#else -#include "WProgram.h" -#endif -#include - - -/*I2C ADDRESS*/ -#define CCS811_I2C_ADDRESS1 0x5A -#define CCS811_I2C_ADDRESS2 0x5B - -#define CCS811_REG_STATUS 0x00 -#define CCS811_REG_MEAS_MODE 0x01 -#define CCS811_REG_ALG_RESULT_DATA 0x02 -#define CCS811_REG_RAW_DATA 0x03 -#define CCS811_REG_ENV_DATA 0x05 -#define CCS811_REG_NTC 0x06 -#define CCS811_REG_THRESHOLDS 0x10 -#define CCS811_REG_BASELINE 0x11 -#define CCS811_REG_HW_ID 0x20 -#define CCS811_REG_HW_VERSION 0x21 -#define CCS811_REG_FW_BOOT_VERSION 0x23 -#define CCS811_REG_FW_APP_VERSION 0x24 -#define CCS811_REG_INTERNAL_STATE 0xA0 -#define CCS811_REG_ERROR_ID 0xE0 -#define CCS811_REG_SW_RESET 0xFF - -#define CCS811_BOOTLOADER_APP_ERASE 0xF1 -#define CCS811_BOOTLOADER_APP_DATA 0xF2 -#define CCS811_BOOTLOADER_APP_VERIFY 0xF3 -#define CCS811_BOOTLOADER_APP_START 0xF4 - -#define CCS811_HW_ID 0x81 -//Open the macro to see the detailed program execution process. -//#define ENABLE_DBG - -#ifdef ENABLE_DBG -#define DBG(...) {Serial.print("[");Serial.print(__FUNCTION__); Serial.print("(): "); Serial.print(__LINE__); Serial.print(" ] "); Serial.println(__VA_ARGS__);} -#else -#define DBG(...) -#endif - -class CCS811 -{ -public: - #define ERR_OK 0 //OK - #define ERR_DATA_BUS -1 //error in data bus - #define ERR_IC_VERSION -2 //chip version mismatch - - uint8_t _deviceAddr; - typedef enum{ - eMode0, //Idle (Measurements are disabled in this mode) - eMode1, //Constant power mode, IAQ measurement every second - eMode2, //Pulse heating mode IAQ measurement every 10 seconds - eMode3, //Low power pulse heating mode IAQ measurement every 60 seconds - eMode4 //Constant power mode, sensor measurement every 250ms 1xx: Reserved modes (For future use) - }eDRIVE_MODE_t; - - typedef enum{ - eClosed, //Idle (Measurements are disabled in this mode) - eCycle_1s, //Constant power mode, IAQ measurement every second - eCycle_10s, //Pulse heating mode IAQ measurement every 10 seconds - eCycle_60s, //Low power pulse heating mode IAQ measurement every 60 seconds - eCycle_250ms //Constant power mode, sensor measurement every 250ms 1xx: Reserved modes (For future use) - }eCycle_t; - /** - * @brief Constructor - * @param Input in Wire address - */ - CCS811(TwoWire *pWire = &Wire, uint8_t deviceAddr = 0x5A){_pWire = pWire; _deviceAddr = deviceAddr;}; - - /** - * @brief Constructor - * @return Return 0 if initialization succeeds, otherwise return non-zero. - */ - int begin(); - /** - * @brief Judge if there is data to read - * @return Return 1 if there is, otherwise return 0. - */ - bool checkDataReady(); - /** - * @brief Reset sensor, clear all configured data. - */ - void softReset(), - /** - * @brief Set environment parameter - * @param temperature Set temperature value, unit: centigrade, range (-40~85℃) - * @param humidity Set humidity value, unit: RH, range (0~100) - */ - setInTempHum(float temperature, float humidity), - /** - * @brief Measurement parameter configuration - * @param thresh:0 for Interrupt mode operates normally; 1 for interrupt mode only asserts the nINT signal (driven low) if the new - * @param interrupt:0 for Interrupt generation is disabled; 1 for the nINT signal is asserted (driven low) when a new sample is ready in - * @param mode:in typedef enum eDRIVE_MODE_t - */ - setMeasurementMode(uint8_t thresh, uint8_t interrupt, eDRIVE_MODE_t mode), - /** - * @brief Measurement parameter configuration - * @param mode:in typedef enum eDRIVE_MODE_t - */ - setMeasCycle(eCycle_t cycle), - /** - * @brief Set interrupt thresholds - * @param lowToMed: interrupt triggered value in range low to middle - * @param medToHigh: interrupt triggered value in range middle to high - */ - setThresholds(uint16_t lowToMed, uint16_t medToHigh); - /** - * @brief Get current configured parameter - * @return configuration code, needs to be converted into binary code to analyze - * The 2nd: Interrupt mode (if enabled) operates normally,1: Interrupt mode (if enabled) only asserts the nINT signal (driven low) if the new - * The 3rd: Interrupt generation is disabled,1: The nINT signal is asserted (driven low) when a new sample is ready in - * The 4th: 6th: in typedef enum eDRIVE_MODE_t - */ - uint8_t getMeasurementMode(); - - /** - * @brief Get the current carbon dioxide concentration - * @return current carbon dioxide concentration, unit:ppm - */ - uint16_t getCO2PPM(), - /** - * @brief Get current TVOC concentration - * @return Return current TVOC concentration, unit: ppb - */ - getTVOCPPB(); - uint16_t readBaseLine(); - void writeBaseLine(uint16_t baseLine); - -protected: - - typedef struct{ - /* - * The CCS811 received an I²C write request addressed to this station but with invalid register address ID - */ - uint8_t sWRITE_REG_INVALID: 1; - /* - * The CCS811 received an I²C read request to a mailbox ID that is invalid - */ - uint8_t sREAD_REG_INVALID: 1; - /* - * The CCS811 received an I²C request to write an unsupported mode to MEAS_MODE - */ - uint8_t sMEASMODE_INVALID: 1; - /* - * The sensor resistance measurement has reached or exceeded the maximum range - */ - uint8_t sMAX_RESISTANCE: 1; - /* - * The The Heater current in the CCS811 is not in range - */ - uint8_t sHEATER_FAULT: 1; - /* - * The Heater voltage is not being applied correctly - */ - uint8_t sHEATER_SUPPLY: 1; - } __attribute__ ((packed))sError_id; - - typedef struct{ - /* - * ALG_RESULT_DATA crosses one of the thresholds set in the THRESHOLDS register - * by more than the hysteresis value (also in the THRESHOLDS register) - */ - uint8_t sINT_THRESH: 1; - /* - * At the end of each measurement cycle (250ms, 1s, 10s, 60s) a flag is set in the - * STATUS register regardless of the setting of this bit. - */ - uint8_t sINT_DATARDY: 1; - /* - * A new sample is placed in ALG_RESULT_DATA and RAW_DATA registers and the - * DATA_READY bit in the STATUS register is set at the defined measurement interval. - */ - uint8_t sDRIVE_MODE: 3; - } __attribute__ ((packed))sMeas_mode; - - typedef struct{ - /* - * This bit is cleared by reading ERROR_ID - * It is not sufficient to read the ERROR field of ALG_RESULT_DATA and STATUS - */ - uint8_t sERROR: 1; - /* - * ALG_RESULT_DATA is read on the I²C interface - */ - uint8_t sDATA_READY: 1; - uint8_t sAPP_VALID: 1; - /* - * After issuing a VERIFY command the application software must wait 70ms before - * issuing any transactions to CCS811 over the I²C interface - */ - uint8_t sAPP_VERIFY: 1; - /* - * After issuing the ERASE command the application software must wait 500ms - * before issuing any transactions to the CCS811 over the I2C interface. - */ - uint8_t sAPP_ERASE: 1; - uint8_t sFW_MODE: 1; - } __attribute__ ((packed))sStatus; - - - void getData(void); - - void writeConfig(); - - virtual void writeReg(uint8_t reg, const void* pBuf, size_t size); - virtual uint8_t readReg(uint8_t reg, const void* pBuf, size_t size); - - - -private: - TwoWire *_pWire; - - uint16_t eCO2; - uint16_t eTVOC; -}; - -#endif diff --git a/src/main/Makefile b/src/main/Makefile deleted file mode 100644 index 2000b24..0000000 --- a/src/main/Makefile +++ /dev/null @@ -1,58 +0,0 @@ -# Optionally some environment variables can be set: -# -# FQBN Fully Qualified Board Name; if not set in the environment -# it will be assigned a value in this makefile -# -# SERIAL_DEV Serial device to upload the sketch; if not set in the -# environment it will be assigned: -# /dev/ttyUSB0 if it exists, or -# /dev/ttyACM0 if it exists, or -# unknown -# -# IOT_NAME Name of the IOT device; if not set in the environment -# it will be assigned a value in this makefile. This is -# very useful for OTA update, the device will be searched -# on the local subnet using this name -# -# OTA_PORT Port used by OTA update; if not set in the environment -# it will be assigned the default value of 8266 in this -# makefile -# -# OTA_PASS Password used for OTA update; if not set in the environment -# it will be assigned the default value of an empty string - -FQBN = esp8266:esp8266:espmxdevkit -IOT_NAME = mush -OTA_PORT = 8266 -OTA_PASS = - -SERIAL_DEV = $(firstword $(wildcard /dev/ttyUSB* /dev/ttyACM*)) - -cli = arduino-cli -b "$(FQBN)" - -BUILD_DIR != $(cli) compile --show-properties | sed -ne 's/^build.path=//p' - -SRC := main.ino -HDRS := $(wildcard *.h) -BIN := $(BUILD_DIR)/main.ino.bin -ELF := $(BUILD_DIR)/main.ino.elf - -all: $(ELF) -.PHONY: all - -compile: $(ELF) -.PHONY: compile - -$(BIN) $(ELF): $(SRC) $(HDRS) - $(cli) compile - -upload: - $(cli) upload -p "$(SERIAL_DEV)" - -PLAT_PATH != $(cli) compile --show-properties | sed -ne 's/^runtime.platform.path=//p' -PY_PATH != $(cli) compile --show-properties | sed -ne 's/^runtime.tools.python3.path=//p' -IOT_IP != getent ahostsv4 mush.local | (read ip _; echo $$ip) - -ota: $(BIN) - "$(PY_PATH)/python3" "$(PLAT_PATH)/tools/espota.py" -i "$(IOT_IP)" -p "$(OTA_PORT)" --auth="$(OTA_PASS)" -f "$(BIN)" - diff --git a/src/main/main.ino b/src/main/main.ino deleted file mode 100644 index 6c2688f..0000000 --- a/src/main/main.ino +++ /dev/null @@ -1,126 +0,0 @@ -#include -#include "ota.h" -#include -#include "CCS811.h" - -#define TEMP_SENSOR_PIN 12 -#define HUMIDITY_SENSOR_PIN 12 -#define FAN_PIN 15 -#define CO2_PIN 16 -#define ULTRASONIC_PIN 12 - -#define PHOTORESISTOR 0 // pin 0 is analog - -#define CHECK_FREQUENCY 2 // check sensors every 2 seconds -#define HUMIDITY_DESIRED 75 -#define HUMIDITY_VARIATION 3 // ultrasonic turns on at (75 - 3 = 72) and off - // at (75 + 3 = 78) -WiFiClient *wific = 0; - -// Tempature + Humidity Sensor -#define DHTPIN 12 -#define DHTTYPE DHT11 -DHT dht(DHTPIN, DHTTYPE); - -/* - * IIC address default 0x5A, the address becomes 0x5B if the ADDR_SEL is soldered. - */ -//CCS811 sensor(&Wire, /*IIC_ADDRESS=*/0x5A); -CCS811 sensor; - -void setup(void) -{ - setupWifi((char *) hostname); - setupOTA((char *) hostname); - - dht.begin(); // temp+humidity sensor - pinMode(PHOTORESISTOR, INPUT); // photo resistor - wific = new WiFiClient(); - - - Serial.begin(115200); - /*Wait for the chip to be initialized completely, and then exit*/ - while (sensor.begin()) { - Serial.println("failed to init chip, please check if the chip connection is fine"); - delay(1000); - } - /** - * @brief Set measurement cycle - * @param cycle:in typedef enum{ - * eClosed, //Idle (Measurements are disabled in this mode) - * eCycle_1s, //Constant power mode, IAQ measurement every second - * Ecycle_10s, //Pulse heating mode IAQ measurement every 10 seconds - * eCycle_60s, //Low power pulse heating mode IAQ measurement every 60 seconds - * eCycle_250ms //Constant power mode, sensor measurement every 250ms - * }eCycle_t; - */ - sensor.setMeasCycle(sensor.eCycle_250ms); -} - -void writeBoth(char *buf) -{ - Serial.print(buf); - if (wific->connected()) { - wific->write(buf); - } -} - -void log_reading (float temp_c, float humidity, int photons, uint16_t co2, uint16_t tvoc) -{ - auto fmt = "T: %.2f H: %.2f HI: %.2f Light: %d CO2: %d TVOC: %d\r\n"; - char buf[500]; - - float heat_index_c = dht.computeHeatIndex(temp_c, humidity, false); - - snprintf(buf, sizeof(buf), fmt, temp_c, humidity, heat_index_c, photons, co2, tvoc); - writeBoth(buf); -} - -struct SensorState -{ - float last_reading; - virtual void sense() = 0; -}; - -struct TemperatureSensor : public SensorState { virtual void sense() { last_reading = dht.readTemperature(); } }; -struct HumiditySensor : public SensorState { virtual void sense() { last_reading = dht.readHumidity(); } }; -struct PhotoSensor : public SensorState { virtual void sense() { last_reading = analogRead(PHOTORESISTOR); } }; -struct CO2Sensor : public SensorState { virtual void sense() { last_reading = sensor.getCO2PPM(); } }; -struct TVOCSensor : public SensorState { virtual void sense() { last_reading = sensor.getTVOCPPB(); } }; - -TemperatureSensor temperatureSensor; -HumiditySensor humiditySensor; -PhotoSensor photoSensor; -CO2Sensor cO2Sensor; -TVOCSensor tVOCSensor; - -SensorState *sensors[] = { &temperatureSensor, &humiditySensor, &photoSensor, &cO2Sensor, &tVOCSensor }; - -void sensor_loop() -{ - for (int i=0; isense(); - } - sensor.writeBaseLine(0x847B); -} - -void loop() -{ - ArduinoOTA.handle(); - - auto ip = IPAddress(192,168,1,2); - auto port = 3141; - if (!wific->connected()) { - Serial.println("Attempting to connect"); - wific->connect(ip, port); - } - - sensor_loop(); - - log_reading(temperatureSensor.last_reading, humiditySensor.last_reading, photoSensor.last_reading, cO2Sensor.last_reading, tVOCSensor.last_reading); - - delay(1000); -} - - diff --git a/src/main/ota.h b/src/main/ota.h deleted file mode 100644 index 28fb37b..0000000 --- a/src/main/ota.h +++ /dev/null @@ -1,98 +0,0 @@ -// Include what is needed to implement Over The Air Update -// The WiFi connection is not done on this include file, so must be done -// in the main program file -// -// This include file provides the functions -// setupWifi(hostname) -// hostname can be an empty string; this function will -// establish the wifi connections, WiFi credentials are supplied -// in the file "wifiinfo.h", see "wifiinfo.h.sample" -// setupOTA(hostname) -// hostname can be an empty string; will be used to retrieve the -// correct board to upgrade Over The Air. -// If an empty string the default name is esp8266-[ChipID] -// The above 2 functions must be called in the setup() function -// -// in the loop function the function -// ArduinoOTA.handle() -// must be called - -#ifndef ota_h -#define ota_h -// needed include files -#include -#include -#include -#include - -// include our Network SSID and PASSWORD -#include "wifiinfo.h" - -// ================================================================== -// Establish WiFi connection -// ================================================================== -void setupWifi(char hostname[]) { - int i = 0; - WiFi.mode(WIFI_STA); - if (sizeof(hostname) > 0) { - WiFi.hostname(hostname); - } - if (Serial) {Serial.println("Connecting ");} - WiFi.begin(ssid, password); - while (WiFi.status() != WL_CONNECTED) { - if (Serial) {Serial.print(".");} - delay(500); - } - if (Serial) { - Serial.println("."); - Serial.print("Connected! IP: "); - Serial.println(WiFi.localIP()); - } -} - - -// ================================================================== -// Setup for OTA update -// ================================================================== - -void setupOTA(char hostname[]) { - // Port defaults to 8266 - // ArduinoOTA.setPort(8266); - - // Hostname defaults to esp8266-[ChipID] - if (sizeof(hostname) > 0) { - ArduinoOTA.setHostname(hostname); - } - - // No authentication by default - // ArduinoOTA.setPassword((const char *)"123"); - - ArduinoOTA.onStart([]() { - if (Serial) {Serial.println("Start");} - }); - ArduinoOTA.onEnd([]() { - if (Serial) {Serial.println("\nEnd");} - }); - ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { - if (Serial) {Serial.printf("Progress: %u%%\r", (progress / (total / 100)));} - }); - ArduinoOTA.onError([](ota_error_t error) { - if (Serial) { - Serial.printf("Error[%u]: ", error); - if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); - else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); - else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); - else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); - else if (error == OTA_END_ERROR) Serial.println("End Failed"); - } - }); - ArduinoOTA.begin(); - if (Serial) { - Serial.println("Ready"); - Serial.print("IP address: "); - Serial.println(WiFi.localIP()); - } -} - - -#endif diff --git a/src/main/wifiinfo.h b/src/main/wifiinfo.h deleted file mode 100644 index fb94cdd..0000000 --- a/src/main/wifiinfo.h +++ /dev/null @@ -1,6 +0,0 @@ -#ifndef wifiinfo_h -#define wifiinfo_h -const char *hostname = "mush"; -const char* ssid = "omni"; -const char* password = "everywhere"; -#endif diff --git a/wifiinfo.h b/wifiinfo.h new file mode 100644 index 0000000..fb94cdd --- /dev/null +++ b/wifiinfo.h @@ -0,0 +1,6 @@ +#ifndef wifiinfo_h +#define wifiinfo_h +const char *hostname = "mush"; +const char* ssid = "omni"; +const char* password = "everywhere"; +#endif -- cgit v1.2.3