Counting Ants

Goal: To make Arduino-based ant counters that can eventually log data for months in ant hills. This information should help figure out how the behavior of colonies of these social insects change as they age. Queen harvester ants may live for a decade and colony behavior evolves over this time. When she dies the colony dies. In addition to recording temperature, humidity, and light level, we have to quantify ant activity. We’ll test it first using ants living in a lab before trying these loggers in an Arizona field this summer.

I’m very new to programming and am starting with an Arduino Uno with a Logger Shield w/ RTC and SD card mounted. I have successfully worked through the well-written introductory guidance and have logged one second light and temperature data from a refrigerator, and graphed files from the SD card in Excel. They work great! I then changed the delay between entries and sync intervals from 1000 to 60000 mills and, sure enough, the Arduino logs well at that rate. I can follow the well annotated code – but don’t understand many of the twists and turns it makes and haven’t a clue how to write code to add features without ruining what works.

To minimize noise in the data, I would like to make registers, zero them, and add 1/60 each of 60 readings taken each second to the respective registers before writing this averaged one minute data to the SD Card. How would one do this?

The next step: two Infrared (IR) sensors look at an IR LED and when an ant blocks the radiation, from first one, then both, then the other, I’d like to increment an “out” register, and if in the opposite sequence, an “in” register (with carry over if an ant happens to be in the beam when writing one minute data to the SD card). To save battery power, the IR LED should be turned on only 1ms every 100 ms (a guess – shorter duty cycle if possible) and the output of the two IR sensors only read then. I’m sure the Arduino can do all these things – but it will take someone that knows more than I to write the instructions for it to follow.

ir beam ants ? i dont think it will work out ! what is the size of the ants you are working on ? to block a n ir beam youll need ants of the sizze of your fingers !

Harvester ants are large (for ants: up to 5 mm) but not as large as a finger. I can use a pinhole to limit the size of the beam so that it only "illuminates" the IR LEDs that are 4 mm apart. The "tunnel" that the ants travel through, and the sensors are in, is 5 mm wide and the sensitive areas of sensors are maybe 9 mm apart.

It would be good to post the code that you have now using the # button.
Since you have several things going on you may have to avoid using delay(), and instead use interrupts, or look at the digital--> blink without delay example in your software. Delay basically freezes the entire program for that time.
To average using delays it would look like:
data1= analogRead(sensorpin);
delay(17); // 17 milliseconds
data2= analogRead(sensorpin);
delay(17); // 17 milliseconds
data3= analogRead(sensorpin); //and so on

average= (data1 + data2 + data3) / 3 ;

You may not want to average an entire second if the ants are moving fast.

I'm only just beginning to learn how to develop code for this so I am now using the code that comes with the Logger Shield: GitHub - adafruit/Light-and-Temp-logger: Example code for Adafruit data logging shield

I see how you averaged data below but wouldn't that take 60 bytes for each of the five data sets? Then having to retrieve them all before adding them together before averaging them. Wouldn't it be easier to use only one variable per sensor, clearing it at the start, then adding 1/60 of each number for 60 times then simply printing the number? That's a different way to make an average that can be done in the same line of code that converts the voltage to degrees C, for example. float temperatureC = float temperatureC + (voltage - 0.5) * 100 / 60 (from a line in the above code) but I don't know how to do this 60 times, or otherwise keep track of when to log the numbers, when the minute is up. How does one use interrupts? What's the digital--> blink you referred to?

I also don't understand the statement: "You may not want to average an entire second if the ants are moving fast." What I hoped to do was to simply count ants going from left to right, and from right to left (through a tunnel) and do this for a minute, along with the temp., humidity,and light readings, then print all five to the SD card. But I don't know how to look at a series of sensor readings, as an ant interrupts the beam to first one sensor, then both, then the second and turn this sequence into a "one ant going out" count. The tunnel will be narrow enough so that only one ant at a time can go through (hopefully).

You can copy and paste the code using the # button.
If you use delay(17); then you won't be able to take any other readings during that time, so instead you could look at examples-->digital-->blink without delay. (it's in your arduino IDE program)
I was thinking that if the ants move really fast then you might only get two positive readings out of 60, which will average out to a low number. There's going to be a little jumpy noise in your readings anyway, your null reading might be between 165-175 so a small reading might average into that and would look like noise.

But I don't know how to look at a series of sensor readings

You can use analogRead for each of the pins and read one after another
Looking at a different temperature logging project might help with coding ideas.

what is the speed at which the ants would be moving generally a normal analogread would be fast enough to read the ir beams and what kind of an ir sensor are you using a custom one i guess generally ir sensors are analog (varying voltage ) look there and you will know hoe to get the sensor's readings something meaningful to you

I'm a nature photographer, I spend a lot of time watching ants and frankly I think you're trying to push sh1t uphill with a pointed stick. This is the old count the number of people in a room problem but a 100x worse because ants are totally random in their behaviour.

Assuming that the tunnel has to be large enough for two ants to pass each other there will be all sorts of scenarios where two are read as one, one stays still in front of the beam while 10 walk past, another gets half way through the beam then decides to go back out, an ant walk in carrying a seed but the gap between them is large enough to register as a break, a worker ant meets a soldier directly in front of the beams, they sense each others pheramones then both the worker and the soldier go out, all combinations of the above at the same time, etc etc.

And if you can't limit the tunnel to only two ants all the above x 10.

There has to be another way, surely you don't have to count every single ant, maybe some system that worked on "ant density" using weight (how much does an ant weigh?), average light over the whole tunnel or something.


Thank you for your comments. It'll be only through iterations that we'll get equipment that works - even though it may evolve into what is possible, not what we dreamed.

The sensor tunnel will essentially block the entrance of an ant hill and be narrow enough for only one ant to go through at a time - that happens in their tunnels if stones prevent their moving them. If that bothers the ants too much (so that they make a way around the sensors) we'll widen it so that two can pass through at the same time. Initially, the only information we wanted was "When do the ants from different age colonies start foraging in the morning, and how late to they stop?" The premise: middle age colonies are more aggressive than younger ones to make sure they get all the worms, if they can (like early birds). So it doesn't really matter if we miss counting some, if we can simply record ant activity. Counting all day should be a function of colony size - without having to dig up the whole nest and count every ant -that does in the colony (which is the only way to do it now).

but I don't know how to do this 60 times, or otherwise keep track of when to log the numbers, when the minute is up. How does one use interrupts? What's the digital--> blink you referred to?

Each time you add to the average, increment a separate counter variable as well. When the counter = 60, log and reset. Something like:

  temperature += (voltage - 0.5) * 100 / 60;
  tempCounter++; //this can be defined as a byte (but if you want to increment up to values above 255, you'll need to use a larger variable
  if(tempCounter == 60){
    //write out your temperature
    //reset variables
    tempCounter = 0;
    temperature = 0;

There are several timer libraries available that will help you easily run the above code at some specified interval. No need to reinvent the wheel, except as a learning experience. But for that you can just read the code those libraries use.

Very good advice, Arduino Rocks - I'll try it :).

What I'm trying to prove at the moment is a circuit similar to the Honeybee Hive Traffic Counter: that uses the Arduino instead of flip-flops and counting module. Once I have the Arduino record a series of signals that represent an ant going first in one direction, then the other, I'll post them for suggestions on how to reduce the swings in analog voltages of the two side-by-side sensors viewing an IR transmitter to a single "in" or "out" count. If we don't succeed, we can always just record "an ant went by", like the bee counter. It would be nice to make an Arduino smarter than that.

Just wondering, how will you know if the ants build another exit from their colony? How will you get your mechanical tunnel into their dirt tunnel?

Biggest question, how do you know that adding equipment to their colony won't change the behavior you are trying to monitor?


The Arduino-based counters are supplements to weeks of actual daybreak to sunset personal observations, which has been the primary mode of taking data at the site for many decades. But folks need R&R and you can't carefully watch more than a few colonies at a time. By watching and taking notes with a few instrumented colonies and a few pristine, of matched age, one can get an idea of the effect of partially blocking an entrance. Larger, and older, colonies have multiple entrances/exits so that they can be monitored before placing a sensor stick to see if traffic changes (the sensors are buried in a broken branch that looks natural so that passersby won't notice them and want to pick one up to examine it when the scientists are not there - the Arduino and battery will be buried a foot or two away and the cable covered - we chose IR sensors so that they don't attract attention at night).

My personal opinion is that you want to force the ants through a dark passage and use near infrared imagery to pick them up, then use machine vision techniques to track individual ants and track how many head which way. This would be far beyond the ability of Arduino, but well within what you could do with gumstix or something akin to that -- an ARM and more than a MB of memory.

Just wondering, how will you know if the ants build another exit from their colony? How will you get your mechanical tunnel into their dirt tunnel?

Biggest question, how do you know that adding equipment to their colony won't change the behavior you are trying to monitor?

But that is already establish scientific fact: Measurement changes behavior.

So it's pretty clear that the 'counting ants' section of this project is really not trivial.

To make it a bit clearer, is this your propsed setup?
(Apologies for ACSII art)

        IR LEDs
<outside         colony> |_ one ant width
     _           _       |
----| |---------| |------ 
       IR Sensors

There are obviously many many issues, some of which have been discussed. What kind of accuracy do you need? Dealing with scenarios, such as those suggested by Graynomad, will be a big part of it. For instance, what if an ant passes the first sensor but by the time he's reached the second another ant has already passed the first? You could say you'll keep them less than an ant's length apart, but then what if two ants enter one after the other really close (touching, say), then separate between the sensors? If you're not looking for to-the-ant accuracy then I'm sure it's possible to come up with something to deal with that, but even then it would require some testing to find out how often you're expected to deal with these non-trivial scenarios.

I think what I'm trying to get across is that I doubt it's going to be a simple case of looking for 'beam 1 broken, beam 2 broken, therefore ant going in'. When you're working at such small scales how will you multiple triggers by the ant's sedmented body shape, for instance or legs or anything else?

But maybe you've consiered this already - Could you describe your physical detection setup a bit more in depth?

If you had more than couple of sets of sensors, you could improve the probability of correctly counting ants.

       IR LEDs                             IR LEDs
<outside                                                                     colony>
----| |----------| |---------------------| |---------| |------
       IR Sensors                         IR Sensors

Repeat the sensor 3 or more times even. Then count separately at each station, and then if any of the stations, or the majority of the stations see an ant going in or out, this is your best guess an actual in/out passage. All this does is add to the chances of at least one station getting a clean count.

With no multiplexing, you should still be able to run 5 or 6 stations.

Quite apart from the technical difficulties in counting I have just though of something else,

How the heck do you prove the code works? :slight_smile:


How the heck do you prove the code works?

Well, what I do for this sort of thing is to write the code and test it on a real computer. There I can write a test harness that can feed fake events into the logic and test all kinds of situations easily, with the help of a debugger and such. Once it's on the Arduino, I think I would knot a bunch of bits of black rubber onto lengths of fine monofilament at various spacings and pull one through one way and another through the other way and see how the Arduino count matches the actual number of knots. Finally, you could video record the comings and goings of ants for little 5-minute stretches and compare visual counts with what the Arduino guesses.

I don't think it would be too hard to establish reasonably sound error bars around the data collected by this method.

How the heck do you prove the code works?

Well you start out by hiring some trained ants and then......