Java Magazine, September/October 2016
ORACLE COM JAVAMAGAZINE SEPTEMBER OCTOBER 2016 22 internet of things The setRGBBrightnessLevel method calls the set BrightnessLevel method for the three VariableBrightness Led instances with the value received as an argument This way the three color components of the RGB LED are set to the same brightness level through a single call The updateLedsBasedOnLight method retrieves the light level description from the SimpleLightSensor instance and calls the previously explained setRGBBrightnessLevel method to set the brightness level for the three components of the RGB LED based on the measured light If it is extremely dark the brightness level is set to 255 If it is very dark the brightness level is set to 128 If it is just dark the brightness level is set to 64 Otherwise the brightness level is set to 0 which means the RGB LED is completely off Now I will write code that uses the BoardManager class to measure the ambient light and set the brightness for the three color components of the RGB LED based on the measured ambient light The following lines show the code for the new AmbientLightAndLed class public class AmbientLightAndLed public static void main String args String lastlightLevel BoardManager board new BoardManager while true board lightSensor measureLight String newLightLevel board lightSensor getLightLevel if newLightLevel lastlightLevel The measured light level has changed lastlightLevel newLightLevel System out format Measured light level s n newLightLevel board updateLedsBasedOnLight try Thread sleep 1000 catch InterruptedException e System err format Sleep interruption s e toString The class declares the main method that is executed when I upload and launch the project on the board First the method initializes the lastLightLevel local variable with an empty String and creates an instance of the BoardManager class named board Then the method runs a loop forever The loop calls the board lightSensor measureLight method to update the ambient light measurement The next line saves the light level description retrieved with the call to board lightSensor getLightLevel in the newLightLevel local variable If the new light level is diferent from the last recorded ambient light level the code updates the value for the lastLightLevel variable prints the measured light level and calls the board updateLedsBasedOnLight method You can run the example and use a flashlight or your smartphone to move light over the photoresistor You should see the printed messages and see that the RGB dims and finally turns off After you reduce the light in the environment the RGB LED increases its brightness The main goal for the SimpleLightSensor class is to convert a quantitative value a voltage value into a qualitative value an ambient light description
You must have JavaScript enabled to view digital editions.