I have a small project that I could use help understanding how best to move forward.

I have a set of 8 batteries of different voltages and age.

I’d like to read the voltages of all, assign an identifier to each battery , store those voltages in an array (I assume), then sort the array from the highest voltage to the lowest, pick the top 4 highest voltage batteries, and then “do something” (like light a led next to each of those 4 batteries indicating the top 4 highest voltages).

Although I’m quite a Arduino newbie, I do know how to read the battery voltages. The rest I have a vague idea but really stumbling with how to sort and then do something with the curated sorted list.

Thanks for any help or guidance!

  • 1
    \$\begingroup\$ This might be a better fit for the Arduino stackexchange. \$\endgroup\$ – Hearth Feb 10 at 17:24
  • \$\begingroup\$ I assume you mean you know how to read the battery voltages in place, because you talk of lighting an LED next to each. \$\endgroup\$ – TimWescott Feb 10 at 17:26
  • \$\begingroup\$ @TimWescott thanks for the reply. Yes, I believe I know how to test in place. The led indicator would be driven from another pin and located next to the battery. \$\endgroup\$ – Nicholas Feb 10 at 18:32

So, your question about how to sort this and do something with it is a general programming question, not specifically an Arduino question.

There's many ways to skin this cat. The way I'd do it would be to define a structure with everything about the battery that I wanted to know -- let's assume it's just the voltage and physical position:

struct BatteryDescriptor {
  float voltage;
  unsigned int position;

I would make an array of that structure, one per battery. Then I'd sort that array on voltage. There are a lot of ways to do this. If you have a full C library available you can use qsort. I'm assuming you don't have the STL library available. Finally, you can roll your own.

There are a LOT of sorting algorithms out there. Because you're only sorting eight things, and you're a beginner, I recommend a bubble sort. Google it. Further, I recommend that you do the sorting in place (as opposed to making an array of pointers to your array of descriptors, or making your descriptors into a linked list).

When you're done, you should have the four highest-voltage batteries at the beginning or end of your list. You can step through that with a for loop and turn on your LEDs.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.