Blynk keeps disconnecting when reading light sensor value (CQ Robot light sensor)

I have tracked it down to the code used to read a light sensor lux value.

void TSL2591_Enable(void)
{
    TSL2591_Write_Byte(ENABLE_REGISTER, \
    ENABLE_AIEN | ENABLE_POWERON | ENABLE_AEN | ENABLE_NPIEN);
}

just calling

TSL2591_Enable();
TSL2591_Disable();

is enough to cause the Blynk connection to be lost randomly. Normally within a minute.

I am reading the value every 10 seconds.

If I do not read the light value the issue goes away.

I am new to this and both use the I2C channel. Any thoughts?

I have the CQ Robot Light sensor.

Arduino uno WiFi Rev2
Blynk 0.6.1

library to read light sensor

Using the Blynk server
running App on iOS

Works

/* Comment this out to disable prints and save space */
#define BLYNK_PRINT Serial

#include <SPI.h>
//#include <Ethernet.h>
#include <WiFiNINA.h>
#include <BlynkSimpleWiFiNINA.h>
#include <EEPROM.h>
#include <avr/wdt.h>
#include <Adafruit_SSD1306.h>

char ssid[] = "XXX";     // the name of your network
char pass[] = "XXX";   //password of your WPA Network
char auth3[] = "XXX";

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
// The pins for I2C are defined by the Wire-library. 
// On an arduino UNO:       A4(SDA), A5(SCL)
// On an arduino MEGA 2560: 20(SDA), 21(SCL)
// On an arduino LEONARDO:   2(SDA),  3(SCL), ...
#define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);


void displayMessage(char *message)
{
  display.clearDisplay();
  display.setTextSize(2);      // Normal 1:1 pixel scale
  display.setTextColor(SSD1306_WHITE); // Draw white text
  display.cp437(true);         // Use full 256 char 'Code Page 437' font
  display.setCursor(0, 0);     // Start at top-left corner
  display.println(message);

  display.display();
}

BlynkTimer timer;

void myTimerEvent()
{
 if (Blynk.connected())
    displayMessage("Connected");
 else
    displayMessage("Lost connection");
 }

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

    // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if(!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
    Serial.println(F("SSD1306 allocation failed"));
    //for(;;); // Don't proceed, loop forever
  }

  Serial.println(F("SSD1306 allocation succeded"));

  display.display();

  displayMessage("Connecting...");

  Blynk.begin(auth3, ssid, pass);

  timer.setInterval(1000L, myTimerEvent);

  displayMessage("Ready");
}

void loop() {
  // put your main code here, to run repeatedly:

   Blynk.run();
   timer.run();
}

Does not work, when I read the lux value (There were other changes, they did not make a difference)

void myTimerEvent()
{
 if (Blynk.connected())
    displayMessage("Connected");
 else
    displayMessage("Lost connection");

    Lux = TSL2591_Read_Lux();
    Serial.print("Lux = ");
    Serial.print(Lux);
    Serial.print("\r\n");
    TSL2591_SET_LuxInterrupt(50,200);
 }

@johnhmccauley please edit your post, using the pencil icon at the bottom, and add triple backticks at the beginning and end of your code so that it displays correctly.
Triple backticks look like this:
```

Pete.

@johnhmccauley you’ve edited your post, but used different characters than the ones I provided for you to copy/paste!

Pete.

Sorry, realized that and fixed it.

Perhaps post full code that doesn’t work… else impossible to see what you might be missing or misconfigured… as in I do not see TSL2591_Init(); and other needed stuff anywhere.

Have you tested your sensor without Blynk?

Yes, works fine. Also works with Blynk, just causes the connection to fail.

/* Comment this out to disable prints and save space */
#define BLYNK_PRINT Serial

#include <SPI.h>
//#include <Ethernet.h>
#include <WiFiNINA.h>
#include <BlynkSimpleWiFiNINA.h>
#include <EEPROM.h>
#include <avr/wdt.h>
#include <Adafruit_SSD1306.h>
#include "DEV_Config.h"
#include "TSL2591.h"

char ssid[] = "xxx";     // the name of your network
char pass[] = "xxx";   //password of your WPA Network
char auth3[] = "xxx";

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
// The pins for I2C are defined by the Wire-library. 
// On an arduino UNO:       A4(SDA), A5(SCL)
// On an arduino MEGA 2560: 20(SDA), 21(SCL)
// On an arduino LEONARDO:   2(SDA),  3(SCL), ...
#define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

UWORD lux = 0;

void displayMessage(char *message)
{
  display.clearDisplay();
  display.setTextSize(2);      // Normal 1:1 pixel scale
  display.setTextColor(SSD1306_WHITE); // Draw white text
  display.cp437(true);         // Use full 256 char 'Code Page 437' font
  display.setCursor(0, 0);     // Start at top-left corner
  display.println(message);

  display.display();
}

BlynkTimer timer;

void myTimerEvent()
{
 if (Blynk.connected())
    displayMessage("Connected");
 else
    displayMessage("Lost connection");

    lux = TSL2591_Read_Lux();
    Serial.print("Lux = ");
    Serial.print(lux);
    Serial.print("\n");
    TSL2591_SET_LuxInterrupt(50,200);
 }

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

    // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if(!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
    Serial.println(F("SSD1306 allocation failed"));
    //for(;;); // Don't proceed, loop forever
  }

  Serial.println(F("SSD1306 allocation succeded"));

  DEV_ModuleInit();
  Serial.println("TSL2591_Init");
  TSL2591_Init();


  display.display();

  displayMessage("Connecting...");

  Blynk.begin(auth3, ssid, pass);

  timer.setInterval(1000L, myTimerEvent);

  displayMessage("Ready");
}

void loop() {
  // put your main code here, to run repeatedly:

   Blynk.run();
   timer.run();
}

Just did some random Googling about that sensor, and one thing that came across is that it can take a but of time to run the full spectrum scan (one article stated up to 600ms). And of course there are other things running as well.

Try giving your code a bit more “maneuvering” room and increase the timer to 1.5 or 2 seconds

Will try that. In the real app the timer is 10s.

Also trying Adafruit library.

Was getting the same issue.

Just failed with 2s.

Also I did try just doing the enable and disable. So no read.

The problem is when this function is called

/******************************************************************************
function:	Send one byte of data to TSL2591 via I2C
parameter:
            Addr: Register address
           Value: Write to the value of the register
Info:
******************************************************************************/
static void TSL2591_Write_Byte(UBYTE Addr, UBYTE Value)
{
    Addr = Addr | COMMAND_BIT;
    I2C_Write_Byte(Addr, Value);
}

Some how it is conflicting with the WiFi module on my Arduino Uno WiFi Rev2.

You have included the AVR watchdog, but dont appear to be using it…

unless there’s something happening in here that you haven’t shared…

Personally, I’s start by stripping everything back to basics…
Start with a simple Blynk sketch that does nothing other than connect and have Blynk.run in the void loop. Ensure that this stays online without any problems.

Then add-in your light sensor library , a timer, and a function to take a reading and send it to Blynk ad to your serial monitor.

If this works then add-in some of the other stuff until you find the culprit.

Pete.

I added #define BLYNK_DEBUG

The error message I get is Packet too big.

Any ideas?

Took an example, worked for 12+ hours. Added just reading the light sensor and writing the value, failed after a while.

/****************************************************************************************************************************
  UNO_WiFiNINA.ino
  For AVR UNO WiFi Rev2 boards using WiFiNINA Shields

  For AVR Mega boards using WiFiNINA Shields

  Blynk_WiFiNINA_WM is a library for the Mega, Teensy, SAM DUE, nRF52, STM32, SAMD and RP2040 boards 
  (https://github.com/khoih-prog/Blynk_WiFiNINA_WM) to enable easy configuration/reconfiguration and
  autoconnect/autoreconnect of WiFiNINA/Blynk

  Modified from Blynk library v0.6.1 https://github.com/blynkkk/blynk-library/releases
  Built by Khoi Hoang https://github.com/khoih-prog/Blynk_WiFiNINA_WM
  Licensed under MIT license

  Original Blynk Library author:
  @file       BlynkSimpleWiFiNINA.h
  @author     Volodymyr Shymanskyy
  @license    This project is released under the MIT License (MIT)
  @copyright  Copyright (c) 2018 Volodymyr Shymanskyy
  @date       Sep 2018
  @brief

  Version: 1.1.1

  Version Modified By   Date        Comments
  ------- -----------  ----------   -----------
  1.0.0   K Hoang      07/04/2020  Initial coding
  1.0.1   K Hoang      09/04/2020  Add support to SAM DUE, Teensy, STM32
  1.0.2   K Hoang      15/04/2020  Fix bug. Add SAMD51 support.
  1.0.3   K Hoang      05/05/2020  Add nRF52 support, MultiWiFi/Blynk, Configurable Config Portal Title, 
                                   Default Config Data and DRD. Update examples.
  1.0.4   K Hoang      13/05/2020  Add support to Arduino UNO WiFi R2 
  1.1.0   K Hoang      28/05/2021  Add support to Nano_RP2040_Connect, RASPBERRY_PI_PICO using Arduino mbed or pico core
                                   Enable scan of WiFi networks for selection in Configuration Portal
  1.1.1   K Hoang      09/06/2020  Add Blynk library Patches for **MBED RP2040-based (Nano_RP2040_Connect, etc.) boards
 *****************************************************************************************************************************/
// To install WiFiNINA_Generic library (https://github.com/khoih-prog/WiFiNINA_Generic)
// and Blynk_WiFiNINA_WM  (https://github.com/khoih-prog/Blynk_WiFiNINA_WM)

#define BLYNK_PRINT Serial
#define BLYNK_DEBUG

#include <BlynkSimpleWiFiNINA_UNO_WiFi.h>
#include <Adafruit_Sensor.h>
#include "Adafruit_TSL2591.h"

// Example for demonstrating the TSL2591 library - public domain!
// connect SCL to I2C Clock
// connect SDA to I2C Data
// connect Vin to 3.3-5V DC
// connect GROUND to common ground
Adafruit_TSL2591 tsl = Adafruit_TSL2591(2591); // pass in a number for the sensor identifier (for your use later)


//#define USE_LOCAL_SERVER      true

#if USE_LOCAL_SERVER

char auth[] = "7z34lBX0Vwf_WN500hgKg06FkH72_Kpn";
String BlynkServer = "account.duckdns.org";
//String BlynkServer = "192.168.2.112";

#else

char auth[] = "7z34lBX0Vwf_WN500hgKg06FkH72_Kpn";
String BlynkServer = "blynk-cloud.com";

#endif

#define BLYNK_SERVER_HARDWARE_PORT    8080

// Your WiFi credentials.
char ssid[] = "W148N9872";
char pass[] = "63B6EC6B7F";

/**************************************************************************/
/*
Shows how to perform a basic read on visible, full spectrum or
infrared light (returns raw 16-bit ADC values)
*/
/**************************************************************************/
void simpleRead(void)
{
// Simple data read example. Just read the infrared, fullspecrtrum diode
// or 'visible' (difference between the two) channels.
// This can take 100-600 milliseconds! Uncomment whichever of the following you want to read
uint16_t x = tsl.getLuminosity(TSL2591_VISIBLE);
//uint16_t x = tsl.getLuminosity(TSL2591_FULLSPECTRUM);
//uint16_t x = tsl.getLuminosity(TSL2591_INFRARED);
Serial.print(F("[ ")); Serial.print(millis()); Serial.print(F(" ms ] "));
Serial.print(F("Luminosity: "));
Serial.println(x, DEC);

Blynk.virtualWrite(V20, x);
}

/**************************************************************************/
/*
Configures the gain and integration time for the TSL2591
*/
/**************************************************************************/
void configureSensor(void)
{
  // You can change the gain on the fly, to adapt to brighter/dimmer light situations
  tsl.setGain(TSL2591_GAIN_LOW); // 1x gain (bright light)
  //tsl.setGain(TSL2591_GAIN_MED); // 25x gain
  //tsl.setGain(TSL2591_GAIN_HIGH); // 428x gain
  // Changing the integration time gives you a longer time over which to sense light
  // longer timelines are slower, but are good in very low light situtations!
  //tsl.setTiming(TSL2591_INTEGRATIONTIME_100MS); // shortest integration time (bright light)
  // tsl.setTiming(TSL2591_INTEGRATIONTIME_200MS);
  tsl.setTiming(TSL2591_INTEGRATIONTIME_300MS);
  // tsl.setTiming(TSL2591_INTEGRATIONTIME_400MS);
  // tsl.setTiming(TSL2591_INTEGRATIONTIME_500MS);
  // tsl.setTiming(TSL2591_INTEGRATIONTIME_600MS); // longest integration time (dim light)
  /* Display the gain and integration time for reference sake */
  Serial.println(F("------------------------------------"));
  Serial.print (F("Gain: "));
  tsl2591Gain_t gain = tsl.getGain();
  switch(gain)
  {
  case TSL2591_GAIN_LOW:
  Serial.println(F("1x (Low)"));
  break;
  case TSL2591_GAIN_MED:
  Serial.println(F("25x (Medium)"));
  break;
  case TSL2591_GAIN_HIGH:
  Serial.println(F("428x (High)"));
  break;
  case TSL2591_GAIN_MAX:
  Serial.println(F("9876x (Max)"));
  break;
  }
  Serial.print (F("Timing: "));
  Serial.print((tsl.getTiming() + 1) * 100, DEC);
  Serial.println(F(" ms"));
  Serial.println(F("------------------------------------"));
  Serial.println(F(""));
}

/**************************************************************************/
/*
Displays some basic information on this sensor from the unified
sensor API sensor_t type (see Adafruit_Sensor for more information)
*/
/**************************************************************************/
void displaySensorDetails(void)
{
  sensor_t sensor;
  tsl.getSensor(&sensor);
  Serial.println(F("------------------------------------"));
  Serial.print (F("Sensor: ")); Serial.println(sensor.name);
  Serial.print (F("Driver Ver: ")); Serial.println(sensor.version);
  Serial.print (F("Unique ID: ")); Serial.println(sensor.sensor_id);
  Serial.print (F("Max Value: ")); Serial.print(sensor.max_value); Serial.println(F(" lux"));
  Serial.print (F("Min Value: ")); Serial.print(sensor.min_value); Serial.println(F(" lux"));
  Serial.print (F("Resolution: ")); Serial.print(sensor.resolution, 4); Serial.println(F(" lux"));
  Serial.println(F("------------------------------------"));
  Serial.println(F(""));
}

void heartBeatPrint(void)
{
  static int num = 1;

  if (Blynk.connected())
  {
    Serial.print("B");
  }
  else
  {
    Serial.print("F");
  }

  if (num == 80)
  {
    Serial.println();
    num = 1;
  }
  else if (num++ % 10 == 0)
  {
    Serial.print(" ");
  }
}

void check_status()
{
  static unsigned long checkstatus_timeout = 0;

#define STATUS_CHECK_INTERVAL     15000L

  // Send status report every STATUS_REPORT_INTERVAL (60) seconds: we don't need to send updates frequently if there is no status change.
  if ((millis() > checkstatus_timeout) || (checkstatus_timeout == 0))
  {
    // report status to Blynk
    heartBeatPrint();

    checkstatus_timeout = millis() + STATUS_CHECK_INTERVAL;
  }
}

BlynkTimer timer;

void myTimerEvent()
{
  simpleRead();
}

void setup()
{
  // Debug console
  Serial.begin(9600);
  while (!Serial);
  //delay(1000);

  Serial.println("\nStart UNO_WiFiNINA using WiFiNINA_Shield on UNO WiFi");

#if USE_LOCAL_SERVER
  Blynk.begin(auth, ssid, pass, BlynkServer.c_str(), BLYNK_SERVER_HARDWARE_PORT);
#else
  // You can also specify server:
  //Blynk.begin(auth, ssid, pass, "blynk-cloud.com", 80);
  //Blynk.begin(auth, ssid, pass, IPAddress(192,168,1,100), 8080);
  Blynk.begin(auth, ssid, pass);
#endif

  if (tsl.begin())
  {
    Serial.println(F("Found a TSL2591 sensor"));
    /* Display some basic information on this sensor */
    displaySensorDetails();
    /* Configure the sensor */
    configureSensor();
    // Now we're ready to get readings ... move on to loop()! 
  }

  timer.setInterval(500L, myTimerEvent);
}

void loop()
{
  Blynk.run();
  timer.run();
  check_status();
}

09:26:32.838 → [ 8159549 ms ] Luminosity: 15451

09:26:32.871 → [8159552] <[14]@q[00|0B]vw[00]20[00]15451

09:26:33.349 → [ 8160050 ms ] Luminosity: 15472

09:26:33.383 → [8160053] <[14]@r[00|0B]vw[00]20[00]15472

09:26:33.824 → [ 8160549 ms ] Luminosity: 15465

09:26:33.857 → [8160560] >[00]@6[00|C8]

09:26:33.907 → [8160560] >[00]=[F7|00|C8]

09:26:33.942 → [8160574] >[86|01|00|CF|00]

09:26:33.989 → [8160604] Packet too big: 52992

09:26:34.265 → [8160991] Connecting to blynk-cloud.com:80

09:26:34.333 → [8161008] <[14]@s[00|0B]vw[00]20[00]15465

09:26:34.390 → [8161013] Cmd error

09:26:34.679 → [ 8161396 ms ] Luminosity: 15551

09:26:35.055 → [ 8161759 ms ] Luminosity: 15534

09:26:35.397 → [ 8162122 ms ] Luminosity: 15500

09:26:35.837 → [ 8162548 ms ] Luminosity: 15461

Note: the example, with not changes except for said, password and authentication.

02:42:30.892 → B

02:42:45.889 → B[30021889] <[06|02|9D|00|00]

02:43:00.918 → B[30021931] >[00|02|9D|00|C8]

02:43:15.854 → BBF[38659706] Connecting to blynk-cloud.com:80

05:06:51.591 → [38659815] <[1D|00|01|00] 7z34lBX0Vwf_WN500hgKg06FkH72_Kpn

05:06:51.591 → [38659876] >[00|00|01|00|C8]

05:06:51.591 → [38659877] Ready (ping: 60ms).

05:06:51.646 → [38659877] Free RAM: 5524

05:06:51.646 → [38659944] <[11|00|02|00]bver[00]1.0.0[00]h-beat[00]45[00]buff-in[00]256[00]dev[00]Arduino UNO WiFi Rev2[00]con[00]WiFiNINA[00]build[00]Jul 5 2021 18:22:53[00]

05:06:51.815 → [38660110] >[00|00|02|00|C8]

Did fail, but recovered.

@PeteKnight I have tried many examples. They fail after awhile. Some do recover. When I add writing to the server. Get Cmd error or Packet size too large and it does not recover.

Which hardware do you test on that you recommend? Need to running for a long time without issue.

I always use NodeMCUs or ESP32s.

Pete.

1 Like

Thanks

I need analog inputs as well as WiFi. Work for many weeks while I am gone.

At present even the simplest example does not last 24hrs on the Arduino UNO WiFi Rev 2.

John

In that case the ESP32 would be my choice as it has 8 Analog pins that can be used at the same time as WiFi…

Pete.

Thanks for your help.