Example Code for Arduino-UV Index Testing

Last revision 2025/12/20

This Sample code is for testing the UV Sensor . Users can learn how to read the analog output of the UV Sensor and calculate the corresponding UV index.

Hardware Preparation

Software Preparation

  • Arduino IDE (version 1.8.x or later), Download Link: Arduino Software
  • No additional libraries are required for this sample code.

Wiring Diagram

SEN0162 Connection diagram

Other Preparation Work

Note: The Analog Value in the diagram above is calculated based on the ADC of Arduino UNO R3 (10-bit, reference voltage 5V). If using other MCUs (such as ESP32) with a different ADC reference voltage and precision, please make the corresponding conversion.

Sample Code

/*
    # This Sample code is for testing the UV Sensor .
    #Connection:
        VCC-5V
        GND-GND
        OUT-Analog pin 0
*/

void setup() {
  Serial.begin(9600);  // open serial port, set the baud rate to 9600 bps
}

void loop() {
  int sensorValue;
  int analogValue = analogRead(A0);  //connect UV sensors to Analog 0
  if (analogValue < 20) {
    sensorValue = 0;
  } else {
    sensorValue = 0.05 * analogValue - 1;
  }

  Serial.print("UV Index: ");
  if (sensorValue < 12) Serial.println(sensorValue);  //print the value to serial
  else Serial.println("11+ Warning: High Ultraviolet! Exceeded UV index range!");
  delay(1000);
}

Result

Open the serial monitor in Arduino IDE with a baud rate of 9600. The serial output will display the calculated UV index value. For example:

  • If the analog value read from pin A0 is less than 20, the UV index will be 0.
  • For analog values between 20 and 260, the UV index is calculated as 0.05 * analogValue - 1.
  • If the calculated UV index is 12 or higher, a warning message will be displayed: "11+ Warning: High Ultraviolet! Exceeded UV index range!".

Additional Information

UV index

Was this article helpful?

TOP