Photon Cyan steady (problem in code)

Hi all,

I have problem with many devices in similar code I use for Temp monitoring.
The project working normally for 3 days, then it stuck with steady cyan LED color.
I don’t know if I have problem in my code or there is some thing need to do in the firmware.

#include <SparkFunBME280.h>
#include <SparkFunMicroOLED.h>

////////////////////
//Webhook
///////////////////
#include <MQTT.h>

char mqttUserName[] = "TSPhotonMQTTDemo";    // Can be any name.
char mqttPass[] = "IXCSWCYXXXX0QW3I";        // Change this to your MQTT API Key from Account > MyProfile.
char writeAPIKey[] = "EDDSVF21R52FXXXX";     // Change this to your channel Write API Key.
long channelID = 666123;                    // Change this to your channel number.
char server[] = "mqtt.thingspeak.com";       // Define the ThingSpeak MQTT broker
int led =D7;

static const char alphanum[] ="0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";  // This variable is used for random generation of client ID.

// Define a callback function to initialize the MQTT client.
void callback(char* topic, byte* payload, unsigned int length) {
}

MQTT client(server, 1883, callback);       // Initialize the MQTT client.

unsigned long lastConnectionTime = 0;
const unsigned long postingInterval = 600L * 1000L; // Post data every 300 seconds.

MicroOLED oled;

// This sketch uses the MicroOLED library to draw a 3-D projected
 // cube, and rotate it along all three axes.
 // 
 // Development environment specifics:
 //  Arduino 1.0.5
 //  Arduino Pro 3.3V
 //  Micro OLED Breakout v1.0
 // 
 // 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 <SPI.h>  // Include SPI if you're using SPI

//////////////////////////
// MicroOLED Definition //
//////////////////////////
#define PIN_RESET D7   // Connect RST to pin D7 (SPI & I2C)
#define PIN_DC    D6  // Connect DC to pin A4 (SPI only)
#define PIN_CS    A2 // Connect CS to pin D3 (SPI only)

BME280 MySensor1;


// connect SCK to pin A3
// Connect SDL to pin A5

//////////////////////////////////
// MicroOLED Object Declaration //
//////////////////////////////////
//MicroOLED oled(PIN_RESET, PIN_DC, PIN_CS);  // SPI Example

void setup()
{
  oled.begin();     // Initialize the OLED
  oled.clear(PAGE);// Clear the display's internal memory
  oled.clear(ALL);  // Clear the library's display buffer
  
  oled.setCursor(0, 0);
  oled.setFontType(1); // Set the text to medium (6 columns, 3 rows worth of characters).
  oled.print("Welcome ");
  oled.print("Sodexo|Hestia");
  oled.display();   // Display what's in the buffer (splashscreen)

  delay(5000);
  oled.clear(PAGE);// Clear the display's internal memory
  oled.clear(ALL);  // Clear the library's display buffer
  

  oled.setCursor(0, 0);
  oled.setFontType(1); // Set the text to medium (6 columns, 3 rows worth of characters).
  oled.print("Tempmonitor ");
  oled.display();   // Display what's in the buffer (splashscreen)

  delay(5000);
  oled.clear(PAGE);// Clear the display's internal memory
  oled.clear(ALL);  // Clear the library's display buffer
  
  Serial.begin(9600);
  
  // Setup the BME Sensor
  
  //***Driver settings********************************
 
    //commInterface can be I2C_MODE or SPI_MODE
    //specify chipSelectPin using arduino pin names
    //specify I2C address.  Can be 0x77(default) or 0x76
    
  MySensor1.settings.commInterface = I2C_MODE;
  MySensor1.settings.I2CAddress = 0x77;
  
  

//***Operation settings*****************************//

    //runMode can be:
    //  0, Sleep mode
    //  1 or 2, Forced mode
    //  3, Normal mode
    MySensor1.settings.runMode = 3; //Normal Mode


    //tStandby can be:
    //  0, 0.5ms
    //  1, 62.5ms
    //  2, 125ms
    //  3, 250ms
    //  4, 500ms
    //  5, 1000ms
    //  6, 10ms
    //  7, 20ms
    MySensor1.settings.tStandby = 0;


    //filter can be off or number of FIR coefficients to use:
    //  0, filter off
    //  1, coefficients = 2
    //  2, coefficients = 4
    //  3, coefficients = 8
    //  4, coefficients = 16
    MySensor1.settings.filter = 0;// before 0


    //tempOverSample can be:
    //  0, skipped
    //  1 through 5, oversampling *1, *2, *4, *8, *16 respectively
    MySensor1.settings.tempOverSample = 1;//before 1


    //pressOverSample can be:
    //  0, skipped
    //  1 through 5, oversampling *1, *2, *4, *8, *16 respectively
    MySensor1.settings.pressOverSample = 0;// before 1

    //humidOverSample can be:
    //  0, skipped
    //  1 through 5, oversampling *1, *2, *4, *8, *16 respectively
    MySensor1.settings.humidOverSample = 1;

    delay(10);  //Make sure sensor had enough time to turn on. BME280 requires 2ms to start up.         
MySensor1.begin();
delay(8);
/////////////////////////////////

// Varulables 
////////////////////////////////



}

float Tin=0; //Tempruture 
float Tcal=1.0;
float H=0; // Humidity
int TD=5000; // Time Delay
 

int AltS=26.2; //Alert Setpoint.
int Alt= 0; //Alert output
int AD= 36000;   //Alert Delay 10hrs
int iA=0;


void loop()
{


///////////////////////
//      Webhook    ///
//////////////////////


 // If MQTT client is not connected then reconnect.
    if (!client.isConnected())
    {
        TempRead();
        Serial.println("Connection lost...");
      reconnect();
      
    }
    
    client.loop();  // Call the loop continuously to establish connection to the server.
    
    if (millis() - lastConnectionTime > postingInterval)
    {
        TempRead();
        Alert();
        mqttpublish();
    }
   
   // show in LCD every 2 second 
    delay(2000);
    TempRead();
    
    
}  // end loop



//////////////////////////////
////   Reconnection to MQTT ///
//////////////////////////////


void reconnect(){
    
     char clientID[9];
     
     Serial.println("Attempting MQTT connection");
     // Generate ClientID
     for (int i = 0; i < 8; i++) {
         clientID[i] = alphanum[random(51)];
     }
     clientID[8]='\0';
     Serial.println(clientID);// Add by MS
     
        
     // Connect to the ThingSpeak MQTT broker.
     if (client.connect(clientID,mqttUserName,mqttPass))  {
         Particle.publish("Conn:"+ String(server) + " cl: " + String(clientID)+ " Uname:" + String(mqttUserName));
     } else
     {
         Particle.publish("Failed to connect, Trying to reconnect in 5 seconds");
         Serial.println("Failed to connect Trying to reconnect in 5 seconds...");// Add by MS
         TempRead();
         delay(1000);
     } 
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


////////////////////////////
////   Publish MQTT  ///////
///////////////////////////


void mqttpublish() {
    
    String Temp = String(Tin);
    String HT = String(H);
    String ALERT= String(Alt);
   // String PR = String(Pout);
    //String AMP = String(Pdif);
   // String AMP2 = String(random(60,80));
    
    
    
    // Create data string to send data to ThingSpeak.
    // Use these lines to publish to a channel feed,
    // which allows multiple fields to be updates simultaneously.
    // Comment these lines and use the next two to publish to a single channel field directly.
    String data = String("field1=" + String(Temp) + "&field2=" + String(HT)+"&field3=" + String(ALERT));
    String topic = String("channels/"+String(channelID)+ "/publish/"+String(writeAPIKey));
    
    //String data=String(t);
    //String topic = String("channels/"+String(channelID)+ "/publish/fields/field1/"+String(writeAPIKey));
    
    client.publish(topic,data);
    
    lastConnectionTime = millis();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////
///   Alert Delay and output    ///
//////////////////////////////////

void Alert(){
if (Tin >=AltS && iA>=0)
{
    iA++;
    Alt=0;
    delay(1000);
}

if (Tin>=AltS && iA==3)

{
Alt=1;
}

if (Tin>=AltS && iA>AD)
{
    iA=0;
}

}//end Alert
////////////////////////////////////////////////////////////////////////////////////////////////////



///////////////////////////////////////
///   Take Reading and Display   /////
//////////////////////////////////////


void TempRead(){

Tin = MySensor1.readTempC()-Tcal;
H=MySensor1.readFloatHumidity();

///////////////////////////////////
// Serial print
//////////////////////////////////

Serial.println("Tempreture        Humidity ");
Serial.print(Tin);
Serial.print("             ");

Serial.println(H);


//////////////////////
// OLED Display
/////////////////////
 // oled.pixel(LCDWIDTH/2, LCDHEIGHT/2); // Add a pixel to the display buffer.


oled.clear(PAGE);
//delay(3000);
oled.setCursor(0, 0);  // Set the text cursor to the upper-left of the screen.
oled.setFontType(2);
oled.print(Tin,1);
oled.setFontType(1);
oled.println(" C");

oled.setFontType(2);
oled.print(H,1);
oled.setFontType(1);
oled.println(" %");


oled.display(); // Draw to the screen


}// end TempRead

///////////////////////////////////////////////

Could you please provide the device log (but please remove your Device ID, ICCID, etc)? What device OS are you using? When you say it’s steady cyan, does that mean blinking or just solid Cyan?

How I get device log?

Device OS: 2.1.0
I mean it is solid Cyan.

Hi,
Try to use SYSTEM_THREAD(ENABLED) in your code and initialize your MQTT client like this:

MQTT client("server", 1883, callback, true); (more info about 4th par here )

also try to get rid of all of your String use snprintf() instead

example of using snprintf() on onlinegdb

#include <iostream>

using namespace std;

float Tin = 2.33897; //Tempruture 
float H = 87.45; // Humidity
int alret = 5; // Alret

const char env_template[] = "\"field1=\"%.2f,\"&field2=\"%.2f,\"&field3=\"%d";
char data[sizeof(env_template) + 32 ];

void mqttpublish() 
{
snprintf(data, sizeof(data), env_template, Tin, H, alret );   
}

int main()
{
    mqttpublish();
    cout<<"env data "<<data;

    return 0;
}

results:

1 Like

Hi @Lahmdi -

Have you managed to to resolve this? Here is what my approach would be; I would use the exact same code but strip all MQTT sections from it. Replace this with Particle.publish() instead and see of the same error occurs.

Of course this would not resolve the MQTT problem but might give you an alternative option?

My reason for suggesting this is that I have had no luck with MQTT so far. To the point where I gave up on trying to use it. Please note I am by no means a great coder, but I have not been able to get it to work without incidents. When using Particle.publish() however, the same code runs hassle free :see_no_evil: :grinning_face_with_smiling_eyes: :exploding_head:

Cheers! Friedl.

Hi @friedl_1977

I don’t have any issue running MQTT client on my photons and mosquitto broker on Rpi3 for 3 month already.
also MQTT has some benefits which Particle.publish() doesn’t

1.is not limited by data operation
2.is not limited to 1 publish per sec or burst of 4

1 Like

I fully understand yes. For me it would just be a quick way to see whether the problem lies within the "publishing code", or elsewhere.

Funny, Mosquito was also the broker I used, no luck. Did get tit to work once on Arduino before I moved to Particle. I was most likely my code then :relaxed:

Best of luck!
Regards.

1 Like

@dreamER
Thanks for your support. :grinning:
I try your code but doesn’t work!
Do we need to add write API key, channel number for this code and other details for this code.

Also, I can’t find iostream in particle IDE.
do I need to added it manually?

Apologize for my questions as I don’t have experience in programing.

Hi @friedl_1977
Actually, I connected MQTT to google sheet to display the current temp every 10 minuets. also, to work log the data.

I don’t know if Particle.publish() can do same.
here below the dashboard display.
It is working fine for 2 - 3 days and after that it getting photons stuck.

2 Likes

HI @Lahmdi

Nice!! :sunglasses:

I am not sure, not very familiar with Google products, but would think this is possible by using Webhooks? For UI I prefer to use @Ubidots You will also be able to send data to Google Sheets very easily using a service like Zapier

Personally I just have had no luck using combination of MQTT and Particle. This is only my experience though and have not even attempted to do this again in the last 2-3 years as I found alternatives :slight_smile: So I am by no means insinuating that it is not possible :sweat_smile:

Hope this helps!!
Regards,

Thanks @friedl_1977 :smiley:
I will read about Zapier and try it.

Best Regards,

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.