Project Digora IOT
Dependencies: libmDot-dev-mbed5
Revision 0:522ad8e780f6, committed 2017-05-19
- Comitter:
- Niiippoooo
- Date:
- Fri May 19 09:26:49 2017 +0000
- Commit message:
- project Digora IOT
Changed in this revision
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Lum_sensor.cpp Fri May 19 09:26:49 2017 +0000 @@ -0,0 +1,187 @@ +#include "Lum_sensor.h" + + +Capt_Lum::Capt_Lum() : i2c(PC_9, PA_8) //initialise la liaison I2C entre le capteur et les pins SDA et SCL du mDot +{ + i2c.frequency(100000); //impose la fréquence de communication recommandée pour le capteur + enablePower(); + +} + +int Capt_Lum::enablePower(){ + int ack = writeSingleRegister( TSL_CONTROL, 3 ); //écrit le mot permettant d'allumer le capteur dans le registre CONTROL du capteur + wait(0.1); + return ack; +} + +int Capt_Lum::disablePower(){ + int ack = writeSingleRegister( TSL_CONTROL, 0 ); //écrit le mot permettant d'éteindre le capteur dans le registre CONTROLdu capteur + wait(0.1); + return ack; +} + +int Capt_Lum::writeSingleRegister( char address, char data ){ + char tx[2] = { address | 160, data }; //0d160 = 0b10100000 //on stocke l'addresse du registre et le mot à écrire dans tx + int ack = i2c.write( TSL_SLAVE_ADDRESS << 1, tx, 2 ); //on écrit le mot data dans le registre d'addresse address + return ack; +} + +char Capt_Lum::readSingleRegister( char address ){ + char output = 255; + char command = address | 160; //0d160 = 0b10100000 //on stocke address dans un registre + i2c.write( TSL_SLAVE_ADDRESS << 1, &command, 1, true ); //on indique que l'on veut lire le registre à l'addresse address + i2c.read( TSL_SLAVE_ADDRESS << 1, &output, 1 ); //on lit un mot que l'on sotcke dans output + + return output; +} + +int Capt_Lum::readMultipleRegisters( char address, char* output, int quantity ){ + char command = address | 160; //0d160 = 0b10100000 //on stocke address dans un registre + i2c.write( TSL_SLAVE_ADDRESS << 1, &command, 1, true ); //on indique que l'on veut lire le registre à l'addresse address + int ack = i2c.read( TSL_SLAVE_ADDRESS << 1, output, quantity ); //on lit un mot que l'on sotcke dans output + + return ack; +} + + +int Capt_Lum::getVisibleAndIR(){ + char buffer[2] = { 0 }; + readMultipleRegisters( TSL_DATA0LOW, buffer, 2 ); //lecture du registre contenant la mesure de luminosité visible et IR + int reading = (int)buffer[1] << 8 | (int)buffer[0]; + + return reading; +} + +int Capt_Lum::getIROnly(){ + char buffer[2] = { 0 }; + readMultipleRegisters( TSL_DATA1LOW, buffer, 2 ); //lecture du registre contenant la mesure d'infrarouge + int reading = (int)buffer[1] << 8 | (int)buffer[0]; + + return reading; +} + + +float Capt_Lum::getLux(){ + int ch0 = getVisibleAndIR(); + int ch1 = getIROnly(); + + // on vérifie que le capteur n'a pas saturé (0xFFFF) + // si c'est le cas on arrête (-1) + if( (ch0 == 0xFFFF) || (ch1 == 0xFFFF) ){ + + return -1; + } + + // conversion en float + float d0 = ch0; + float d1 = ch1; + + // We will need the ratio for subsequent calculations + double ratio = d1 / d0; + + // division par le temps d'intégration + int itime = readIntegrationTime(); + d0 *= (402.0/itime); + d1 *= (402.0/itime); + + // division par le gain du capteur + int gain = readGain(); + d0 /= gain; + d1 /= gain; + + // conversion en lux d'après les équations de la datasheet : + if (ratio < 0.5) + { + lux = 0.0304 * d0 - 0.062 * d0 * pow(ratio,1.4); + if (ratio<0.125) + { + lux = 0.0304*d0-0.0272*d1; + } + else if (ratio < 0.250) + { + lux = 0.0325*d0-0.0440*d1; + } + else if (ratio < 0.375) + { + lux = 0.0351*d0 - 0.0544*d1; + } + else + { + lux = 0.0381*d0 - 0.0624*d1; + } + } + else if (ratio < 0.61) + { + lux = 0.0224 * d0 - 0.031 * d1; + } + else if (ratio < 0.80) + { + lux = 0.0128 * d0 - 0.0153 * d1; + } + else if (ratio < 1.30) + { + lux = 0.00146 * d0 - 0.00112 * d1; + } + else if (ratio >= 1.30) + { + lux = 0; + } + return lux; +} + +//calcule le temps d'inégration d'après les équations de la datasheet : +float Capt_Lum::readIntegrationTime(){ + char timing = readSingleRegister( TSL_TIMING ); + char integ = ( timing << 6 ) >> 6; // keep bits 0 & 1 + int itime; + switch (integ) { + case 0: + itime = 13.7; + break; + case 1: + itime = 101; + break; + case 2: + itime = 402; + break; + default: + itime = 0; + break; + } + + return itime; +} +//calcule le gain du capteur d'après les équations de la datasheet : +int Capt_Lum::readGain(){ + char timing = readSingleRegister( TSL_TIMING ); + char gain_bit = ( timing << 3 ) >> 7; // keep only bit 4 + //printf("gain_bit = %i\n\r", gain_bit); + int gain; + switch (gain_bit) { + case 0: + gain = 1; + break; + case 1: + gain = 16; + break; + default: + gain = 0; + break; + } + + return gain; +} + +float Capt_Lum::obtenirLuminosite() +{ + float lux = getLux(); //mesure et calcule la luminosité + if (lux>0) + { + printf("\n\rLuminosité : %.2f lux\n\r", lux); //affiche la luminosité + } + else + { + printf("\n\rErreur lecture luminosité\n\r"); + } + return lux; //retourne la luminosité pour une utilisation ultérieure +} \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Lum_sensor.h Fri May 19 09:26:49 2017 +0000 @@ -0,0 +1,42 @@ +#ifndef LUM_SENSOR_H +#define LUM_SENSOR_H + +#include "mbed.h" + +#define TSL_SLAVE_ADDRESS 0x29 //addresse du capteur +#define TSL_CONTROL 0x00 //registre pour allumer et éteindre le capteur +#define TSL_TIMING 0x01 //registre contenant les informations sur le gain et le temps d'intégration +#define TSL_THRESHLOWLOW 0x02 +#define TSL_THRESHHIGHLOW 0x04 +#define TSL_INTERRUPT 0x06 +#define TSL_ID 0x0A +#define TSL_DATA0LOW 0x0C +#define TSL_DATA1LOW 0x0E + +class Capt_Lum +{ + private: + I2C i2c; //pins I2C initialisés par le constructeur + float lux; //variable dans laquelle on stocke la luminosité mesurée + + public: + Capt_Lum(); //Constructeur + int enablePower(); //allume le capteur + int disablePower(); //éteint le capteur + int writeSingleRegister( char A, char B); //écrit le mot B à l'addresse A + int readMultipleRegisters( char A, char* B, int N); //recopie N mots lus dans le registre d'addresse A dans le tableau d'adresse B + int getVisibleAndIR(); //mesure la luminosité du visible et des infrarouges + int getIROnly(); //mesure uniquement la luminosité infrarouge + float getLux(); //convertit les donnée ent lux + float readIntegrationTime(); //calcule le temps d'intégration necessaire pour une mesure correcte + int readGain(); //calcule le gain necessaire pour une mesure correcte + char readSingleRegister( char A); //retourne un mot lu dans le registre d'addresse A + float obtenirLuminosite(); //calcule, affiche et retourne la luminosité + +}; + + + + + +#endif \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Sound_sensor.cpp Fri May 19 09:26:49 2017 +0000 @@ -0,0 +1,27 @@ +#include "Sound_sensor.h" + + + +Capt_Son::Capt_Son() : SonPin(PB_1) {} //initialise la liaison analogique entre le capteur et le pin PB_1 du mDot + + +float Capt_Son::obtenirSon() +{ + Son=0; //réinitialisation de la mesure + for (int i=0; i<32; i++) //boucle répétée 32 fois + { + Son += SonPin.read(); //sommes des 32 valeurs mesurées + wait(0.01); + } + + Son = Son * 1023; + Son = Son/32; //division par 32 + if ((Son) > 0) //vérification de cohérance des mesures + { + printf("\nBruit = %f \n\r", Son); //affichage de la mesure + } + wait(0.01); + + return Son; //on retourne le niveau sonore pour une utilisation ultérieure + +} \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Sound_sensor.h Fri May 19 09:26:49 2017 +0000 @@ -0,0 +1,19 @@ +#ifndef SOUND_SENSOR_H +#define SOUND_SENSOR_H + +#include "mbed.h" //inclusion de mbed_os pour l'utilisation de la library + + +class Capt_Son +{ + private: + AnalogIn SonPin; //pin d'entrée analogique initialisé par le constructeur + float Son; //variable dans laquelle on stocke le niveau sonore mesuré + + public: + Capt_Son(); //constructeur + float obtenirSon(); //mesure,affiche et retourne le niveau sonore + +}; + +#endif \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/TempHum_sensor.cpp Fri May 19 09:26:49 2017 +0000 @@ -0,0 +1,70 @@ +#include "TempHum_sensor.h" + + +Capt_TH::Capt_TH() : i2c(PC_9, PA_8) //initialise la liaison i2c entre le capteur et les pins SDA et SCL du mDot +{ + i2c.frequency(100000); //on communique à la même fréquence qu'avec le capteur de luminosité +} + +void Capt_TH::WriteCommand() +{ + i2c.start(); + i2c.write(0x88); // Initialisation du mode écriture à l'adresse 0x44 : 7 bits d'adresse (0x44 = 1000100) + // + 1 bit de mode (0x88 = 10001000 pour le mode écriture) + i2c.write(0x24); // Premier octet du message 0x240B correspondant au mode MEDIUM REPEATABILITY MEASUREMENT (cf. datasheet) + i2c.write(0x0B); // Second octet + i2c.stop(); +} + +void Capt_TH::ReadTempHum() +{ + i2c.start(); + i2c.write(0x89); // Initialisation du mode lecture à l'adresse 0x44 : 7 bits d'adresse (0x44 = 1000100) + // + 1 bit de mode (0x89 = 10001001 pour le mode lecture) + + for (int i=0;i<6;i++) // Lecture des données envoyées par le capteur + { + readbuffer[i] = i2c.read(1); // readbuffer[0] et readbuffer[1] contiennent les valeurs de la température + // readbuffer[3] et readbuffer[4] contiennent les valeurs de l'humidité + // readbuffer[2] et readbuffer[5] contiennent des CRC checksum. + } + i2c.stop(); + + + ST = readbuffer[0]; // ST contient le bit de poids fort de la température. ex : ST = 01011111 (0x5F) + ST <<= 8; // Décalage de 8 bits pour récupérer les bits de poids faible. ex : 11101010 (0xEA) + ST |= readbuffer[1]; // Concaténation des 2 octets, ST = 01011111 11101010 (0x5FEA) + + SRH = readbuffer[3]; // Même principe pour l'humidité + SRH <<= 8; + SRH |= readbuffer[4]; + + temp = ST; // Conversion de la valeur reçue en degrés Celsius : T = -45 + 175*[ST/(2^16 - 1)] + temp *= 175; + temp /= 0xFFFF; + temp = -45 + temp; + + hum = SRH; // Conversion de la valeur reçue en humidité relative : RH = 100 * [SRH/(2^16 -1)] + hum *= 100; + hum /= 0xFFFF; +} + +void Capt_TH::getTempHum() +{ + WriteCommand(); //indique au capteur quel type de mesure effectuer + ReadTempHum(); //récupère et convertit les données du capteur en température et humidité +} + +float Capt_TH::obtenirTemperature() +{ if (temp<100) { //vérifie la cohérence de la mesure + printf("\n\rTempérature = %.2f °C\n\r", temp); //affiche la température en degrés Celsius + } + return (temp); //retourne la température pour l'envoi via le réseau LoRa +} + +float Capt_TH::obtenirHumidite() +{ if (temp<100) { //vérifie la cohérence de la mesure + printf("\n\rHumidité Relative = %.2f %%\n\r", hum); //affiche l'humidité relative en pourcentage + } + return (hum); //retourne l'humidité pour l'envoi via le réseau LoRa +} \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/TempHum_sensor.h Fri May 19 09:26:49 2017 +0000 @@ -0,0 +1,36 @@ +#ifndef TEMPHUM_SENSOR_H +#define TEMPHUM_SENSOR_H + +#include "mbed.h" + +#define SHT31_ADDR 0x44 //addresse du capteur +#define SHT31_WRITE 0x88 //addresse pour écriture +#define SHT31_READ 0x89 //addresse pour lecture + +//les différents registres permettant de varier la fréquence et la répétabilité des mesures +#define SHT31_MEAS_HIGHREP_STRETCH 0x2C06 +#define SHT31_MEAS_LOWREP_STRETCH 0x2C10 +#define SHT31_MEAS_HIGHREP 0x2400 +#define SHT31_MEAS_MEDREP 0x240B +#define SHT31_MEAS_LOWREP 0x2416 + + +class Capt_TH +{ + private: + I2C i2c; //pins I2C initialisés par le constructeur + float temp; //variable dans laquelle on stocke la température mesurée + float hum; //variable dans laquelle on stocke l'humidité mesurée + uint16_t readbuffer[6]; //tableau d'entiers (buffer) sur 16 bits dans lequel on stocke les valeurs mesurées avant leur conversion en température et humidité + uint16_t ST, SRH; //température et humidité avant conversion, récupérées dans le readbuffer + + public: + Capt_TH(); //constructeur + void WriteCommand(); //indique au capteur quel type de mesure effectuer + void ReadTempHum(); //récupère et convertit les données du capteur en température et humidité + void getTempHum(); //execute les deux fonctions précedentes + float obtenirTemperature(); //affiche et retourne la température + float obtenirHumidite(); //affiche et retourne l'humidité +}; + +#endif \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/libmDot-dev-mbed5.lib Fri May 19 09:26:49 2017 +0000 @@ -0,0 +1,1 @@ +https://developer.mbed.org/users/Niiippoooo/code/libmDot-dev-mbed5/#1d6ee4fad6ff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/main.cpp Fri May 19 09:26:49 2017 +0000 @@ -0,0 +1,298 @@ +//Envirennement mbed +#include "mbed.h" + +//Capteurs +#include "Lum_sensor.h" //inclusion de la classe capteur de luminosité +#include "Sound_sensor.h" //inclusion de la classe capteur de son +#include "TempHum_sensor.h" //inclusion de la classe capteur de température et humidité + + +//Librairie mDot +#include "mDot.h" +#include "MTSText.h" +#include "MTSLog.h" +#include <iostream> +#include <fstream> +#include <string> +#include <cmath> +#include <vector> +#include <sstream> +#include <cstdio> + + +namespace patch +{ + template < typename T > std::string to_string( const T& n ) + { + std::ostringstream stm ; + stm << n ; + return stm.str() ; + } +} + + + +void log_error(mDot* dot, const char* msg, int32_t retval); + + + +// Configuration du Reseau de la Gateway +// On peut aussi directement donner la clé, et l'ID du réseau +static std::string config_network_name = "digora2017"; +static std::string config_network_pass = "digora2017"; + + +int main() +{ + + float son = 0; + float Temperature = 0; + float Hum = 0; + float Luminosity = 0; + + Capt_Son SON; //initialisation capteur luminosité + Capt_Lum LUM; //initialisation capteur son + Capt_TH TH; //initialisation capteur température et humidité + printf("\n\n\r#################################\n\rInitialisation capteurs OK\n\r#################################\n\r"); + + + + + //---------- CONNEXION A LA GATEWAY ---------- + + + int32_t ret; + mDot* dot = NULL; + std::vector<uint8_t> data; + std::vector<uint8_t> data_recv; + std::string data_str; + + /** Get a handle to the singleton object + * @returns pointer to mDot object + */ + + dot = mDot::getInstance(); + + /** Reset config to factory default + */ + dot->resetConfig(); + + /** Resets current network session, essentially disconnecting from the network + * has no effect for MANUAL network join mode + */ + dot->resetNetworkSession(); + + /** Get library version information + * @returns string containing library version information + */ + printf("version: %s\r\n", dot->getId().c_str()); + + + /** Set network join mode + * MANUAL: set network address and session keys manually + * OTA: User sets network name and passphrase, then attempts to join + * AUTO_OTA: same as OTA, but network sessions can be saved and restored + * @param mode MANUAL, OTA, or AUTO_OTA + * @returns MDOT_OK if success + */ + if (dot->getJoinMode() != mDot::OTA) + { + logInfo("changing network join mode to OTA"); + if (dot->setJoinMode(mDot::AUTO_OTA) != mDot::MDOT_OK) + { + logError("failed to set network join mode to OTA"); + } + } + + + /** Set network name + * for use with OTA & AUTO_OTA network join modes + * generates network ID (crc64 of name) automatically + * @param name a string of of at least 8 bytes and no more than 128 bytes + * @return MDOT_OK if success + */ + printf("setting network name...\r\n"); + if ((ret = dot->setNetworkName(config_network_name)) != mDot::MDOT_OK) + { + log_error(dot, "failed to set network name", ret); + } + + /** Set network passphrase + * for use with OTA & AUTO_OTA network join modes + * generates network key (cmac of passphrase) automatically + * @param name a string of of at least 8 bytes and no more than 128 bytes + * @return MDOT_OK if success + */ + printf("setting network password...\r\n"); + if ((ret = dot->setNetworkPassphrase(config_network_pass)) != mDot::MDOT_OK) + { + log_error(dot, "failed to set network password", ret); + } + + /** Set the device class A, B or C + * @returns MDOT_OK if success + */ + logInfo("changing network mode to class C"); + if (dot->setClass("C") != mDot::MDOT_OK) + { + logError("failed to set network mode to class C"); + } + + + + /** Save config data to non volatile memory + * @returns true if success, false if failure + */ + logInfo("saving configuration"); + if (!dot->saveConfig()) + { + logError("failed to save configuration"); + } + + /** Attempt to join network + * each attempt will be made with a random datarate up to the configured datarate + * JoinRequest backoff between tries is enforced to 1% for 1st hour, 0.1% for 1-10 hours and 0.01% after 10 hours + * Check getNextTxMs() for time until next join attempt can be made + * @returns MDOT_OK if success + */ + + uint8_t freq = dot->getFrequencyBand(); + printf("freq : %u\n\r", freq); //Set frequency sub band + printf("joining network\r\n"); + + + while ((ret = dot->joinNetwork()) != mDot::MDOT_OK) + { + log_error(dot, "failed to join network", ret); + wait(2); + } + string type; + + //############ RELEVE DE MESURES ############ + + while(true) + { + printf("\n\n"); + TH.getTempHum(); //mesure de la température et de l'humidité + TH.obtenirTemperature(); //affichage de la température + TH.obtenirHumidite(); //affichage de l'humidité + LUM.obtenirLuminosite(); //mesure et affichage de la luminosité + SON.obtenirSon(); //mesure et affichage du niveau sonore + + //################################################## + + + //-------- ENVOI SON -------- + + data_str = patch::to_string(son); + /** + * Fill the vector that we will send with the data + */ + for (std::string::iterator it = data_str.begin(); it != data_str.end(); it++) + data.push_back((uint8_t) *it); + type = ":dB"; + for (std::string::iterator it = type.begin(); it != type.end(); it++) + data.push_back((uint8_t) *it); + + /** Send data to the gateway + * validates data size (based on spreading factor) + * @param data a vector of up to 242 bytes (may be less based on spreading factor) + * @returns MDOT_OK if packet was sent successfully (ACKs disabled), or if an ACK was received (ACKs enabled) + */ + if ((ret = dot->send(data)) != mDot::MDOT_OK) + { + log_error(dot, "failed to send", ret); + } + + else + { + printf("successfully sent data to gateway\r\n"); + } + + data_str.clear(); + data.clear(); + + wait(10); + + //-------- ENVOI TEMPERATURE -------- + + data_str = patch::to_string(Temperature); + for (std::string::iterator it = data_str.begin(); it != data_str.end(); it++) + data.push_back((uint8_t) *it); + type = ":*C"; + for (std::string::iterator it = type.begin(); it != type.end(); it++) + data.push_back((uint8_t) *it); + + if ((ret = dot->send(data)) != mDot::MDOT_OK) + { + log_error(dot, "failed to send", ret); + } + + else + { + printf("successfully sent data to gateway\r\n"); + } + + data_str.clear(); + data.clear(); + + wait(10); + + //-------- ENVOI HUMIDITE -------- + + data_str = patch::to_string(Hum); + for (std::string::iterator it = data_str.begin(); it != data_str.end(); it++) + data.push_back((uint8_t) *it); + type = ":%"; + for (std::string::iterator it = type.begin(); it != type.end(); it++) + data.push_back((uint8_t) *it); + + if ((ret = dot->send(data)) != mDot::MDOT_OK) + { + log_error(dot, "failed to send", ret); + } + + else + { + printf("successfully sent data to gateway\r\n"); + } + + data_str.clear(); + data.clear(); + + wait(10); + + //-------- ENVOI LUMINOSITE -------- + + data_str = patch::to_string(Luminosity); + for (std::string::iterator it = data_str.begin(); it != data_str.end(); it++) + data.push_back((uint8_t) *it); + type = ":Lux"; + for (std::string::iterator it = type.begin(); it != type.end(); it++) + data.push_back((uint8_t) *it); + + if ((ret = dot->send(data)) != mDot::MDOT_OK) + { + log_error(dot, "failed to send", ret); + } + + else + { + printf("successfully sent data to gateway\r\n"); + } + + data_str.clear(); + data.clear(); + + wait(10); + } + + + + //return 0; Jamais atteint à cause du "while(true)", donc inutile... +} + + +void log_error(mDot* dot, const char* msg, int32_t retval) { + printf("%s - %ld:%s, %s\r\n", msg, retval, mDot::getReturnCodeString(retval).c_str(), dot->getLastError().c_str()); +} \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-os.lib Fri May 19 09:26:49 2017 +0000 @@ -0,0 +1,1 @@ +https://github.com/ARMmbed/mbed-os/#269f58d75b752a4e67a6a2d8c5c698635ffd6752