Lux Readings onto Local Web Page

Hi all! I'm currently working on a project where I control an LED array using a local web browser. I'm currently using the Arduino Uno Wifi R2 and so far, I've been able to create the Wi-Fi connection and also display a webpage that has two hyperlinks "Turn LED ON" and "Turn LED OFF". As you can see, clicking on either hyperlink will turn on/off the array.

My issue now is that I can't seem to get the lux readings from my TSL2591 photosensor to display onto the webpage. Can you all help me? I'd like for this bit of information to be displayed on the same page with my turn on/off LED links.

As it stands, the page currently spits out "Lux: 18" but I'm about 100% that's not the actual lux reading.

My current code is below:

#include <SPI.h>
#include <WiFiNINA.h>
#include <TimeLib.h>
#include <TimeAlarms.h>
#include <Wire.h>
#include <SparkFunDS1307RTC.h>
#include <DS1307RTC.h>  // A basic DS1307 library that returns time as a time_t.
#include <Adafruit_Sensor.h>
#include "Adafruit_TSL2591.h" // The photoresistor module.
#define led 9
int brightness = 255; // How bright the LED is from (0-255)
int fadeAmount = 1; // How many points to fade the LED by
int targetbrightness = 255; // Target brightness
int luxCheck; // Checking lux of light
char ssid[] = "Sonic-b045";
char pass[] = "71e99a19ee";
int keyIndex = 0;
Adafruit_TSL2591 tsl = Adafruit_TSL2591(2591);
//configure TSL2591
void configureSensor(void)
{
  tsl.setGain(TSL2591_GAIN_MED);
  tsl.setTiming(TSL2591_INTEGRATIONTIME_300MS);
  
  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("------------------------------------"));
}

// Code to connect to Wifi 

int status = WL_IDLE_STATUS;
WiFiServer server(80);

String readString;

void setup() {
  pinMode(led, OUTPUT);
  Serial.begin(9600);
  rtc.autoTime();
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to Network named: ");
    Serial.println(ssid);
    status = WiFi.begin(ssid, pass);
    delay(15000);
    setSyncProvider(RTC.get);

    Alarm.alarmRepeat(6,00,0,MorningAlarm);
    Alarm.alarmRepeat(23,00,0,EveningAlarm);
  }
  configureSensor();
  server.begin();

  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);
}

// Reads IR and full spectrum then converts to Lux and checks for less than 500 Lux value
void advancedRead(void)
{
  sensors_event_t event;
  tsl.getEvent(&event);
  uint32_t lum = tsl.getFullLuminosity();
  uint16_t ir, full;
  ir = lum >> 16;
  full = lum & 0xFFFF;
  if ((event.light < 500))
    {
      luxCheck = 0;
      Serial.println(F("WARNING: LUX NOT WITHIN DESIRED RANGE!"));
      Serial.print(F("Lux: ")); Serial.println(tsl.calculateLux(full, ir), 2);
      Serial.println(F("------------------------------------"));
    }
    else
      { 
        luxCheck = 1;
        Serial.print(F("Lux: ")); Serial.println(tsl.calculateLux(full, ir), 2);
        Serial.println(F("------------------------------------"));
      }
}


void loop() {

  
  WiFiClient client = server.available();
  if (client)
  {
    Serial.println("new client");
    String currentLine = "";
    while (client.connected())
    {
      if (client.available())
      {
        char c = client.read();
        if (readString.length() < 100)
        {
          readString += c;
          Serial.write(c);
          
          if (c == '\n') {
            client.println("<a href=\"/?lighton\"\">Turn On Light</a>");
            client.println("
"); // This is to add a line break.
            client.println("
");
            client.println("<a href=\"/?lightoff\"\">Turn Off Light</a>
");     
            client.println(F("Lux: ")); client.print(F(A4));
            delay(1);
            
            if(readString.indexOf("?lighton") > 0)
            {
              digitalWrite(led, brightness);
              delay(1);              
            }
            else{
              if(readString.indexOf("?lightoff") > 0)
              {
                digitalWrite(led, LOW);    
                delay(1);
              }
            }           
            readString="";

            delay(1);
            client.stop();
            Serial.println("client disonnected");
          }
        }
      }
    }
  }
}
// functions to be called when an alarm triggers
void MorningAlarm() {
  // write here the task to perform every morning
  Serial.println("Turn light on");
  digitalWrite(led, brightness);
}
void EveningAlarm() {
  // write here the task to perform every evening
  Serial.println("Turn light off");
  digitalWrite(led, LOW);
}

this line

            client.println(F("Lux: ")); client.print(F(A4));

prints the digital pin number for Analog pin 4 which happens to be 18. You also do not need the F() macro since that is only for strings to save memory.

Instead, you should be calling setting a global variable inside your advancedRead() function and then use that.

2 questions:

  1. How and where should I set a global variable?
  2. Is there a way to make the LED fade while using a webpage? I can’t seem to digitalwrite to the pin in a way that makes it fade when going through a webpage.

vutnguyen:
2 questions:

  1. How and where should I set a global variable?

Really? You do not know how to declare a global variable? If this is the case, you need to learn C/C++ and/or study some of the example code that comes with the IDE to figure this out.

Your current code has many global variables near the top of the sketch. Use that as a guide.

As for where would you set it - maybe in the function where you are reading/calculating the value?

  1. Is there a way to make the LED fade while using a webpage? I can’t seem to digitalwrite to the pin in a way that makes it fade when going through a webpage.

DigitalWrite() does just that HIGH or LOW. Fading is accomplished by using analogWrite() which does pulse width modulation (PWM) and takes a value from 0 (OFF) to 255 (ON)

So is there anyway to control the AnalogWrite function through the Web-page?

How about you replace digitalWrite() with analogWrite()? You are already writing the value of the variable 'brightness' using digitalWrite() [which is not really correct, but works]. If brightness is something below 255, your led will be dimmer.

blh64:
How about you replace digitalWrite() with analogWrite()? You are already writing the value of the variable 'brightness' using digitalWrite() [which is not really correct, but works]. If brightness is something below 255, your led will be dimmer.

For whatever reason, I can't seem to keep the LED on to fade it up or down. It seems to momentarily come on for like 1 second and then cut off.

/* TSL2591 Digital Light Sensor */
/* Dynamic Range: 600M:1 */
/* Maximum Lux: 88K */
#include <SPI.h>
#include <WiFiNINA.h>
#include <TimeLib.h>
#include <TimeAlarms.h>
#include <Wire.h>
#include <SparkFunDS1307RTC.h>
#include <DS1307RTC.h>
#include <Adafruit_Sensor.h>
#include "Adafruit_TSL2591.h"
Adafruit_TSL2591 tsl = Adafruit_TSL2591(2591); // Pass in a number for the sensor identifier

/* Setting up initial LED states */

#define led 9
int brightness = 200; // How bright the LED is from (0-255)
int fadeAmount = 1; // How many points to fade the LED by
int targetbrightness = 255; // Target brightness
int luxCheck; // Checking lux of light

/* Setting up Wi-Fi information */

char ssid[] = "Sonic-b045";
char pass[] = "71e99a19ee";
int keyIndex = 0;
int status = WL_IDLE_STATUS;
WiFiServer server(80);
String readString;

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)
}

/* Setup code to run once */

void setup(void) {
  pinMode(led, OUTPUT);
  Serial.begin(9600);
  rtc.autoTime();
  /* Configure the sensor */
  configureSensor();
  
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to Network named: ");
    Serial.println(ssid);
    status = WiFi.begin(ssid, pass);
  }
    delay(10000);
    server.begin();
    Serial.print("SSID: ");
    Serial.println(WiFi.SSID());
    IPAddress ip = WiFi.localIP();
    Serial.print("IP Address: ");
    Serial.println(ip);
}
void advancedRead(void)
{
  // More advanced data read example. Read 32 bits with top 16 bits IR, bottom 16 bits full spectrum
  // That way you can do whatever math and comparisons you want!
  uint32_t lum = tsl.getFullLuminosity();
  uint16_t ir, full;
  ir = lum >> 16;
  full = lum & 0xFFFF;
  Serial.print(F("[ ")); Serial.print(millis()); Serial.print(F(" ms ] "));
  Serial.print(F("Lux: ")); Serial.println(tsl.calculateLux(full, ir), 6);
  const int A4 = (tsl.calculateLux(full, ir), 6);
}
void loop() {
  //  advancedRead();
  WiFiClient client = server.available();
  if (client)
  {
    Serial.println("new client");
    String currentLine = "";
    while (client.connected())
    {
      if (client.available())
      {
        char c = client.read();
        if (readString.length() < 100)
        {
          readString += c;
          Serial.write(c);
          
          if (c == '\n') {
            client.println("<a href=\"/?lighton\"\">Turn On Light</a>");
            client.println("
"); // This is to add a line break.
            client.println("
");
            client.println("<a href=\"/?lightoff\"\">Turn Off Light</a>
");     
            client.println(F("Lux: ")); client.print("A4");
            delay(1);
            
            if(readString.indexOf("?lighton") > 0)
            {
              analogWrite(led, brightness);
              if (hour() >= 6 && hour()<= 14) {
                brightness = brightness + fadeAmount/18000;
              }
              else if (hour() > 14 && hour() <= 19) {
                brightness = brightness - fadeAmount/28800;
              }
              else { brightness = 0;
              }
              delay(1);              
            }
            else{
              if(readString.indexOf("?lightoff") > 0)
              {
                digitalWrite(led, LOW);    
                delay(1);
              }
            }           
            readString="";

            delay(1);
            client.stop();
            Serial.println("client disonnected");
          }
        }
      }
    }
  }
  advancedRead();
}

Seriously? Come-on. This code is crap.
What do you thing this does?

  const int A4 = (tsl.calculateLux(full, ir), 6);

or this code?

            client.println(F("Lux: ")); client.print("A4");

or this?

                brightness = brightness + fadeAmount / 18000;

brightness takes a value from 0-255. fadeAmount is the value 1. Doing integer math (1/18000) is 0. There are no fractions in integer math.

I seriously suggest you put this project aside and read/study/learn some of the examples in the IDE. You should also search for some tutorials on C/C++.

There is nothing wrong with starting out, but it seems you are way over your head and I am not going to write your code for you or continue to look at this crap.

I'm not asking anyone to write my code for me and I really have been putting in so much time to learn this. I didn't realize it was so hostile on this forum.

I'd like to point out that I've been able to fade up and down using "fractional" math in my code before. Just now I'm trying to do it over a simple local web page. Only able to turn it on and off, not able to implement fade.

Clearly vutnguyen is a noob so lets work from that vantage point people !

Smaller words less attitude.

:sunglasses:

ballscrewbob:
Clearly vutnguyen is a noob so lets work from that vantage point people !

Smaller words less attitude.

:sunglasses:

Thanks, Bob. It's so frustrating for me, I understand that it'll be frustrating to a pro that's done this for a while to understand why it is my code is a certain way. But I've been trying to figure this out little by little for months.

I can make an LED fade up and down.
I have code that reads sensor data to tell me what the brightness levels are.

But now that I'm trying to create a little web page for it using my Arduino Uno Wifi, I'm just running into some issues.

"I'd like to point out that I've been able to fade up and down using "fractional" math in my code before. Just now I'm trying to do it over a simple local web page. Only able to turn it on and off, not able to implement fade."

Not clear what you are wanting to do. Do you want to fade an led connected to an arduino using a command from a web page? The "I'm trying to do it over a simple local web page" is not totally clear. Web page actions are usually individual request/commands made to the web server.

Hi there, zoomkat!

What I’m trying to accomplish is this:

I have an LED array that I want to fade up and down but automatically! When it’s 6AM, fade up and then stay on at 255 from 11AM until 2PM and from there fade down.

I have a light sensor that reads and sends me back lux readings.

I also want to be able to turn the lights on and off through a webpage.

I can do all three of these things separately. It’s the tying them all together part that I’m having a hard time with.

Right now, I sort of have a local web page that allows me to turn the LED array on or off. When I turn this LED array on using my web page, I’d like for it to fade. This is my priority piece. I wish I could just get it to fade at all whenever I press “turn on LED” on the webpage.

I would also like to display the current lux reading on the webpage.

Admit to not having looked through all this so apologies if I am wrong.
Also sudo guess :fearful:

Sketch should have a variable word to initiate the fade eg "NowFade=1 (for ON)" and "NowFade=0 (for off)"

Get that working WITHOUT the web so if you enter "1" or "0" into the serial terminal it sets off the fade section of your code.

Once you have that then you can get the web page to send that same variable with a single key press.

Assign other keys as needed in a similar manner.

It should POLL the sketch for the LUX reading but first concentrate on getting the initial controls going and leave that for now until you have the basics going.

vutnguyen:
I can make an LED fade up and down.

Then use that code in this sketch

I have code that reads sensor data to tell me what the brightness levels are.

Then put that code into this sketch as well.
All the code you have posted so far does not seem to indicate that. Having the sketch also respond as a web page is really has nothing to do with the fundamental issues we have been discussing about the code.