Wind Direction and Rain from Weather Shield + Photon

Hi. I’m using Sparkfun Weather Shield and Photon to get temperature, wind speed, direction & rain level and then send these details to another device using MQTT. I can get the temperature and wind speed values, but not the other two. I’m using the latest code from Weather Shield’s git.

I have no problem in sending this data through MQTT, by which I’m getting the log in JSON like below.
{“Temp”: “80.712502”, “Pres”: “75.750000”, “SM”: “2”, “WS”: “0.000000”, “WD”: “0.000000”, “Rain”: “0”}
{“Temp”: “80.712502”, “Pres”: “75.750000”, “SM”: “2”, “WS”: “1.3452030”, “WD”: “0.000000”, “Rain”: “0”}

Can somebody help me with this? I’ve attached the code below (code needs to be cleaned up, plz bear with that):

// This #include statement was automatically added by the Particle IDE.
//#include "HTU21D/HTU21D.h"

// This #include statement was automatically added by the Particle IDE.
#include "MQTT/MQTT.h"

// This #include statement was automatically added by the Particle IDE.
#include "MyTemp.h"

// This #include statement was automatically added by the Particle IDE.

/*// This #include statement was automatically added by the Particle IDE.
#include "Adafruit_MPL3115A2/Adafruit_MPL3115A2.h"
Adafruit_MPL3115A2 baro = Adafruit_MPL3115A2();

void setup() {
  Serial.begin(115200);
  delay(5000);
  
  Serial.println("Adafruit_MPL3115A2 test!");
  
  while(! baro.begin()) {
    Serial.println("Couldnt find sensor");
    delay(1000);
  }
}

void loop() {
  float pascals = baro.getPressure();
  // Our weather page presents pressure in Inches (Hg)
  // Use http://www.onlineconversion.com/pressure.htm for other units
  Serial.print(pascals/3377); Serial.println(" Inches (Hg)");

  float altm = baro.getAltitude();
  Serial.print(altm); Serial.println(" meters");

  float tempC = baro.getTemperature();
  Serial.print(tempC); Serial.println("*C");

  delay(250);
}*/
/******************************************************************************
  SparkFun_Basic_MPL3115A2_Example.ino
  Joel Bartlett @ SparkFun Electronics
  Original Creation Date: June 30, 2015
  This sketch prints the barrometric preassure, altitude, and temperature F
  to the Seril port.

  Hardware Connections:
	This sketch was written specifically for the Photon Weather Shield,
	which connects the MPL3115A2 to the I2C bus by default.
  If you have an MPL3115A2 breakout,	use the following hardware setup:

    MPL3115A2 ------------- Photon
      GND ------------------- GND
      VCC ------------------- 3.3V (VCC)
      SCL ------------------ D1/SCL
      SDA ------------------ D0/SDA

  Development environment specifics:
  	IDE: Particle Build
  	Hardware Platform: Particle Photon
                       Particle Core

  This code is beerware; if you see me (or any other SparkFun
  employee) at the local, and you've found our code helpful,
  please buy us a round!
  Distributed as-is; no warranty is given.
*******************************************************************************/
//#include "SparkFun_MPL3115A2.h"
//HTU21D htu = HTU21D();
// digital I/O pins
//const byte WSPEED = 3;
//const byte RAIN = 2;
const byte STAT1 = 7;
const byte STAT2 = 8;

// analog I/O pins
const byte REFERENCE_3V3 = A3;
const byte LIGHT = A1;
const byte BATT = A2;
//const byte WDIR = A0;

int WDIR = A0;
int RAIN = D2;
int WSPEED = D3;

//Global Variables
float pascals = 0;
float altf = 0;
float baroTemp = 0;

int sensorValue = 0;
int sensorPin = A1; // For soil moisture sensor
int count = 0;

int thresholdUp = 400;
int thresholdDown = 250;

int val = 0;//variable to store soil value
int soil = A1;//Declare a variable for the soil moisture sensor 
int soilPower = D5;//Variable for Soil moisture Power

//Global Variables
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
long lastSecond; //The millis counter to see when a second rolls by
byte seconds; //When it hits 60, increase the current minute
byte seconds_2m; //Keeps track of the "wind speed/dir avg" over last 2 minutes array of data
byte minutes; //Keeps track of where we are in various arrays of data
byte minutes_10m; //Keeps track of where we are in wind gust/dir over last 10 minutes array of data

long lastWindCheck = 0;
volatile long lastWindIRQ = 0;
volatile byte windClicks = 0;

//We need to keep track of the following variables:
//Wind speed/dir each update (no storage)
//Wind gust/dir over the day (no storage)
//Wind speed/dir, avg over 2 minutes (store 1 per second)
//Wind gust/dir over last 10 minutes (store 1 per minute)
//Rain over the past hour (store 1 per minute)
//Total rain over date (store one per day)

byte windspdavg[120]; //120 bytes to keep track of 2 minute average

#define WIND_DIR_AVG_SIZE 120
int winddiravg[WIND_DIR_AVG_SIZE]; //120 ints to keep track of 2 minute average
float windgust_10m[10]; //10 floats to keep track of 10 minute max
int windgustdirection_10m[10]; //10 ints to keep track of 10 minute max
volatile float rainHour[60]; //60 floating numbers to keep track of 60 minutes of rain

//These are all the weather values that wunderground expects:
int winddir = 0; // [0-360 instantaneous wind direction]
float windspeedmph = 0; // [mph instantaneous wind speed]
float windgustmph = 0; // [mph current wind gust, using software specific time period]
int windgustdir = 0; // [0-360 using software specific time period]
float windspdmph_avg2m = 0; // [mph 2 minute average wind speed mph]
int winddir_avg2m = 0; // [0-360 2 minute average wind direction]
float windgustmph_10m = 0; // [mph past 10 minutes wind gust mph ]
int windgustdir_10m = 0; // [0-360 past 10 minutes wind gust direction]
float humidity = 0; // [%]
float tempf = 0; // [temperature F]
float rainin = 0; // [rain inches over the past hour)] -- the accumulated rainfall in the past 60 min
volatile float dailyrainin = 0; // [rain inches so far today in local time]
float batt_lvl = 11.8; //[analog value from 0 to 1023]
float light_lvl = 455; //[analog value from 0 to 1023]


void callback(char* topic, byte* payload, unsigned int length);

volatile unsigned long raintime, rainlast, raininterval, rain;

MQTT client("192.168.0.102", 1883, callback);


MPL3115A2 baro = MPL3115A2();//create instance of MPL3115A2 barrometric sensor

void rainIRQ()
// Count rain gauge bucket tips as they occur
// Activated by the magnet and reed switch in the rain gauge, attached to input D2
{
    
	raintime = millis(); // grab current time
	raininterval = raintime - rainlast; // calculate interval between this and last event

	if (raininterval > 2) // ignore switch-bounce glitches less than 10mS after initial edge
	{
		dailyrainin += 0.011; //Each dump is 0.011" of water
		rainHour[minutes] += 0.011; //Increase this minute's amount of rain

		rainlast = raintime; // set up for next event
	}
}

void wspeedIRQ()
// Activated by the magnet in the anemometer (2 ticks per rotation), attached to input D3
{
    
	if (millis() - lastWindIRQ > 3) // Ignore switch-bounce glitches less than 10ms (142MPH max reading) after the reed switch closes
	{
	    //client.publish("/eco, \"dailyrainin\":%fn/spark/temperature","wspeedIRQ");
		lastWindIRQ = millis(); //Grab the current time
		windClicks++; //There is 1.492MPH for each click per second.
	}
}

//Calculates each of the variables that wunderground is expecting
void calcWeather()
{
	
	//Calc windspeed
	windspeedmph = get_wind_speed();
	
	//Calc winddir
	winddir = get_wind_direction();
        

	//Calc windgustmph
    //Calc windgustdir
    //Report the largest windgust today
    windgustmph = 0;
    windgustdir = 0;

    //Calc windspdmph_avg2m
    float temp = 0;
    for(int i = 0 ; i < 120 ; i++)
      temp += windspdavg[i];
    temp /= 120.0;
    windspdmph_avg2m = temp;

    //Calc winddir_avg2m
    temp = 0; //Can't use winddir_avg2m because it's an int
    for(int i = 0 ; i < 120 ; i++)
      temp += winddiravg[i];
    temp /= 120;
    winddir_avg2m = temp;

    //Calc windgustmph_10m
    //Calc windgustdir_10m
    //Find the largest windgust in the last 10 minutes
    windgustmph_10m = 0;
    windgustdir_10m = 0;
    //Step through the 10 minutes
    for(int i = 0; i < 10 ; i++)
    {
      if(windgust_10m[i] > windgustmph_10m)
      {
        windgustmph_10m = windgust_10m[i];
        windgustdir_10m = windgustdirection_10m[i];
      }
    }

    //Total rainfall for the day is calculated within the interrupt
    //Calculate amount of rainfall for the last 60 minutes
    rainin = 0;
    for(int i = 0 ; i < 60 ; i++)
      rainin += rainHour[i];
}

//Returns the voltage of the light sensor based on the 3.3V rail
//This allows us to ignore what VCC might be (an Arduino plugged into USB has VCC of 4.5 to 5.2V)
float get_light_level()
{
	float operatingVoltage = analogRead(REFERENCE_3V3);

	float lightSensor = analogRead(LIGHT);

	operatingVoltage = 3.3 / operatingVoltage; //The reference voltage is 3.3V

	lightSensor = operatingVoltage * lightSensor;

	return(lightSensor);
}

//Returns the voltage of the raw pin based on the 3.3V rail
//This allows us to ignore what VCC might be (an Arduino plugged into USB has VCC of 4.5 to 5.2V)
//Battery level is connected to the RAW pin on Arduino and is fed through two 5% resistors:
//3.9K on the high side (R1), and 1K on the low side (R2)
float get_battery_level()
{
	float operatingVoltage = analogRead(REFERENCE_3V3);

	float rawVoltage = analogRead(BATT);

	operatingVoltage = 3.30 / operatingVoltage; //The reference voltage is 3.3V

	rawVoltage = operatingVoltage * rawVoltage; //Convert the 0 to 1023 int to actual voltage on BATT pin

	rawVoltage *= 4.90; //(3.9k+1k)/1k - multiple BATT voltage by the voltage divider to get actual system voltage

	return(rawVoltage);
}

//Returns the instataneous wind speed
float get_wind_speed()
{
    
	float deltaTime = millis() - lastWindCheck; //750ms
    //char test[255];
    
    //sprintf(test,"windClicks %d",windClicks);             
	deltaTime /= 1000.0; //Covert to seconds
    //client.publish("/econ/spark/temperature",test);
	float windSpeed = (float)windClicks / deltaTime; //3 / 0.750s = 4

	windClicks = 0; //Reset and start watching for new wind
	lastWindCheck = millis();
    //sprintf(test,"windClicks %d",windClicks);
    // client.publish("/econ/spark/temperature",test);
	windSpeed *= 1.492; //4 * 1.492 = 5.968MPH

	/* Serial.println();
	 Serial.print("Windspeed:");
	 Serial.println(windSpeed);*/

	return(windSpeed);
}

//Read the wind direction sensor, return heading in degrees
/*
int get_wind_direction()
{
	unsigned int adc;

	adc = analogRead(WDIR); // get the current reading from the sensor
	// The following table is ADC readings for the wind direction sensor output, sorted from low to high.
	// Each threshold is the midpoint between adjacent headings. The output is degrees for that ADC reading.
	// Note that these are not in compass degree order! See Weather Meters datasheet for more information.

	if (adc < 380) return (113);
	if (adc < 393) return (68);
	if (adc < 414) return (90);
	if (adc < 456) return (158);
	if (adc < 508) return (135);
	if (adc < 551) return (203);
	if (adc < 615) return (180);
	if (adc < 680) return (23);
	if (adc < 746) return (45);
	if (adc < 801) return (248);
	if (adc < 833) return (225);
	if (adc < 878) return (338);
	if (adc < 913) return (0);
	if (adc < 940) return (293);
	if (adc < 967) return (315);
	if (adc < 990) return (270);
	return (-1); // error, disconnected?
}
*/
//Read the wind direction sensor, return heading in degrees
int get_wind_direction()
{
  unsigned int adc;

  adc = analogRead(WDIR); // get the current reading from the sensor

  // The following table is ADC readings for the wind direction sensor output, sorted from low to high.
  // Each threshold is the midpoint between adjacent headings. The output is degrees for that ADC reading.
  // Note that these are not in compass degree order! See Weather Meters datasheet for more information.

  //Wind Vains may vary in the values they return. To get exact wind direction,
  //it is recomended that you AnalogRead the Wind Vain to make sure the values
  //your wind vain output fall within the values listed below.
  if(adc > 2270 && adc < 2290) return (0);//North
  if(adc > 3220 && adc < 3299) return (1);//NE
  if(adc > 3890 && adc < 3999) return (2);//East
  if(adc > 3780 && adc < 3850) return (3);//SE

  if(adc > 3570 && adc < 3650) return (4);//South
  if(adc > 2790 && adc < 2850) return (5);//SW
  if(adc > 1580 && adc < 1610) return (6);//West
  if(adc > 1930 && adc < 1950) return (7);//NW

  return (-1); // error, disconnected?
}
    
// recieve message
void callback(char* topic, byte* payload, unsigned int length) {
    char p[length + 1];
    memcpy(p, payload, length);
    p[length] = NULL;
   /* String message(p);

    if (message.equals("RED"))    
        RGB.color(255, 0, 0);
    else if (message.equals("GREEN"))    
        RGB.color(0, 255, 0);
    else if (message.equals("BLUE"))    
        RGB.color(0, 0, 255);
    else    
        RGB.color(255, 255, 255);
    delay(1000);*/
}
//---------------------------------------------------------------
void setup()
{
//    Serial.begin(9600);   // open serial over USB at 9600 baud
    
     client.connect("192.168.0.102");

    // publish/subscribe
    if (client.isConnected()) {
        client.publish("/econ/temp","MergedApp");
        client.subscribe("/econ/test");
    }
    //Spark.publish("beamStatus","intact",60,PRIVATE);
    //Initialize
  	while(! baro.begin()) {
  	    client.publish("/econ/temp","InLoop");
//          Serial.println("MPL3115A2 not found");
          delay(1000);
     }
     client.publish("/econ/temp","OutLoop");
//     Serial.println("MPL3115A2 OK");
     //MPL3115A2 Settings
     //baro.setModeBarometer();//Set to Barometer Mode
     baro.setModeAltimeter();//Set to altimeter Mode
     
     baro.setOversampleRate(7); // Set Oversample to the recommended 128
     baro.enableEventFlags(); //Necessary register calls to enble temp, baro ansd alt
    
    //weather shield 
    pinMode(WSPEED, INPUT_PULLUP); // input from wind meters windspeed sensor
	pinMode(RAIN, INPUT_PULLUP); // input from wind meters rain gauge sensor
	
	pinMode(WDIR, INPUT); // input from Wind direction pin

	seconds = 0;
	lastSecond = millis();

	// attach external interrupt pins to IRQ functions
	attachInterrupt(RAIN, rainIRQ, FALLING);
	attachInterrupt(WSPEED, wspeedIRQ, FALLING);
	
	//attachInterrupt(0, rainIRQ, FALLING);
	//attachInterrupt(1, wspeedIRQ, FALLING);
	
	//Humidity
/*	while(! htu.begin()){
	    Serial.println("HTU21D not found");
	    delay(1000);
	}*/

	// turn on interrupts
	interrupts();

}
//---------------------------------------------------------------
void loop()
{
    if (client.isConnected())
    {
       
        client.loop();
        delay(1000);
        //Get readings from sensor
        getBaro();
        
       // humidity = htu.readHumidity();
        //Rather than use a delay, keeping track of a counter allows the photon to
        //still take readings and do work in between printing out data.
         count++;
        //alter this number to change the amount of time between each reading
       
        //----------------------------------
         if(millis() - lastSecond >= 1000)
    	{
    		
        
            lastSecond += 1000;
    
    		//Take a speed and direction reading every second for 2 minute average
    		if(++seconds_2m > 119) seconds_2m = 0;
    
    		//Calc the wind speed and direction every second for 120 second to get 2 minute average
    		float currentSpeed = windspeedmph;
    		//float currentSpeed = random(5); //For testing
    		int currentDirection = get_wind_direction();
    		windspdavg[seconds_2m] = (int)currentSpeed;
    		winddiravg[seconds_2m] = currentDirection;
    		//if(seconds_2m % 10 == 0) displayArrays(); //For testing
    
    		//Check to see if this is a gust for the minute
    		if(currentSpeed > windgust_10m[minutes_10m])
    		{
    			windgust_10m[minutes_10m] = currentSpeed;
    			windgustdirection_10m[minutes_10m] = currentDirection;
    		}
    
    		//Check to see if this is a gust for the day
    		if(currentSpeed > windgustmph)
    		{
    			windgustmph = currentSpeed;
    			windgustdir = currentDirection;
    		}
    
    		if(++seconds > 59)
    		{
    			seconds = 0;
    
    			if(++minutes > 59) minutes = 0;
    			if(++minutes_10m > 9) minutes_10m = 0;
    
    			rainHour[minutes] = 0; //Zero out this minute's rainfall amount
    			windgust_10m[minutes_10m] = 0; //Zero out this minute's gust
    		}
    	}
        calcWeather();
        //----------------------------------
        if(count == 5)//prints roughly every 10 seconds for every 5 counts
        {
            printInfo();
            count = 0;
        }
    }
}
//---------------------------------------------------------------
void printInfo()
{
//This function prints the weather data out to the default Serial Port

    //Take the temp reading from each sensor and average them.
 //  / Serial.print("Baro Temp: ");
 //   Serial.print(baroTemp);
    //Spark.publish("Temparature",String(baroTemp));
    //Serial.print("F, ");

    //Serial.print("Pressure:");
    //Serial.print(pascals);
    //Serial.print("Pa, ");
    
    // String baroStr = String(baroTemp, 1); // "30.5"
    // calcWeather();
    char buffer[512];
    // // snprintf(buffer, sizeof(buffer), "{\"Temperature\":" + baroStr + "}");
    /*
    Serial.println();
	Serial.print("$,winddir=");
	Serial.print(winddir);
	Serial.print(",windspeedmph=");
	Serial.print(windspeedmph, 1);
	Serial.print(",windgustmph=");
	Serial.print(windgustmph, 1);
	Serial.print(",windgustdir=");
	Serial.print(windgustdir);
	Serial.print(",windspdmph_avg2m=");
	Serial.print(windspdmph_avg2m, 1);
	Serial.print(",winddir_avg2m=");
	Serial.print(winddir_avg2m);
	Serial.print(",windgustmph_10m=");
	Serial.print(windgustmph_10m, 1);
	Serial.print(",windgustdir_10m=");
	Serial.print(windgustdir_10m);
	Serial.print(",humidity=");
	Serial.print(humidity, 1);
	Serial.print(",tempf=");
	Serial.print(tempf, 1);
	Serial.print(",rainin=");
	Serial.print(rainin, 2);
	Serial.print(",dailyrainin=");
	Serial.print(dailyrainin, 2);
	Serial.print(",pressure=");
	Serial.print(pressure, 2);
	Serial.print(",batt_lvl=");
	Serial.print(batt_lvl, 2);
	Serial.print(",light_lvl=");
	Serial.print(light_lvl, 2);
	Serial.print(",");
	Serial.println("#");
    */
    sprintf(buffer, "{\"Temp\": \"%f\", \"Pres\": \"%f\", \"SM\": \"%d\", \"WS\": \"%f\", \"WD\": \"%f\", \"Rain\": \"%d\"}", baroTemp, pascals, readSoil(),windspeedmph,winddir,dailyrainin);
    //sprintf(buffer, "{ \"Soil Moisture\": %d, \"windspeedmph\":%f, \"winddirection\":%f, \"rainin\":%d}", readSoil(),windspeedmph,winddir,dailyrainin);

    client.publish("/econ/spark/temperature", buffer);
    //Serial.print("Altitude:");
    //Serial.print(altf);
    //Serial.println("ft.");

}
int readSoil()
{
    digitalWrite(soilPower, HIGH);//turn D6 "On"
    delay(10);//wait 10 milliseconds 
    val = analogRead(soil);
    digitalWrite(soilPower, LOW);//turn D6 "Off"
    return val;
}
//---------------------------------------------------------------
void getBaro()
{
  baroTemp = baro.readTempF();//get the temperature in F

  pascals = baro.readPressure();//get pressure in Pascals

  altf = baro.readAltitudeFt();//get altitude in feet
}
//---------------------------------------------------------------


Update:
I’m able to get the Wind Direction values but still not able to get rain gauge value. The issue I’m facing is, whenever Rain gauge generates an interrupt, my device(Photon) freezes and I’ve to restart the kit to make it working again. Any solution for this?

@ramprasad.rp A few things I am noticing as I go though this. (using the sparkfun library as the reference that I have gotten everything to work with)

I don’t see this include statement #include “SparkFun_Photon_Weather_Shield_Library/SparkFun_Photon_Weather_Shield_Library.h”

I also do not see a lot of the initalization commands to get the sensors reading in your setup like so

  Serial.begin(9600);

 //Initialize the I2C sensors and ping them
 sensor.begin();

 /*You can only receive acurate barrometric readings or acurate altitiude
 readings at a given time, not both at the same time. The following two lines
 tell the sensor what mode to use. You could easily write a function that
 takes a reading in one made and then switches to the other mode to grab that
 reading, resulting in data that contains both acurate altitude and barrometric
 readings. For this example, we will only be using the barometer mode. Be sure
 to only uncomment one line at a time. */

 sensor.setModeBarometer();//Set to Barometer Mode

 //baro.setModeAltimeter();//Set to altimeter Mode
 //These are additional MPL3115A2 functions the MUST be called for the sensor to work.
 sensor.setOversampleRate(7); // Set Oversample rate
 //Call with a rate from 0 to 7. See page 33 for table of ratios.
 //Sets the over sample rate. Datasheet calls for 128 but you can set it
 //from 1 to 128 samples. The higher the oversample rate the greater
 //the time between data samples.
	
  delay(10000);

Is there a reason you omitted these?

Thanks. The header file you mentioned is for Altitude, Pressure and Barometer values for which I had no trouble in getting the readings. So I haven’t included the header file with my app. Also, I need only the Pressure value for my purpose.

@ramprasad.rp Ah okay, What does your MyTemp.h look like? I am trying to test what you have on my end but I am missing the code for that file.

Here it is:

MyTemp.h

/*
 MPL3115A2 Barometric Pressure Sensor Library
 By: Nathan Seidle
 SparkFun Electronics
 Date: September 24th, 2013
 
 Updated for Particle by Joel Bartlett 
 SparkFun Electronics
 Date: June 30, 2015
 
 License: This code is public domain but you buy me a beer if you use this and we meet someday (Beerware license).

 Get pressure, altitude and temperature from the MPL3115A2 sensor.

 */


/*#if defined(ARDUINO) && ARDUINO >= 100
 #include "Arduino.h"
#else
 #include "WProgram.h"
#endif

#include <Wire.h>*/

#include "application.h"

#define MPL3115A2_ADDRESS 0x60 // Unshifted 7-bit I2C address for sensor

#define STATUS     0x00
#define OUT_P_MSB  0x01
#define OUT_P_CSB  0x02
#define OUT_P_LSB  0x03
#define OUT_T_MSB  0x04
#define OUT_T_LSB  0x05
#define DR_STATUS  0x06
#define OUT_P_DELTA_MSB  0x07
#define OUT_P_DELTA_CSB  0x08
#define OUT_P_DELTA_LSB  0x09
#define OUT_T_DELTA_MSB  0x0A
#define OUT_T_DELTA_LSB  0x0B
#define WHO_AM_I   0x0C
#define F_STATUS   0x0D
#define F_DATA     0x0E
#define F_SETUP    0x0F
#define TIME_DLY   0x10
#define SYSMOD     0x11
#define INT_SOURCE 0x12
#define PT_DATA_CFG 0x13
#define BAR_IN_MSB 0x14
#define BAR_IN_LSB 0x15
#define P_TGT_MSB  0x16
#define P_TGT_LSB  0x17
#define T_TGT      0x18
#define P_WND_MSB  0x19
#define P_WND_LSB  0x1A
#define T_WND      0x1B
#define P_MIN_MSB  0x1C
#define P_MIN_CSB  0x1D
#define P_MIN_LSB  0x1E
#define T_MIN_MSB  0x1F
#define T_MIN_LSB  0x20
#define P_MAX_MSB  0x21
#define P_MAX_CSB  0x22
#define P_MAX_LSB  0x23
#define T_MAX_MSB  0x24
#define T_MAX_LSB  0x25
#define CTRL_REG1  0x26
#define CTRL_REG2  0x27
#define CTRL_REG3  0x28
#define CTRL_REG4  0x29
#define CTRL_REG5  0x2A
#define OFF_P      0x2B
#define OFF_T      0x2C
#define OFF_H      0x2D

class MPL3115A2 {

public:
  MPL3115A2();

  //Public Functions
  bool begin(); // Gets sensor on the I2C bus.
  float readAltitude(); // Returns float with meters above sealevel. Ex: 1638.94
  float readAltitudeFt(); // Returns float with feet above sealevel. Ex: 5376.68
  float readPressure(); // Returns float with barometric pressure in Pa. Ex: 83351.25
  float readTemp(); // Returns float with current temperature in Celsius. Ex: 23.37
  float readTempF(); // Returns float with current temperature in Fahrenheit. Ex: 73.96
  void setModeBarometer(); // Puts the sensor into Pascal measurement mode.
  void setModeAltimeter(); // Puts the sensor into altimetery mode.
  void setModeStandby(); // Puts the sensor into Standby mode. Required when changing CTRL1 register.
  void setModeActive(); // Start taking measurements!
  void setOversampleRate(byte); // Sets the # of samples from 1 to 128. See datasheet.
  void enableEventFlags(); // Sets the fundamental event flags. Required during setup.

  //Public Variables

private:
  //Private Functions

  void toggleOneShot();
  byte IIC_Read(byte regAddr);
  void IIC_Write(byte regAddr, byte value);

  //Private Variables

};

:+1:

@ramprasad.rp Thanks for providing me that. If you don’t mind me asking, what do you have it reporting to? I see its reporting out to that IP but I am assuming you are seeing this info from the photon logs?

@ramprasad.rp, if you uncomment the Serial.print() statements, does the publish buffer get constructed correctly (with all the values showing as expected)?

My main objective is to experiment with the MQTT protocol, and for that I’m sending this data to another device(PC) running MQTT. I just parse and store the data there. :smile:

Back to the topic, do you see any issue with the code?

I will check and let you know as I don’t have my kit right now to know the output. But I think there shouldn’t be any problem with that.

@ramprasad.rp I am looking into it now, just have some errors to fix when trying to build the code. once I get those fixed I will let you know what I find since if its not the included libraries issue, then it must be something in the code.

Hi, feel free to use this code as reference. Works well. -Rob

1 Like

Update 2: Finally, I’m able to get the Rain Gauge value after removing the rainHour[minutes] value within the “rainIRQ” interrupt handler function. I don’t know the reason, but it’s working now.

Can someone please tell me what caused the problem?

void rainIRQ()
// Count rain gauge bucket tips as they occur
// Activated by the magnet and reed switch in the rain gauge, attached to input D2
{
    
	raintime = millis(); // grab current time
	raininterval = raintime - rainlast; // calculate interval between this and last event

	if (raininterval > 2) // ignore switch-bounce glitches less than 10mS after initial edge
	{
		dailyrainin += 0.011; //Each dump is 0.011" of water
		// rainHour[minutes] += 0.011; //Increase this minute's amount of rain

		rainlast = raintime; // set up for next event
	}
}

It seems that minutes is never initialized. Try to set the value to 0 at the beginning, or in setup().

1 Like

hello,
i have a photon weather shield and i am struggling to make it work using this code with mqtt, any one managed to compile this please share it
Thank you.

Hello,

I am also having issues getting this to compile.
@ramprasad.rp are you still using this code?

Jay