Example Code for Arduino-Reading Data Using UART

This project demonstrates how to read ultraviolet (UV) data including voltage, index, and risk level from the Gravity: 240370 Ultraviolet Index Sensor using UART communication with an Arduino UNO. Users will learn to interface the sensor via UART, install necessary libraries, and interpret serial monitor output.

Hardware Preparation

  • DFRduino UNO Controller x1
  • Gravity: 240370 Ultraviolet Index Sensor x1

Software Preparation

Wiring Diagram

Other Preparation Work

  • Connect the module to the UNO controller according to the wiring diagram above. Of course, you can also use an expansion board for a more convenient and quicker prototype construction.
  • Switch the sensor's selection switch to the UART side.
  • Download and install the UVIndex240370Sensor and RTU libraries.
  • Open the Arduino IDE, upload the following code to the UNO controller.
  • Open the serial monitor of the Arduino IDE, adjust the baud rate to 115200, and observe the serial print results.

Sample Code

#include "DFRobot_UVIndex240370Sensor.h"
#include <SoftwareSerial.h>

SoftwareSerial mySerial(4, 5);
DFRobot_UVIndex240370Sensor UVIndex240370Sensor(&mySerial);

void setup()
{
  mySerial.begin(9600);
  Serial.begin(115200);
  
  while(UVIndex240370Sensor.begin() != true){
    Serial.println(" Sensor initialize failed!!");
    delay(1000);
  }
  Serial.println(" Sensor  initialize success!!");
}

void loop()
{
  uint16_t voltage = UVIndex240370Sensor.readUvOriginalData();
  uint16_t index  = UVIndex240370Sensor.readUvIndexData();
  uint16_t level = UVIndex240370Sensor.readRiskLevelData();
  Serial.print("voltage:"); Serial.print(voltage); Serial.println(" mV");
  Serial.print("index:"); Serial.println(index);
  if(level==0)
    Serial.println("Low Risk");
  else if(level==1)
    Serial.println("Moderate Risk");
  else if(level==2)
    Serial.println("High Risk");
  else if(level==3)
    Serial.println("Very High Risk");
  else if(level==4)
    Serial.println("Extreme Risk");
  delay(100);
}

Result

This experiment needs to be tested under sunlight. The serial monitor will print information similar to the following:

voltage:82 mV
index:1
Low Risk

Wherein, "voltage:82 mV" represents the raw value of ultraviolet light, "index:1" indicates the UV index, and "Low Risk" signifies that the current UV level poses a low risk.

Was this article helpful?

TOP