Added code to check if the state of the sensor changed, added comments.