Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add light sensor event that only fires when valid reading is available. #3

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

GeorgeWort
Copy link
Owner

New event MICROBIT_DISPLAY_EVT_LIGHT_SENSE_READY is introduced to resolve two issues.

  • Invalid results in first 3/4 readings.
  • Invalid results when using bluetooth.
  • Invalid results when touching the pins.

This allows for four different behaviours depending on how you interact with the light sensor as shown in the code sample below.

#include "MicroBit.h"

MicroBit uBit;
int lightLevel;

bool valid_only = false;
bool use_new_event = false;

void lightLevelReady(MicroBitEvent) {
  lightLevel = uBit.display.readLightLevel(valid_only);
  uBit.serial.send(lightLevel);
  uBit.serial.send("\r\n");
}

int main() {
  uBit.init();
  if (use_new_event) {
      uBit.messageBus.listen(MICROBIT_ID_LIGHT_SENSOR, MICROBIT_DISPLAY_EVT_LIGHT_SENSE_READY, lightLevelReady);
  }
  else {
      uBit.messageBus.listen(MICROBIT_ID_DISPLAY, MICROBIT_DISPLAY_EVT_LIGHT_SENSE, lightLevelReady);
    }
  uBit.display.readLightLevel();
  while (1) {
    fiber_sleep(20);
  }
}
  • Using the old event and passing either nothing or false to readLightLevel gives the same behaviour as before, simply returning the values (including invalid ones) every time a reading is taken.
  • Using the old event and passing true to 'readLightLevel' causes an error value of -1 to be returned for the first few readings, and stale but valid readings to be returned whenever invalid results are produced.
  • Using the new event means that readLightLevel is only called when a valid reading is available.
    • Passing true to readLightLevel when using the new event means that even if a bad result is produced between the event firing and the call to readLightLevel, a valid reading will still be returned (either the reading taken when the event was fired, or a more recent valid reading).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant