Code is Science is back: the journal code policy tracker now covers 24 journals.See the tracker

Reliable code for research sensors and data loggers: a field guide

What every record should contain, how to keep timestamps honest, how to survive power cuts, and how to test and version logger firmware before a field season.

PracticeBy the Code is Science editorsNov 23, 202610 min read
Line illustration of an open data logger box with a circuit board and battery, cabled to a soil probe and a weather sensor on a stake, with a laptop beside it
Key takeaways
  • Log raw sensor values with UTC timestamps; apply calibration later in versioned scripts.
  • Rotate files daily or weekly and close them often, so a power cut loses minutes, not a season.
  • Test firmware logic on a desktop and burn in the full logger on a bench before the field.
  • Print the firmware commit into every data file and archive the code with the dataset.

Code for research sensors and data loggers is the firmware and scripts that read an instrument, stamp each reading with a time, store it and turn it into a dataset. In short: log raw values with UTC timestamps, keep calibration separate from the raw data, write files so a power cut cannot destroy them, test the logic on a desk before the field, and record the firmware version inside every data file. Those five habits decide whether a season of measurements can be trusted and reused.

Low-cost loggers built on Arduino-compatible boards have made long field deployments affordable. The ALog loggers described by Wickert and colleagues in Hydrology and Earth System Sciences run for one to two years on three AA cells and have recorded data on glaciers, tundra and wetlands. The hardware is cheap. The weak point is usually the code: a sketch copied from a tutorial, edited in the field, with no record of which version wrote which file.

Groups solve this in different ways. A student may own the firmware for a thesis, a campus research software engineer may take it over, or, once a network grows to dozens of nodes with remote telemetry, a lab may hire a company that offers internet of things software development services for the firmware and server side while the scientists keep calibration and validation in house. The practices below apply in every case.

Why does sensor code need the same care as analysis code?

Sensor code produces the primary data, so its bugs cannot be fixed later by rerunning an analysis. A wrong unit conversion in a Python script is corrected and rerun. A logger that silently skipped readings for three weeks, or stamped them with the wrong hour, leaves a gap that no reanalysis can fill.

Field code also runs where nobody is watching. It has to survive cold, flat batteries, a full memory card and a sensor that stops answering. A 2021 review of low-cost environmental sensors by Chan and colleagues in Progress in Physical Geography notes that such sensors can deliver research-grade data, but only with sensor-specific calibration and careful documentation. Code is where much of that documentation either happens or gets lost.

What should every logged record contain?

Every record should carry enough context to be understood without the person who deployed the logger. A good rule: if the card were found in a drawer five years from now, could someone rebuild the dataset from it alone? The fields below make that possible.

FieldWhere it goesWhy it matters
Logger ID and site codeFile header and file nameCards get swapped between loggers; the ID ties data to a place.
Firmware version or git commitFile headerTells you which code produced the file when a bug is found later.
Timestamp in UTC, ISO 8601Every rowAvoids daylight-saving jumps and time-zone guesses.
Raw sensor valueEvery rowLets you recalibrate without going back to the field.
Converted value (optional)Every row or post-processing onlyConvenient, but never the only copy.
Battery voltageEvery row or once per hourExplains drift and gaps when the supply sags.
Status or error codeEvery rowSeparates "sensor said zero" from "sensor did not answer".

Plain comma-separated text is still the safest format for the card itself. The ALog firmware writes ASCII CSV for exactly this reason: anyone can open the file without the original software.

How do you keep timestamps trustworthy?

Use a real-time clock, set it to UTC, and measure its drift at every visit. Timestamps are the field that fails most quietly, because a wrong time still looks like a valid time.

  • Use a temperature-compensated RTC. Wickert and colleagues report about ±0.43 seconds per day of drift for the clock on the ALog boards, which adds up to a few minutes a year. A cheap uncompensated clock can drift far more in a cold enclosure.
  • Do not timestamp with the microcontroller's uptime counter. On Arduino boards millis() is a 32-bit count of milliseconds and wraps to zero after about 49.7 days. Code that compares raw values across that wrap breaks in the middle of a deployment.
  • Log clock checks. At each visit, compare the logger's time with a reference (a GPS receiver or a phone synced to network time), write both into a field log, then reset the clock. Post-processing can then correct drift linearly between visits.
  • Detect clock resets. If the backup cell dies, many RTCs restart at a default date such as 1 January 2000. Have the firmware flag any timestamp earlier than the deployment date instead of writing it as normal data.

How do you record calibration so it can be redone?

Store raw readings on the logger and apply calibration in versioned post-processing code. Calibration coefficients change: a sensor is recalibrated after a season, a better reference becomes available, or someone finds an error in the original fit. If the logger only stored converted values, every one of those changes means data you cannot fix.

In practice, keep a calibration table in the project repository with one row per sensor serial number, the coefficients, the date and method of calibration, and the reference instrument used. The processing script joins raw data to this table by sensor ID and date. When a coefficient changes, you edit one row, rerun the script and get a new, documented version of the dataset. Our guide to testing research code shows how to pin the output of such a script with a regression test.

How do you stop power loss from corrupting data?

Write data in small, closed chunks so that a power cut costs at most the last few readings. Flash cards hold data in a buffer until the file is flushed or closed, and a battery that dies mid-write can leave the file system damaged.

  1. Flush or close after each record, or after a small batch if power budget matters. Measure the cost on the bench rather than guessing.
  2. Start a new file each day or week. A corrupted file then loses a day, not a season.
  3. Write the header at the top of every file, so each one stands on its own.
  4. Enable the watchdog timer so a hung sensor read reboots the board instead of stopping logging for good, and log every reboot with its cause.
  5. Stop logging before the battery is flat. Read the supply voltage and close files cleanly below a threshold you have tested.

Low-power design matters as much as safe writing. The Cave Pearl loggers described by Beddows and Mallon in Sensors (2018) were built to run at least a year on common batteries, which depends on the firmware putting the board to sleep between readings.

How do you test firmware before it goes to the field?

Split the firmware into hardware code and plain logic, test the logic on a desktop computer, and test the whole logger on a bench for longer than you think necessary. Many field failures come from logic that was never exercised: a month rollover, a full card, a sensor returning an error value.

  • Unit tests for pure functions. Unit conversion, file naming, timestamp formatting and threshold checks need no hardware. Tools such as PlatformIO's unit testing can run them on the desktop and on the board.
  • Fake sensors. Put each sensor behind a small interface so a test can return a value, a timeout or garbage, and check that the logger records the right status code.
  • Bench burn-in. Run the complete logger, at the real logging interval, for at least a week before deployment. If possible, put it in a fridge or freezer for part of that time, since cold changes battery voltage and clock behaviour.
  • Edge dates. Set the clock to just before midnight on 31 December or 28 February and watch the file rollover happen.

How do you version firmware across a deployment?

Keep firmware in version control, tag the exact commit flashed for each deployment, and print that tag into the header of every data file. A common failure is the field edit: someone changes the logging interval on a laptop at the site, flashes it, and the change exists nowhere else. Our guide to version control for researchers covers the basics.

A simple scheme works: one tag per deployment season, such as v2026.1-field, and a build step that writes the short commit hash into a constant the firmware prints at startup. When you publish the dataset, archive the firmware with a DOI next to it, so readers can see exactly what code recorded the numbers.

What should the path from memory card to dataset look like?

Treat the files from the card as read-only raw data and build everything else with scripts. A reliable pipeline has four stages:

  1. Copy and checksum. Copy the card's files into a raw-data folder named by site and date, record checksums, and never edit them again.
  2. Parse and merge. A script reads every file, checks headers, and merges records into one table per logger.
  3. Correct and calibrate. Apply clock-drift corrections from the field log and calibration from the calibration table.
  4. Flag, do not delete. Mark suspect values (out of range, after a reboot, low battery) with quality flags instead of removing them, so users can choose their own filter.

With the pipeline in place, a small web dashboard can show the latest readings to collaborators; our comparison of Streamlit, Dash and Shiny for research data helps pick a tool.

When does a sensor project need professional engineering help?

A sensor project needs engineering help when it adds remote telemetry, over-the-air updates, dozens of nodes or users in other labs. A thesis-sized deployment of a few loggers visited by hand is well within reach of a researcher who follows the steps above. The engineering load changes when the project grows:

  • Remote telemetry. Sending data over cellular or LoRaWAN adds radio power budgets, retries, server ingestion and security.
  • Over-the-air updates. Updating firmware on nodes you cannot reach needs signed images and a safe rollback path.
  • Dozens of nodes or several sites. Device management, monitoring and alerting become a system, not a sketch.
  • Use by other groups. If other labs will build and run your design, it needs documentation, releases and support.

At that point the options are a funded research software engineer, a campus RSE team or an outside engineering firm. Whoever writes the code, the group should own the calibration, the validation against reference instruments and the decision about which data are fit to publish.

Pre-deployment checklist for logger code

  1. Firmware commit tagged, and the tag printed in every file header.
  2. Clock set to UTC and checked against a reference; the reading noted in the field log.
  3. Raw values logged next to any converted values.
  4. Calibration table updated for every sensor serial number in the deployment.
  5. Files rotated daily or weekly, with a header in each.
  6. Watchdog enabled and reboots logged.
  7. Low-battery shutdown tested on the bench.
  8. One week of bench burn-in at the real interval completed.
  9. Processing script run on the burn-in data, end to end.

None of these steps needs special equipment; they need a few days of bench time before the season starts.

Questions about sensor and logger code

Should a data logger store raw values or calibrated values?

Store raw values, and calibrated values too if that helps in the field. Calibration coefficients change after recalibration or when an error is found, and only raw readings let you reprocess the data without returning to the site. Apply calibration in a versioned script that reads a calibration table.

Which time zone should a research data logger use?

UTC, written in ISO 8601 format. Local time introduces daylight-saving jumps, duplicated or missing hours, and confusion when data from several sites are merged. Convert to local time only for display.

How much clock drift is normal for a field logger?

It depends on the clock chip and temperature. A temperature-compensated real-time clock typically drifts by well under a second a day, a few minutes a year; uncompensated clocks can drift much more in the cold. Check the clock against a reference at each visit and correct drift in post-processing.

Is Arduino good enough for research-grade measurements?

It can be. Published platforms such as ALog and the Cave Pearl logger have run for a year or more in the field. Data quality depends on the sensor, its calibration and the firmware, not on the brand of microcontroller, so document all three.

How should I cite or share the firmware used to collect a dataset?

Tag the exact firmware version used in the deployment, archive that release in a repository that issues a DOI, such as Zenodo, and cite it in the dataset description and the paper alongside the data.

Keep reading. More from the desk.