Category Archives: Teacher Resources

Creating a Normalized Vegetation Index Sensor with two LEDs

Here I’m using the 2019 classroom logger to create a custom ‘Leaf Transmittance Index’ based on readings from an IR LED and the red channel of the RGB indicator already on the logger. Although using generic LED’s introduces non-optimal aspects wrt frequency & bandwidth, the trial successfully distinguished ‘healthy’ vs ‘unhealthy’ plant leaves where a simple visual inspection could not.

When we released the 2019 version of the classroom logger  we updated the starter script to include a technique that uses the indicator LED as a light sensor. This under-appreciated technique leverages the timing capability of microprocessor inputs, rather than the more common approach of using an op-amp to amplify sensor output. Reversing the potential across a diode charges it’s internal capacitance, which can then be discharged by light photons hitting the surface.  In ‘reverse bias’ mode, the photon flux is linearly related to the discharge current, however this depletion method changes the voltage across the capacitor at the same time (+ other factors), so we see a response with exponential decay instead of linear.

Typical discharge curve for an LED charged up to 5 V and then discharged to a threshold of 1.7 V under artificial lighting (fluorescent tube).    Figure 8 from: Absorbance Based Light Emitting Diode Optical Sensors and Sensing Devices pg 2462

Electrically speaking, there is little difference between an LED and a typical photo-diode sensor however an LED’s capacitance is considerably smaller. ( 25 – 60 pF ) The tiny light sensing surface area of an LED (~0.1mm squared) only generates about 50 pA of discharge current in normal ambient conditions, and the reverse leakage through LED’s is exceptionally low (~0.002 pA). The net result is that LED’s are rather slow light detectors, and this phenomenon would be nothing more than a curiosity except for one important aspect: most LEDs detect a relatively narrow band of light wavelengths, making it possible to build a frequency-selective detector without the filters (or monochromators) you’d need to do the same job with photo-diodes or LDRs.

Illustration from that same Sensors review paper, but originally from: Novel fused-LEDs devices as optical sensors for colorimetric analysis.  Talanta 2004, 63, 167–173. Their next paper: Quantitative colorimetric analysis of dye mixtures using an optical photometer based on LED array Sensors and Actuators (2006), used a series of different emitter LEDs and a low band gap IR LED as a universal light detector.

This makes a host of new LED-based instruments possible at the DIY level, and Forest Mims demonstrated this with some  elegant experiments using near-IR LEDs detecting atmospheric water vapor, aerosols with twilight photometers, and he even proved that a single red LED reading provides a reasonable proxy for total PAR. Since Mim’s pioneering work in 1977, the number of applications for LED sensors has grown so fast that now it’s hard to keep up with the ‘review papers’,  let alone the individual publications.  Bench-top chemistry is seeing a host of fluorescence & reaction cell experiments based on frequency matched LED emitter-detector pairs.  By rapidly toggling the same LED between emitting and detecting light, several projects have created other types of sensors, and one can only imagine what will happen when up-converting nanoparticles get thrown into that mix.

What can we do with our logger
using this LED measurement technique
?

Here a day of raw readings from all three LED channels are compared to an LDR in same classroom logger. The unit was deployed in a south facing window with diffusing tape over the housing surface.

Light detectors are often used to make measurements of energy balance, usually by tracking solar insulation. Using the RGB indicator LED already on the logger means we only have a limited number of light frequencies to work with, so we can’t create a ‘full spectrum’ pyranometer unless we use a more advanced solution like SparkFun’s Triad Spectroscopy Sensor . Combining that with good mounting bracket , would provide enough frequency coverage to match some commercial instruments

Figure 2.1. LED-based Sun photometer for the GLOBE project. The rectangles with the green (505nm) and red (625nm) spheres represent the LEDs.  From The Contribution of Dutch GLOBE Schools to Validation of Aerosol Measurements from Space

Despite this limitation, a few dedicated groups have proven that LED photometers can still be quite capable. Most notably the 2-LED Globe program photometers by Brooks et al. at the Institute for Earth Science Research and Education It is quite inspiring to see students using hand-made instruments to produce research good enough to publish in peer-reviewed journals. 

The Globe device uses a more traditional op-amp approach to reading the LEDs, but several aspects of those instruments are directly transferable to other light-sensing projects:

  1. LED based sensors are exceptionally stable over time.
  2. Students can manually aim the detectors at the sun, enabling a basic instrument to do the work of more complicated “sun tracking” machines.
  3. In addition to that directional control, collumnators, or shadow bands are often used to measure diffuse irradiance. Two or more measurements are needed because it’s the difference between those readings that allows you to derive the property you were actually trying to measure.
  4. This also involves correcting for scattering/absorbance by the atmosphere ( Path Length = 1/cos(θ) ) based on the suns angle in the sky (also note: many diy PAR projects hack the white plastic domes out of old photometers as cheap cosine correctors.)

All of Forest Mims LED-based experiments could be replicated with the Cave Pearl classroom logger using the capacitance discharge method instead of op-amps. But there’s a lot more information to be had from LED-sensors by anyone willing to do a little tinkering, especially in the area of vegetation monitoring.

Spectral Characteristics of Vegetation:

Note the relatively absorption-free range: 550-630nm.

Photosynthetic pigments absorb significant amounts of the red and blue light falling on healthy vegetation. Many papers focus on chlorophyll, but there are several other ‘antenna pigments’ which also absorb light to enhance photosynthetic efficiency. Approximately half of the un-absorbed visible radiation is reflected, leading to the green appearance of leaves. Reflectance is much higher at near infrared (NIR) frequencies than in the visible region due to the cellular structures inside the leaves.

Normalized Vegetation Indexes:

A friend recently sent me a link to Rick Shory’s extensive work on the greenlogger which hit the in-box around the same time as SciAm’s article: Earth Stopped Getting Greener 20 Years Ago. Reading about the global decline in vegetation set me on a deep dive into how indexes are used in bio-physical monitoring:

NDVI was developed to estimate vegetation cover from remote sensing data. It is calculated from red and NIR spectral reflectance measurements, and the first key understanding is that spectral reflectances are normalized ratios of the reflected over the incoming radiation in each spectral band. Feeding those ratios into the NDVI calculation means that it can only produces values between -1 to +1.

The second key understanding is that using the ratio of the difference of the red & infrared over their sum corrects for the effect of the solar zenith angle. This eliminates irradiance from the equation, and largely corrects for differences due to topography and transmittance loss in the atmosphere. This allows the comparison of remote sensing data from different times of day, and different latitudes.

NASA uses NDVI as a an indicator of drought, When water limits vegetation growth, it has a different relative NDVI than when the same plant is hydrated because the spongy mesophyl layer deteriorates, and the plant absorbs more of that near-infrared light rather than reflecting it. This is a significant factor for agricultural yield prediction..

Moderate NDVI values represent low density of vegetation (0.1 to 0.3), while high values indicate dense vegetation (0.6 to 0.8)  Zero indicates the water cover, and lower values of NDVI (-0.1 and below) correspond to barren areas of rock, sand, or urban/built-up.  In addition to land cover classification, people use NDVI to infer parameters like Leaf Area Index (LAI) or fractional light interception (fPAR), to  wildfire  burn-area, and other aspects of the biological environment.   But the NDVI index also has some limitations: Any time there’s very low vegetation cover (majority of the scene is bare earth), NDVI will be sensitive to that soil. On the other extreme, where there’s a large amount of vegetation, NDVI tends to saturate.

Over time NDVI has been tweaked in various ways and today there are a large number of different Broadband ‘Greenness’ Indexes that accent different aspects of plant physiology.  And the booming agricultural drone business seems to be inventing more by the day, with claims that somehow their camera tweak produces a new index that’s superior to those of it’s competitors, while their competitors make equally strident claims that company #1 doesn’t know what they are talking about. Public lab has an active community of people hacking  cameras for this kind of imagery.

Can we use the RGB LED on the Classroom logger to measure a Vegetation index?

Fig.4.24, pg49, Approximated Emission and Sensitivity Spectra (of an OSRAM LH-W5AM RGB led)  from: Using an LED as a Sensor and Visible Light Communication Device in a Smart Illumination System, Dissertation by André Filipe Rato Bispo

The first challenge is figuring out what we can actually detect, since each index works with a given set of frequencies. LEDs generally have peak detection capability 20-60nm shorter than the wavelength they emit, but this information is rarely available from the manufacturers because it’s a use case they were never designed for.  So there are not many sources that compare the emission and detection frequencies for the different LED chemistries. LEDs: Sources and Intrinsically Bandwidth-Limited Detectors (Figure 5) has a reasonable list of specific LEDs characterized as both sources and detectors, but even they didn’t bother to test a garden variety RGB.  Fortunately a few researchers working on visible light communication projects have tested them, generally finding that the blue emitter shifts into UV-A detection range, the green emitter shifts down to about 440-460 nm (so its now detecting blue…on top of chlorophyll B’s absorbtion band…), and the red LED channel shifts down to ~560-575nm, with a spectral spread 2 to 3 times wider than its emission band.

Testing to see how a 488nm dichroic mirror  (blue cut-off filter) affected readings on the Green LED detection channel. Note that in this case the round lens was also removed from the top of the LED with sandpaper to both collumnate and diffuse the incoming light. But with the PTFE tape layer added later, the sanding was unnecessary for the index measurements.

But was this true for my LED?  Since we didn’t have a “wavelength scanning monochromator” just lying around I tested the green channel with a blue-cutoff Dichroic Mirror Unlike regular filters, dichroic mirrors are intended to work only for incoming light that is normal to their surface – but given the 20 degree dispersion angle of typical 5mm led bulbs, that’s probably OK. 

Sure enough, the discharge on the ‘blue-shifted’ green channel took more than 10x longer with the filter in place, indicating that the green channel was detecting frequencies below the filters 488nm cut-off.  If the red LED channel also follows the pattern from Bipso’s paper, then red’s detection will include some green & some red, with a peak at yellow.  We might be able to use these frequencies for a BLUE vs GREEN variant of NDVI, but several sources indicating that blue indexes were sub-optimal because that chlorophyll absorption is strongly overlapped by carotene. So blue based indexes usually show less contrast between stressed versus non-stressed plants.  The loss of both the blue channel (now a UV detector) and the green channel (now a blue detector) meant that we need to add an IR led to have enough information for a viable index.

Distance sensor modules on eBay are one inexpensive source of IR LEDs.  These sensors are somewhat limited when used for their intended purpose, but a little cut & paste lets you merge the emitter LED with a daylight filter ‘cap’ cut from the photo-transistor on the same board:

IR detectors can be sensitive to visible light unless you add a daylight filter, and this little hack is much cheaper than buying a Wratten 87, 87B, or 87C. These distance modules usually have LEDs which emit at 940nm, but the same shorter wavelength-shift also applies to the IR LED, and this pulls the detection peak into the 920nm range – safely out of the absorbance well created by atmospheric water vapor. (something to keep in mind if you are actually trying to build a water vapor sensor – you probably need to select an emitter at least 25 nm above 940)

Note that the negative terminal of the IR LED is under the same screw terminal (D7) as the common cathode leg of the RGB indicator led. Columnating the LEDs with heat shrink tubing should also make them less sensitive to light reflections inside the logger. Note: our GitHub code uses a port command that assumes that shared ‘negative’ pin to be one of D3 to D7 on the pro mini. Here I’ve set #define LED_GROUND_PIN 7 as the common connection, and the positive side of the IR led is on pin D8. I disconnected the un-used blue channel of the RGB LED and set  #define BLUE_PIN 8 to force the default code to take the IR LED reading. Also note: that our code ‘lights’ the indicator LED via INPUT_PULLUP mode, instead of setting the pins to OUTPUT & HIGH, so limiting resistors are not necessary.

Even with a filter and heat shrink tubing the IR LED was easily saturated, and it took 28 layers of plumbers tape to bring readings from the IR LED into approximately the same range as the RGB readings (which had only 1 layer of diffusing PTFE tape on it)  This was done with the logger tethered a laptop, displaying readings in the serial monitor window. I simply added one layer at a time until the readings under direct full sunshine for both the IR & Red channel were in the 300 to 500 range (using our logger code from Github). Then I add some heat shrink to hold those layers of teflon tape in place, leaving only the round dome of the LED(s) exposed.

Even with IR on board, the lack of a sharp red detector means we can’t produce the traditional NDVI. (unless we add a Wratten25) With the ‘red’ LED channel actually detecting from 525 to 650 (FWHM 560-610) and peaking around 575nm we have to invent our own pseudo index that might be described as  ‘lime-green’ NDVI.  This actually isn’t so bad, as several recent papers demonstrate that green  based NDVIs are more sensitive to chlorophyll than the red based indexes, and they have stronger correlation with total leaf area.

Other Challenges:

With a tinfoil wrap, light can only enter through the 5 x 8cm exposure window above the LEDs. One layer of blank label-maker tape on the lid diffuses the light and prevents the plastic struts inside the housing from creating hot-spots. A final outer wrap of clear packing tape protects the tinfoil.

Bandgap voltages vary with temperature, changing the LED emission wavelength by ~ 0.1nm/°C.  Detection wavelengths should follow suit, so it’s probably best to make sure the temperature varies as little as possible between our scale points and the target readings.  Since the LED detectors are inside a Plano box, there is potential for some frequencies to be lost, but materials like high density polyethylene (HDPE)  have remarkably smooth absorption curves that don’t become extreme until you reach UV. The fact that Vi’s are ‘a ratio of ratios’ means that we have to compare the raw sensor readings to direct insulation values before the index can be calculated. Housing losses should affect the high reference and the target readings in the same way, so it should not throw off the final index – essentially we treat it like transmittance loss in the atmosphere.

Since we can’t know the responsivity of our garden variety LEDs without lab testing, the best we can do is standardize the data by scaling it against a “maximum” reading (when the sun is shining directly on the top of the logger) and a second “minimum” point for each channel (obtained by covering the entire logger with tinfoil).  The dark point reading also address thermal leakage through the LEDs.  One drawback of this mcu-based method is that the raw discharge-time readings follow an exponential decay curve, so we need to take the log of those readings to linearize the data before scaling, and since our decay-time readings are inversely related to the photon flux, we need to apply  1/LN(reading)  to all data before the max/min scaling. Technically speaking, photon flux is not the same as irradiance, but the the index’s normalization sweeps that little issue under the rug too.

Using the sun as our high scale point necessitates that the readings are done under a clear blue sky. Clouds passing overhead between readings (or other haze / humidity variations) could change the ratio of IR to visible light more than the plants you are trying to monitor:

Rain is another potential complication, as water strongly absorbs IR.  So the readings have to be taken long enough after a rainfall that no water droplets are present on the surfaces. So with the basic 2x LED configuration I’m using here, you have to wait for good weather, and take the readings under a clear blue sky, between mid morning & mid afternoon.

Cloud induced variations could be compensated by putting two sets of sensors on the logger (one pointing up  &  one pointing down) for simultaneous correction of direct insolation vs surface reflectance, but for now this is just a prototype trial to see if a decent ‘lab exercise’ can be developed for the Cave Pearl Loggers with minimal additions to the basic build.

Does it work?

Backyard trial testing the reflectivity of my lawn in an area deliberately chosen as “unhealthy” grass .

With all the rough assumptions up to this point I was surprised to find the reflectance readings falling within the broad range of ‘textbook’ values. A reading 1m above a relatively healthy section of my lawn produced an index of 0.39 while a reading above a mangy half-dead section (photo: right) produced a much lower index value around 0.215   A patch of bare dirt read at 0.044, and my gravel driveway produced an index of -0.13   The front flower garden produced a reading of 0.292  It’s hard to know how representative this is given the wide range of values listed for different plant species in the various spectral libraries.

With the challenges of species variation & water condition, the use of verified bright & dark targets is pretty common in biophysical sensing. White panels coated with barium sulfate paint, Komatex, or Teflon are sometimes used because they have reflectance near 100% with very little specular artifact. NASA’s Aster Spectral Library suggests that most flat black paints have a similar response through visible and NIR, so some Rustoleum on a big sheet of cardboard might work as a 4% calibration point.

A better idea for the classroom:

Covering large areas with a grid of these single-shot readings would take a substantial amount of time, and even relatively short trials run into issues with trees and other large shadows creeping into the test patches throughout the day. So logging reflectance is more suited to long-term measurements of vegetation cover at single location. (or forest canopy transmittance)

After a bit more reading,  I began to notice a pattern:

(click to enlarge) Leaves cover the input window, secured to prevent wind shifting.

So index calculations ought to work with light that is transmitted through the leaves because the two curves contain very similar information. With the standard reflectance-based NDVI, ratings between 0 and 0.33 indicate unhealthy or stressed plants, 0.33 to 0.66 is moderately healthy, and 0.66 to 1 is very healthy. Flipping the calculation to a transmission-based version will shift those values significantly, but we can still use that trend as a rough guide to whether the method is working.

As luck would have it, this insight occurred just before another fieldwork trip, so it was more than a week before I could test the idea. The first trials used leaves from tropical almond trees which are dry-season deciduous. Re-capturing some of their ‘energetically expensive’ chlorophyll turns the leaves pinkish-red or yellow-brown due to the leftover pigments such as violaxanthin, lutein, and zeaxanthin. These Xanthophylls are yellow pigments from one of the two major divisions of the carotenoid group (the other division is formed by the carotenes). They act to modulate light energy and may also serve as a non-photochemical quenching agents to deal with excited states of chlorophyll that are overproduced during photosynthesis under the intense light conditions.

Leaf Number Red RGB channel: scaled
% of full sun reading
IR LED reading: scaled
% of full-sun reading
(gYr) “Transmission
based” NDVI
#1 (green) 37.24 82.81 0.380
#2 (orange) 59.47 83.13 0.166
#3 (red) 42.22 80.95 0.314
#4 (yellow) 67.62 82.91 0.102

All leaves were ‘fresh-picked’ from the tree, and the percent transmission numbers were averaged from five readings taken one minute apart. Natural light is notoriously variable, so most index sensors use considerably more sample averaging than that.

It’s not surprising that the yellow leaf was well discriminated, but the fact that the green & red leaves produced similar values highlights an issue with our rough prototype: the widened spectral spread of the red LED channel makes it difficult to distinguish between light frequencies on either side of the response curve.

Leaf (click to enlarge)  Red RGB channel: scaled
% of full sun reading
IR LED reading: scaled
% of full-sun read
(gYr) T-NDVI
#10 (Dead on ground) 26.96 65.38 0.416
#11 (yellow patch) 44.90 79.45 0.278
#12 (green & healthy) 34.27 76.17 0.379
#13 (>50% yellow) 55.56 77.79 0.167

Despite the limited red/green selectivity, this set shows that, at least for ‘fresh’ leaves, our custom index can still discriminate the loss of the chlorophyll. The dead leaf suggests that will only work up to a point. Dead vegetation reflects a greater amount of energy than healthy vegetation throughout the visible spectrum but reflects less IR, so any actual ‘dead-spots’ will raise a transmission-based index value. This is a limitation for our method – which does not produce a natural separation between healthy and dead vegetation like a reflectance based index would. This would be serious problem for remote sensing applications, but when a leaf that you can hold in your hand is that badly off, you probably don’t need a sensor to tell you the plant is not thriving.

Does this transfer to other plant species?

Leaf (click to enlarge)  Red RGB channel:
scaled % of full sun
IR LED reading: scaled
% of full-sun read
(gYr) T-NDVI
#14 (Green leaf – from
stressed plant1)
39.29 77.51 0.327
#15 (Brown spots – from stressed plant1) 37.71 76.23 0.338
#16 (Green leaf from
healthy plant2)
21.83 68.05 0.514
#18 (>50% yellow – other stressed plant3) 32.65 65.47 0.334

As expected, the overall light transmission numbers were different for palm than they were for the tropical almond leaves. So a calibration set would need to be created for each plant species to put these numbers into context. I’m assuming the green/yellow discrimination is due to chlorophyll levels in the almond leaves, but there could be other confounding factors like Anthocyanin in the hardier palm leaves. (Antho. also absorbs in our sensor band, and is abundant in senescing leaves) 

While #14 and #15 look different they were taken from same plant, and the yellow-brown spots on #15 make it clear the plant was under some kind of stress.  Visually, I would not have been able to distinguish leaf #14 from #16 but the index identified #14 as being from an “unhealthy” plant.  Given the relatively wide spectrum we are working with here, this is a remarkable result – suggesting that with a bit of homework to find LED’s with tighter detection bands, we could produce an inexpensive chlorophyll meter (like the SPAD?) or we could tune the idea for other pigments/applications. Using a white LED emitter above the leaf could enable a variant of our simple approach that was not dependent on the sun, and adding couple of reads using only green & red emitters above the leaf would enable us to distinguish which side of that wide detection curve we were on. Commercial chlorophyll meters sometimes use emitters at 660 nm & 940 nm , measuring both reflectance AND transmission so an accurate absorbance value can be calculated. Even then plants cease to create chlorophyll once a certain threshold has been reached, so these meters are often used to detect deficiencies (by comparison to a well fertilized control group) rather than concentrations.

And finally, a classroom lab could combine this kind of index-based characterization with paper chromatography to verify the pigments in the leaves via their Rf factors. A more advanced approach would do this quantitatively, turning this index into a true diagnostic tool. This could also be a good accompaniment to the many other Arduino based plant monitoring projects, as a growth or health verification stage. In northern climates this could even be done with house plants by taking readings ‘before’ and ‘after’ some experimental intervention. With those large temporal separations, you would want to take new max/min readings each time for the scaling & avoid using artificial light sources as these  introduce frequency artifacts that could interfere with the index.

Easy 1-hour Pro Mini Classroom Datalogger [Feb 2019]

Dupont jumper variant of the “fully soldered’ Classroom Data Logger from the Cave Pearl project: This version uses dupont jumpers to reduce assembly time to about 1 hour

(Last Updated: Oct 2019)

It’s only been a couple of weeks since the release of the 2019 EDU logger, and we’re already getting feedback saying all the soldering that we added to that tutorial creates a resource bottleneck which could prevent some instructors from using it:

“Our classroom has just two soldering stations, and the only reason there are two is I donated my old one from home. So we simply don’t have the equipment to build the logger you described. And even if we did, some of my students have physical / visual challenges that prevent them from working with a soldering iron safely…”

Or goal with that design was to give students their first opportunity to practice soldering skills that are highly useful when doing field research. However helping people do science on a budget is also important – so that feedback sent us back to the drawing board.  After a little head scratching we came up with a new version that combines the Dupont jumper approach we used in 2016, with this flat-box layout. In the following video, I assemble one of these ‘minimum builds’ in about one hour.  To put that in perspective, the fully soldered version takes 2 – 2.5 hours for someone with experience.

Note: After you’ve seen the video to get a sense of where you are headed, it’s usually much better to work from the photos (below) when assembling your logger. Youtube videos make it look easier than it actually is when you are just starting out. So the first one you build could take several hours as you figure out what you are doing, the second will take half as long, and the third one you make usually takes less than two hours.

This variation of the basic 3-component logger is optimized for quick assembly, so the soldering has been reduced to adding header pins and bridging the A4/A5 I2C bus to the outer terminals.  An instructor could easily do that ahead of time with about 15 minutes of prep per unit, leaving only the solder-less steps for their students. After the header pins are in place, connections to the central Pro Mini are made by simply twisting stripped wire ends together and clamping them under screw terminals.

You must use Lithium AA batteries with a 2-cell unregulated supply because the steep slope of an ‘alkaline’ battery discharge would bring the system  below the SDcard’s minimum of 2.7v quickly. While the voltage of a ‘brand new’ Lithium AA is usually 1.8v/cell, that upper plateau provides a sleeping logger voltage of ~1.715 v/cell once the batteries settle, and that briefly dips to about 1.625v/cell under load during data saves. At low temps of about 5°C (in my refrigerator) those SD card voltage dips go down to about 1.525 v/cell. Unloaded readings of 1.5v on a Li AA = battery is dead.

This time reduction involves a few trade-offs, and bringing the I2C bus over to A2 & A3 leaves only two analog ports readily accessible ( although A6 & A7 are still available if you add some jumpers). Removing the regulator & battery voltage divider adds ~30% more operating life, but it also forces you to deal with a changing rail voltage as the Lithium AA batteries wear down. The daily variation is usually quite small, but for quantitative comparisons on monthly scales you will need to correct for the change in rail voltage over time if your sensor circuits are not ratio-metric. To do this voltage compensation multiply your raw sensor readings by the the ratio of (3300mv) / (current rail voltage).  Here 3300mv is just an arbitrary comparison point, which you could replace with any rail voltage reading from the data saved by your logger. Batteries have a lot of mass, so thermal lag in battery voltage can also cause hysteresis for analog temperature sensors unless you read the reference under the same conditions.

 (NOTE: complete parts list with supplier links are located at the end of this post)

Pro Mini Prep:

Solder the 6 UART pins & test board with the blink sketch:  To upload sketches select (1) TOOLS> Board: Arduino Pro or Pro Mini  (2)TOOLS>ATmega328(3.3v, 8mhz) in addition to the (3)TOOLS> COM port

Remove the power LED [in red]. Removing the pin13 LED [yellow square above] is optional. Leaving the pin13 LED in place lets you know when data is being saved to the SD card because the SPI bus SClocK signal flashes the LED.

Remove the voltage regulator with snips. Your system voltage will vary over time, but our starter script records that rail voltage without a voltage divider.

Add pin headers to the sides & Serial input end of the Pro Mini.

Bridge the two I2C bus connections for side access with the leg of a resistor. Connect A4->A2 & A5->A3.

Adding DIDR0 = 0x0F; in Setup disables digital I/O on pins A0-A3 so they don’t interfere with I2C bus coms.

NOTE: The Screw Terminal board we use in this build was designed for the 5v Arduino NANO, so the shield labels don’t match the actual 3.3v Pro Mini pins on the ‘analog’ side. (the digital side does match) To avoid confusion may want to tape over those incorrect labels and hand write new labels to match the pattern above. Wire connections in this tutorial will be specified by ProMini pin labels:  D10-13 are used for the SD card, A4=A2 is the I2C Data line, and A5=A3 is the I2C clock line, A0 & A1 are not used.

Technically speaking, bridging the I2C bus (A4=data & A5=clock) over to A2 & A3 subjects those lines to the pin capacitance and input leakage of those analog pins (regardless of whether that channel is selected as input for the ADC p257). But in practice, the 4K7 pull-up resistors on the RTC module can easily handle that at the 100 kHz default bus speed. To prevent digital I/O on A2 & A3 from interfering with the I2C bus, add bitSet (DIDR0, ADC2D); bitSet (DIDR0, ADC3D); to setup in your code.

Also note: On the UART adapter in the picture above, the USB to TTL adapter pins are in the reverse order to the Pro Mini board. This is a fairly common issue with clones and if the blink sketch never uploads flip the adapter around and try again. I have connected 3.3v ProMinis to UART modules the wrong way round many, many times, and not one of them has been harmed by the temporary reversal.

Screw-Terminal Component Stack:

Add 3 layers of double sided tape so the tape is thicker than the solder pins.

Align RX&TX corner pins before inserting. The GND points on the screw terminal board may be interconnected (via the back-plane) & must match the ProMini’s GND pins.

Gently rock the Pro Mini back to front (holding the two short sides) until the pins are fully inserted. Some ST shields have mis-aligned headers so this insertion can be tricky.

Remove the last three ‘unused’ pin headers to make room for the SD adapter

Note: Screw-terminal board labels do not match the ProMini pins on the ‘analog’ side

Remove bottom 3 resistors from the adapter – leave the top one in place!

Separate Dupont Cable wires & click them into a 6-pin shroud.

Cable Color Pattern:     Black =GND,   Purple=MISO,   Brown=CLocK,   Orange=MOSI,   Grey=CSelect,      and   Red=3v3

 

 

 

Use foam tape to attach SD module to the Screw Terminal board. Metal tabs should be visible on top surface.

Measure, cut & strip the 4 SPI bus wires (NOTE the ‘Nano’ ST board labels say A0-A3 which does not match the D10-13 Pro Mini pins on this side of the board)

Grey (CS) to ProMini D10Orange (MOSI) -> pm D11,      Purple (MISO) ->pm D12,        Brown (CLK) -> pm D13    

 

 

Add three jumper wires to the red power line from the SD module, one with a male end pin. I often add Dupont ends with a crimping tool, rather than using a pre-made jumper.

Strip & twist the 4 red power wires together & add heat-shrink for strain relief. Bundling wires like this is easier if you make the stripped area a bit longer.

A short red jumper goes to RAW(pm)=VIN(st) to recruit the orphan capacitor.

Long red jumper bridges power to ‘unused’ screws on other side of the Terminal board, and the wire with the Dupont male end will go to the breadboard.

Add 2 extra wires to the black GND wire from the SD module (1 with a male Dupont end ). Jumper one black wire across the Promini to an unused terminal beside the red power wire.

The GND bundle completes Pro Mini / ST board / SD module stack. The ‘pinned’ Red & Black ‘pinned’ jumpers shown here are about 1 inch too short to reach the breadboard easily… make yours longer.

Note: You could connect the battery holder lead wires directly into the multi-wire Vcc & GND bundles: skipping the 2 jumpers crossing over to the other side of the ST shield.  But adding those jumpers provide extra Vcc/GND connection points & the ability to easily replace the battery holder later if you have a battery leak.

I always try to make my Dupont connectors so that the metal & plastic retainer clips are accessible (in this case facing upwards) after the logger is assembled. That way you can diagnose bad wire connection with the tip of a meter probe, and if necessary, pull out & replace a single bad wire in the Dupont connector without taking everything apart.

RTC module:

Remove two SMD resistors from the RTC board with the tip of your soldering iron.

The DS3231 modules often have flux residue – clean this off with 90% isopropyl

 

Cable: Blk(gnd), Red(vcc), White(sda), Yellow(scl), Blue(sqw).  Shroud retainer clips face up & there is no wire on 32K output.

First tape layer

Next two tape layers

OPTIONAL: the pass-through port on the RTC is another access point for the I2C bus (note: add male headers on the ‘battery holder side’ for this build)

Optional added step: After removing the two SMD resistors on the module, you can clip the Vcc leg on the RTC chip which forces the clock to run entirely from the backup coin-cell battery. This reduces the loggers overall power use by 0.09mA bringing a “no-reg & noRTCvcc” build below 0.1mA while the logger sleeps between sensor readings. But the risk is that if you bump the RTC backup battery loose, that disconnection resets the clock time to Jan 1st, 2000. (note: while the time stamps will be wrong after that reset, the logger will keep running)   A couple of pieces of soft 1.6mm heat shrink tubing under the spring makes the negative coin-cell connection stronger, an a touch of hot melt glue will secure the battery on the top edges.  A CR2032 can power the RTC about four years but you have to set bit six of the DS3231_CONTROL_REG to 1 to enable alarms when running from the coin-cell. (our starter code does this by default) This modification also disables the 32.768 kHz output.  Visit our RTC page for more detailed information on this clock module.

Final Assembly:
(Note: references here are to pin numbers/labels on the ProMini which do not match ST board labels on the analog side)

Attach the Pro Mini stack & RTC to housing with the double-sided tape.

Trim white & yellow I2C wires from the RTC & add 1 extra wire with dupont ends for each I2C line to bring the bus over to the breadboard

Attach yellow SCL line from the RTC beside the red 3v rail (ie to A3=A5 on the ProMini) then the white SDA line from the RTC to A2=A4.

The four extra jumper wires with male Dupont ends on Vcc, GND, & both I2C lines. These get patched over to the breadboard so you can add I2C sensors.

Each wire must be plugged into its own separate row on the breadboard. Add a 2nd layer of foam tape to the bottom of the bread-board before attaching.

The RTC power line joins that short red jumper on RAW(pm)=VIN(st) at the end of the screw-terminal board.

Some of the box bottoms have slight bowing. If any component doesn’t stick well enough: add another layer of foam tape.

Attach the RTC’s black ground wire to GND & the blue SQW alarm line to ProMini pin D2

Attach 2xAA battery holder with 2 layers of foam tape. Trim wires to length. Use black 30lb Mounting Tape for extra strength.

Battery wires join the black & red jumpers from other side of the terminal board. All six of the ‘unused’ screw terminals we clipped earlier can be used to make secure ‘dry wire’ connections in this way.

Connections complete except the indicator. 5050 LED modules often come with pre-installed limit resistors which make them safer for the classroom. But you can use a raw 5mm LED if you only light the LED  with the INPUT_PULLUP command.

A ‘common cathode’ RGB LED module on pins  Red=D6, Green=D5,   Blue=D4, &  GND=D3.

Your Logger is ready for testing!

(Note: Most of the time the tests listed below go well, however if you run into trouble at any point read through the steps suggested for Diagnosing Connection Problems at the end of this page.)

Install the Arduino IDE into whatever default directory it wants to be in – we’ve had several issues where students tried to install the IDE into some other custom sub-directory, and then code will not verify without errors because it doesn’t know where to look for libraries. If you have not already done so, there are three things you need to set under the IDE>TOOLS menu to enable communication with the logger:

Note: that the “COM’ setting will be different for each computer, so you will have to look for the one that appears on your system AFTER you plug in the UART module.

The one that’s easy to forget is choosing the 328P 3.3v 8Mhz clock speed. If you leave the 328p 5v 16mhz (default), the programs will upload OK, but any output to the serial monitor will be garbled by the clock speed mismatch.  Also be sure to disconnect battery power (by removing one of the AA batteries) whenever you connect your logger to a computer.

1. Test the LED – Edit the default blink sketch, adding commands in setup which set the digital pin 3 connected to the ground line of the LED to “OUTPUT” and “LOW”
      pinMode(3, OUTPUT);   digitalWrite(3, LOW); 
Since we removed the ‘default’ indicator led on the Pro Mini board, you will also need to change LED_BUILTIN variable in the blink code example to one of the pins connected to a color channel on your led module. (in this example change LED_BUILTIN to either 4, 5, or 6)

2. Scan the I2C bus with the scanner from the Arduino playgound. The RTC module has a 4K eeprom at address 0x56 (or 57) and the DS3231 RTC should show up at address 0x68.

The address of the eeprom can be changed via solder pads on the board, so sometimes it moves around. If you don’t see at least these two devices listed in the serial monitor when you run the scan, there is something wrong with your RTC module or the way it’s connected: It’s very common for a beginner to get at least one set of wire connections switched around during the assembly. With the screw terminals this takes only a few moments to fix. Also have a spare RTC module on hand in case you get a defective module…which is fairly common.

NOTE: Some sensors really need the stability provided by the on-board voltage regulator. Here is an alternative arrangement of parts for the classroom logger that leaves the 3.3v regulator in place on the ProMini and powers the logger from 4xAAA batteries (NOTE: regulated builds also leave out the short red jumper that was used to recruit the orphan capacitor on the raw vin line.  The RTC & added sensors now get connected ONLY to the Pro-Mini’s regulated 3.3v rail instead of the battery input line)   We’ve designed the Cave Pearl Logger for maximum flexibility, so you can change components and positions like this to suit the needs of your experiment.

3. Set the RTC time, and check that the time was set – The easiest method would be to use the SetTime / Gettime scripts from our Github repository, but first you need to download & install this RTC control library  The SetTime script, automatically updates the RTC to the time the code was compiled (just before uploading) so you only run SetTime once, and then immediately upload the GetTime sketch to get the SetTime code out of memory. Otherwise it will reset the RTC to to that first ‘compiler time’ point every time the Arduino starts (and the Arduino restarts EVERY TIME you open the serial window…) 

There are dozens of other good Arduino libraries you could use to control the DS3231, and there is also a script over at TronixLabs.com that lets you set the clock without installing a library. [ in 24-hour time, & year with two digits eg: setDS3231time(30,42,21,4,26,11,14);  ] The trick with Tronix’s “manual” method is to change the parameters in the line: setDS3231time(second, minute, hour, dayOfWeek, dayOfMonth, month, year);  to about 2-3 minutes in the future, and then upload that code until about 20 seconds before your computers clock reaches that time (this compensates for delay caused by the compilers processing & upload time). Open the serial window immediately after the upload finishes, and when you see the time being displayed, and when you’ve checked that it’s not too far off, upload the examples>blink sketch to remove the clock setting program from memory.

4. Check the SD card is working with CardinfoChanging chipSelect = 4; in that code to chipSelect = 10;  Note that this logger requires the SD card to be formatted as fat16, so most 4GB or larger High Density cards will not work. Most loggers only generate 5 Kb of CSV format data per year when they are running, so you don’t need a really big SD card. In fact older smaller SD cards actually use less power.

Zip-Tie Mounting Bases are an easy way to add attachment points inside your logger to secure sensor cables, or desiccant packs. These adhesive cable tie mounts come in many varieties, and cost about 10¢ each at most hardware stores.

5. Optional: If you are running with no regulator AND using analog sensors: Calibrate your internal voltage reference with CalVref from OpenEnergyMonitor.

This logger uses an advanced code trick to read the positive rail voltage to ~11mv resolution by comparing it to the internal 1.1v reference inside the processor. That internal ref. can vary by ±10% from one chip to another, and CalVref gives you a constant which will make the rail/battery voltage calculation more accurate. Load CalVref while the logger is running from USB power and then measure the voltage between GND & the positive rail with a good quality voltmeter. Then type that voltage into the serial monitor window entry line & hit enter. Write down the voltage & reference constant which is then output to the serial monitor window. I usually write these ‘chip-specific’ numbers inside the logger with a black sharpie. You will need to add that info to the core data logger code later by changing the line #define InternalReferenceConstant 1126400L to match the long number output from CalVref.

This calibration brings the starter script’s battery readings within ±15mv of actual but you can skip this procedure if you are only using digital sensors as that the code will still produce reasonably good battery readings with the default 1126400L value. Increasing the rail reading accuracy is only important when you are using ANALOG sensors (which use that rail voltage as the ADC reference voltage) but it has little effect on the logger operation.

6. Find a script to run your on logger. For test runs on a USB tether, the simplest bare-bones logger code is probably Tom Igoe’s 1-pager at the Arduino playground. It’s not really deploy-able because it never sleeps the processor, but it is still useful for teaching exercises and testing your sensors after you set chipSelect = 10;  In 2016 we posted an extended version of Tom’s code for UNO based loggers that included sleeping the logger with RTC wakeup alarms. Our latest logging “Starter Script” has grown in complexity to ~750 lines, but it should still be understandable once you have a few basic Arduino programming concepts under your belt.

After 60 seconds of kneading you have ~ 60 seconds to work the putty into place. (it will be rock-hard within ~5-10 minutes). Be sure to leave yourself enough extra wire/space inside the housing so that you can open and close the lid easily without disconnecting anything after the putty hardens. This seal is not strong enough for underwater deployments, but it should easily withstand exposure to rain-storm events. This putty is also a quick way to make custom mounting brackets, or even threaded fittings if you wrap it around a bolt (which you carefully remove before the putty hardens completely)

In the previous tutorial we attached external sensors with a cable gland passing through the housing and epoxying them into a pvc cap. But for a simpler classroom project you could simply drill small a hole through the lid and stick the sensor/module on top of the housing, seal the hole with double-sided tape. Thicker pass-through wires can be sealed reasonably well with plumbers epoxy putty from the hardware store. This putty is non-conductive, and adheres quite well to both metal & plastic surfaces. 

Remember that breadboard connections are very easy to bump loose, so once you have your prototype circuits  working, its usually best to re-connect the sensors directly to the screw terminals before deploying a logger where it could get knocked about. In a pinch you can secure breadboard pins with a ‘tiny’ drop of hot glue to keep them from wiggling around.

 

Using the logger for experiments:

Logger mounted on a south-facing window and held in place with double sided tape. Here the top surface of the housing was covered with two layers of white label-maker tape to act as a light diffuser. PTFE is another excellent light diffusing material available in different sheet thicknesses. The ‘divot’ on the lid of the Plano box is just a bit larger than 55mm x 130mm x 3mm (depth). The “teflon” tape that plumbers use to seal threaded joints can also be used in a pinch. PTFE introduces fewer absorbance artifacts than other diy diffusers like ping-pong balls, or hot melt glue.

Many types of sensors can be added to this logger and the RTC has a built-in temperature register which automatically gets saved with our starter script. The transparent enclosure makes it easy to do light-based experiments. Grounding the indicator LED through a digital pin allows it to be used as both a status light, and as a light sensor.   The human eye is maximally sensitive to green light so readings made with that LED channel approximate a persons impression of overall light levels.  Photosynthesis depends on blue and red light, so measurements using LED’s that detect those two colors can be combined for readings that compare well to the photosynthetically active radiation measurements made with “professional grade” sensors. In fact Forest Mimms (the man who discovered the light sensing capability of LEDs in the first place) has shown the readings from red LED’s alone can be used as a reasonable proxy for total PAR.  Photoperiod measurements have important implications for plant productivity, as do  measurements of transmittance through the plant canopy. Chlorophyll fluorescence is another potential application, and the response of plants to UV is fascinating.

The original code for using LEDs as sensors is from the Arduino playground. This polarity reversal technique does not require the op-amps that people typically use to amplify the light sensing response but it does rely on the very tiny parasitic capacitance inside the LED. (~50-300pF) This means that the technique works better when the LED is connected directly to the logger input pins rather that through the protoboard (because breadboards add random capacitance) . We have integrated this into the starter script which you can download from GITHUB. I’ve tweaked the playground version with port commands so the loop execution takes about 100 clock cycles instead of the default of about 400 clock cycles.  The faster version was used to generate this light exposure graph with a generic 5mm RGB LED, with a 4k7Ω limiter on the common ground which was connected to pin D3:

Red, Green & Blue channel readings from the indicator LED in the logger photo above.  The yellow line is from an LDR sensor the same unit, that was over-sampled to 16-bit resolution. The LED sensor has a logarithmic response and the left axis on the graph is a time- based measurement where more light hitting the LED sensor results in a lower number. Note how the RED signal changes more quickly than Blue & Green at sunrise & sunset.  LED’s work well with natural full-spectrum light, but their limited frequency sensing bands can give you trouble with the spectral distribution of  indoor light sources. The peak spectral response of LED’s is usually around 30–50nm lower than their peak emission wavelength So the blue channel is actually recording in the near-UV range, the Green channel is responding at ~ 420nm (blue) and the red channel is actually responding to a wide band of yellow-green light. 

Characterizing light absorption and re-emission is also a primary technique in climate science . For example, measuring light intensity just after sunset with LEDs inside a heat-shrink tube pointed straight up can provide a measure of suspended particles in the stratosphere. An “ultra bright” LED has more than enough sensitivity to make these collumnated readings, in fact on bright sunny days you usually have to place the LED/sensor beneath a fair thickness of white diffusing material (like PTFE tape) to prevent it from being completely saturated.  Older LEDs that emit less light can sometimes be easier to work with because they are less sensitive, so the discharge time does not go to zero in high-light situations. Other sensor experiments are possible with LED’s in the IR spectrum which can be used to detect total atmospheric water vapor. A light transmission-based variant of the NDVI ratio can be used to determine plant health after adding an IR LED to the classroom logger.

One thing to watch out for is that full sun exposure can cook your entire logger: reaching temps above 80°C can cause batteries to leak or fry the SD card. If you have to leave the logger in full sun, consider adding a bit of reflective film or a layer of aluminum foil around the outside to protect the electronics. Though if use a light sensor you’ll need to leave a little un-covered window for it to take a reading. 

You might also find it handy to add a few holes as tie-down points,

and it’s always a good idea to add desiccant packs inside the box to prevent condensation. If you use a desiccant with color indicator beads, you can check whether they are still good simply by looking through the transparent housing.

If you clipped the RTC leg, your logger should pull less than 0.1mA while sleeping. Back of the envelope for Lithium AA’s is about 7 million milliamp-seconds of power, with your logger burning about 8600 mAs/day at 0.1mA.  So clipping the voltage regulator and adding the RTC mod should get you out to about a year before you fall off the “upper plateau” of the lithium cell’s burn-down curve, and out to two years if your sensors don’t use much juice (…and you have a well behaved SD card).  With the RTC power leg still attached you’ll see sleep currents in the 0.16mA range, so at least 6 months of operation before you come close to triggering the low voltage shutdown embedded in the code. I’m being conservative here because it all depends on your sensors and other additions you make to the base configuration.

While the LED sensor idea is fun to work with, it’s a very slow method that keeps the logger running for many seconds per reading when light levels are low ->so reading all three color channels will probably cut your operating life in half again. Figuring out how to only take those light readings during the day is a good coding exercise for students that saves quite a bit of power. The RTC’s temperature record is pretty crude, so we’ve also added support for the DS18b20 temperature sensor in the base code. If you have a genuine DS18b , these venerable old sensors draw virtually no power between readings.


TransparentSinglePixl
Bill of Materials: $20.50
Plano 3440-10 Waterproof Stowaway Box
Sometimes cheaper at Amazon as an “add-on” item.  $4.96 at Walmart and there are a selection of larger size boxes in the series. 6″ Husky storage bins are an alternate option.
$5.00
Pro Mini Style clone 3.3v 8mHz
Get the ones with A6 & A7 broken out at the back edge of the board.
$2.20
‘Pre-assembled’ Nano V1.O Screw Terminal Expansion Board
by Deek Robot, Keyes, & Gravitech (CHECK: some of them have the GND terminals interconnected)  You will also need to have a few small flat head screw drivers to tighten those terminals down.  Since this shield is was originally designed for an Arduino Nano many of the labels on ST board will not agree with the pins on the ‘analog side’ of the ProMini.
$1.85
DS3231 IIC RTC with 4K AT24C32 EEprom (zs-042)
Some ship with CR2032 batteries already installed.  These will pop if you don’t disable the charging circuit!  
$1.25
CR2032 lithium battery  $0.40
SPI Mini SD card Module for Arduino AVR
Buy the ones with four ‘separate’ pull-up resistors so that you can remove three of them.
$0.50
Sandisk or Nokia Micro SD card 256mb-512mb 
 Test used cards from eBay before putting them in service. Older Nokia 256 & 512mb cards have lower write currents in the 50-75mA range. This is less than half the current draw on most cards 1gb or larger.
$2.00
Small White 170 Tie-Points Prototype Breadboard
These mini breadboards for inside the logger are also available in other colors.
$0.60
Dupont 2.54mm F2F 40wire ribbon cable Without Housing
Cheaper if you get the ones with the black plastic shrouds on the ends, but removing those shrouds by hand is slow  work. Each $2.70 cable will let you make 2 loggers, and you”l need a couple of  6-pin connector shrouds.
$1.55
3×1.5V AA Battery Batteries Holder w Wire Leads
If you are using alkaline  batteries, changing to a 4xAA battery holder doubles the run time.
If you are running an unregulated system on 2 lithium batteries, then you can use a 2x AA battery holder.
$0.50
5050 LED module (with built-in limit resistors) 
(Alternatively, you can also use cheaper 5mm diffused LEDs with a  4K7 limit resistor on the GND line that you add yourself)  
$0.75
3.3V 5V FT232 Module
  *Be sure to set the UART module to 3.3v before using it!* and you will also need a USB 2.0 A Male to Mini B cable. You may need to install drivers from the FTDI website.
$2.75
3M Dside Mounting Tape, 22awg silicone wireheader pins, etc… $1.00
Comment:   You might need some extra tools to get started:                (not included in the total above)
2in1 862D+ Soldering Iron & Hot Air station Combination
a combination unit which you can sometimes find as low as $40 on eBay.
Or you can get the Yihua 936 soldering iron alone for about $25. While the Yihua is a so-so iron, replacement handles and soldering tips cost very little, and that’s very important in a classroom situation where you can count on replacing 1-2 tips per student, per course, because they let them run hot & dry till they oxidize and won’t hold solder any more.  Smaller hand-held heat guns are also available for ~$15.
$50.00
SYB-46 270 breadboards (used ONLY for soldering pins on Pro-Mini )
Soldering the header pins on the pro-mini is MUCH easier if you use a scrap breadboard to hold everything in place while you work. I use white plastic breadboards  that they only have one power rail on the side since they do not look like my regular breadboards &  I write ‘for soldering only’ on them with a black sharpie.  
$1.30
SN-01BM Crimp Plier Tool 2.0mm 2.54mm 28-20 AWG Crimper Dupont JST
I use my crimping pliers almost as often as my soldering iron –  usually to add male pins to components with lead wires too thin for safe connection on a breadboard. But making good crimp ends takes some practice.   Jumper wires that you make yourself are always better quality than the premade ones.
$16.00
Micro SD TF Flash Memory Card Reader
Get several, as these things are lost easily. My preferred model at the moment is the SanDisk MobileMate SD+ SDDR-103 or 104 which can usually be found on the ‘bay for ~$6.
$1.00
Donation to Arduino.cc
If you don’t use a ‘real’ Pro Mini from Sparkfun to build your logger, you should at least consider sending a buck or two back to the mother-ship to keep the open source hardware movement going…so more cool stuff like this can happen!
$1.00

.. and the required lithium AA batteries are also somewhat expensive, so a realistic estimate is about $25 for each logger before you add sensors.


Addendum: Diagnosing Connection Problems

Once you’ve run the blink sketch, you know the Promini part of the logger is working, so other issues during the testing stage are due to incomplete connections from the outside to the Promini I/O ports.

This is the connection pattern inside the white breadboard. Take care that you don’t connect the breadboard jumper wires together by accidentally plugging them in to the same row or – the I2C bus will stop working.

For example, if you see only “Scanning I2C….. ” but nothing else appears when running the bus scanner, then it means that the ProMini can not establish communication with the RTC module. The most common cause of this problem is that the white & yellow wires were switched around at one end. It’s also easy to not quite remove enough insulation from the wires to provide a good electrical connection under the screw terminals, so undo those connection and check that the wires were stripped, cleaned & wrapped together ‘cleanly’ before being put under the  terminals. Those screws need to be clamped down relatively tight on the thin Dupont wires and if you are not careful, you might have accidentally cut away some of the thin copper wires inside the Dupont cable when you did the insulation stripping.

Scanner lockup can also happen if one of the I2C devices on the bus is simply not working: usually about 1 in 10 logger builds ends up with some bad component that you have to identify by process of elimination. (These are 99¢ parts from eBay…right?) It only takes a moment to swap in a new RTC board via the black Dupont connector and re-run the scan. If the replacement RTC also does not show up with the I2C scanner then it’s likely that one of the four bus lines does not have a complete connection between the ProMini & the RTC module.

On this unit I measured 1 ohm of resistance on the I2C clock line between the ProMini A5 pin and SCL header pin on the RTC module. So this electrical connection path is good.

To diagnose this: set a multi-meter to measure resistance and put one probe lead on the topmost point of the promini header pins, and the other probe on the corresponding header pin of the RTC module. If there is a continuous electrical connection between the two points then the meter should read near zero ohms. If you do not see the meter go to a very low number then you don’t have a complete electrical path between those points even if it looks connected:

1) the ground (black) wire should provide a continuous path from the ground pin on the digital side of the Promini board to the GND pin on the RTC module
2) the positive power (red) wire should provide a continuous path from the Promini positive rail pin (the one with the bundle of 4 red wires) to the VCC pin on the RTC
3) A4 (I2C data) near the 328P chip on the Promini must connect all the way through the screw terminal board and through the white Dupont wires to the SDA post on the RTC
4) A5 (I2C clock) beside A4 on the Promini must connect through through the yellow Dupont wire to the SCL header pin on the RTC .

You occasionally get a bad Dupont wire where the silver metal end is not in contact with the  copper wire inside because the crimp ‘wings’ folded over plastic insulation. With a pair of tweezers, you can lift the little plastic tab on the black shroud holding the female Dupont ends in place, and replace any single bad wire.

Also look at the little jumpers used to bridge the A4>A2 and A5>A3. If you have a ‘cold’ solder join, or an accidental bridge connection to something else, it could stop the bus from working. Remelt each connection point one at a time, holding the iron long enough to make sure the solder melts into a nice ‘liquid flow’ shape for each solder point.

The ‘process of elimination’ procedures described above also apply to the connections for the SD adapter board. Sometimes you end up with an adapter that has a defective spring contact inside the SD module, but the only way to figure that out is to swap it with another one.

This is also how you would patch into the A6 & A7 connections,

Sometimes those screw terminal boards have a a poor connection inside the black female headers which receive the pins on the under-side of the Promini. Or there may be a bad solder connection to one of the terminal posts on the bottom of the shield. If you have only one bad connection, you can jumper externally from the Promini header pins on top, down to the other wires under the corresponding screw terminal. If you strip the threads on a single screw terminal, you can use this same approach to move that set of wires over to one of the three ‘unused’ screw terminals beside the SD card adapter at the end of the board.

If you’ve gotten through all of the above steps and still have not fixed the problem, then it might be time to simply rebuild the logger with a different screw terminal adapter board.

Also note: The environment is written in Java, and the IDE installer comes with its own bundled Java runtime, so there should be no need for an extra Java installation. However we have seen machines in the past which would not compile working code due until Java was updated on those machines; but this problem is very rare.

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. (unless you have a vacuum chamber)

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.

Addendum 20190423:

A year long experiment in OLED burn-in. Significant dimming of the most used pixels after 4 weeks, but the screens were still operational after one year.

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 six weeks 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.”

Teachers also have to teach themselves first, which is always a hard sell to program admins.  With those things 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, What’s Going On in This Graph?, 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. (esp: Fondriest Environmental Learning Center ) 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 shouldn’t 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 and you are never too old for some fun & gamesOthers 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” + “sensor”, which will often take you to the larger sites like the Arduino Project hub. Sparkfun has moved their Inventor Kit tutorials over to a teachers resource platform called Workbench, which has recently been acquired by Google Classroom. To give you a sense of that scale, here’s a sampling of just their LED tutorials

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 data (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 hardware 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. And he’s not alone, Schuyler St. Leger’s Arduino 101 is notable as perhaps the youngest student-made tutorial.   Jeff Feddersen & Tom Igoe have produced some of the the best quality videos available for Arduino for the ITP program at NYU. Jeff & Tom have been producing these videos for a good while now so there’s a lot of great material. If you are just getting started with Arduino, an excellent sub-set might be the Digital & Analog series, followed by their Sensors videos, and then their set on Serial Communication.  Paul McWhorter also has an extensive tutorial series for beginners, though I find his stuff pretty slow going.

And don’t forget to search for the many other tutorial 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 step-by step data logger 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:
Once you know your way around the Arduino, Nick Gammon’s Microcontroller Forum is an invaluable resource.  There is also a good set of technical videos at Makecourse.com and on the Forcetronics channel. Though it’s a bit dry, All About Circuits has a complete electronics 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 UNO sub-components at Rheingold Heavy’s ‘Build an Arduino From Scratch’ series, and Bruce Land’s AVR lectures take you right down to the “bare iron”.  And finally, I’d be remiss if I didn’t mention the excellent Mini-notebook series that that Forest Mimms wrote back in the 70’s. 


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
It’s Okay To Be Smart
Steve Mould

People who put things together:
Kevin Darrah
Julian Ilett – the Bob Ross of makers
Andreas Spiess – tests every sensor on the market
Electronic Basics by GreatScott
Adam Savage’s Tested
The Thought Emporium
James Bruton

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
Facts in Motion
PhET: interactive physics simulations

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
Knowing Better
The Good Stuff
TedX Talks
Today I Found Out

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 , Plasma Channel, 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)


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.


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 and you can hear more from him at Arduino: The Documentary

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.

Also note: The first four videos from Tom & Jeff’s  sensor series (  Survey1&2, Datasheets & Interfacing ) make an excellent accompaniment to the written material here.


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. For a specific range of conditions, a common rule of thumb is: R-fixed = square root of (R-sensor min × R-sensor max)

The most common analog sensors are those that change their resistance in response to temperature (thermistors), light (photo resistors) or pressure (& it’s force / stretch / bend variants)  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 with a smoothing capacitor. (related method:  Capacitance Meter )

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. And many red, yellow and green LEDs have a little known property: with reverse bias, they behave like a photo diode where the reverse current is proportional to the external light falling on them. So they can also be used to sense light because from a physics point of view, a rectifier diode, a light emitting diode and a photo-diode are basically the same device. While LEDs don’t produce the same signal strength as photodiodes designed for the job, they can be an inexpensive way to build spectrally selective detectors.  LEDs detect a much narrower band of light than they emit, having a peak sensitivity at a wavelength about 50nm shorter than their peak output wavelength.  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 be 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 applications 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 comparatos other input:

These boards switch their high/low output when the sensor circuit voltage crosses the threshold set by the trimpot divider; and this changes the analog sensor voltage divider output into an environmentally responsive threshold alarm. It’s such a generic circuit, and you could connect other resistive sensor dividers 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 sensor dividers output directly with the ADC if you want to.

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 somewhat redundant, since the Arduino has a built-in analog comparator that can do this job with pins D6 (reference) & D7 (sensor divider) .  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 lets you make high resolution analog readings with digital pins 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.

Note: the RCWL-1601 is the 3.3v version of this board which is code compatible with the 5v HC-SR04

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 physical 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 digital ones 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. And it never hurts to review the difference between Resolution, Precision & Accuracy before you choose a sensor.

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();

Addendum 201907:

The latest revision of our logger starter sketch dispenses with the string manipulation described above, and just writes the variables to the SD card directly with file print statements.

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.

Addendum 2019-09-27

Microsoft has added a ‘data streaming’ plugin that’s free for Office 365 users which will accept data directly from an Arduino. If you are a student, the 365 software itself is also free. But for those of us running older versions of Office, the cut and paste method described above still works fine.

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 cheapest possible suppliers – you are doing great if you can run a fully developed course for $150 a seat. If you purchase a soldering station for every single student, and use UNO’s + a typical Pro Mini logger build, you’re looking at about twice that much for the initial run of your course.


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 Arduino open source project going.
$24.95
UnoClone_100pxw UNO clone (incl. USB cable)
If your budget forces you to go this route, choose clone boards with ATmega16U2 or 8U2 UARTs (like those in the genuine 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 – but CH340 UARTS  do not work with Macs.
$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 a lot of time. Check left/right side orientation of the holes on the board before buying and the ones with the larger threaded nylon standoffs tend to be better options.
$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 surface. If you are attaching your breadboards to acrylic plates beside an UNO – add an extra layer of double sided foam tape to the bottom of the breadboards before sticking them down.
$1.20
40p10cmdupont 40wire Dupont 10cm Jumper cable
An alternative to loose jumpers wires, and they make the student kits look much nicer at the beginning of the term. Have students make longer or shorter jumper wires by hand when they need them to provide 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 solid core jumper wire sets as the set lengths are almost never the right size. Striveday also sells mixed boxes of solid core wire.
$20.00/box
SDmodule Micro SD Card Memory Shield Module
This shield is ONLY for UNO based loggers (not the ProMinis) 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 built-in limit resistors)
There is nothing special about this common cathode 5050 LED module, 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 built-in on the green pre-mounted boards give you a current that approaches Arduino pin limits, so it wouldn’t hurt to add another 500-1k ohm on the GND line with these modules for extra safety.
$0.80
Tweezers_100pxw Vetus ESD-15 bent tip tweezers
There are many different kinds: ESD-15 have rounded 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 one is for projects that need a lot of internal space –  it could also be pressed into service as a housing for larger UNO based projects going outdoors ( ie: lots of room for big 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 and indicator LED’s can still shine right through: We use these on the Pro Mini based logger build. The actual usable “interior space” of the box is 8.1cm x 15.5cm x 3.5mm, which is just a a bit too small for the 83mm x120mm acrylic platform bases used for the UNOs (you can press them in, but they are very tight – better to cut 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 as the plano box. 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 all readings and don’t try to measure large resistors in the Meg ohm range (because the meter itself interferes with that reading) . Expect 20% of your order to arrive broken during shipment from China.
$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, but again not as accurate as the EX330. 
$15.00
eyeloupe Folding Magnifier (5x)
Useful for inspecting solder connections but not good for soldering because you inevitably need both hands to do the work. For the soldering stations we pick up cheap reading glasses from the local dollar store.
$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 extra 30m rolls of RED & 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.

Where to buy them: I’m going to list several kits from Electrodragon as examples, but there is nothing special about them and you can often find a very similar sets 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, and that can stretch to 8 weeks. So if you realize that you need something quickly, go to Sparkfun/Adafruit/Pololu/Amazon etc and just pay the $15 delivery charge. The thing that makes this complicated is that now a lot of domestic websites like Amazon, Digikey etc, often just acting as distributor for these exact same components from China. Another draw back with Amazon is that those easily recognized boxes are big targets for porch thieves.

My rule of thumb with dodgy flea market sites like Banggood, 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. Overseas suppliers are best used where fakes are unlikely (or don’t matter) like resistors, LEDs, displays, pin headers, switches, wires, vanilla transistors, battery holders and similar items. Or a one-time thing you just want to play with to see how it works. For more complex sensors and microcontrollers it’s very easy to get counterfeits or rejects that kinda seem to work initially, but are way out of spec. In those cases I’m prepared for a percentage of duds, and so far I’ve only had one out of maybe 30  purchases. The cost of returning is usually more than the item’s worth, so you have to be prepared to bear the loss. There are even some complex components I wouldn’t buy anywhere else like the ESP’s, since these are manufactured in Shanghai, so you wouldn’t find these cheaper somewhere else.

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 bog-standard signal diode so it might be worth keeping some of those on hand. When losses matter @ low voltages and low currents, it’s better to use 1N5817 Shottky’s (ie: for things like isolating 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. They can’t switch much current, but if you are careful it is possible to control parallel mosfets for increased capacity

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 (usually) connects the load to the ground line. 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 the control signal at low voltage, then connect that to a P-fet on the higher voltage side.
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. Expect a few duds in the batch you order.
$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 936b 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. As an FX888 surely would…
ReplHandle_160pxw Replacement handle for Yihua 936 station
Yes, soldering irons do break if you drop them, or if a student leaves them to cook for a couple of hours at the maximum heat setting – especially these cheap ones. This is 5 connector handle is not the same as Hakko 936.  And with spare handles this cheap, it’s much faster to just change the whole handle when you want to work a different tip, rather than waiting for the tip sleeve 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 in these 5-packs after you get one “mixed set”. Of course these are all fakes:  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’ (which came with my Hakko 880) as my default tip for many 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 sandard 40/60 tin/lead 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 the 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
Thermaltronics TMT-TC-2 Lead Free Tip Tinner (20g) in 0.8oz
Once tips oxidize from running hot and dry they will not hold solder and become impossible to work with. Dunking the hot tip in this compound a few times ( & scraping clean again) will bring many of those abused tips back to life.
$9.00
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
Heaterizer_100pxw Heaterizer XL-3000 Heat Gun
A cheaper option than a full re-work station, but also much noisier. Also available on eBay 
$13.95
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 baseplateSnap Flow coolant hoses also work, and Julian Ilett makes good use of Blue Tac to hold parts in place while soldering.
$6.00
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 dollar-store 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.  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. Of course having a pot of liquid solder lying around is also something of a safety hazard.
$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!)  MAS marine epoxy is a much cheaper alternative option for larger jobs, if you don’t mind mixing it yourself, and using syringes to apply it to the circuit boards.
$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
Extech EX330 Autoranging Multimeter
Cheap multi-meters have a host of issues, like for example, not being able to measure meg-ohm size resistors because their internal resistance forms a parallel circuit with the resistor being measured.  So you need to invest in at least one better quality multimeter for your classroom. Though the EX330 is would still be considered “low-end” by professionals, it has served me well for years. 
$48.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…