Category Archives: Teacher Resources

Tutorial: Adding the SSD1306 OLED Screen to an Arduino Logger (without a library)

An SSD1306 OLED screen mounted on a climate station build.

This is the third installment in a series on adding output screens to Cave Pearl Data loggers. It builds on the Nokia 5110 LCD tutorial and the post describing how I store fonts in the Arduino’s internal EEprom to save program memory – so you might want to have a look at those two posts before diving in here.

While the Nokia 5110’s are a cheap, low-power option with great visibility in full sun, they reacted badly to pressure directly on the LCD surface.  Since this project deploys loggers in an underwater environment I went looking for something more robust and the SSD1306 OLED’s caught my attention. (@ ~$3.50 on eBay) These little screens are showing up in hacked toyscompasses, GPSanalog meters, ECG’s, and theres even a tiny oscilloscope project at Hackaday. But those applications typically use the u8g2 library which is fantastic for graphic output, but also quite memory intensive; what I need is a bare bones solution that uses the fewest system resources on a unit that’s already near memory limits. Though these 0.96 inch displays are quite small, 128×64 pixels lets you render several lines of readable text.

While the I2C variants of this screen are easy to use, the SPI version lets me re-purpose unused analog lines to drive this display without interfering with the sensor or SD card bus because it can be driven via shift-out on any pins that are available. Powering the screen from A0 brings the screen down to zero current while the logger is sleeping, and also lets me get rid of the Reset & Cable Select lines. The only thing to watch out for is that you bring all the control lines low when you cut power so that reverse bias doesn’t end up “back powering” the screen controller.

Connecting the OLED:                                {Click any image to see larger versions.}

The data sheet for the SSD1306 controller specifies that the reset input needs to be LOW, during initialization, after which the pin should be HIGH for normal operation. To achieve this low -> high  transition, I tie the Reset line to the middle of an RC bridge made from a 104 (0.1uF) capacitor and a 10k resistor. When you add the 25k inside the 328p used to pull A0 high, you get a 63.2% time constant of about 3.5ms.

Begin by tinning the pins, and bending them 90 degrees for alignment with the RC bridge which also connects to the CS pin.  Once that delayed rise circuit is soldered in place, also jumper the incoming GND line over to Cable Select. You would not do this if the display was on the normal hardware SPI bus, because it would exclude other devices on the SPI bus. But since we are using a separate set of wires for the display we can get away with this trick.

The connections for the SSD1306 OLED display are the same as the ones for the Nokia 5110: (D0=clock, DC=command, D1=data in)  Note that I’m not using the 3.3v rail from the pro-mini,  and YOU MUST BE USING A 3.3V ARDUINO FOR THIS WIRING TO WORK UNLESS YOUR OLED BOARD IS 5V TOLLERANT.  Some of the breakouts  from eBay are OK at 5v, and some are not – check THIS before you buy if you are using a 5V Arduino.  (Note that  most breakouts sold by Adafruit include regs & level shifters to handle both voltages.)

When all the incoming lines have been added to the board, thread them through the housing and verify that the screen is still working. The analog A0-A5 lines on an Arduino can be re-purposed as digital I/O so I usually break them out with a 6-pin Deans Micro Plug (incl. GND & Vcc)  In this case the screens Vcc line is being re-routed to pin-powering from A0 so the pro-mini’s rail voltage is not used.  Cut away or heat-shrink over the unused Vcc pass-through on the screen side of the connector (which is still visible & exposed in the photo on the right) as you don’t want it accidentally contacting something later on inside the housing.

After the operation test, cork the pass-through hole with a bead of plumbers epoxy putty  about the size of your fingertip. Wrap that putty so that it is on both sides of the wires before smoothing it down on the housing.  (The sensor cap shown below has four housing penetrations sealed by this method)  On the top of the sensor cap, wrap a grape-sized lump of well worked putty around the wires on the back of the screen. Then carefully press the screen down into the PVC well so that the putty compresses into a support pillar that holds the screen as near level as possible. The putty hardens in about 10 minutes and then you can pour the first layer of potting epoxy. Here I’ve used Loctite HYSOL E-60NC, with a 50ml applicator & MA6.3-21s mixing nozzles. The air space for the reflective back light forced me to use clear epoxy with the 5110 LCD screens, but since these OLED’s emit their own light, you can bring that black epoxy right to the edge of the display – covering the board & any ugly soldering… 🙂  Check the epoxy over the next couple of hours and pop any bubbles that rise to the surface with a pin. 

Always TEST before potting!

Let that initial layer of epoxy cure for 24 hours, then drill a 7/32″ hole at a safe distance away from the screens edge. Mount an RGB indicator led inside the housing and seal it in place with plumbers putty. At this point you can simply add a second layer of clear epoxy to protect the screen, but in our experiments with the Nokia LCDs, seawater caused a serious fogging problem.  So I recommend a top surface of more chemically resistant material for that kind of application. Here I’ve used a 1/4″ thick plexiglass disk (~$0.35 each on eBay)
First apply a thin layer of clear epoxy over the screens surface so that it self-levels to thickness of about 1-2mm. Then hold the edge of the acrylic disk and carefully tilt it over the epoxy film with an even contact edge that moves across the disk slowly enough to let the air escape.  Don’t make that first layer of clear epoxy too thick or it will over-top the edge when the plexi settles into place and this will form blobs on the surface. Once the acrylic is in place, you can slowly add drops of epoxy on the side to bring the level up to match the edge.  Give the clear epoxy another 24 hours to cure.

The display draws more current as you increase the number of pixels turned on.  As a point of reference: the screen output shown above (generated from the code on Github ) draws 3.4 mA.  And I haven’t seen any nasty current surges that might exceed the pin limit when the display is first powered up.

The shore hardness of the plexiglass is not much higher than cured epoxy, but the optical clarity is considerably better. The photos in this post don’t capture it well, but this mounting method really shows off the razor-sharp output you get from an OLED, and it’s readable from just about any angle.  For surface loggers a 1/8″ disk should provide sufficient protection, but for the underwater units I will use 1/4″ thickness to resist the compression at depth. I won’t be able to test those underwater versions in the real world for a few months, but if the acrylic fails I will change to  a stiffer glass overlay.

A few might wonder why I added an indicator LED when the logger now has full display capability. There are plenty of situations where brief LED pips communicate the progression of duty cycle events that are too fast and too numerous for screen output. I also use the LED as a noise generator when I want to squeeze higher resolution from the ADC through oversampling.  These days I add an NTC thermistor to every build to capture ambient temperature.

The Code Example on Github uses a cascading method to break text strings up for single character rendering with : oledWriteString–>oledWriteCharacter–>oledWriteData  and I’ve co-opted that with a new split-character method to print larger numbers to the screen in a two-pass method.  The shift-out code for those functions is basically the same as that used for the Nokia 5110. I went over all that in some detail in the earlier posts so I wont re-fry those beans here. The key thing to keep in mind is that this new screen driving script uses EEPROM.read which assumes you’ve already loaded the font definition(s) into your Arduinos internal eeprom with this helper utility.  That utility loads a ‘reduced’ font set to leave 500 bytes of space for file header data in the EEprom as well. (so the 5×7 font is caps only, and large characters are #’s only).  If you don’t need that level of memory optimization in your build, you can switch back to simply storing the screen fonts in program memory;  just transfer the PROGMEM based string->character->data functions (and the font arrays) over from in the NOKIA 5110 code example.

The housekeeping functions that take care of  initializing the screen, clearing the memory, and setting the XY position are more complex for the OLED than those for the PCD8544 Nokia because the SSD1306 controller has more operating parameters.  But the overall approach transferred easily between the two controllers and I suspect this method could be re-used with most of the larger SPI OLED screens on the market (like the SH1106) provided they stay below the pin current limit on A0.

Time to go shopping!  🙂

 

Addendum 20181019:

A helpful commenter has informed me that it’s possible to try a similar approach with I2C screens because you can bit-bang I2C devices over any two spare wires.  Now that we’ve pulled off this isolation trick with SPI, I’ll look into bang’n as a way to shut down high current I2C sensors when they are not in use.  I’d want those off the regular I2C bus because it necessarily has a few “always on” devices that might not respond well to a lump of dead wood hanging off the same wires.

Starting Points & Ideas for your Arduino STEM Curriculum

Arduino Starter Kits can be assembled from $10 to $100 per seat depending on the complexity of your course. We generally order parts about a month beforehand and then spend a day pulling it all together into “ready to go” lab kits at the start of term.

Over the last decade the open source Arduino platform has been embraced by STEM educators, and there are a growing number of pay-per-use resources available with pre-made lesson plans, etc. (eg: becauselearning.com While most welcome viable business models in the sector, it struggles against the problem of ever shrinking education budgets. Where the rubber meets the road you are faced with the stark reality that many teachers now have to pay for teaching materials with their own money:

“Classroom teachers spent an average of $468 out of pocket on classroom supplies and equipment in the last year — amounting to nearly 1 percent of an average teacher’s salary in the United States. Nearly eight in 10 teachers — 77 percent — spent “at least” $200, with some as high as $5,000, according to the latest results of an annual survey.”


With that in mind, I’ve started this list of links to STEM learning resources, curriculum, and activities for Arduino.  Unlike more formalized lists of this type, the focus here will be on creative IDEAS and resources that teachers can access for FREE ( eg: WeTeachNYC’s Gr9 lesson plans , textbooks online, etc.)

This page will grow over time as I find more material:


Arduino project IDEAS:

Any teacher worth their salt already knows how to make lesson plans, so the tough part is finding a theme that really motivates your students.  If you are looking for science project ideas, it wouldn’t hurt to browse through a few commercial data logger websites sites to see how people use loggers in the real world. Then search through the Arduino sensors forum and see if someone has already posted helpful information about the application your students find interesting.  Though the Cave Pearl Project is focused on environmental monitoring, you should’nt overlook the other cool things that people do with Arduinos for more information on integrating sensors (eg: building instruments like the TC1 slinky seismometer) Browsing through the Arduino project hub gives you some sense of the range.  A good number of artists create interactive pieces by adding motion, sensing, LEDs & sound. Wear-able projects are also pretty groovy.  Others create simple robots with their Arduinos, and there are plenty of body/wheel/motor kits to get you rolling. Drones get all the media attention, but I think underwater ROV’s are also interesting.

There are lots of great maker resources to search through if can appreciate their sense of humor (though you might want to avoid clock projects 🙂  Intructables is heaving with Arduino projects which you can find simply by searching for “Arduino” + “subject”.  If you find an Arduino book that sounds interesting, there is a good chance that there are sample projects on the web from the book that you can review.  GPS tracking opens up interesting possibilities and the folks over at the RIFFLE project have been pulling that location data out of digital camera photos, with their data logger hanging from a kite.  So really, the sky is the limit . . . or maybe not even that . . . commander Sparkles.


Most ” Discovering Arduino ” resources follow a pattern something like this:

Introduction of the Arduino board. (hardware)
Introduction of the Arduino programming environment and the structure of a script. (software)
Introduction of the breadboard. (hardware)
Blinking the internal LED at pin 13. (software)
Connecting a LED to Arduino using a breadboard. (hardware)
Using a digital output pin to blink the LED. Using multiple digital output pins & leds (software)
Pulse-width modulation for fading LEDs. (software)
Connecting a button to the Arduino, with de-bouncing cap/resistor combination. (hardware)
Programming  to support the button input , if/then/else conditional behavior. (software)
Introducing the serial monitor for text output of events (software)
Connecting analog sensors to the Arduino with voltage dividers. (hardware)
Capturing sensor readings with the ADC and storing them in a variable. (software)
Using the serial plotter for live display of sensor output (software)
Advanced programming concepts (e.g., for/while loops, counters, switch/case). (software)
Connecting digital bus sensors with pull-up resistors (usually I2C or OneWire ) (hardware)
Including code libraries to so you can read data from those digital sensors (software)

As you can see, learning the Arduino platform is like climbing a ladder, where each step you take toward understanding the electronics is matched by one learning how to write code.

Where To begin:
The instructables beginners guide is a good place to start, as is Udemy’s free Learn the Basics Arduino Tutorial. Actually instructables has been busy building a range of free beginners classes on subjects from the internet of things to 3D printingetc.  There are plenty of other “Getting started” videos available with  another free video course offered at the Programming Electronics Academy (also see their other Youtube videos). Many of these courses require some kind of registration, and given the nature of their business you can expect a fair amount of self promotion messages to be peppered throughout. And finally, don’t overlook the official Arduino example tutorials that come built into the IDE. There are some great learning examples in there like the Tone Pitch follower with tutorials by Massimo Banzi himself.

Special Mention:
Be sure to check out Jeremy Blum’s Arduino Tutorials which are essentially a complete course on the Arduino;  all the more impressive because he did the entire thing as a one-man-band while he was still a student.  In my opinion,  the best quality videos available for Arduino are the ones created by Jeff Feddersen & Tom Igoe for the ITP program at NYU, though there’s a lot to wade through, and some of those tutorials might be pitched at too high a level for beginners. Paul McWhorter also has an extensive tutorial series on youtube.

And don’t forget to search for the many new videos that people have posted. Youtube has grown into a universal self-teaching tool and we’ve entered the game with clips from our fieldwork, and build tutorials.

Arduino in a Nutshell is a free e-book resource worth looking into, as is the Programming Guide from instesre.org. And though I’m not sure if they are still a going concern, the old Earthshine Starter kit manual PDF can still be found floating around the internet. If e-books like that are your thing, and you are willing to shell out a few bucks, there are sometimes good Humblebundle deals, though those are often in weird combinations of topics, and the individual books also available the Make website.

Sparkfun is also a great place to look for teacher resources.

It’s a lot to wade through, but the Adafruit tutorial list  is another one of the best resources out there. Just be aware that they have developed their own library “system”, so sometimes their tutorials are tailored to that.

Tronixstuff has a large number of  specific hardware tutorials when you are ready to go further with your Arduino projects, and there are a host of cool Arduino projects to dig through at instructables site. I really believe that you can improve engagement and understanding by providing hands-on experience with real data, but there are plenty of other practical things you can do with the same basic setup.

If you google around, you can find curriculum documents, individual lesson plans, and other resources all over the place, like for example this conductivity lab over at teachengineering.org or this beginners set from Arduino 101.  The challenge is that most of the sites were developed for a different curriculum than yours, so first figure out what you want to tackle, then go sifting through the tutorial sites for material that matches your learning outcomes. Otherwise you will just get buried in the shear volume of it all.

If you want to abstract away the entire IDE interface for younger students, there are a few visual programming tools out there for the Arduino like Visuino, or MIT’s Scratch, for which there are plenty of tutorials on youtube.

Going further:
There is also a long set of more detailed videos at Makecourse.com. Though it’s a bit dry, All About Circuits has a complete textbook online [see: Vol. I – Direct Current (DC) ] And if you really want to dig deep, several universities like Stanford, MIT & Berkeley have made full electronics courses available, though that goes well beyond the Arduino landscape. There is a good walk through the sub-components that make up an UNO at Rheingold Heavy’s build an Arduino From Scratch series.  And I’d be remiss if I didn’t mention the Mini-notebook series that that Forest Mims wrote back in the 70’s.


Using Social Media to find resources:
Like Pinterest, Reddit has grown into one of the most useful social media sites for leveraging other peoples knowledge to help you find useful resources.  I’ve compiled a short list of places that might be good starting points.  You can also find material with the right hashtags on twitter such as #DIYscience.  But social media like Twitter/Facebook/etc can easily waste as much of your time as it saves, so finding good material is directly related to how particular you are about following people who actually contribute resources to the community (as opposed to those who are merely talking about it)

A few Teacher & Maker sub-reddits:

Teaching & Education
/r/ScienceTeachers/ – Chemistry, Biology, Physics, Astronomy, and General Science for K-12
r/matheducation
r/education -news articles about America’s education system, from Pre-K through PhD
r/teaching

Electronics:
/r/arduino – Arduino and compatibles. Lots of projects posted, discussion leans more towards programming with dabbling in circuit design

/r/electronics – About electronic circuit design and occasionally embedded systems
/r/raspberry_pi – Discussion about the Raspberry Pi & /r/raspberrypi
/r/embedded – Similar to /r/arduino and /r/raspberrypi but not platform specific
/r/3Dprinting – 3D printers

Others that instructors may find interesting:
/r/diy – The granddaddy of them all. Largely focused on home improvement but has content from just about everything.
/r/crafts – Sewing, knitting, scrapbooking, kids crafts, etc. and /r/craftit – Smaller version of /r/crafts
/r/somethingimade – Largely arts & crafts related, occasional woodworking or self made website posted
/r/maker – For people who make things. Doesn’t seem to be very active.
/r/woodworking – 50/50 between using power tools and hand tools. Wide variety of projects posted from simple to “they must be professionals”
/r/metalworking – Stuff you can do with metal
/r/welding – Welders, machinists and all other enthusiasts of joining two things together
/r/outstruments – Musical instrument making
/r/lego – Lego is made of ABS plastic and you can use a tiny dab of ABS plumbing solvent (nasty stuff!) to weld it together into a custom bullet-proof housing for your Arduino project. Great for internal scaffolding too.  also see /r/AFOL – Custom designed LEGO creations.


YouTubers on Science & Technology:

Like the other flavors of social media, YouTube can give a boost to your STEM lessons, provided you don’t go down that rabbit hole until after you already have clear lesson outcomes in mind.  It’s hard to pick a favorite, but Ben Krasnow @ Applied Science might take the title because he does incredible things without the over-the-top wow-yuck factor that the media seems to feel is the only way to make science interesting.  When Ben wants an electron microscope – he builds one.  Super Conductor? ditto. Plasma tube? easy-peasy.

Life, the universe, & everything:
Veritasium – An element of truth – videos about science, education, and anything else
Kurzgesagt – In a Nutshell – finding a new way to end the human race with every video
SciShow – delves into popular scientific subjects with lots of flash for younger audiences
Physics Girl – Physics videos for every atom and eve
Vsauce – Michael Stevens combines discussions of science and philosophy
BrainCraft – Vanessa Hill explains why we humans act the way that we do
ASAPscience  -explains topics in science with their trademark kinetic typography and drawings
minutephysics -physicist Henry Reich explains physics concepts simply  in a few minutes

People who put Arduino-things together:
Kevin Darrah
Julian Ilett – the Bob Ross of makers
Electronic Basics by GreatScott

People who take things apart:
bigclivedotcom – random take apart videos from expensive toys to cheap junk from China

People who explain how things work:
Engineerguy
Real Engineering
Practical Engineering
3Blue1Brown:  Brilliant animated introductions to complex math subjects

The Do-ers:
Smarter Every Day-engineer Destin Sandlin films himself doing his own experiments
Mark Rober
Cody’sLab
The Slow Mo Guys
Mike Boyd

The Story Tellers:
Curious Droid (Paul Shillito)
LindyBeige

The incomparable Colinfurze.  Close tie for the #1 spot because Colin is kind of like Ben Krasnow’s unhinged alter-ego from some parallel dimension where humans have very short lifespans.  Like ArduinovsEvil , and the site-which-must-not-be-named, this highly inappropriate material is best viewed at 1am when you’ve already killed off any high-function brain cells with a 10-hour exam marking marathon. (ie: Don’t show Colin’s videos to impressionable young minds unless you want to be fired, and never show content from AvE, and IFLS without serious vetting)


Other inspiring links:

What’s the Maker Movement and Why Should I Care?

The Maker Movement in K-12 Education: A Guide to Emerging Research

Progressive Education and The Maker Movement

TED Talk – Massimo Banzi (the primary founder of Arduino) – How Arduino is Open-Sourcing Imagination

Hans Rosling as an advocate for a “fact-based worldview” with his amazing bubble charts.

Tutorial: Adding Sensors ( & Modules ) to Your Arduino Data Logger

This in-cave micro-climate recorder had pressure & temperature sensors mounted in little wells of Loctite E30-CL epoxy. This sensor potting method is described in our Pro Mini build tutorials.  Weather sensing stations are the most popular type of Arduino-based Sensor project on the instructables.com website.

This post isn’t another How-To tutorial for a specific sensor because the Arduino community has already produced a considerable number of resources like that You’d be hard pressed to find any sensor in the DIY market that doesn’t give you a dozen cookbook recipes to follow after a simple Google search. In fact, you get so many results from “How to use SensorX with Arduino” that beginners are overwhelmed because few of those tutorials help people decide which type of sensor suits their skill level. This post attempts to put the range of different options you can use with a Cave Pearl data logger into a conceptual framework, with links to examples that illustrate the ideas in text.

One thing to note before you start is that many modern sensors will only accept 3.3v inputs, so UNO based projects need to check if the sensor they want to use is 5v tolerant. Most sensors from vendors like Adafruit put regulators on their breakout boards to handle this 3.3v-5v translation, but you may have to place level shifters between some of the more advanced digital sensors and an UNO based logger. Occasionally you run into the opposite situation where the sensor requires 5v (or more) forcing Pro Mini based systems to do the same thing.


Analog Sensors:

Some substances react to energy input by changing their physical or electrical properties. Arduinos can only read voltages, so to record these changes in the physical world some kind of circuit is needed to convert those properties into a voltage. Sensors that output continuously varying voltages in response to natural phenomenon are called analog sensors. Arduino pins A0 to A7 are analog input pins, and the ADC inside the microprocessor converts those voltages into a numerical value between 0 and 1023. It’s worth keeping in mind that those numbers are somewhat arbitrary depending on the reference voltage, and the behavior of your sensing circuit – so it’s up to you to figure out how to convert the raw ADC readings back into understandable units of the phenomenon you were trying to measure (like degrees Celsius for temperature, or m/second of wind speed, etc.)

A typical photoresistor divider from Sparkfun’s Voltage Divider Tutorial It’s worth noting that many LDRs go from 100 Ohm to over 1 MOhm. So you would have to change the series resistor to capture  a range that large.

The most common analog sensors are those that change their resistance in response to temperature (thermistors), light (photo resistors) or pressure (variants: force / stretch / bend )  If a sensor varies in resistance, you can turn that into a voltage by adding a fixed resistor to create a voltage divider circuit.  The non-sensing resistor in the divider is usually chosen with a value near the midpoint of the sensing devices range. For example, a photoresistor might vary between 1kΩ in the light and about 10kΩ in the dark, so a suitable resistor to pair it with would be ~5kΩ. For analog sensors that change by really small amounts, more sensitive Wheatstone bridge arrangements combine 2 or 4 sensors in the same circuit to expand the delta, but it’s the same basic idea: you are converting a change in resistance into a change in voltage.

Divider methods are referred to as ratiometric because the output voltage from the circuit is some fraction of the supply voltage determined by the resistances of the components. If the input voltage is doubled, the output voltage is doubled, so these circuits work fine on 5v UNO and on a 3.3v Pro Mini. By default the Arduino ADC takes a reading by comparing it to the same rail voltage supplying the resistive divider, and sensor nerds like me get all excited about this because it means that noise from your power supply will have no effect on the readings. You can squeeze more sensitivity per bit out of the Arduino’s humble 10-bit ADC by changing to a lower internal reference voltage. However once the Aref is different from your supply, that rail noise shows up on the divider output unless you squelch it out a smoothing capacitors.

Some light sensors get used in conjunction with a emitter for reflectance and ranging applications. You can create a reasonably good color sensor by combining an RGB LED emitter with a simple photoresistor. However, the humble LED  not only emits light, but can also be used to sense it because from a physics point of view, a diode is simply a PN junction, so a rectifier diode, a light emitting diode and a photo-diode are basically the same device.  Forrest Mims built some cool filterless photometers with LED sensors long before the mainstream media started waxing philosophical about ‘citizen science’.  (Also see: jpiat’s Li-Fi )

Most analog sensors are simple devices, but there are more complicated versions providing modified analog output, where some extra circuitry has been added to convert the highly non-linear response you get from typical resistance based sensors into the kind of straight y=m(x) relationship you get from a TMP36. This greatly simplifies the math required to convert your analog voltage readings into the real world property you were actually trying to measure. Some analog sensors (like thermocouples) generate tiny voltages, but those signals may so small that they need to be amplified before the Arduinos ADC can read them, so these analog sensors may also be sold with supporting electronic boards to boost the output.

Sensors can be mounted  inside a housing with a couple of layers of 3M Scotch Outdoor Mounting Tape. Sensors mounted this way have stayed in place for many years of deployment. The adhesive will sag somewhat under gravity if you expose your loggers to temps >55C.

At the top of the analog sensor food chain, there are complex Micro Electro Mechanical (MEMS) devices like accelerometers. In these sensors, silicon has been machined into very tiny physical devices made from springs, coils and flat sheets. These micro-cantilevers form capacitors that react to movement by changing a voltage and they are usually arranged in sets of three on x,y,&z axes. This means you need to read three separate input pins to capture a complete reading from the device. Since the Cave Pearl data loggers use pins A4 & A5 for communications with the RTC module, and A0 to track the main battery voltage, a complex analog sensor like the ADXL335 can use up all of the remaining analog inputs on the logger unless you build it with an Arduino that makes inputs A6 & A7 available. (the Pro Mini does, the UNO does not)  The limited number of analog input pins can motivate people to switch over to digital-bus sensors, though multiplexers provide another possible solution to the problem.

If you start with the project’s basic UNO logger script , adding a new analog sensor requires only three lines of code. Add

int AnalogSensorReading = analogRead(A0);  
// change A0 to match the input pin you connect the divider to

at the top of the main loop. Then add that new sensor data to the concatenated dataString which is saved to the SD card at the end of the main loop:

dataString += ", "; //comma separates new data from that already in the string
dataString = dataString + String(AnalogSensorReading);

That’s it. This simplicity is why analog sensors are usually the first ones people encounter when they are learning the ropes. Of course there are some advanced tricks you can play to supercharge Arduino’s humble 10-bit ADC, and you’ll find more useful tips over at Nick Gammon’s ADC tutorial.

Digital Sensors:

A bullet-proof de-bouncer from www.ganssle.com.    Compare this to the 5-key de-bouncing circuit from the IBM 705

Unlike analog sensors, digital sensors only output two voltages: High & Low. Usually the high voltage is the same as your power rail, and the low voltage is your system ground. In some ways that makes digital sensors easier to use, but there are some devils hiding in the details, and digital sensors cover the entire range from crude noob level devices to Gordian knots with more computational horsepower than the Arduino itself. Even the most complicated digital sensor usually has an analog sensor hiding somewhere at its core.

I group digital sensors into three conceptual categories:

Flippers,   Thumpers,  &   Thinkers

This is based on what kind of output they produce, rather than the complexity of their electronic circuits. And it’s not unusual for more advanced IC-based digital sensors to be as easy to use as the flippers & thumpers, because some kind soul has released a library that takes care of the gnarly low-level details.

1) Flippers

The humble push-button can be thought of as a crude pressure sensor that can be in only two states: open or closed. Add a couple of passive components for debouncing, and reed switches become the digital sensor of choice for event counting sensors like the tipping-bucket rain gauges you find in weather stations.  IR break-beam switches are another common implementation with on/off output.

When you first look into digital sensors there seems to be a bewildering array of different ‘breakout boards’ and ‘sensor modules’ for the Arduino. These are often sold in bundles of twenty, thirty or even sixty different pieces. Once you get a closer look at them, you notice that many these cheap sensor modules look similar to each other:

That’s because most of those boards are simply a voltage divider connected to one leg of a five cent comparator circuit, with a twenty cent trimming pot setting the voltage on the other side:

These boards switch their high/low output when the sensor voltage crosses the threshold set by the trimpot; changing the original analog voltage divider into an environmentally responsive threshold alarm. It’s such a generic circuit, and you could connect other resistive sensors and the board wouldn’t even notice. If you use these modules with the Cave Pearl loggers, look for boards that also break out that 4th analog pin so you can also read the sensors output with the ADC.

Integrating simple on/off digital sensors to your logger code would use almost the same pattern as the analog sensor reading:

pinMode(PinNumber, INPUT);  // Declaring the pin as an digital Input
int DigitalSensorReading = digitalRead (PinNumber);

dataString += ", ";         //comma that separates new data
dataString = dataString + String(DigitalSensorReading);

Those eBay boards are all somewhat redundant, since the Arduino has a built-in analog comparator on pins D6 & D7 already.  However there are many high/low output sensors with more complicated circuits that are not as easily replicated.  Proximity sensors can have complex internal circuitry and perhaps the most common of these more-advanced-but-still-simple sensors would be the passive infrared (PIR) motion sensors that seem to occupy every corner of the modern world.  Adafruit has a fantastic tutorial on how to use them with an Arduino, which also demonstrates how the boolean HIGH or LOW value you get back from digitalRead() can be used with if statements to select different courses of action:

Reading = digitalRead (PinNumber);

if(Reading == HIGH)
  {   Serial.println("input is HIGH");   }

if(Reading == LOW)
  {   Serial.println("input is LOW");   }

All the I/O pins on an Arduino can be used as digital inputs  (including the analog lines) and the cool thing about that is the circuitry hidden behind those pins inside the microprocessor. The  Schmitt trigger on each pin has read-high vs read-low threshold voltages. This lets you replicate what those cheap eBay modules do by replacing the fixed resistor in your analog voltage divider with variable one, and then connecting the output of that divider to a digital input pin. Inferring resistance (or capacitance) by timing threshold crossovers on a digital I/O pin can produce respectably high resolution analog readings because micro-controllers count time far more precisely than ADC’s measure voltage.

2) Thumpers:

Flippers change state slowly by microcontroller standards, and since they can be read with a single digitalRead() command, they won’t get you much cred at the local hacker-space. To get into the digital world’s caffeine-driven middle class you have to start working with Thumpers. These are sensors which convey information by varying the amount of time the sensor outputs a high voltage at a given frequency (called pulse-width modulation or PWM) OR by changing their output frequency with a fixed 50/50 split between on&off time (this is called frequency modulation or FM) .

This kind of output was common long before the Arduino existed because putting an analog sensor into the oscillator circuit feeding a 555 timer chip changes the pulses coming out the other end in proportion to the sensors resistance / capacitance / etc. You’d be hard pressed to find any environmental sensor that can’t be constructed with a couple of op-amps and a 555 (See: the conductivity sensing post for examples).

Three common methods for reading pulsed signals with an Arduino are:

  1. The pulseIn() Function
  2. External Interrupts
  3. Pin Change Interrupts

The output of the pulseIn() function is the time in microseconds that it took for the pin to go (or be) LOW, then go HIGH, then go LOW. This is the method of choice for PWM thumpers, and it is extremely easy to use provided the incoming signal is a clean square wave.
Unfortunately, it does not handle frequency modulation very well at the high end, because it’s susceptible to errors in timing when detecting the start and end of really short pulses.

Range finding sensors often output PWM signals, and the most popular of those is the HC-SR04 which is used for collision avoidance by just about every Arduino-based robot on the planet. Self-balancing robots are one of the maker movements “killer apps”, and it doesn’t hurt that the SR04 transceivers just happen to look like a pair of eyes. There’s currently a bit of a turf war between the SR04 and slightly more expensive IR rangefinders. Ultrasonic energy is absorbed by soft materials, and SR04’s are susceptible to interference & multi-path issues in environments where there are lots of flat rigid surfaces. Infrared sensors have a much more focused beam so you get better results finding small objects…like the other robot you’re currently doing battle with.  (For more precise work you can go upscale to the VL53L0X Time of Flight distance sensors, and if money is no object, you can take that all the way to LIDAR.  To get the highest level range-finding merit badge of them all: MaxBotix Sonar sensors let you play the game under water…)

A code-side implementation for the HC-SR04 could be as simple as this:

digitalWrite(triggerPin, HIGH);       // send out (transmit) the pings
delayMicroseconds(10);                // give the sensor 10 ms to settle
digitalWrite(triggerPin, LOW);        // stop the outgoing pings
duration = pulseIn(echoPin, HIGH);    // listen for the echo and return time. 
Distance2reflectingSurface = (duration/2) / 29.1;
// Divide by 2 since the sound ping travels out & back = twice the distance
// Speed of sound in air = 340 meters per second or ~29 microseconds per centimeter
// Then divide the duration by 29 cm = distance in centimeters.

External interrupts handle both PWM and FM efficiently with the limitation that there are only two hardware interrupt lines on a typical Arduino. The Cave Pearl loggers are already using D2 for the RTC wakeup alarms, and that leaves only D3 available for hardware methods calling attachInterrupt().

It’s worth noting that there is also a near IR (940nm) sibling in the TSL family: the TSL245

The TSL235R light-to-frequency sensor outputs a square wave (50% duty cycle) with a frequency proportional to light intensity. The TSL235 is self-contained, well calibrated, and very linear over the ultraviolet-to-visible light range of 320 nm to 700 nm. Calibration in manufacturing is something that most companies will try to avoid, and when you include the fact that this sensor works from 2.7-5.5v, you have a $3 sensor that’s nearly perfect for use with Arduino-based data loggers. Rob Tillaart has posted a simple bit of code that counts the interrupt pulses per second from this FM sensor over at the Arduino playground. It should be easy to integrate these functions into the Cave Pearl base code, and to modify it to work with any other FM output sensor. Data from light sensors usually requires post processing with somewhat complicated luminous efficiency calculations, but if you Google around you’ll find plenty of Arduino tutorials on those steps (also see: Insolation Models).

Only D2 & D3 support external interrupt signals by default, but with a little bit of extra code interrupt signals can be received on any of the Arduinos I/O pins.  Interrupts triggered from pins other than D2 & D3 are referred to as Pin Change Interrupts. Pin change interrupts are grouped into 3 ‘ports’ on the MCU. This means there are only 3 interrupt subroutines to handle input from all 20 pins. This makes the code somewhat more complicated than Rob Tillarts example, as it now needs to determine which pin triggered the ISR. That extra complication usually motivates people to use something like the PinChangeInt library for situations with a limited number of input pins.  Anemometers often use interrupt-based approaches because they work with output that’s so variable that it can’t really be classified as PWM or FM.

There are many great frequency counting libraries but it’s important to note the difference between ones which count the number of pulses during a fixed “gate interval” time, and those measuring the period of a single high frequency pulse.  Rob Tillart’s code uses the counting method, and this works well for relatively high frequencies, because many cycles are counted during the gate interval and this reduces error. At lower frequencies, very few cycles are counted, and the precision suffers, so measuring the elapsed time during a single cycle is a better option at low frequencies.

This image is from PJRC’s FreqCount Library page, which goes into more detail on the FM sensing process. It’s worth noting some of the other useful sensor libraries that Paul Stoffregen has released including: Onewire library for the ever popular DS18B20 temperature sensor, SerialFlash to simplify SPI memory builds, and their project blog is a font of other highly interesting things.

According to PJRC: Frequency Counting: works best for 1 kHz to 8 MHz and Period Measuring: works best for 0.1 Hz to 1 kHz.  There is some wiggle room there, and you should check your sensors data sheet to make sure your method matches the output range.

If you’d rather skip the libraries, you can get closer to the bare metal with the advanced timer over-flow methods described at www.fiz-ix.com and at Nick’s Timers & Counters page. Nick’s page describes a method to measure frequency with the input capture unit on pin D8. While that’s some pretty advanced code, it allows you to measure pulsed inputs to a resolution approaching the frequency of your system clock.

3) Thinkers

This Grove I2C hub connects several the sensors to the bus, so only one jumper set needs to be patched down to the logger platform. The mounting shown here was done with plumbers putty, which hardens quickly, and adheres well to most plastic enclosures.

Modern chip-based sensors offer high resolutions and complex signal processing capabilities that can be hard to replicate on the Arduino.  Most of these digital sensors send data using serial communication protocols over a common set of “bus” wires that are physically connected to all of the sensors. Serial protocols can be intimidatingly complex for beginners, but you rarely need to worry about the details because most of the vendors in the Arduino landscape release libraries to simplify the use of the sensors they sell. These libraries make it quite easy to work with complex sensors, and they are one of the reasons that companies like Adafruit and Sparkfun have such a dedicated following in the maker movement.

Newer versions of the Arduino IDE have a Library Manager which provides access to a large list of libraries with a one-click install. Sensors that have been used for a few years by the community often have a library available through the manager. However for new sensors, you usually have to download a library and manually place it in your

Username>Documents>Arduino>Libraries folder.

You can Learn more about installing Arduino libraries at:
Sparkfun :Installing an Arduino Library,    All About Arduino Libraries at Adafruit 
and  Installing Additional Arduino Libraries at Arduino.cc.

Note that these little bits of library code can be located in several different places on your hard drive but it’s best to keep the ones you add in your sketchbook folder because the Arduino Software (IDE) upgrades itself by first erasing everything in the program root directory: including any libraries that were stored there. Libraries in your personal document folders are not deleted during the Arduino Software (IDE) update process.

Here I’ve added a resistor which pulls the CS pin high to tell this ADXL345 accelerometer to communicate with the I2C protocol rather than SPI. The value of that pull-up resistor is not critical, so they can range from a 200Ω to 10kΩ.

The digital sensor protocols you are most likely to see used with an Arduino are SPI and I2C. It’s fairly common for chip-based sensors to support BOTH protocols and for those you usually add a pull-up or pull-down resistor to tell the chip which one to use.  SPI is preferred when fast communication is needed to move large amounts of data, but this is rarely the case for environmental monitoring. More importantly, the Arduino SD card libraries expect the SPI bus to be operating in Mode0. Adding a sensor to the Cave Pearl Logger which changes the SPI bus to one of the other three operating modes would prevent data from being saved until the bus was reset to Mode0. I have yet to find an SPI-only sensor that doesn’t have an I2C equivalent on the market.

 

I²C sensors are often the best choice for Cave Pearl Data Loggers.

The DS3231 RTC breakout module used on the Cave Pearl logger has a cascade port at one end, making a perfect attachment point for other I2C devices

The I²C bus or TWI (Two Wire Interface) allows a single master (the Arduino) to share communication lines with more than 100 slave devices (the sensors). Cave Pearls use an DS3231 RTC for timekeeping and the I²C breakout board carrying it provides 4.7k pullups resistors on the SDA and SCL communication lines. Each new I²C sensor gets connected to the same wires as the RTC board. If you have a good library to go with your sensor, about the only thing that might prevent it from working is a bus address conflict. Because I²C devices are all connected to the same wires, the Arduino needs a way to talk to only one device at a time. It does this using the I²C address of each sensor. (kind of like a phone number)

The first thing to do with a new sensor after connecting it to your Arduino, is run a bus scanner which queries every possible address to see if any devices are responding. If two devices are trying to use the same address, only one of them will show up in the scan, and sometimes neither of them will. Code for this basic utility for this can be found at the Arduino playground.

Running that bus scanner on a Cave Pearl data logger before any sensors are attached should produce:

This output screen tells us that the RTC breakout board is functioning and the I²C communications are working. It also tells us that the I²C “device addresses” are 0x57 ( this is the EEprom on that module ) and 0x68 (the DS3231 RTC).  Adafruit has compiled a list of typical I2C addresses for different sensors and scanning through that list for the two we are already using on the logger finds some potential conflicts:

0x57
MB85RC I2C FRAM (0x50 – 0x57)
MAX3010x Pulse & Oximetry sensor (0x57)  (uh-oh… this sensor will not work with our logger!)

0x68
This address is popular with real time clocks – almost all of them use 0x68!
AMG8833 IR Thermal Camera Breakout (0x68 or 0x69)
DS1307 RTC (0x68 only)
PCF8523 RTC (0x68 only)
DS3231 RTC (0x68 only)
MPU-9250 9-DoF IMU (0x68 or 0x69)
MPU-60X0 Accel+Gyro (0x68 or 0x69)
ITG3200 Gyro (0x68 or 0x69)

Some I²C devices have only one fixed address and but most offer a small range of different addresses that you can set by connecting different pins on the module to power or to ground. This will let you resolve an address conflict, but be make sure to make corresponding changes in your code if you change a sensor address away from it’s default. Most sensor libraries will have a modifiable parameter for the device address that is used to initialize the sensor. If you have a sensor with a fixed address, you will only be able to hook up one of those sensors to the logger at a time unless you add an I2C multiplexer to resolve the address conflict.

Once you’ve confirmed the sensors show up on a scan of the I²C bus, the next steps depend on the complexity of your sensor. I²C sensors that only do one thing can often be read with a minimal amounts of code after the #include <Wire.h> statement embeds the TWI library that’s built-in to the IDE . You often see this with a basic temperature sensors like the TC74

//All I2C coms start with a handshake transaction with the device @ address
Wire.beginTransmission(address);
Wire.write(0);  //Sends a bit asking for register 0, the data register of the TC74
Wire.endTransmission(); // nothing is sent over the wires until wire.end is executed

//then you request the temperature data from the TC74 sensor
Wire.requestFrom(address, 1);  //this requests 1 byte from the specified address
int celsius= Wire.read();

For sensors that do more complicated things there can be many more steps, especially during sensor initialization when you might have to configure the bit-depth of the readings, the sampling speed of the sensor, and a host of other options. I’ve posted an extensive tutorial about this for tech-savvy users (see: How to configure I2C sensors ) but for beginners the best approach to adding a new I²C sensor is

1) Find a suitable tutorial by typing “How to use SensorX with Arduino” in Google or by reviewing the tutorials available at: Hookup Guides at Sparkfun, the Sensor tutorials at Adafruit, or search for code examples and links at the sensors forum.

2) Download the associated sensor library and install it into your Documents>Arduino>Libraries folder

3) Add #include <SensorLibrary.h> to the start of your code

4) Initialize the sensor in startup following the code examples for your tutorial located on GitHub

5) Read the sensor in the main loop

Most libraries are written to provide InitializeTheSensor() and ReadTheSensor() functions that so steps 4) & 5) often end up adding only couple of lines to your code.

As a simple example look at the MCP9808 temperature sensor from Adafruit:

The Tutorial   &   The example code on Github

That script is quite small because the library condensed a lot of I2C handshaking down to

tempsensor.begin();  // initializes the sensor
tempsensor.readTempC();   // reads the sensor

For an example of a library driving a more complex sensor, look at the BMP180 pressure sensor from Sparkfun

Hookup guide   &  The example code on Github

There’s an important step at the start of the code:

#include <SFE_BMP180.h>
#include <Wire.h>
SFE_BMP180 pressure;    // creates an SFE_BMP180 object, called pressure
#define ALTITUDE 1655.0 // Altitude of SparkFun's HQ in Boulder, CO. in meters

In setup, theobjectname. appears before each call to library functions:

pressure.begin()       //initializes the sensor in setup

And then in the main loop, the sensor uses a four step process to complete one reading.

status = pressure.startTemperature();
delay(time);
status = pressure.getTemperature(T); 
// the temperature must be read before the pressure!

status = pressure.startPressure(3);  // with oversampling set to 3
delay(time);
status = pressure.getPressure(P,T);

Multi-step read procedures like that are quite common, because it takes time to capture high resolution readings, and in this case the temperature has to be sent as a correction factor for the pressure reading.

Then there are two more functions in the example program worth noting:

p0 = pressure.sealevel(P,ALTITUDE);
a = pressure.altitude(P,p0);

The pressure sensor returns absolute pressure, and Sparkfun have provided extra code in their library to do calculations which convert that number into sea level equivalent & altitude equivalent numbers.  That Sparkfun code example is pretty typical of what you get with libraries for more complex sensors, and it should not be too hard to just open two IDE windows to copy and paste the required pieces of code from the Adafruit & Sparkfun examples into the basic Cave Pearl Logger script on Github.  There is nothing magical about libraries: they are just pieces of code that you can read through yourself by opening the .cpp file listed in the same Github repository. I recommend that you always review the library code, as figuring out how someone else’s stuff works is an important part of learning how to program the Arduino.

Think about your housing-logger interconnections before you start your build.  My current favorite connectors are Deans Micro Plugs, which are available in 2,3,4,5,6,& 8 pin versions. Use a consistent color convention for different bus wires.

Most libraries will include a simple example sketch with the downloadable file. These show up in the IDE in the FILE>EXAMPLES> pull-down menu after the library is installed, so you don’t usually have to go all the way to Github like I did here. The included examples usually only initialize the sensor and print out some raw readings, but that’s exactly what you need to verify the sensor is working before you merge those bits into your own code.

The real benefit of a good library is not just the code, but the significant amount of time someone spent slogging through a sensors data sheet figuring out the correct sequence of operations.  Just because a library exists for your sensor does not mean that it is necessarily a good one – especially when you find them out in the wild. So you should test different libraries when you have options. I generally chose libraries that require the least amount of memory at compile time, and/or ones that give me access to the ‘raw’ sensor readings in addition to the processed output. Raw sensor readings let you do calculations later in Excel to make sure the library didn’t introduce an error somewhere.  Another thing to keep in mind is that sensor libraries don’t have to be continually upgraded like the software you run into on a more complex system. Once a sensor library is working, it will hang around for years with no updates because none are needed.

Well… this post swelled into another voluminous tome, but hopefully no one lost sight of the forest for the trees.  Generally speaking you can buy each type of sensor in all of the data output ‘flavors” described in this post.  As an example, there are both analog (voltage) & digital (pulsed) anemometers, and the digitals range from simple reed-switch thumpers to ones with onboard IC’s doing most of the raw signal processing to provide calibrated wind-speed numbers over an I2C bus.  Don’t mistake the Analog vs Digital divide as any indication that one kind of sensor is necessarily better for the job you are doing.  Same goes for my tongue-in-cheek categories for Flippers, Thumpers & Thinkers. They’re just conceptual tools to use when you are hunting through tutorials on instructables, or when you run into an intimidating wall of information like the Interfacing with Hardware page at Arduino.cc.

Although this post has been focused on capturing sensor data with a logger, you should also keep in mind that there are many different physical methods to measure the same phenomenon. Using the anemometer example, most people think of the traditional egg-cup spinners because that’s what they are used to seeing on rooftops, but heat-loss methods, and ultra sonic methods are also quite common. A Google search on ‘how to measure water level’ shows the incredible range of different sensors can be put to that simple task.  When you are faced with a range of methods like that, the ‘best sensor’ for the job is the one you can actually get working, and that usually boils down to the amount of programming complexity you are comfortable with. Good libraries can level the playing field quite a bit, making complicated sensors almost as easy to add to your data logger as basic analog voltage dividers.

Addendum 20171218

A few people have commented about my use of string variables in the basic logger code, and the general consensus is that the String class should be avoided because it can lead to memory fragmentation. It is better to use character arrays, but there is a significant learning curve there and strings will let you build a working data logger when you are just starting out. Majenko has one of the most concise summaries of steps to address this issue, and there is a reasonably good introduction to character arrays, and many other helpful concepts at the Starting Electronics: Arduino Programming Course  (see: Section 18).  Personally, I find that having to re-jig sprintf() statements when I want to add another sensor to my logger is a pain in the backside. A more memory friendly approach could be to simply open the file and then save the variables directly to the SD card without the string concatenation steps.

dataFile.open(FileName, O_WRITE | O_APPEND);
dataFile.print(AnalogSensorReading); dataFile.print(",");
dataFile.print(DigitalSensorReading); dataFile.print(",");
[...]
dataFile.close();

An alternative way to address String memory issues is to use the Pstring library by Mikal Hart.   “Print-to-String” is a lightweight Print-derivative string class that renders text into a character buffer that you define at the start of your program.

char DATABuffer[30];  //This character array receives the ascii characters
// it's worth noting that you can't move more than 30 bytes at a time 
// over the I2C bus due to limitations of the wire library buffer, 
// so my receiving arrays are usually [30] bytes long.

The data concatenation steps I described previously for the basic UNO logger:

dataString += ", ";      //comma that separates new data
dataString = dataString + String(DigitalSensorReading);

are slightly different for the more advanced Cave Pearl logger code which uses the Pstring library:

PString str(DATABuffer, sizeof(DATABuffer));// set the array as the receiving buffer
str = "";                                   // this empties the receiving buffer
str.print(CycleTimeStamp); str.print(",");  // this data is already in ASCII format
str.print(DigitalSensorReading); str.print(",");     // this data is an integer
//add more variables as needed  up to the [30] char limit
// separating each additional sensor reading with a comma

It does not matter what what the source variable format is – float, integer, etc – it all gets rendered into ascii by the str.print statements. And Pstring will never cause a buffer overflow because any excess data that you try to add to the DATABuffer is simply discarded. That receiving buffer will always contain valid (i.e. NULL-terminated) C string data. This makes the method much friendlier for people who are new to programming.

To save the sensor data stored in the char array buffer to the SD card use file.write:

file.open(FileName, O_WRITE | O_APPEND);
file.write(DATABuffer, sizeof(DATABuffer));
file.close();

 

Tutorial: Using the Arduino UNO Serial Plotter for Live Data Acquisition

Using an UNO and an ADS1115 ADC module to monitor current use by a pro mini logger

Here, I’m using the basic UNO Logger as a tethered Data AcQuisition device, recording the current used by a second data logger. Since the second logger is ‘floating’ with no connection to the UNO’s ground line, the voltage drop across the 5Ω shunt resistor is recorded using a differential channel on the ADS1115. Differential readings are also useful for sensor applications that use a wheatstone bridge arrangement.

I recently picked up a ADS1115 breakout board, and it was fairly easy to use that with the serial data plotting capability of the Arduino IDE. It’s not often that something works this well on the first try, and I thought I would post about using  the combination as a kind of  ‘poor mans oscilloscope’.   The plotter’s vertical axis auto adjusts as the value of your output increases or decreases, while the X axis is fixed at 500 points, with each tick of the axis equal to an executed serial println command.  Having the ability to spool data to the screen with a simple print statement, turns the exercise into a “What happens if I do this?” kind of process, which is perfect for providing feedback to students learning how to program Arduinos.  I posted the code used to generate these graphs on GitHub, but you will have to noodle around with it to figure out what the threshold settings should be for your particular application.

Although I already have a good method to estimate the overall power consumption of my loggers, I was motivated by this Jeelabs post to see if there was a way I could look at individual events. Even if you have a nice Rigol to play with, it can still be tricky to get all the settings and timings right because the loggers can draw anything from 0.15mA while sleeping, all the way to up to 100mA during SD writing events.  Jeelabs elegant solution to this ranging problem uses two shunt resistors and a diode, but with 15bits of differential range on the 1115, the 8x gain setting can do the job with a single resistor. (…provided I don’t exceed the ±0.5 volt limit that PGA setting imposes…) 

After installing Rowbergs I2Cdev library, and running a couple of jumpers, my drip sensors were generating raw count output like this:

Cave Pearl data loggers

Of course that was scrolling by like crazy, and the re-scale feature meant that the y-axis was jumping round like a bullfrog on a hotplate. You can bring the vertical axis under control by adding a few delimiter separated constants before the final data println:

Serial.print(4000); Serial.print(” “);     // sets a stable upper value line
Serial.print(0); Serial.print(” “);             //this constant sets a stable lower value

But to prevent the x axis from scrolling forever, I had to setup a trigger threshold, that would only capture a new set of readings when an actual event was occurring:


void loop(void)
{
int sensorOneCounts=adc0.getConversion();  //note we already set the mux to differential in setup
if(sensorOneCounts >= LoopThreshold) {      //rapid sampling loop to capture the event
start=millis();
for (int Cycle = 0; Cycle < ADCcycles; Cycle++) {
currentADCreadings[Cycle]=adc0.getConversion();
}
elapsed=millis()-start;// elapsed gives you the timebase for your samples
}
//A separate loop to output of the samples to the text monitor or serial plotter
for (int Cycle = 0; Cycle < ADCcycles; Cycle++) {
Serial.println(currentADCreadings[Cycle]);
}
#ifdef ECHO_TO_SERIAL    //TEXT only output of the time it took for your data acquisition loop
Serial.print(F(“Time for “));Serial.print(ADCcycles);Serial.print(F(” readings: “));Serial.print(elapsed);Serial.println(F(” milliseconds”));
#endif

}

A few runs with text-only output showed the sleeping logger generating around 65 raw counts on the ADC, so I set the LoopThreshold to 75, and the plotter started behaving like an oscilloscope’s triggered sweep: scrolling 500 new readings across the screen each time the drip sensor woke up.  With a known shunt resistance, and the millivolt resolution per bit from the datasheet, I could convert the raw ADC counts to μA in the printing loop. Just for fun I also tried speeding up the I2C bus to see the temporal resolution of that sample loop at 400Khz:

Running ADS1115 with UNO as DAQ - with I2C bus running at 400HZ, the system outraces the ADCSo I was asking for data faster than the 1115’s top speed of 860sps could deliver it.  A few more trials showed that even with the Arduino’s default 100Khz bus, I had to add delayMicroseconds(400);  into the capture loop to keep the UNO from outpacing the ADC module.  I expect that will be different for Arduinos with different clocks like the promini, so one would have to make manual adjustments based on the elapsed times for each system.

These drip logger events are the result of straightforward code that follows the steps:

1) Wake from interrupt & clear the registers, update count variable
2) Turn indicator LED on & sleep for 15ms
3) Wake, turn LED off & sleep for another 32ms (to let impact vibrations die down)
4) Set accelerometer registers & go into deep sleep: wait for next accelerometer interrupt

Since you can drop as many constants on the plotter as you want, it’s easy to determine the current level at a specific point on the plot by intersecting it with a new line:

Cave Pearl data loggers

Though there were no surprises in the pattern per se, it was handy to find out that the “in-event” sleep current was about twice the normal standby state. (which I confirmed at 0.2mA using a DMM)  Now I can go digging through the code to figure out what’s drawing  that extra power.

After resetting I2C bus, I tweaked the delays to exactly match the 860 sps output from the ADC. Then I sat back and waited for one of the real time clock alarms to fire:

Cave Pearl data loggers

This was my first view of that complex logger event, with variable juggling, time stamp creation, eeprom buffering, counter resets, etc. With I2C devices being able to stretch the clock whenever they need to, I had no idea how long these kind of events actually took, and I certainly never managed to capture one so easily on the old clunker scopes I could get my hands on.  The comb pattern you see there is a result of sleeping the processor for 15ms after sending data to I2C device registers; instead of using a 6ms delay while the Arduino waits for the devices to respond.  This lengthens the overall duration of the event, but the time spent running at full power is reduced.

By how much? I reset the logger to use delays after I2C writes rather than sleeps and re-captured the event:

Cave Pearl data loggers

The horizontal axis is at the same scale as before. The start of the event now looks like a solid block and the overall event is about 50ms shorter.  For comparison, I’ve inset the previous graph with the sleep gaps cut out and the spikes moved together, and the two white rectangles at the top represent area equivalent to sleep gaps that were removed.  The grey area shows the power saved by using 15ms sleeps instead of 6ms delays.  To do this properly I would need to take another reading of the 3xAA power supply voltage and calculate the total power used (minus the loss on the shunt resistor), but you can see at least 25% improvement simply by comparing the plots. That kind of feedback is very helpful when you are trying to optimize your code.

Now, I can already hear people scoff that even $3 is too much to pay for a scope that won’t reach 1Khz. Indeed, with a minimum temporal resolution of just over a millisecond, the ADC frequently misses brief current peaks. I know my 8mhz promini based loggers usually draw more than 4mA while running, and you see the longer operations in the RTC/delays event pushing up towards 6 mA.

Cave Pearl data loggers

But even with the upper third lopped off those spikes by timing errors, I can still use this method to make a reasonable estimate of the power being consumed by logger events provided they don’t last more than 580 milliseconds. ( The serial plotter provides a window for only 500 samples and the UNO barely has enough variable memory for a 16bit integer array that size.) If you add the SD card library to your script you are only left with enough memory for about 100 of these samples in your capture loop, although you could try reducing the ADC readings down to 0-256 with a well tuned map function. Then you could use an uint8_t integer array, and store twice as many readings in the limited variable memory of the Arduino.  If you were just doing a classroom demo, that range would probably still give you a decent display on the plotter.

Despite these limitations, the setup is so simple that I think the serial plotter tool will become a go-to for quick looks at sensor data, perhaps even replacing some processing based demos.  The ability to connect four of these ADC modules to a single Arduino makes the platform look quite respectable as a classroom level data acquisition system, especially for environmental data that rarely requires high frequency sampling.  

If you switch to a beefier 1280 based Arduino like the Mega, or the Moteino, those memory limitations disappear and recording much longer events would become possible.  With the delays I had to put in, my gut feeling is that you could juggle a couple of these boards at a time; interleaving the readings to double or triple the effective sampling frequency. (at least until the input impedances start to mess with the shunt resistor…)  And finally, I think adding a couple of well chosen diodes to clamp the input voltage to the ±limits imposed by your PGA setting would be a good idea in the classroom, or you might loose a few of those ADS1115 modules.

It is worth noting that there is a comparator function in the ADS1115 that can be programmed to send a pin change alert when a given threshold is crossed. If I can figure out how to get ADS1115’s built in comparator working with the differential modes, this would even let me put the DAQ to sleep between sampling runs. The ADC module also has a ‘data ready’ alarm that can be enabled to tell you exactly when it has the next reading available.  I did not go that route as the generic approach used here is applicable to sensors without these features, including the ADC built into the Arduino. 

There are plenty of other serial data plotting programs, but using the free IDE version like this is an iterative exercise, forcing you to switch between the serial text monitor & the serial plotter a few times to tweak the delays and constants. If you are using an UNO in a classroom setting, this in itself is a useful activity.  And given how cheap basic DAQ modules are these days, choosing to use an Arduino is always about the showing the process rather than just getting a final result.

Addendum 2016-08-15:     A MUCH faster DAQ with the native UNO ADC

 Here I’m reading the voltage across a 10Ω resistor with the UNO’s built in ADC. To do that I need to join the ground lines because the Arduino can only take single-ended readings. That also forces me to put the shunt on the low side line so I don’t exceed the 1.1 vref. This arrangement causes the drip sensors’s effective ground line to jump around as the current through the resistor changes.


Here I’m reading the voltage across a 10Ω resistor with the UNO’s built in ADC. To do that I need to join the ground lines because the Arduino can only take single-ended readings. That also forces me to put the shunt resistor on the low side line so I don’t exceed the 1.1 vref. This arrangement causes the promini logger’s effective ground line to jump around as the current through the resistor changes.

The folks over at Measuring Stuff  posted a page called The Arduino DAQ Chronicles, which goes into some detail on the process.  It’s a good chunk of background reading even if you are using the ADS1115 ADC described above. The Arduino’s native ADC delivers 10-bit readings, (ie 0-1023) and compared to the relatively pokey ADS1115, a typical UNO can take several thousand analog readings per second; outperforming the ADS1115 by a fair margin. The challenge is balancing the reduced resolution with the other limits imposed by the method itself. Even if you increase the sensitivity of the native 10-bit ADC by changing to the internal 1.1vref, you only reach 1.1v/1024 steps = 1.07 millivolt per bit. Remember that my loggers are sleeping at 0.2 milliamp x 5Ω shunt resistor = 1 millivolt so we are operating right on the lower limit of the ADC resolution. With that 1.1v cap on the ADC input, and a potential 100mA peak current (during SD card data saves), the largest shunt resistor I can use is 1.1v/0.1a= 11Ω. So to get the Arduino to discriminate the low currents we need to use a pretty  large shunt resistor value, and allowing the voltage drop to get that high imposes another challenge in that the drip logger would only be left with 4.5v (the 3xAA battery) 1.1v drop on shunt = 3.4v. That’s right at the minimum input voltage needed by the 3.3v regulator on the Arduino promini board, risking a potential brown-out in the middle of the SD card writing process.

But hey, lets pop in some new batteries, and see what we get:

FirstRaw

Not too bad, but that’s a noisy plot with lots of jitter on the base line. Having 1-2 bits toggle like that is typical for ADC’s so there is probably nothing I can do to get rid of it. And the drip sensors resting state reads at zero when it should be registering at least two counts. It is also common for an ADC to under or over read by a few bits, so I added an offset adjustment into the code to bring that sleeping baseline up to the 0.2mA that I have already confirmed with a multimeter.

Then I realized I still had the 400us delay in there from the ADS1115, so I took that out:

Cave Pearl data loggers

Crikey! Even with the code overhead, that thing is taking over 8000 samples a second! That’s far too many readings for the serial plotter to handle if I want to view long events.  And that first spike goes upt to about 5mA – exactly where it should have been on the ADS1115 readings if that module had not missed them at 860sps.  So how do I maintain the Arduino’s ability to spot those rapid sample peaks, but only send 500 readings to the screen?

Instead of delays, I decided to create an “oversampling loop” that creates a running average using a low pass filter, but also checks for peaks throughout the process. You can dig into the code for this over at GitHub, but the basic idea that is if a peak occurs, then the highest reading in an interval becomes the final reading. If a decreasing trend is found, then the output from a leaky integrator becomes the final reading for that interval. So the readings get smoothed on the way down, but not on the way up.

Here is a try with the oversampling interval set to six ADC readings:

BothEvents6xoversampling

That’s the RTC event (with delays) and the drip triggered event at the same scale.

Now here’s another run with a 15:1 ratio:

OS15-900msPerloop

Squashing more than 7000 raw readings into a 500 line display really starts to distort the curve, but everything is still recognizable, and more importantly, the peaks did not get chopped off like they did with the ADS1115.  Woot!

Now we have a method that lets us adjust the serial plotter’s display to match the event we are trying to see, provided we don’t over-interpret the accuracy of those heavily averaged interval numbers. And rapid sampling can introduce other issues to deal with. For example: Dustyn Roberts has a useful post on creating very precise time stamps with the micros(); function when you are sampling faster than 1 millisecond. 

So within limits, a standard Arduino gives you good temporal resolution but can not detect less than 1 millivolt of change, while the ADS1115 gives you precision down to an impressive 0.0078 millivolts (@16x gain) but is not so great for tracking really brief events.  If you need both resolution & speed, you need opamp circuits designed for the specific situation, as in the Jeelabs example. It’s also worth mentioning that the Arduino ADC also supports a comparator that you could use for the threshold function more elegantly than I’ve done here.  And with such a low impedance input, you can also double or triple the sampling rate by changing the ADC clock prescalers (this is also in the code on GitHub) Both of those things are described in detail over at Nick Gammons excellent page on ADC conversion on the Arduino.

Addendum 2016-08-16

Hopefully they will add export options (like other serial tools) to the plotter in the future, but for now you can manually copy data out of the serial text monitor and paste it into Excel.  Before you start a long run for export to a spreadsheet, comment out the constants that you were printing to stabilize the plotters y – axis, so that only the numbers you are interested in are sent to the serial output.  If you are waiting for an event to happen, it often helps to add a threshold test so that the serial monitor is not just filling up with uninteresting data that you would have to prune away later anyway:thresholdprintline

Then after your DAQ has been capturing events for a while, click inside the serial monitor window,  select all the data & copy it (on a windows machine that would be [CTRL]+[A] followed by [CTRL]+[C] ) then open a new spreadsheet and simply paste the data into an empty column.

This lets you compare the events side by side:

CopySerialdataintoExcelIf you want to graph more than one number, then add a comma between them with Serial.print(“,”);  remembering to use println on the last variable being sent.  Then you need to add the intermediate steps of pasting the data into a text editor like notepad, and saving that text file. Then change the ending from .txt to .csv and Excel will open it directly. If you can’t change the filename, you can still import the text file and specify comma delimiters:

TextImportExcel

to put the numbers into adjacent columns. If you don’t have excel, there are plenty of other data plotting options out there. And programs like coolterm, can save you from having to do those cutting & pasting steps.

Addendum 2016-10-13

Gokul Shrinivas just posted a neat little bit of code at hackster.io that reads the Arduino ADC at a cracking 68k samples per second out of a Arduino Due by directly accessing the ADC ports as soon as the DataReady interrupt is triggered. 

He starts with defines:

#define ADC_MR * (volatile unsigned int *) (0x400C0004) /*adc mode word*/
#define ADC_CR * (volatile unsigned int *) (0x400C0000) /*write a 2 to start convertion*/
#define ADC_ISR * (volatile unsigned int *) (0x400C0030) /*status reg -- bit 24 is data ready*/
#define ADC_ISR_DRDY 0x01000000
#define ADC_START 2
#define ADC_LCDR * (volatile unsigned int *) (0x400C0020) /*last converted low 12 bits*/
#define ADC_DATA 0x00000FFF 

And the sampling loop becomes

ADC_CR = ADC_START ;
  for (i=0; i<320; i++){
    // Wait for end of conversion
    while (!(ADC_ISR & ADC_ISR_DRDY));
    // Read the value
    analog_data[i] = ADC_LCDR & ADC_DATA ;
    // start next
    ADC_CR = ADC_START ;
  }

He used an LCD screen for the scope, but I am wondering if it would be possible to refine my oversampling trick to squeeze that many data points on the serial plotter somehow…

And I wonder if this trick is even available on the 328p? I guess I will have to go looking at other Arduino Oscilloscope projects. The problem is that most of them seem to be using 8-bit signals from “free-running” modes, and I rarely have an application that needs less resolution. Here’s a project doing Interrupt-Driven Analog Conversion  with an ATMega328p, and Nick Gammon mentions it here, but no one does a speed comparison with the ten analog 10-bit readings you get per millisecond using plain old analogRead();

Even if there is no speed gain, perhaps I could do calculations while I was letting the ADC read continuously to speed up the overall sampling loop.  I could see myself getting out of sync pretty easily though, unless I deactivate the general interrupt flag and activate it again (with  cli() and sei()) or I would randomly miss readings.

Nick posted a code example of reading the Analog-to-Digital converter asynchronously that seems to solve the synchrony problem.  He’s also posted an interesting ‘sleep during ADC conversion’ example buried in there, but that’s only useful if you are not using timers & PWM at the same time, and I often do that…

Update: the Hackster.io project listing magically evaporated… and I just found exactly the same code at Bruce Land’s Hackaday project from 6 months ago. So I think proper attribution for the script above should go to Bruce.

Addendum 2017-01-10

I’ve been playing around with the ADC clock prescalars, and with the asynchronous reading code available over at Nick Gammon’s site to try to get better temporal performance out of my little UNO-scope.  With such a low value shunt resistor the ADC seems to read fine even if you crank it up to about 40k samples/second. Unfortunately you pass a point of diminishing returns due to the processing overhead with the interrupt based asynchronous readings,  so async reading actually reduces the number of readings per millisecond at the higher clock speeds. If you want to play with this approach yourself, I’ve posted the update with the prescalar settings to GitHub.

Addendum 2017-02-27

Anyone interested in using an Arduino as at data acquisition device will probably want to see my recent post: Enhancing ADC resolution with Dithering & Oversampling
For an unmodified UNO,  Qwerty’s triangular dither method is probably the easiest one to use, but for 3.3v boards I’d go for the Toggled pin dither method I outline at the bottom of the post.

Build your own Arduino Starter Kit for the Classroom

A typical student starter kit.

It’s August, and we’re assembling kits for another run of the instrumentation course.  Over time we have come to rely on 328p based microcontroller boards (aka: Arduinos) so I though I would post a list of the parts & materials we use to help others fire up their own classroom. More than a few people have requested this since I posted the UNO based logger tutorial.

This information should also be looking to buy an all in one solution for their first citizen science project.  Don’t reinvent the wheel if you don’t have to: there are lots of premade Arduino kits out there.  However we found that many had parts we simply didn’t need, as we wanted a minimal ‘starter kits’ designed to exactly match the lessons in a course focused on environmental monitoring.  We also hand out extra parts for some tutorials as needed through the course, and the students receive a second project box when they start building their stand-alone  projects. Cave Pearl data loggers Even if you want that level customization, it might worth looking at some basic electronic component kits, and building your classroom set on top of those. The DIY approach will save money, but you pay for it with time.  Most of the eBay parts shown here took about two weeks to ship, with some stragglers taking almost a month to arrive.

You will need more than an Arduino and a few components  to set up a classroom, so I am including tools & other miscellaneous bits of hardware that we use in the lab. I would not describe any of these as high quality equipment, but they are ‘good enough’ to get things rolling on a modest budget.  Even if you go with eBay stuff,  you are doing great if you can run a course where students build ‘real world’ deployable prototypes for $100 a seat, once you include the tools and other bits.


Components for the UNO based Datalogger:

TransparentSinglePixl
UNO Data logger Kit: $25-50 / seat
UNO_100pxw Arduino UNO R3
The real thing, and tough as nails. All of my old UNO R1 boards are still operational despite years of abuse. If you can’t afford the real thing due to budget limitations, then at least donate a few bucks to help them keep the open source project going.
$24.95
UnoClone_100pxw UNO clone (incl. USB cable)
If your budget forces you to go this route, choose boards with ATmega16U2 or 8U2 UARTs (like those in the original UNOs) to avoid problems with the IDE. If you can deal with the driver issues, there are clones for as little $3 with alternate UART chips like the CH340.
$7.20
PlatformBase_100pxw
Transparent Experimental Platform Base-plate
Last year we made our own base plates with M3 risers and Plastruct Styrene sheets. But these acrylic boards save time. Check left/right side orientation of the holes on the board before buying.
$1.50
MiniBreadboard_100pxw Mini Solderless Breadboard 400 Tie-points
Get at least two per student, in case they need to expand their projects. The plastic in these cheap breadboards tend to “warp” slightly over time and the adhesive layer on the back is not thick enough to accommodate this bending so they will slowly come away from the mounting surfaces. So if you are attaching your breadboards to acrylic plates beside an UNO – add an extra layer of double sided foam tape to the back of the breadboards before sticking them down.
$1.20
JumperWires_100pxw 65pcs Jumper Wire kit
Need at least one of these for every two students. These pre-made ones are pretty crappy – these days I make my own jumpers with crimping pliers.
$1.40
40p10cmdupont 40wire Dupont 10cm Jumper cable
An alternative to loose jumpers wires, and they make the student kits look nicer tidy at the beginning of the term. Have students make longer or shorter jumper wires by hand when they need them provides practice with the crimping tool. Jumpers you make yourself are always more reliable.
$1.00
JumperWire22AWG_100pxw 22AWG Solid Hook up Wire Kit
One box will cover the entire class and they should know how to cut and strip wires properly. Don’t bother with pre-cut jumper wire sets as the longer lengths are never the right size. Striveday also sells mixed boxes of solid core wire.
$20.00/box
SDmodule Micro SD Card Memory Shield Module
And don’t forget to buy μSD cards to go with them. Test any used ones to make sure they are ok.
$1.00
RTC_100pxw DS3231 & AT24C32 IIC RTC Clock Module
I have a page describing these RTC board in some detail here. You will also need a CR2032 3v Lithium coin cell backup battery, after you remove the charging circuit resistor. The DS3231-S and -N chips are MUCH better than the DS3231M variant.
$1.00
Keyes3ColorRGBLED_100pxw 3-Colour Rgb Smd Led Module (with limit resistors)
There is nothing special about this common cathode 5050 LED, but it’s easy to remove & re-insert without bending the pins, and the low profile helps it fit in the kit boxes. The 200k limit resistors that come on these boards give you a current that approaches Arduino pin limits, so it would not hurt to put another 500-1k ohm in series with these modules for extra safety.
$0.80
Tweezers_100pxw Vetus ESD-15 bent tip tweezers
Make sure they have the rounded shaped ends that come to a sharp point. 
$1.00
ICbox_100pxw 10 Compartment Small Part Storage Case
To keep all the led’s, resistors, etc. from rolling around loose inside the larger clip boxes. Get ones where the section walls can be removed to make room for longer parts. There’s a range of other cheap fishing tackle and (non-waterproof) compartment boxes available.
$0.70
SteriliteBox Sterilite 1961 – Small Clip Box for Lab kits
Expensive, but they survive in a student back pack. You can find $1 clip box alternatives (like the photos at the top of this post)  at your local dollar store.  Various  other clip lock food / snack containers can also be used, and some can even be pressed into service as project housings.
$4.25
Outdoor Products Watertight Box
Measures 3.5 x 6.8 x 8 inches with 1.5-liter capacity so this ones pretty big, but it could also be pressed into service as a housing for larger UNO based projects going outdoors ( w lots of room for batteries! ) Also see:  the $6.00 Husky 6″parts bin, 7×5.25×3.5″ Parts Organizer , and 4x4x2 in. Grey Sch.40 PVC junction boxes are another housing option, which are also available with 4 & 6 in. depths.  
$6.99
Plano 3440-10 Waterproof Stowaway (3400 Series)
Makes a reasonable “instant” waterproof housing for smaller projects that indicator LED’s can still shine through. The actual usable “interior space” of the box is 8.1cm x 15.5cm x 3.5mm, which is just a smidgen less than the standard 83mm x120mm acrylic platform bases used for the UNOs (you can press them in, but they are very tight – better to shave them down a bit)   Pelican 1020 Micro Cases accomodate that UNO platform easily though they are the luxury polycarbonate option which cost more than 2x as much. Polyc does allow you to put display screens and solar cells inside the housing because it passes all of the visible spectrum with little loss. Of course that also means that whatever’s inside the case will really cook (60-90°C) if you leave those housings exposed to full sun.
If your build is “skinny” enough, 2″ PVC compression couplings can be used as a housings with pvc plugs at each end. All these ideas require you to add cable glands and wire pass-through connections.
$4.96
CheapMultimeter_100pxw Basic Digitial Multimeter DT-830D
We have better meters in the lab (like the EX330 which is pretty good for ~$50) but at $3.00 each you don’t have to worry about students loosing or breaking them. Have replacement 9v batteries on hand, as people frequently forget to turn them off. Expect 1-2% error on readings. If you order 8-10 expect at least one to arrive broken during shipment.
$3.40
UT120C Super Slim Pocket Digital Multimeters
Often you need a “shirt-pocket” sized multimeter during fieldwork, and we usually have a couple of these along for the ride. Cheap enough to be expendable, but functional enough for most jobs on site. 
$15.00
eyeloupe Folding Magnifier (5x)
Useful for inspecting solder connections.
$0.55 ea.
Note: The stuff above this line goes into every UNO logger kit, but I am adding a few optional things to this list that might be appropriate for other courses:
MinimalKit_100pxw Minimal electronic components kit
Even though we don’t use them, I wanted to put this in here as an example of a minimum component package that could be a starting point for your custom kits.
$3.50
ElecfansKit Slightly less minimal component kit
Another one that’s almost tempting. Search eBay for ‘Electronics starter kit for Arduino’ and you find oodles of these. If you are only making a small number of kits these might be the way to go. But if you are making six or more, check the basic components list below, as most of the parts in these packages are pennies each if you buy them separately.
$7.70
6xAAbattery_100pxw 6xAA Battery Holder Box for Arduino
These will power an UNO for about 40 hours of continuous stand alone operation. You can stretch that out with processor sleeping & other tricks.
$2.45
PWradapters_100pxw 9 VDC 1000mA regulated power adapter
5.5mm/2.1mm barrel jack, positive tip. Expect these cheap ones to be noisy as heck compared to the ones from Adafruit. We run most of the UNO based lessons tethered to a USB cable, so these rarely get used.
$2.27
LongBreadboard_100pxw MB-102 Solderless Breadboard 830 Tie Points
They don’t go into the student kits, it’s a good idea to have a few of these longer breadboards around.
$2.00
TranspShield_100pxw Arduino UNO R3 Transparent Case
An alternative to the flat platform approach we use  would be to try these in combination with a breadboard shield
$1.60
BreadboardShield_100pxw Mini Breadboard Prototype Shield
With a little creativity you could squeeze low profile components for the data logger onto this if you find an SD card adapter, and an RTC with perpendicular pins.
$1.80

Basic Electronic Components:

Most electronic components can be had for pennies if you buy them in quantity. And the difference between low end parts and name brand stuff can be more than an order of magnitude.  That doesn’t mean that off the shelf kits are a bad thing, it just means that what you are really paying for is someone’s time selecting and packaging it.  That still might be the better option for you if you can afford it.

TransparentSinglePixl
Basic Components:
StanleyBins Stanley Removable 10 Compartment Organizer
Before you buy a bunch of tiny little parts, you need some way to organize them. I usually put the items into 3″x 5″ or 4″x 6″ bags, which then go into these compartments.  Pink 4Mil Anti-static Poly Bags come in all sizes, and work well for this. Being able to remove the section boxes from these organizers to lay out specific parts for a tutorial also comes in handy.  See: Organizer Bin Storage Unit See: Stacking organizers See: Tool Storage
$17.00
StanleyShallowOrg Stanley Shallow Organizer, 25 Compartment
This organizer is better for really small components & IC’s that you only have a few of, but you still need to bag them or they get jumbled.
$12.00
ELENCO WK-106 Solid Hook-Up Wire Kit 22 AWG
22 AWG works reasonably well with breadboards, get at least 6 colors/150 feet. Remember to specify how much to cut from the spool in your lab instructions, or your students will pull 2 feet of wire from the box when they only need a couple of inches on the breadboard. Get two boxes at the start of term.
$19.00
AdafruitWire_100pxw 26AWG Silicone Cover Stranded-Core Wire – 2m
This high strand count wire from Adafruit is the nicest stuff you are ever going to work with, and is my favorite after trying just about everything else on the market. Simply fold & cut those pre-cut 2m lengths four times and you end up with 12cm lengths which are perfect for including in kits. [Colors:Red,Black,White,Yellow,Green,Blue,Grey,Orange]
$0.50/m
CheapWire_100pxw 60m/box 26 AWG 10m x 6 colors Cbazy / Striveday Silicone Jacket Wire
As your projects get more advanced you can never have enough different colors of wire. And there are other box sets to add Orange, Brown & Purple . The thing to watch out for with wire sourced from eBay wire is that some vendors sell crappy seven-strand wire,  which will not stand up to frequent bending like the highly stranded Adafruit 26awg. I also keep some thinner 28AWG and 30AWG wire with high strand count around for finer soldering jobs (eg  here)
$17.00/box
CBAZY Stranded Hook up Wire 26-30 AWG Flexible Silicone Wire (108 Feet)
You can never have enough of certain colors, so I always order 30m rolls of RED and BLACK wire for battery connections.  [Colors:Red, Black, Blue, Brown, Green, Grey, Orange, Purple, White, Yellow]  16-30awg available. ~$0.33/m
$12/30m
Hshrinkspool_100pxw 1/16″ 2:1 Clear Heat Shrink (MIL-I-23053/2, class 2)
Unlike normal heat shrink, mil-spec is very thick and holds its shape after cooling; making it easier to route cables in a housing. Watch for eBay vendors that advertise mil-spec, and send you the thinner cheap stuff.   I think of 1/16″(=1.5mm) heat shrink as “1-wire sized”, 2mm = “2-wire size” and 1/8″(=3mm) as “3-wire size” when working with 26awg. Always buy clear heat-shrink tubing for the classroom – so that you can see when poor soldering has caused a problem with the circuits.
$12.00/100ft
I add male DuPont crimps & a bit of heat shrink to thin lead components to make the breadboard friendly

Resistors: Lead diameter makes a resistor breadboard friendly or not. You generally want 0.6 mm not 0.4mm leads, though it is inevitable that you will end up buying a few cheap multipacks with the thin leads. ( Note: You can add male DuPont crimp ends & a bit of heat shrink to components with thin leads to make them breadboard friendly : see inset photo) Brand-names like Vishay, Xicon, KOA Speer are usually very good, but you pay 2-5 cents each for them. Ironically, the cheap old carbon resistors often tend to have thick steel leads while the better brands have softer copper leads which bend more easily. I find 1/4 watt to be the most practical size and 1/2W metfilms are physically about the same size as 1/4W carbons. Beige-background carbon resistors seem to be much easier to read than blue-background metals, but if you need 1% tolerances, you won’t have much choice. 1/8watt metfilms are very tiny, which can be helpful if you need to put a resistor into a small place, like between two pins on a breakout board. Wherever possible, buy 1% tolerance (or better) resistors, rather than 5%, as this affects your sensor accuracy when you use them in voltage dividers – which is a common way to read sensors.

MetfilmResisorSet1 130 values 1-10MΩ 1/4W Metal Film Resistors Assortment
Crappy thin leads, but a huge range of values to have on hand at the beginning of a class – in fact I would order two of these to get started.   Then order 50-200 of the individual resistor values as needed for your labs/exercises. Be prepared for it to take 2-4 weeks for resistors to show up if you order them via eBay.
$10/2600pc
IndMetfilms MetFilm Resistor 1/4W 0.25W ±1% [Various Sizes]
100 pc of specific sizes with thin leads. We usually put five to ten of 330Ω, 1K, 4.7K & 10K in each kit, but you can tune this to your curriculum and/or hand out other specific sizes at the beginning of each lab.  After you get better at soldering, you will probably switch over to 1/8 watt resistors, as their smaller size lets you put them into tight spaces: like between the pins on a promini board. Also note that metal film resistors use a 5-band code to indicate their value, rather than the 4-band you see on carbon resistors. But we teach students to always check resistance values with a DVM to catch manufacturing errors, and because it’s quite common for them to cook their resistors, or bend the wires too much & break the connection,  when they are just learning to solder.
$1.89/100pc
HalfwattCarbons 1/2W Carbon Film Assortment (30value x10pc 1-3MΩ)
Sometimes the 1/2 watt size is easier for beginners to handle. It also helps to have “exercise specific” resistor values look physically different from the other resistors in the kits. These still have thin leads though.
$3.80/300pc
carbons Carbon Resistor 1/4W 0.25W 5% [Various Sizes]
Just a typical eBay search link to give you an idea what’s available. Usually these carbons have nicer thicker leads but the quality varies. Check for free shipping.
$1.00/100pc
Components: Most hobby market parts distributors have “Assortment Kits” for commonly used components and its a good idea to just buy a selection those when you are starting out. It might be a while before you actually dig into that mixed bag of capacitors for the odd value you need for that circuit you just found on the internet, but when it happens you will be glad you spend that $1 six months ago. I’m going to list several from Electrodragon as examples, but there is nothing special about them and you can often find a very similar set on eBay for significantly less. A common problem with all the overseas suppliers is that it usually takes 3-4 weeks for stuff to arrive. So if you realize that you need something quickly, go to Sparkfun/Adafruit/Pololu/Amazon etc. My rule of thumb with dodgy flea markets like Dealextreme, AliExpress, etc. is: “If this order never arrives, how unhappy would I be about that?” If the answer to that question is “Quite a bit” then you should order that part from a reputable vendor.  More than 95% of the things I order from eBay do arrive…eventually…though it’s common for things like sensor modules to be significantly different than the photos shown in the listing.
LED's 5mm LED Light Diffused Assorted (5 Kinds*20PCs)
Having the colored plastic makes it easier for students to identify which LED is which. [red, green, yellow, blue, white]
$1.80/100pc
RGBled10mm LED diffused RGB 10MM Common cathode
Having the RGB led a different physical size from the one-color LEDs makes it easier to identify them in the kit. Common cathode means you can use one limit resistor on the ground line. You can use a CR2032 coin cell to identify which leg is which color quickly by putting the common line on the negative side of the battery.
$2.65/10pc
mixedcaps Ceramic Capacitor Assortment (10 Kinds x 50 PCs)
The most important thing to know about ceramic capacitors is that they have the worst thermal coefficients of any component you are ever going to see.  So to build a circuit which will work in real-world environments you need the dielectric to be rated at X7R (±15% from -55 to 125C) or better.  Garden variety Y5V (±82% from -30 to 85C) caps also loose about 30% of their capacitance in their first year of operation (X7R’s loose <10%) and you need to compensate for that too.   And finally you need to buy caps rated for 50v, if you want to use them with 5v because the bizarre rating system means that you could loose up to 80% of the rated value as you approach the rating on the label. 
$11/500pc
cCaps 100PCs Ceramic Capacitor [30pF,10nF,100nF]
The four most common sizes of capacitors to keep on hand are 10μF (106), 1μF (105), 0.1μF (104) and 10nF (103). Get 100 of each to start, as they are frequently used for bypass/decoupling. Most of the time you will be using: 104 (100nF) but like resistors it’s handy to have small mixed assortments on hand for one-of builds. 
$0.80/100pc
EcapAssortment Electrolytic Capacitor Assorted (0.22UF-470UF, 12Kinds)
I rarely use these (unlike the little ceramics which get used all the time) Keep an eye on polarity because electrolytics (and Tantalum capacitors) will explode if you put them in backwards.
There are other kinds of capacitors out there, and for sensor circuits that have to be stable with temperature, or over long periods of time, plastic film capacitors are often a much better choice than either electrolytics or ceramics: I use Polyphenylene Sulphide (PPS +/-1.5%) or Polypropylene (CBB or PP +/-2.5%) when I can since their aging rate (expressed as % change /decade hours operation) is negligible. The only drawback is that they are relatively large, so for a given value, the film cap might be the size of a jellybean, when the equivalent ceramic cap would barely big enough to solder to without a magnifier lens.
$3.30/120pc
GeneralDiodePack General Diode Pack (8 Kinds)
(1N4148 -25PCs, 1N4007 -25PCs, 1N5819 -10PCs, 1N5399 -10PCs, FR107 -10PCs, FR207 -10PCs, 1N5408 -5PCs, 1N5822 -5PCs)
$3.00/100pc
INDdiodes 50PCs Diode [Individual types]
1N4148 is the standard signal diode so it might be worth ordering those.
1N5817 Shottky’s are also useful to isolate battery banks from each other.
$0.75/50pc
DiodePack_100pxw Common Zener Diode Pack, 0.5|1W, 3.3V-30V
(14 kinds, 5pcs each) Each Zenner has a specific breakdown voltage, so it might be a good idea to wait till you know which ones actually need and order only those specific types.
$1.70/140pc
TransistorPack General Transistor Pack (17 Kinds x 10PCS, Low Power)
Like Zenners, there are many different flavors of transistor out there, and you should figure out which one you need before buying too many of them. So perhaps just order this pack as a backup, and wait till you know which specific ones you need. For example: the 2N2222A is one common NPN BJT that most everyone seems to use, and they are about a penny each.  See: Building a Friendstrument. See: Transistor as a Switch  See:TransistorCalculator.       Rule of thumb for using cheap transistors as switches:  Size your base resistor to make the base current twice the calculated value for the smallest hFE you see listed in the data sheet (see calculator here) provided that does not exceed ~20mA digital pin current on an Arduino. Don’t forget to add pull up/downs for stability. Note: E-B-C pinouts are not standardized For most 2N2222s, when the flat side is facing you, the pins are E-B-C but some  are C-B-E.  If  you get C/E reversed the transistor will still sort of work but with a lower β (beta). This is highly annoying to debug…      To test an unknown transistor with a DVM in diode test mode, attach the red positive lead to the base of the transistor, and the black neg. lead to each of the two unknown legs in succession: The slightly lower of the two voltages will correspond to the collector-base junction, and the slightly higher reading will be the emitter-base junction.
$2.60/170pc
2N7000 2N7000 TO-92 N-Channel Mosfet (200mA max)
These mosfets are like “Transistors for Dummies” and work great as digital switches when connected to 5v Arduino digital pins – and you don’t have to do the calculations for the base currents, etc. So they are much easier for beginners to use although they will set you back a whopping four cents each. Note: A 100K resistor between the gate and ground keeps the N-fet off by default, but you can generally operate mosfets without a pin-gate resistor, though many recommend 150 ohms there. N-channel mosfets are usually placed on the ground side of the controlled circuit.


Note for 3.3v systems: The 2n7000 can be used with a 3.3v Arduino to control things like LED’s, but they only pass between 30-60mA because the controlling voltage (Vgs) needs to be at least 4.5v for the 2n7000 to be fully turned on. With only 3.3v control, the resistance across the 2n7000  is ~ 3-4 ohms, so there will also be substantial voltage drop across it.  Although “logic level” is not exactly as standard term, mosfets designed to work with 3.3v mcu’s often have an “L” in the part number, ex: IR540 (non logic level) vs. IRL540 (logic level).  Ideally you want the MAX value for Vgs(threshold) to be lower than 2.4v in the datasheet, or you want to see an RDS(On Resistance) quoted for 2.4v, or lower.  When considering the On Resistance, calculate the voltage drop that will occur when the MOSFET is On and the load is operating. If the load draws 50mA, and the RDS(on) is 3 ohms, the vdrop across the fet is 0.05*3=0.15v. The tricky thing about this calculation, is that the On resistance changes with the level of the controlling Gate Voltage, and as you get closer to the Vgs(th)threshold voltage, the on resistance increases – so you need to dig into the graphs on the datasheet to figure out what the actual vdrop is going to be. Since the whole point of using a MOSFET as a switch, is to achieve lower Vdrops than you would get using a BJT, you want the vdrop  across the FET to stay below 0.25v maximum.   Probably the closest thing to a 3.3v version of the 2n7000 would be one of the Supertex TN0702 or TN0604, which come in the same TO-92 package.

You can solder legs onto SMD parts to make them breadboard friendly.

Most of 3.3v N-channel mosfets come in tiny surface mount SOT-23 packages:  The Philips pmv30, pmv31 and pmv56, and the Vishay Si2302, Vishay Si2356DS  , Si2312BDS (or Si2333DS /DDS for P-channel)  The Fairchild NDS331 / 335 is another good option with very low on resistance and a gate threshold of only 1v.  The problem is that none of them are available in breadboard friendly TO-92 packages  so  you might have to mount them on SOT-23 adapter boards to use them, and if you willing to do that it might be worth going to the Si4562DY which gives you both N & P channel mosfets in the same package. A P-channel mosfet is used on the positive side of the load whereas an N-channel mosfet is used on the negative or ground side of the load. When triggered, a P-fet connects the input on the load to the positive source whereas an N-fet connects the output from the load to ground. Keep in mind that you can’t drive a p-channel directly from an Arduino if the circuit being switched is a different voltage from the control logic, but that can be solved by using an N-fet to invert, then connect it to a P-fet in succession
Also see: P channel FDN338P and N channel FDN337N, STN4NF03L.

$2.00/50pc
Rotary pots 10K Linear Rotary Potentiometer 15mm
Also available in other values like 1K These B1k/10k’s can be put right onto a breadboard, though they are also good for soldering lessons and then you are ready for the ever popular LED Bar graph tutorial at Arduino.cc  For some reason, it’s cheaper to buy the plastic knobs separately.
$2.60/10pc
BBorardTrimpot Breadboard trim potentiometer 1 & 10K
These guys are really nice to use on a breadboard as you can turn them with your fingers, however they are more than a buck each. If you can stand using a screwdriver to adjust, the cost of a smaller trimpot goes down to about 20cents each. There are also 3296 Assortment packs of other styles available.
$1.25
Momentary switches Push Button Momentary Switch (12x12x7.3mm)
15pcs with a selection of different color caps. Cheaper if you get larger quantities. Sometimes there are little bumps on the bottom that you have to snip off to make them breadboard friendly.
$3.70/15pc
LatchingPushButton Latching Push Button Switch DPDT 8x8mm
I prefer these latching push buttons to slide switches because they are less likely to pop out of the breadboard by accident when you are using them.
$3.00/15pc
HeaderPins 2.54mm 40P Break Away Pin Header [Female/Male]
Get both male and female sets. You frequently need to add male header pins to sensor breakout boards.
$0.80/10pc
doubleheader Double Length 2.54mm M-M Header Pins
Extra long header pins are handy at times, as are 90 degree lateral pin headers
$1.60/10pc
DupontRibbon 40 pin Dupont wire jumper cables 20CM
M-M, F-F & M-F. Usually you tear off a strip with the specific number of wires you need for a particular situation, like adding a jumper cable to a UART module that did not come with one. Often it’s convenient to buy these cables without the black plastic end covers so you can tear off ribbon strips to make custom cables, but you pay more for that. Those shrouds can be purchased in any combination from 1-8pins wide so you can make your own sensor connectors.
$0.99

Basic Sensors:     (also see: Adding Sensors ( & Modules ) to Your Arduino Data Logger)

With so many different types of transducers, I can only list a few examples here. And rather than a strict definition, I think of a sensor as ‘basic’ if it’s fairly easy to get the output you are after when you connect it to an Arduino. That can happen for different reasons: (1) Sometimes the raw sensor is electrically simple, such as ‘modulating’ sensors that change their physical properties (like resistance) in the presence of heat, light, etc. and these can easily be turned into a voltage with a simple divider. Some of these sensors are ‘self -generating’, producing a small signal which can be fed directly into the Arduino’s input pins. (2) Others fall into the basic bucket because someone else has put the sensor and some fancy electronics together inside an IC package or onto a cheap breakout board/module, to make connecting to the Arduino easier than it would be with the raw sensor. (3) And other times it’s because someone has released an open source “library” that teaches your Arduino to “talk” to the sensor, which might be more electronically complicated than the Arduino itself. (Although sometimes those sensors tend to have so many settings to take care of when you start them up, that even with a library they still end up the “Advanced sensor” category. We have tutorial pages discussing how to use those more advanced sensors.)

TransparentSinglePixl
Basic Sensors
reedSwitch Magnetic Reed Switch
Perhaps the most fundamental type of sensor is a switch. You can think of push buttons as crude pressure sensors, and magnetic reeds as proximity sensors. They show up in applications like rain gauges and anemometers because they are robust and draw no current most of the time. Find a good tutorial on pull-up resistors, and de-bouncing is another important issue with switch sensors.
$1.00
Photocell 5528 Photocell 10KΩ LDR
This light dependent resistor might be the easiest sensor to start your lessons with. Put a fixed 10K resistor in series and read the middle of the voltage divider with a analog pin. That’s it. Add a passive piezo buzzer module and you are ready for the popular Light Theremin exercise.
$1.00/20pc
thermistor NTC Thermistor 10KΩ B=3950 1% tolerance
Thermistors change their resistance with temperature just like LDR’s do with light. So you use the same electrical circuit to read them as the LDRs. The devil though, is in the details. Thermistors are very non linear, so you need to so some fancy calculations to translate the analog readings into an actual temperature. There are lots of great tutorials out there to help with that. Generally, I prefer to use 100K NTC thermistors, since they have less problem with self-heating.
$1.00/10pc
FSresistor Force Sensitive Resistor 0.5″
In this case the resistance changes with applied pressure. In fact there is a whole family of Force / Stretch / Bend sensors like this and they get used for all sorts of things like measuring water level. Unfortunately they are also pretty darned expensive, so sometimes its better for students to make their own FSR sensors instead.
$6.95
piezo sensors Piezo knock/bump Sensor 27mm
Piezos can generate significant voltages, so they get connected with a shunt resistor to damp things down; protecting the Arduino. Be sure to get the ones with the lead wires already soldered on.
$2.60/20pc
When you move away from raw sensors, there seems to be a bewildering array of ‘breakout boards’ and ‘sensor modules’ for the Arduino and they sell them in mega bundles of twenty, thirty or sixty different pieces. Like the component kits it is probably OK to get one of these when you are starting out; just to play with them and see which ones fit your curriculum. Watch for custom connectors that force you to buy extra cables & interface boards. I actually like the Grove System, and similar systems like the Itead Electronic Bricks, but from a teaching point of view those are better suited to creating ‘snap together’ lessons with younger students. (or no wiring at all if you populate a Multi-sensor Expansion shield) That’s not so good if you want them to become comfortable making their own circuits on a breadboard.
sensor module kit 37 in 1 Sensor Modules Kit
Just an example of one common module set from eBay. So you will have to hunt around for a set that looks interesting to you, and it might be worth an extra buck or two to get one that comes with an organizing case. For some, like the Keyes series, you can find pinout guides and instruction wiki’s There are usually several “How to use it” tutorials for each sensor at instructables.com and on YouTube.
~$20.00
Once you get a closer look at them, you’ll notice that most of these cheap sensor modules look the same:

ComparatorModule_620pxw

That’s because at least 50% of those boards are simply a voltage divider like you would use to read the raw sensor connected to one input of a 5 cent comparator circuit. While a 20 cent trimming pot sets the voltage on the other input:
LM393circuitThese boards take an analog voltage, compare it to a threshold, and then produce a digital on/off output on Dout which you would read on digital input pins on the Arduino. Essentially turning an analog sensor into a kind of switch. This is such a generic circuit, that you could put other resistive sensors on those pins and it would work fine.  Look for boards that give you the 4th analog output pin if you want to read the actual sensor value with the ADC.

LDRmodule Photoresistor Sensor Module for Arduino
Here is that same 5528 LDR I listed at the beginning, being sold as a “sensor module”.
$1.00
TC5000IRpair TCRT5000 Reflective Infrared Emitter&Sensor Pair (Raw) $1.00/10pc
TCR5000module TCRT5000 Reflective IR Switch (module)
Sometimes used for line following/distance sensing in robots.
$1.00
HR31resistiveHumidity HR31 Analog Resistive Humidity/Temp Sensor (Raw)
You get one combined Humidity/Temp impedance number out of this sensor, which you have to decode to work out the humidity.
$2.75/2pc
H31module HR31 Analog Resistive Humidity Sensor Module
Be careful which one you order. 3pin=On/Off threshold output only & 4pin modules will let you read the analog output of the divider. By now I hope you see the pattern in these cheap sensor module boards. The list goes on forever…
$3.00
PIRmotionSensor HC-SR501 PIR (Passive Infrared) Motion Sensor
This module has vastly more complicated supporting electronics than the simple comparator boards above, but you use it in essentially the same way. Adjust some trim pots and then look for High/Low output on a digital pin.
$1.00
capsensor Capacitive touch sensors
Tons of these on eBay, and dirt cheap, but nowhere near as much fun as making a really big capacitive sensor yourself with some flat sheets of aluminum foil and the Arduino capsense library.
$1.50
In addition to modules, you also run into integrated circuit sensors where more electronics are embedded inside the sensor itself. These can have either analog, or digital output, but the digital output is no longer limited to simple on/off information . Analog sensors are generally easier for beginners to use, since all you have to do is read an ADC pin to get your numbers. The digital sensors have to “talk” the Arduino, and that usually involves including a library at the start of your sketches to handle the low level details of the serial communication protocol. There are far to many to cover here, so I will just leave you with a comparison of two sensors that have nearly identical sensing capability, with one being analog, and the other as digital. Equivalent pairs like this exist for other environmental parameters like pressure, humidity, etc.
TMP36 TMP36 – Analog Temperature Sensor
Unlike a raw thermistor, these sensors have a bunch of circuitry for amplification and signal conditioning so that the output given to the Arduino’s ADC is beautifully linear.
$1.50
TMP36 DS18B20 – One-Wire Digital Temp Sensor
This ‘one-wire library dependent’ temperature sensor is often the first one people use when they make that transition, and it is one of my personal favorites. Digital sensors come with various serial communication protocols, but in return for the added code complexity you get the ability to hook many sensors to the same ‘bus’ wires, and in the case of the DS18b20, those can be up to 100 meters long.  DS18b20’s are also commonly available on 1m cables inside waterproof metal housings which can be quite convenient for a student project that needs to measure several different temperatures. However if you actually do want them to operate under water, I’d recommend adding another full layer of marine grade adhesive lined heat shrink over the sensor-cable connection because the potting job on the cheap ds18b20s can be pretty badly done. Cheap eBay sensors can also be outside the +- 0.5C spec, but that can sometimes be useful when teaching a lesson on calibrating temperature sensors.  The real thing to watch out for is the sleep current – DS18b20s should automatically go to sleep around 8 nA. If you measure more than that the sensor is probably a dud, that will mess up it’s own readings by self heating.
$1.30
Making the transition from simple analog to true digital sensors is like earning your merit badge with the Arduino. There is usually a digital version for every different kind of analog sensor at about the same cost, and in some cases the digital version offers tremendous advantages in terms of resolution. But one of the first things you want to know is: Are there good libraries to make this sensor work with an Arduino? While there are plenty of independent coders posting open source libraries to GitHub, suppliers like Adafruit & Sparkfun often release them in conjunction with a cool new sensor, and it’s one of the reasons why people in the Makers movement like them so much. Though I have listed several low end commodity parts here, I still spend a significant amount at those first tier vendors: both to get sensors I can rely on, and to show them some love for all that hard work.  For a more detailed discussion of these options see our page on Adding Sensors ( & Modules ) to Your Arduino Data Logger.

Tools:

Before the comments fill up with dire ‘You get what you pay for…’ warnings, I’d like to point out that when I’m buying tools for myself, I check three places: Adafruit, Sparkfun, and EEVBlog. If you want quality tools go there and buy what they recommend because they really know their stuff. However in the real world a teacher is lucky if they get $500-1000 to spend on materials for a 10-12 student class.   See: Collins Lab tool video.

TransparentSinglePixl
Soldering Stations: ~$130 / station
YiHua936b Yihua 936b soldering station
Unlike thin pencil style irons, These guys have enough thermal mass to handle soldering beefy connectors. Get the ones with the switch on the front and the blue metal stands. Buy a full set of replacement tips at the start of each term – you will need them.
$23.00
Comment: I love my Hakko FX-888D, in fact I wish I’d bought that before working my way through a bunch of crappy soldering irons. However you can buy four of these cheap knock offs for less money, and that really helps the budget if you need enough for a whole classroom. It also helps that these things are big & ugly if you are working in a place were things tend to grow legs and walk away on their own…
ReplHandle_160pxw Replacement handle for Yihua 936 station
Yes, soldering irons do break if you drop them – especially the cheap ones. This is 5 connector handle is not the same as Hakko 936.  With spare handles this cheap, it’s faster to just change the whole handle when you want to work with different tips, rather than waiting for everything to cool down, and re-threading.
$2.77
Tipset_100pxw 12pc Soldering Iron Tip set Hakko 936 (& Yihua)
The ultra thin pointy tip that comes with the 936b is nearly useless.  900M-t-1.2D ‘screwdriver’ and 900M-T-B ‘cone’ tips are not bad for beginners, and it’s cheaper buying those individually after you get one “mixed set”. Of course these are all fake tips:  real Hakko tips usually cost around $10 each.  Because I do a lot of fine work, I’ve been using the  T18-S4 ‘conical sharp’ (came with my Hakko 880) as my default tip years. It’s not great for heavy jobs, but if you need to work at the level of a IC chip leg the T18 is a good choice. Genuine tips usually have laser engraved markings on the sides. Do not buy lead free tips unless you are using lead free solder, as the chemistry does not mix with 60/40 and you end up with a weird blue-green rind forming on the tip.  Remind your students to always apply fresh solder to the tips before turning off your iron, because once they go dry the tips are often ruined. Sometimes they can be brought back to life with tip-tinner.
$9.85/12pc
TipCleaner_160pxw Soldering Iron Tip Cleaning sponge
And you will need some replacement sponges eventually.
$2.80
Metal Iron Stand For 936 Soldering Station
These lunkers are much more stable than the flimsy wire ring style holders & work with most cheaper irons.
$5.00
400gSolder 400G 0.8mm 60/40 Rosin Core Solder Wire
A large roll like this is for soldering stations that you don’t have to take down at the end of each class. But it should last quite a while.
$17.00
SolderHolder1_160pxw Solder Wire Holder for large rolls
A holder for the large solder rolls like the one above. There are better looking ones out there a few dollars more..
$5.00
Solderwire_100pxw 0.6mm 60/40 Rosin Core Solder Wire
I use  0.5-0.6mm wire for things like pin headers and general solder joins. Buy a few per station, as small 50 gram rolls get used up quickly. For really fine work on IC chip legs, it’s also handy to have a roll of 0.3mm around.
$1.50
SolderWick_100pxw Solder Removing Wick 3mm braided
Get a couple for each soldering station.
$1.50
SYB-46 270 Tie-point Breadboard
I put these single rail protos into the soldering kits as “sacrificial”  breadboards that the students can use to hold header pins in place while pinning up pro-mini boards and sensor modules.  Write “FOR SOLDERING ONLY” in a black sharpie on the boards, because once the heat’s been on them, they are pretty much useless for anything else.
$1.90
NoCleanFluxPaste MG Chemicals 8341-No Clean Flux 10 ml Syringe
Doesn’t make a mess like the $1 options from eBay, easy to pack up & lasts for years without drying out if you remember to put the cap back on…which students never do…
$10.00
Thermaltronics TMT-TC-2 Lead Free Tip Tinner (20g) in 0.8oz
Students always forget to leave solder on the tips after working. Once tips oxidize from running hot and dry they will not hold solder. This will bring most of those abused tips back to life once or twice. 
$9.00
PanaviseJr_160pxw Panavise Jr. – PV-201
This is one of those rare items for which there really aren’t any other equivalent products on the market – though you could try the attaching a PanaVise 207 Vise Buddy Jr (made of plastic) to a DIY base. Don’t forget the Neoprene Jaw Pads and the Speed Control Handle which add a lot to the functionality. As would one of these things.  
$28.00
HelpingHands_64px Third Hand Soldering Stand / Holder
I use these guys to hold wires in place, while a Panavise holds the board I am working on. The alligator clips always fail with time and there are other things that might also do the job. At EMS labs, they make their own with thick wire. Hobby Creek Helping hand Arms work pretty well as third hands on their own, or you can attach them to a baseplate.
$6.00
Heaterizer_100pxw Heaterizer XL-3000 Heat Gun
A cheaper option than a full re-work station, but also much noisier.
$13.95
HeatShrinkKit_100pxw Assorted 2:1 Heat Shrink Tubing Kit
You rarely use the larger sizes, but a general assorted size kit like this is good when you are starting out. It is much easier to spot soldering problems if you use CLEAR heat shrink tubing but its not as pretty. Keep a good stock of 1.5 mm, 2mm and 3mm on hand, in fact buying those smaller sizes by the roll might be a good idea.
$3.10/328pc
Glasses_100pxw 3.25 diopter Reading glasses
The cheapest option for close-up soldering work. And get hard shell cases so they can just be tossed into the station kits without scratching.
$2.00
WireStrippers_100pxw AWG 30-20 Precision Wire Strippers
Hakkos are the gold standard, but these ones from H.Depot are ok. They gave the Ideal T-stripper model 45-121 a good review over at the EMS blog.
$4.71
CuttingPliers_100pxw #170 Flush Side Shear Cutting Pliers
Again the Hakko CHP-170 would be my first choice, but these work.
$2.00
Pliers_100pxw Bent Nose Jewelry Pliers
You can find others for a buck if you go hunting, but I like the handles on these. If the budget allows, also get a few extremely pointy long-nose pliers like the Hakko CHP PN-2007.  It is often helpful to be able to bend one wire into a tiny eyelet shape before soldering it to a pin, and you need a fine tip pair of pliers for that.
$2.50
Baskets_100pxw Plastic Locker Bins with Handles
Reasonably large plastic bins let you pack up the soldering stations after class and put them in storage. Most dollar stores have something like this on hand.
$1.00
Comment: Even if you teach the course with breadboards, you will need at least one complete solder station for things like adding header pins to your breakout boards. A full set like this will set you back about $130, and but depending on your scheduling, you might get by with one full station for every two or three students. We usually set them up around the perimeter of the classroom.

TransparentSinglePixl
Other Useful Tools:
CrimpTool_100px SN-01BM Dupont Connector Crimping Tool
If you keep your eyes open, you can find them for less than $20.00. Many recommend the better quality PA-09 crimping tool, but those usually run ~ $50.00 
$25.00
Make polarized (non reversable) connectors by mixing Male & Female connectors

Make non-reversible  connectors by  combining M&F pins

Comment: Before you get a crimp tool, you have no idea why you would want one. Afterward, you use it almost as often as your soldering iron. Dupont connectors are ubiquitous and lots of electronic components have leads too thin to use on a breadboard, so you end up crimping male DuPont ends onto them just to plug them in. It does take a bit of practice to get the hang of it, but there is no other way to make interconnecting cables this quickly & inexpensively. See Instructible: Make a Good Dupont Pin-Crimp Every Time

DupontMalecrimps_100px Dupont 2.54 Connector Crimp Ends
Be sure to get both Male and Female ends. Buy 2x as many female as male pins.
$1.52/100
Terminal Ends Dupont Jumper Plastic Terminal Ends
Get at least 200: 2x, 3x, 4x and 6x plastic covers. I don’t use the 1x ends any more, as I simply put black heat shrink over them. There are and infinite number of other cable variations that you can build.
$0.90/50pc
SolderPot_100pwx 50mm Solder Pot
Once you start building things you end up having to tin allot of wire ends, and a solder pot makes that much faster than using your soldering iron. You only need one of these per lab, and you could probably skip it if you are doing primarily breadboard work.
$17.00
AligatorCables Alligator to Alligator Prototyping Cables 50cm $2.00/10pc
AtoBcables_100pxw Banana to Alligator Cable Pair Black & Red
A set for every voltmeter, for the times when you need hands-free use.
$0.90
EpxoyApplicator_100pxw 50ML Epoxy Sealant Applicator Gun 1:1 and 2:1
There are a few different variants on the market and you have to match up all the parts of the system with your brand. This one works with Loctite.
$10.00
Hysol Loctite Hysol 30-CL, Clr, 50mL, Cartridge
This stuff has proven to be a good potting compound after more than a year of marine water exposure at depth. Takes >24 hours to cure. Alternatively, you could pot with a neutral curing silicone like RTV 128. but be careful with silicone as many emit circuit-wrecking acetic acid while they cure (so if they smell like vinegar – do not use them!)
$11.40
Nozzles Static Mixer Nozzle BT MA6.3-21-s
Don’t use the shorter nozzles with less than 20 elements, or the epoxy does not mix &  set properly.
$21/50pc
ScotchMountingTape Scotch Permanent Mounting Tape, 1 x 450 Inches 5LB
This stuff is immensely useful when you are putting a prototype together, and you just need to mount your boards inside a housing. Always have a roll on hand.
$15.00
LableMaker1 Deluxe Label Maker
A label maker is a vital piece of lab equipment. I go through 4-6 ribbons on my old old Brother P-touch setting up for each class. Not sure which one to recommend from the current crop, so you have to do your own homework there. But just get one.
$25.00
screwdriverSet Multi-tip Precision Screwdriver Set
Get one with at least 30 bits. And it never hurts to have a few of the $1/6pc sets around as well. If you are not budget limited, get the ones with the longer extension rod.
$4.50/32pc
conformalcoating MG Silicone Conformal Coating : 422
The best way to protect Arduino boards & RTC modules from moisture in the field. Clean the boards thoroughly with 90% isopropyl alcohol first, and apply the conformal in a fume hood, as this stuff is really nasty. In a pinch you can also use clear nail polish as a protective coating instead. Avoid bathroom silicone rubbers for potting electronics, as they off-gas vinegar during curing which destroys electronic circuits.  And if your students are putting their loggers into the wild, throwing in a couple of silica gel packets into the case will protect from excessive moisture. Get the ones with color indicator beads, so you know if they are still working.  You can also re-use these packs if you dry them out with repeated short 10-15 sec intervals in the microwave, but the procedure takes a while to do properly because you have to let them cool down between zaps.
$15.50
openingpliers_100 5″ Opening Pliers
If you run into a situation where your heat shrink doesn’t quite fit over the item, these fix the situation.
$6.50
DrillPress_100px WEN 4208 8-Inch 5 Speed Drill Press
You can use a hack saw for most small cuts, but sooner or later someone is going to need holes in something, and this Sears knock off is cheaper than many hand drills. I also use a bench top band saw quite often, but table top scroll saws are probably safer for classroom situations though it’s nearly impossible to get a straight cut out of them. And if you are handy with the soldering iron,  you can often retrofit lithium batteries into portable hand tools after their original cells are shot. It’s also fairly  easy to remove the rust from any cheap tools you come across at a garage sale. 
$70.00

Addendum 2016-09-15:

Finally have things set up for the next bunch of students, and since it’s unlikely to look this pretty again for a while, I though I would post photos of the classroom set ready to go:

labstorage1    labstorage2

It all fits comfortably into these two cabinets, but we could probably get that down to just one if we had to.

Addendum 2017-10-01:

Just found an interesting circuit visualization idea at instructables.  It’s a pretty time consuming method, but it’s easy to see how this would be applied in a classroom setting. One of the drawbacks of standard breadboard methods is everything on the underside of the boards is hidden once the pins are in place. You could do this with cheap pre-cut acrylic platforms.

Addendum 2017-10-15:

Codebender is an online Arduino IDE alternative that uses a javascript plugin to let your browser access your computers serial ports. The subscription is $10/month, and the .edu version of the service opens the possibility of collaborative projects with your students for an extra $0.50 per seat, perhaps even giving you the ability to grade/guide student work from any location without having to move a bunch of script files around. As an Arduino instructor, Codebender could save you 2-3 hours of computer setup just installing local IDE’s for a workshop. I’m a big fan of the default IDE, but given how much of a pain Github can be for Arduino-scale projects (especially if you work from multiple computers, or if your hard drive fails and you have to rebuild everything), this provides an interesting code-sharing alternative worth looking into. They also have more than 600 sensor libraries in their archive, and since library installation is always a stumbling block for people new to the Arduino platform, this could help beginners.

There are a few issues that are worth considering though: it only works in chrome or firefox, and everything internet related breaks eventually, and will continue to do so in the future, so you need a backup plan for any downtime or loss of the network. If you experiment with weird new Arduino compatible board variants, there’s a good chance those board definitions won’t be available in Codebender, and none of the libraries I use regularly were there because they were one-of variants that I found after digging through GitHub.

Addendum 2017-12-14:

Looks like I’m really late to the party, as Arduino has had its own web editor & cloud service for quite some time now. The Arduino Web Editor is supported on Windows, Linux, Mac and Chrome OS. The Chrome OS version is a buck a month, which is considerably cheaper than Codebender.  The thing about this that’s mysterious is that I work on the platform almost every day, scouring forums for code tricks, looking for cool sensors, etc.  –  and I’d never heard about it.  At least not in the forums & blogs.  Makes me wonder if the board discovery method that’s baked in to their service means that all the clone boards like moteinos, rockets, etc are not allowed to join the party(?) Fair enough I guess, since they need to make a little coin to keep something like that flying, but still curious…

Arduino UNO Datalogger Project for Beginners (ie: no soldering)

Addendum 2017-02-20:

This post is the second in a series of online tutorials that I’ve been developing to help teachers bootstrap their own Arduino based curriculum. The full set are listed at  How to Build an Arduino Data Logger which walks you through the most recent versions in a more or less logical progression.  But if that material leaves you in the dust because you are teaching yourself as you go along ( like most people in the makers movement! ) then check out the beginner’s guides & video tutorials in the Ideas for an Arduino STEM Curriculm post. 

Also Note: Once you’ve mastered the basic UNO logger described in this tutorial, you can transition to smaller Pro Mini Based versions that run the same code, but provide much longer battery-powered operation. [see:  This open access paper describing how we use those for scientific research.]


Original Post from 2015-12-22:

Since posting the step-by-step build guide in November, I’ve had enquiries from people saying that the equipment & time required for that build still presented a significant barrier in the classroom.  A few asked if I could come up with a plan based on the Uno/Breadboard combination that has become a standard starting point for many people.  So here is a simplified data logger for those high-school teachers who want to add environmental monitoring projects to the curriculum:

An Uno-based basic data logger, with no soldering required.  As the instructor, you can assemble this logger very quickly with pre-made jumpers but we found the connections were too easily knocked loose by clumsy students, so it’s worth taking the time with them to put stiff solid core wires in place. Note: I used an older UNO R1 I had lying around for the photos on this page, and the current R3 has A4&A5 broken out again on the right side above AREF, so follow the pin labels rather than the physical positions to accommodate your particular board revision (R1 / R1 / R3) pinouts

LevelshiftedSDCard

SPI micro SD card adapters like this can be had for less than $1 on eBay, and these can be connected directly to the pins of 5 volt Arduino’s like the UNO or the smaller form factor NANO. (note: the SPI pin labels are on the back).

Similar approaches to assembling a DIY logger can found at other places on the web (including many pre-built data logger combinations), but I thought I would add a quick breadboard logger to my other tutorials for those who Googled their way to this blog looking for something fun to try with an UNO – even if they did not have much experience with electronics.  If you go with no-name clones, the approach I’ve outlined here might also qualify as the cheapest option available (…if you are funding the everything out of your own pocket, like some of the science teachers I know…). The key difference between using an (unmodified) UNO, and the smaller pro-mini style loggers described in my earlier tutorials, is that UNO’s operate at 5v, while smaller form factor boards are generally regulated to 3.3v. This limits the sensors you can connect directly to those capable of operating with 5v logic levels, but most importantly it affects the SD cards, as they can only handle 3.3v. So you would need to use a raw adapter board with a level shifter to accommodate the different voltages. Fortunately, SD modules that already have the regulator & level shifter on the breakout board are very inexpensive, so this issue does not add complexity to the basic connection plan.  These cheap regulators are notorious power wasters, but most people operate UNO based projects on a USB tether for live sensor data in the serial plotter, or power them via a wall ac power adapter.


Parts you will need:

Arduino Uno ($24.95)
 A few students used less expensive clones for their personal projects (~$4.00) and they worked OK, though the soldering looked a bit dodgy, and a couple of the eBay ones used non standard UART chips so we had to go hunting for drivers. I often use the cheap stuff when I am noodling around on the workbench trying to get something working, and then deploy better quality hardware in the field. If you are just starting out, I suggest that you save yourself the driver headaches and use the standard kit. If you do go with the clones, donate something to the Arduino group as a thank you for making such awesome software
DS3231 & AT24C32 RTC module ($1.00)
Mini 400 Contact Solderless Breadboard ($1.50)
CR2032 coin cell battery for the RTC ($0.50)
SanDisk microSD card:  256MB to 1GB ($2.00-4.00)
Stick with cards smaller than 2Gb and format them with SDformater utility (not windows!) to fat16 and test with H2testw.  I generally buy 1Gb MUVE music cards from eBay because they are usually genuine; drawing lower sleep currents. WRT Filenames: use 8.3 format and don’t use spaces or special characters.
SPI microSD breakout ($1.00)
Common Cathode RGB LED (<$1.00)
+Various tools including needle-nose pliers, wire cutters, strippers, soldering irons, etc.

Total parts cost:  $15 to $35 depending on which Arduino board you use


Optional parts:
USB cable A-B ($1.00)
Jumper wire kit ($2.00)
I usually go with thicker 22 AWG, but 24 works too
Resistor kit ($2.00) 
The limit resistor for the LED can range from : 1,000Ω, to 30,000Ω with 10K being a reasonable option. Note that cheap multi-pack resistors often have thin 0.4mm wire leads which are not “breadboard friendly”, while more expensive resistors from Vishay or Speer usually have 0.6mm leads which stand up much better to handling
6xAA battery holder ($2.00)  or 8xAA battery holder ($6.95) with 5×2.1mm power jack
for longer life a 9v D-cell pack should get you out to a couple of weeks of operation
Scotch Outdoor foam Mounting Tape, 5Lb ($4.00)
Plastruct #91105 .060 White Styrene Sheets 3Pack ($10.00)
We attached the UNOs & breadboards to cut rectangles of styrene with the double sided tape to make stable platforms that the students could just pop into their project boxes when class was over. But premade acrylic mounting plates are also available.

For an extensive list of parts & materials see:  Building your own Arduino Classroom


Arduino software & libraries:

Before you tackle the assembly, install the Arduino IDE and test that it can communicate with your Arduino. Then there are a few libraries to download and install so that they are available when the Arduino IDE compiles & uploads you programs.

a) A library to control the RTC:
https://github.com/MrAlvin/RTClib
(Note: there are many other good libraries out there that you could use and confusingly most of them have the exact same name, but this one allows you to set sub-minute alarms if you need to)

b) An I2C bus scanning utility:
http://playground.arduino.cc/Main/I2cScanner
(to make sure your RTC and I2C sensors are connected & working)

c) A utility to test communication with the μSD card :
https://www.arduino.cc/en/Tutorial/CardInfo
(You will need to change the CSelect variable to pin 10 from the pin 4 in the code at arduino.cc)

d) A library that puts the Arduino processor to sleep between readings:
https://github.com/rocketscream/Low-Power
(you can’t put the UART to sleep on an UNO, but every little bit still helps save power)

e) A program to make the logger read & save data on the SD card:

A good place to start would be Tom Igoe’s excellent analog pin reading example at Arduino.cc   (but change const int chipSelect = 4; to const int chipSelect = 10; for the build described in this tutorial) 

 For something a little more advanced, I have prepared basic data logger script that puts the data logger to sleep and wakes it up again based on timed alarms from the real time clock. These are both just starting points for you to add to as you learn more about programming an Arduino


Putting it together:

1)  Prepare the RTC board

Resistor to remove from RTC

I usually begin by removing the resistor highlighted in red to disable the battery charging circuit. There is also a power wasting LED on the RTC board that you can remove as well, but that’s only worth doing if you want to run the logger on batteries. For more details about these cheap DS3231 breakout boards, you can dig into this RTC Post.

I have been using these cheap DS3231 RTC boards for a while now. They have proven to be very robust, although they have one element that is slightly annoying: they come with a charging circuit that assumes you have a rechargeable LIR2032 backup coin cell installed. You can use the RTC board as-is if you have on of those LIR’s in your RTC, but since you are not supposed to ship lithium batteries in the post, you almost always receive these RTC boards with no battery, or even worse they will just stick an non-rechargeable CR2032 in there which will pop if you leave it plugged in for long with the charging circuit connected. I usually end up finding a local supplier for non-rechargeable CR2032 coin cells which work fine as a backup power source for the clock provided you disabled the charging circuit by removing the resistor highlighted in red above.  You can cut that resistor off with a knife, but I find it easier to flick it off the board with the tip of a hot iron ( I know I promised that this was a solder-less build… but I didn’t say anything about de-soldering 🙂 ) Then insert a fresh CR2032 coin cell into the backup battery holder on the other side. If you forget to put in the battery the logger will still run, but the RTC will forget the date/time every time you shut your logger down, so the time stamps will not be correct unless you reset them every time you start the logger.

2)  Power the breadboard rails

1_pwrJumperBring the ground and 5v lines over to the power rails on the breadboard with some solid core 22 gauge wire.  I usually do this at the end of the board that is farthest from the rest of the wires I am patching over. Its worth tucking them in as neatly as possible so that they don’t get bumped around later. Make sure you have stripped enough insulation from then ends that the bare wire penetrates into the riser holes enough for a good connection.

3)  Jumper the RTC module

Connecting the RTC to an Uno

Connecting the DS3231 RTC to an Uno:  This is possible because the DS3231 has a wide voltage range from 3.3v to 5v.  Many other I2C devices would require a 3.3-5v level shifter before they could be connected to the 5v UNO pins. Note: The long red & black wires at the bottom are simply patching power over to the rails on the other side of the mini breadboard.

The RTC board has clearly written silk screened labels for each pin:

Connect VCC & Ground to the appropriate rails on your breadboard.

Since the RTC is an I2C device, it uses the A4 pin on the Arduino as the SDA data line (white) and the A5 pin as the SCL clock signal line (yellow). There are many easy to use I2C sensors (that have pre-written libraries) that you may use with your logger, and they will be connected to these lines in parallel with the RTC. ( …if those sensors can tolerate 5v logic levels like this RTC ) To enable I2C communications, this RTC breakout board already has 4.7K pullup resistors installed on those two lines, so any other sensors you wish to connect to the SDA and SCL communication lines will probably not need pullup resistors to function. Many sensor breakout boards also have pullups on them, which you can usually leave in place, provided that the combined resistance of your parallel pullup resistors does not fall below 2.2k ohms.

Jumper the SQW line (blue) from the RTC board to Arduino pin D2. This wire will carry the “wakup alarm” signal from the RTC to the INT0 line. (note: the angle on the diagram above makes it look like the wire is in D3, but it is D2)

4)  Set the time on the RTC module

Before connecting any other components to the Arduino you should make sure you have the RTC working. Download the library ZIP file, extract the package, and move the library into your Documents/Arduino/Libraries folder.  The moved folder must be re-named ‘RTClib’ for the compiler to find the library and sometimes un-zipping adds extra folder layers that you have to remove to get to the library you want.

Update: 2016-10-12: I just noticed that they have taken the setTime & getTime utilities out of that RTC library that were current when I wrote the original post.  Now you will need to load File/Examples/RTClib/ds3231_v2 and set the time by following the instructions on screen in the serial text monitor. The new method should let you set your RTC more accurately than using the compile time with setTime.

OLD instructions: the greyed out instructions below apply to older versions of the RTClib that were distributed with the gettime & settime utilities.  I’ve posted copies of setTime & getTime utilities to my GitHub and there is an alternate version of the setTime sketch with Paul Stoffregens DS1307RTC library, which sets the RTC to the compile time with the command  RTC.adjust(DateTime(__DATE__, __TIME__)); but I found I also had to install Paul’s Time Library, to use his version of settime.

gettime

I set my loggers to UTC to avoid problems with local daylight savings time variations. To do this simply change the time zone on your computer before uploading the settime sketch.

RTClib includes two useful utilities called setTime & getTime that can be found via the IDE pulldown menus after the library is installed at: File / Examples / RTClib / settime   &   File / Examples / RTClib / gettime  Open the settime sketch, verify it, and then  upload it to your Arduino via a USB cable connection. This takes the time signature from the compiled code itself and sets the RTC clock with that time. Do not open the serial window while settime is running or the program restarts – setting the time again incorrectly. Immediately after the settime has been run, LOAD the gettime sketch in the IDE and upload it to the Uno. Now open the serial widow, set the IDE serial window speed to match the script,  and you should see the date & time being read from the RTC.

Technically speaking, if your RTC is showing the correct date and time in the serial window,  you can move on to the next assembly stage. However, I usually run other programs to make sure that both the RTC and the AT25C32 eeprom on the breakout board are working properly.  Rob Tillaart wrote a bus scanning utility which is quite useful for this:      http://playground.arduino.cc/Main/I2cScanner.
If you run this utility you will usually find that the RTC is on the bus at address 0x68 and the 4K chip is on the bus at address: 0x57 – although the eeprom can move around from one board to the next. In fact the memory address can be changed to avoid conflicts with other devices by connecting the solder pads provided on the breakout board.

On that arduino.cc page you will also find a  link to a “Multispeed I2C Scanner” which I like because it scans the I2C bus with different speeds. This is useful as it identifies when your wires have become so long that capacitance is starting to interfere with the serial communication signals and cause the devices to act flaky and/or “drop off the bus”, but the basic scanner works just fine for most cases, especially when you are adding new sensors to your logger and you don’t know their bus address.

Note: If you see junk characters scrolling across the screen when you run any of these little utility programs, you probably need to check that your serial window is set to the same speed specified in the serial.begin command inside the program:

USBspeed

* I have also found that with some of the cheap UART boards that are needed for Pro-mini style Arduinos, I end up having to set the serial window to 1/2 the speed listed in the arduino code to make them work because they are not consistent with the standard board definitions. But the smaller 3.3v units have their clock prescalars set differently, so this should not affect the Uno based builds.

5)  Connect the indicator LED

Trimming

I find that its easier to keep the wires tidy by connecting one end of the wire to the Arduino, and then bend / fold it into place before trimming the other end.

Connect a three color common cathode LED to Red=D4, Grn=D5, Blue=D6.  A KEYES KY-009 SMD 5050 breakout board is pictured here, but any common cathode LED would work fine. Use at least a 1 kΩ resistor to connect the common ground line to the ground rail on your breadboard, to limit the current flowing through your LED.  As the limit resistor gets bigger the LED will become dimmer, but most are still visible with limit resistors up in the 20-30 kΩ range so the value is not critical. You do not need a three color indicator LED, but I find it helpful to put different color led flashes in the code so that I can keep track of what the Arduino is doing when I don’t have it connected to the serial window. So I turn on red for SD writing, blue for eeprom buffering, green for sensor reading, etc. 

LED and RTC connected

Two extra I2C jumpers (white and yellow) shown here simply patch those lines to the other side of the breadboard. These are not necessary, but they make it easier to add I2C sensors to your logger later without disturbing the RTC connections. The 220 Ω limit resistor pictured here is an absolute minimum, and probably should be bumped up to between 1-10K Ω.

6)  Connect the SD card Adapter

Place the SD card holder on the breadboard and jumper the following SPI lines from the adapter board ( check and match the labels printed on your particular SD board):
D12=MISO,    D11=MOSI,    D13=SCK,     D10=CS
Then patch the Ground and VCC lines to the rails on your breadboard.

SD card connections1

Before connecting your Arduino to test these connections, you need to insert a micro SD card in the adapter. Check a new card on your computer first, and delete any files that already exist on the card, then save a new blank text format file named “datalog.txt” onto the card (note: name in lowercase letters). Eject the sd card with the blank text file on it from your computer, and insert it into the SDcard adapter on your breadboard. It should slide into the socket. It should register with a nice click when it is in place. I often buy used MUVE music 1-3 GB micro sd cards because they are genuine Sandisk cards so they sleep at low current, and they are cheap because of the DRM on them that only lets you see 1gb of space – which is far more than you need for most data logger applications. (A typical logger recording Date/time and a few sensor readings every 15 minutes might generate about 5mb of text data after running for a year)

7)  TEST the SD card with CardInfo

This handy utility can be downloaded at:   https://www.arduino.cc/en/Tutorial/CardInfo

From there  COPY & PASTE the Cardinfo code into a new window in the IDE and make the following changes to the default CARDinfo script:

(a) CHANGE the chipselect from pin 4, to pin 10 with:  const int chipSelect = 10;   at the beginning of the script. We have already used pin 4 to drive our indicator LED’s red channel.

(b) ADD   #include <SPI.h>   to the beginning of the script if it is not there already.

VERIFY & SAVE this file on your computer with the name CardInfo. (you will end up using this utility many times again in the future!)  Then plug in your Arduino and upload the code, and open a serial window. You should see something like the following:

Card found OK
If you do not see a message like this one, it is possible that
-> The SPI line jumper wires are not in the correct place or you have a loose wire somewhere. There is some variation in the different board pin locations so review these on your board first to make sure you have everything connected properly. Note that your particular SD card adapter board pin-outs may not match my diagrams here, so you will have to adjust for that.
-> Your SD card is not formated as fat16 or the card is not inserted properly. I usually use smaller 1-2gb cards, as some of the new larger HDSC cards don’t format as fat16.
-> You have a bad sd card adapter board. I have had plenty of crummy sd card adapters with bad spring contacts, so try to have 2-3 of these on hand in case you get a bad one too.

At this point your jumpered connections should look something like this:

A basic Uno & Breadboard logger

Note that some overhang the SD card adapter board needs to sit “in the groove” at the center of the breadboard so that the pins make proper contact. The RTC and LED boards don’t require that, but it makes the build look a bit neater if you move them to match.

and your pretty much ready to start using your data logger.

8) Upload a basic data logger script

The code for your logger can now be downloaded from github via this LINK

Starting with Tom Igoe’s excellent example at Arduino.cc, (which would also work fine with this build if you make sure to change CS to pin 10, but that code does not make use of the RTC, etc)  I added some functionality to create a time stamp and read the temperature register from the DS3231, and then write that information to a file on the SD card. Here is graph of typical temperature output from that RTC:     (@ 15 min interval)

typical

The RTC  temperatue record only resolves 0.25°C, but I have found these chips to be far more accurate than the ±3C listed in the data sheet – often less than half a degree away from sensors like the MCP9808

The code also puts the UNO’s cpu to sleep between readings, and it wakes up again to take a sensor reading when the RTC alarm goes off. The serial print output is all optional, so you can comment out those statements when the logger is running in stand alone mode. When you start making changes to the code, commenting out the lines you don’t need is generally much safer than deleting them.

This script is only meant to provide you with a basic starting point, and it should be easy to add other I2C sensors, or simple analog sensor readings following the example from Arduino.cc . Before you add some new sensor to your logger, spend time searching through the forum at Arduino.cc, as someone has probably already answered any question you might have about getting it to work. When you are just starting out, choose sensors that already have good libraries written for them.

It’s worth noting here that this code would also run fine on my pro-mini based logger builds. All you would have to add is a few lines to read analog A0 which tracks the main battery via a resistor voltage divider which is not included in this UNO build. The main Arduino page has a lot of free books and resources as well as explanations for all of the built in code examples.  There are also plenty of good Arduino programming references out there if you google around, which should help you customize the script.


Running the logger:

6xAA battery packs like this are fairly common, and should power an uno based logger for about 4-5 days

Six in series AA battery packs like this are fairly common, and should power this basic Uno logger for a few days of stand alone operation – especially if you use Lithium AA’s which have a flat discharge curve. 8xAA packs are available, but you have to be careful that over-voltage on new batteries does not push the total output above the UNO’s 12v maximum. The optimal solution might be to use 7 batteries in an 8-series battery pack, with a simple wire soldered across the last holder. 18650’s in series would be another option. If you need something that runs longer, rare earth magnets (soldered to the ends of jumper wires) make it easy to connect a number of C or D cell batteries into a custom power supply held together with painters tape. I would not try to power this logger from a 9V battery, as I don’t think it can deliver enough current for safe SD card writing. Rechargeable LiPo shields are also available if your pockets are deep enough.

Always do tethered test runs with sensor output echoed to the serial port so you know the code is working before you run the logger in stand alone mode.  In fact, I assume that most people will use this logger as a data acquisition system so I’ve put together a separate tutorial on using the Arduino as a basic DAQ with the serial plotter tool.  (scroll down to the 2016-08-15 addendum for the UNO only section) Note that to copy data from the serial window and paste it into excel you need commas printed between your numbers, and cartridge returns after, by using println rather than print for the last bit of data. Sometimes students have trouble cutting and pasting from the serial text window, or they accidentally shut the serial window by pressing the wrong button. So it is still a good idea to save to the SD card (if you have enough memory…) because this makes it easy to graph the data later. (with Excel or Google Docs)

One of the weird behaviors to know about with Arduinos is that every time you open the serial window from the IDE, the program that is running on the Arduino will restart, so if you are writing header data to the datalog.txt in the setup section, you will see a new copy of that header in the file each time the serial window is opened.

 

The easiest way to estimate how long your logger will run on batteries is with one of these USB power meters. Insert one of these $4 adapters between a USB power supply adapter & the datalogger. Reset the timer and let it run for a few hours and then look at the cumulative mAh number. Divide that into the rated mAh of your battery and you have a ballpark run time estimate. For reference, most alkaline AA batteries provide about 2000 mAh. It is even possible to make your own power meters.

Once you are comfortable with the serial plotter tool in the IDE you can look at other methods for  graphing the data in real time. One common method is by using another program called Processing. But be sure you test everything before your classes, as I’ve had some challenges getting processing to work on different windows systems (with the data on the SD card saving the day once again…) There is also an Excel macro called PLX-DAQ that can be used to monitor any serial port and display the data sent through it, but I believe that macro only works with older versions of excel/windows and I’ve never gotten it to work on my versions. Like Processing, it requires a few extra lines of code to be embedded in the Arduino sketch to direct the data to specific cells in the spreadsheet.  Plot.ly might also be worth using to share data online in a way that looks professional.  And if you are really get the bug, you could take it all the way to the ‘Internet of Thingslevel if you add a shield or two. Home automation & wireless gardening, are popular applications, with some people using  Google Charts to display live data on their websites.

Note:

With the always on UART chip, it’s hard to get an UNO to run for long on batteries, but you should still be able to get few good days out of a set of AA’s with this plan.  If you want a smaller footprint, you could bend the pins 90° and connect the RTC & SD boards with a lower profile to one of the many ‘stack on top’ proto shields available. Probably the best of the lot is the Dead Bug Prototype shield for an Arduino UNO (~$24.00), as this shield also lets you run an UNO for a very long time on batteries, though you would have to wrangle with his code a bit to make things work.  That shield has the RTC, & SD carrier already built in, so my advice is build a jumpered UNO logger as per this tutorial, then when you get all your code & sensors working properly in tethered mode, transpose what you have learned to create a stand alone unit using the Dead Bug shield. Moving on from there: another option that really helped me at the beginning of this project is the compact TinyDuino platform, which is code compatible with all of the larger Arduino boards so you can usually use your existing programs directly. I used Tiny’s in several of my earliest loggers, and some of them were still running after more than two years.  When you are ready to graduate to other small form factor Arduinos like the pro mini, perf-boards & wire wrapping is a quick way to make solder-less prototypes that can be disassembled afterwards. Once you are really comfortable with the different Arduinos, it is even possible to use the raw Atmel processor by itself on the same breadboard as your other parts.  Strip-boards are another popular way to go from circuits on a breadboard to a deployable prototype.

platform parts

In the stand alone logger tutorials, I describe how to build a housing from 4″ PVC fittings, but those parts are all available in larger diameters so the same basic idea could be used with the larger UNO based logger, though the caps get a bit expensive at that size.

With your ‘deployment’ build ready, you can go hunting for a waterproof enclosure for your combination (here is an example using a prebuilt project box and anti vibration mount), or you could try building something more creative with pvc plumbing.  Lego blocks are not waterproof on their own, but they are made from standard ABS, so a little dab of ABS plumbing solvent around the edges lets you quickly assemble very robust internal scaffolds for your prototypes.

 


Addendum 2016-01-05:

Instrumentation & field methods students building data loggers.

After UNO based labs, the students move on to pro-mini based logger builds with many different sensor combinations. The Pro Mini is essentially just a stripped-down Uno and uses the same pin mapping. So it is generally possible to transfer UNO logger code into a Pro-mini based build with few (if any) changes to the programming.

It’s also worth noting that this UNO logger has been ‘field tested’ many times during Trish’s Instrumentation course. I am happy to report that once the solid core wires are firmly in place, the students were able to reassemble the loggers quickly at the beginning of each class by simply popping the RTC, LED & SD adapter back into place. This saved a great deal of time, and the students used the UNO’s as a code development platform while they built “stand alone” loggers for their final projects.

However there were a few bumps along the way that I would like to share with other instructors:

1) No matter how many times you tell your students to unplug the Arduino from the computer before changing wires around on the breadboard, they will forget, and start changing wires around while the whole system is live. (…making plenty of mistakes in the process) While our Arduinos survived, the USB ports they were connected to sometimes did not. I would recommend that you use a sacrificial powered usb hub between the computer and the Uno to protect the computer’s usb ports from this abuse.

2) The single most common mistake that the students made was forgetting to put the limit resistor on the LED, and a few digital I/O’s were lost from resulting high currents if student failed to notice the the led was unusually bright.  (Again, I am amazed the mcu’s survived these events without needing surgery)  With younger students, I suggest that you pre-solder a 10k limit resistor directly to the ground line of the LED’s before you hand out the parts so that there is no way to make this mistake. They will still hook the thing up wrong, and three color led’s will light up with unusual color combinations if you ground any of the 4 lines, but I don’t think we lost any digital pins that way.


Addendum 2016-03-10

Well looks like someone sent this post to Scrbd. I guess that means you can download it as a PDF from there.  Slightly annoying to see advertising over top of something that is being given away free, but more so that their page comes up higher in search results than the original. Though I guess it’s all good in the end, if it helps more people get started with their logger projects.


Addendum 2017-12-17

After you’ve built your logger you will probably want to add some sensors to it. To get some pointers on how to do that pop over to Part 2 of the UNO logger series at:  Adding Sensors to an Arduino Data Logger