Skip to content

Instantly share code, notes, and snippets.

@ShawnHymel
Last active April 20, 2023 15:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ShawnHymel/7a6fd7d56b006b19f304d4c303ea61dc to your computer and use it in GitHub Desktop.
Save ShawnHymel/7a6fd7d56b006b19f304d4c303ea61dc to your computer and use it in GitHub Desktop.
Battery Babysitter Demo
/**
* Battery Babysitter Demo
* June 22, 2016
*
* RGB LED changes colors based on LiPo state of charge
*
* Hardware:
* Babysitter | LED (Common Anode) | Arduino
* -------------|---------------------|---------
* GND | | GND
* VPU | | VCC
* SDA | | A4
* SCL | | A5
* VOUT+ | | RAW
* | R | 9
* | GND | GND
* | G | 6
* | B | 5
*/
#include <SparkFunBQ27441.h>
// Pins
const int R_PIN = 9; // Red
const int G_PIN = 6; // Green
const int B_PIN = 5; // Blue
// Settings
const unsigned int BATTERY_CAPACITY = 400; // 400mAh battery
const int thresh_green = 60; // % state of charge
const int thresh_yellow = 40; // % state of charge
const int thresh_orange = 20; // % state of charge
const int thresh_red = 0; // % state of charge
// Global variables
unsigned int full_capacity;
void setup()
{
// Set up pins
pinMode(R_PIN, OUTPUT);
pinMode(G_PIN, OUTPUT);
pinMode(B_PIN, OUTPUT);
// Configure battery monitor
Serial.begin(9600);
setupBQ27441();
}
void loop()
{
// Read battery stats
unsigned int soc = getSOC();
// Display SOC on LED
if ( soc >= thresh_green )
{
showColor(0, 255, 0);
}
else if ( soc >= thresh_yellow )
{
showColor(150, 255, 0);
}
else if ( soc >= thresh_orange )
{
showColor(150, 10, 0);
}
else if (soc >= thresh_red )
{
showColor(255, 0, 0);
}
else
{
showColor(0, 0, 0);
}
delay(1000);
}
void setupBQ27441(void)
{
if (!lipo.begin())
{
Serial.println("Error: Unable to communicate with BQ27441.");
Serial.println(" Check wiring and try again.");
Serial.println(" (Battery must be plugged into Battery Babysitter!)");
while (1) ;
}
Serial.println("Connected to BQ27441!");
lipo.setCapacity(BATTERY_CAPACITY);
full_capacity = lipo.capacity(FULL);
Serial.print("Full charge capacity set to: ");
Serial.println(String(full_capacity) + " mAh");
}
unsigned int getSOC()
{
// Get battery stats
unsigned int soc = lipo.soc();
unsigned int mv = lipo.voltage();
int current = lipo.current(AVG);
unsigned int capacity = lipo.capacity(REMAIN);
full_capacity = lipo.capacity(FULL);
// Print stats
String toPrint = String(soc) + "% | ";
toPrint += String(mv) + " mV | ";
toPrint += String(current) + " mA | ";
toPrint += String(capacity) + " / ";
toPrint += String(full_capacity) + " mAh";
Serial.println(toPrint);
return soc;
}
void showColor(uint8_t r, uint8_t g, uint8_t b)
{
// Invert the PWM for common anode RGB LED
analogWrite(R_PIN, 255 - r);
analogWrite(G_PIN, 255 - g);
analogWrite(B_PIN, 255 - b);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment