dhiltonp

get_charge_state hexbright

Dec 26th, 2012
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.15 KB | None | 0 0
  1. // charging constants
  2. #define CHARGING 1
  3. #define BATTERY 7
  4. #define CHARGED 3
  5.  
  6.  
  7.         // returns CHARGING, CHARGED, or BATTERY
  8.     // This reads the charge state twice with a small delay, then returning
  9.     //  the actual charge state.  BATTERY will never be returned if we are
  10.     //  plugged in.
  11.     // Use this if you take actions based on the charge state (example: you
  12.     //  turn on when you stop charging).  Takes up 56 bytes (34+22).
  13.     static byte get_definite_charge_state();
  14.     // returns CHARGING, CHARGED, or BATTERY
  15.     // This reads and returns the charge state, without any verification.  
  16.     //  As a result, it may report BATTERY when switching between CHARGED
  17.     //  and CHARGING.
  18.     // Use this if you don't care if the value is sometimes wrong (charging
  19.     //  notification).  Takes up 34 bytes.
  20.     static byte get_charge_state();
  21.  
  22.  
  23. byte hexbright::get_charge_state() {
  24.   int charge_value = analogRead(APIN_CHARGE);
  25. #if (DEBUG==DEBUG_CHARGE)
  26.   Serial.print("Current charge reading: ");
  27.   Serial.println(charge_value);
  28. #endif
  29.   // <128 charging, >768 charged, battery
  30.   if(charge_value<128)
  31.     return CHARGING;
  32.   else if (charge_value>768)
  33.     return CHARGED;
  34.   return BATTERY;
  35. }
  36.  
  37. // reading twice costs us 28 bytes, but improves reliability.
  38. // The root problem is when the charge value goes from <128 to >768 (or the
  39. //  reverse, from topping off), it passes through the middle range.  If we
  40. //  read at the wrong time, we can get a BATTERY value while we are still
  41. //  plugged in.
  42. // Reading twice with a sufficient delay, we can guarantee that our state is correct.
  43. byte hexbright::get_definite_charge_state() {
  44.   byte val1 = get_charge_state();
  45.   // do something that will take some time...
  46.   // delayMicroseconds costs an extra 20 bytes (because nowhere else is it called)
  47.   // If other code needs delayMicroseconds, switch to it.
  48.   //delayMicroseconds(30);
  49.   read_thermal_sensor(); // delay a little...
  50.   byte val2 = get_charge_state();
  51.   // BATTERY & CHARGING = CHARGING, BATTERY & CHARGED = CHARGED, CHARGED & CHARGING = CHARGING
  52.   // In essence, only return the middle value (BATTERY) if two reads report the same thing.
  53.   return val1 & val2;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment