I'm a design teacher trying to help a student with a programming challenge, so I code for fun, but I'm no expert.

She needs to find the mode (most frequent value) in a dataset built using data from sensors coupled to an Arduino, and then activate some functions based on the result.

We've got most of it figured out, except how to calculate the mode in Arduino. I found the post Get the element with the highest occurrence in an array that solves the problem in JavaScript, but I haven't been able to "port" it.

Best Answer:

I've used a HashMap to replace the js {} dynamic object instance and floats, but @weberik's port looks more straightforward.

void setup() {

    int numValues = 10;

    float[] values = new float[numValues]; //Create an empty sample array

    for(int i = 0 ; i < numValues ; i++) values[i] = random(0.0,100.0); //Populate it with random values.

    println("mode: " + mode(values));


float mode(float[] source) {

    if (source.length == 0)

        return -1;

    HashMap<Float,Integer> modeMap = new HashMap<Float,Integer>();

    float result = source[0];

    int maxCount = 1;

    for (int i = 0; i < source.length; i++) {

        float el = source[i];

        if (modeMap.get(el) == null)




        if (modeMap.get(el) > maxCount) {

            result = el;

            maxCount = modeMap.get(el);



    return result;


You've mentioned sensor input, so I presume data will be sampled continuously, so values could be stored at a certain interval, then sent to Processing for the mode. Just a wild guess, but isn't she looking to average/smooth out sensor readings a bit? If so, she could cache a few values (say 10) in an array in Arduino and get the average everytime a new values is added:

int vals[10]; //Array to store caches values.

void setup() {


    for (int i=0 ; i < 10 ; i++) 

        vals[i] = 0; //Init with zeroes


void loop() {


    int currentVal = average(analogRead(0));




int average(int newVal) {

    int total = 0; //Used to store the addition of all currently cached values

    for(int i = 9; i > 0; i--) { //Loop backwards from the one before last to 0

        vals[i] = vals[i-1]; //Overwrite the prev. value with the current(shift values in array by 1)

        total += vals[i]; //Add to total


    vals[0] = newVal; //Add the newest value at the start of the array

    total += vals[0]; //Add that to the total as well

    return total *= .1; //Get the average (for 10 elemnts) same as total /= 10, but multiplication is faster than division.


Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs