Simvik

Average current of a duty cycle

Turn the states of one cycle into an average current and a battery life in days. An easy embedded C problem (A current budget and battery life), run and…

easy · A current budget and battery life · power · arithmetic · battery

A device repeats a cycle of phases, each with a current (µA) and a duration (ms):

typedef struct { double ua; double ms; } phase_t;

Write:

  • average_ua(p, n): the average current over the cycle, the sum of current × time divided by the total time. 0 for an empty cycle.
  • battery_days(mah, avg_ua): how many days a battery of mah lasts at that average, counting 80 % of its capacity as usable. A non-positive average lasts for ever: return -1.

Starter code

double average_ua(const phase_t *p, int n) {
  double sum = 0;
  for (int i = 0; i < n; i++) sum += p[i].ua;
  return n ? sum / n : 0;
}

double battery_days(double mah, double avg_ua) {
  return mah / avg_ua / 24;
}

Example tests

A sensor that sleeps, measures and transmits

phase_t cycle[] = { { 2, 899650 }, { 3000, 50 }, { 25000, 300 } };
double avg = average_ua(cycle, 3);
printf("%.2f uA, %.0f days on 2500 mAh\n", avg, battery_days(2500, avg));

Expected output:

10.50 uA, 7937 days on 2500 mAh

Always awake

phase_t cycle[] = { { 5000, 1000 } };
printf("%.2f uA, %.1f days on 220 mAh\n", average_ua(cycle, 1), battery_days(220, average_ua(cycle, 1)));

Expected output:

5000.00 uA, 1.5 days on 220 mAh

Learn it first