I learned about the ML8511 UV sensor from a tutorial, but the code provided didn’t include a library. Is it okay to use it that way, or should we include a library?
UV index meter interfacing Arduino or ESP32 with ML8511 – Circuit Schools
Using The UV Ray Detection Module GY-ML8511 with Arduino - Phipps Electronics
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
int UVOUT = 15; //Output from the sensor
int REF_3V3 = 4; //3.3V power on the ESP32 board
#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);
void setup()
{
Serial.begin(9600);
pinMode(UVOUT, INPUT);
pinMode(REF_3V3, INPUT);
display.begin(SSD1306_SWITCHCAPVCC, 0x3C); //initialize with the I2C addr 0x3C (128x64)
display.clearDisplay();
}
//Takes an average of readings on a given pin
//Returns the average
int averageAnalogRead(int pinToRead)
{
byte numberOfReadings = 8;
unsigned int runningValue = 0;
for(int x = 0 ; x < numberOfReadings ; x++)
runningValue += analogRead(pinToRead);
runningValue /= numberOfReadings;
return(runningValue);
}
float mapfloat(float x, float in_min, float in_max, float out_min, float out_max)
{
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
void loop()
{
int uvLevel = averageAnalogRead(UVOUT);
int refLevel = averageAnalogRead(REF_3V3);
//Use the 3.3V power pin as a reference to get a very accurate output value from sensor
float outputVoltage = 3.3 / refLevel * uvLevel;
float uvIntensity = mapfloat(outputVoltage, 0.99, 2.8, 0.0, 15.0); //Convert the voltage to a UV intensity level
Serial.print("output: ");
Serial.print(refLevel);
Serial.print("ML8511 output: ");
Serial.print(uvLevel);
Serial.print(" / ML8511 voltage: ");
Serial.print(outputVoltage);
Serial.print(" / UV Intensity (mW/cm^2): ");
Serial.print(uvIntensity);
Serial.println();
display.setCursor(20,0); //oled display
display.setTextSize(1);
display.setTextColor(WHITE);
display.println("UV Ray Intensity");
display.setCursor(20,20); //oled display
display.setTextSize(3);
display.setTextColor(WHITE);
display.println(uvIntensity);
display.setCursor(20,45); //oled display
display.setTextSize(2);
display.setTextColor(WHITE);
display.println("mW/cm^2");
display.display();
delay(300);
display.clearDisplay();
}