How To Use Light Sensor In Windows 10 Universal App


In Windows 10 the light sensor is a type of environmental sensor that allows apps to respond to changes in the user's environment.
An ambient light sensor is used to extend battery life and enables easy-to-view display that is optimized to the environment in portable devices such as tablets, smartphones, and laptops.
It is very helpful to conserve battery life for mobile phones.
Let’s see the steps:
  1. Create a new Windows 10 universal app.
  2. Design the UI according to your wish; here I have created one button to start the light sensor reading.
  3. Now go to the coding part and write the following code. Firstly, add the following namespace to access the Light sensor API.
    1. using Windows.Devices.Sensors;    
  4. Create one object for the LightSensor,
    1. LightSensor mylightSensor;    
  5. Now get the default properties and reading using GetDefault method.
    1. mylightSensor = LightSensor.GetDefault();    
  6. Then set interval to read the value from certain interval.
    1. mylightSensor.ReportInterval = 15;    
Now create one event light sensor reading changes to handle the readings and assign it to your light sensor.
  1. mylightSensor.ReadingChanged += MylightSensor_ReadingChanged;     
Now start the application and get the values from the light sensor.
To read the light sensor value use LightSensorReadingclass or formatted string.
The full code looks like the following code.
  1. LightSensor mylightSensor;    
  2. publicasyncvoid StartLightSensor() {    
  3.     mylightSensor = LightSensor.GetDefault();    
  4.     mylightSensor.ReportInterval = 15;    
  5.     mylightSensor.ReadingChanged += MylightSensor_ReadingChanged;    
  6. }    
  8. privatevoid MylightSensor_ReadingChanged(LightSensor sender, LightSensorReadingChangedEventArgs args) {    
  9.     LightSensorReading read = args.Reading;    
  10.     string values = String.Format("Light Sensor Reading:\t{0}\t{1}", args.Reading.Timestamp.ToString(), args.Reading.IlluminanceInLux.ToString());    
  11. }     
Read more articles on Windows 10:


In this article, we learned about How To Use Light Sensor In Windows 10 Universal App.  

Similar Articles