Sharjah, UAE GST
Home/ Projects/ Lesson 5: Calibrate Your Sensor
Lesson 5 of 9 Sensing Beginner ◎ 40 min

Lesson 5: Calibrate Your Sensor

Turn the UNO into a measuring instrument: type the ruler distance and it prints the average, error and spread of 10 readings, ready for a spreadsheet.

Arduino Ultrasonic Distance & Parking Learning Kit
One of 9 projects in the Arduino Ultrasonic Distance & Parking Learning Kit — the parts below are from that kit.

Before you start

Time
40 min
Do these first
On your own
You can do this lesson on your own.

Exact parts

PartHow many
Wiring from Lesson 1 (the other parts can stay)
Ruler or tape measure, flat card (yours)1
Masking tape to mark distances (optional)

Not in the box

  • A ruler or tape measure and a flat piece of card (yours)

What you build and learn

  • Calibration: comparing a sensor with something you trust
  • Error and spread - two different ways a measurement can be wrong
  • Sending a number from the computer to the UNO
  • Copying data into a spreadsheet

You type the true distance from the ruler and press Enter. The sketch reads your digits one by one and builds the number: 2 then 0 makes 20.

It then takes 10 pings and prints one row: ruler_cm, average_cm, error_cm, min_cm, max_cm, spread_cm, echoes.

Error tells you whether the sensor reads too far or too near. Spread tells you how much it wobbles. A good sensor has both small.

Real sensors are often a little off in the same direction. Once you know the error, you could correct for it in code.

New words

Calibrate
Check a measuring tool against a known reference, such as a ruler.
Error
Reading minus true value. +2 means it reads 2 cm too far.
Spread
Biggest reading minus smallest. A small spread means steady readings.
CSV
Comma-separated values: rows of numbers with commas, which spreadsheets can read.

What this project uses

Every item below is in the kit. Not in the box: A ruler or tape measure and a flat piece of card (yours).

Build this with

Arduino Ultrasonic Distance & Parking Learning Kit

All 9 parts in one box, with this project and 8 more to build from them.

AED 85.00 See the kit
Need only these parts? Order them loose · from AED 78.30
Used in this project tick what you still need
Also needed untick if you already have them
Selected parts AED 78.30

One of each part. Packs (resistor assortment, jumper wires) already hold more than a single build needs. a ruler or tape measure, a flat card, a spreadsheet (optional): included in the kit, ask us for it loose. Delivery is AED 20, free on orders AED 100+.

Connections

Unplug USB before you change any wire. Pin names are the labels printed on the board.

Lesson 5: Calibrate Your Sensor - connection diagram with labelled pins
Connection diagram, drawn from this lesson's pin plan - not a photo of a tested build. Tap to open it full size. The table below says the same thing in words.
Part / pinConnect toNote
No changesSensor as in Lesson 1TRIG pin 9 · ECHO pin 10

Step by step

One thing at a time. Tick nothing off until it matches the diagram.

  1. Upload the Lesson 5 code. No wiring changes are needed.
  2. Open the Serial Monitor at 9600 baud. In the box at the bottom right choose "New Line".
  3. Tape a ruler or tape measure to the table, starting at the front of the sensor's eyes.
  4. Stand the card upright and square to the sensor at 10 cm. Type 10 and press Enter. A row appears after about a second.
  5. Repeat at 20, 30, 50, 75 and 100 cm (as far as your table allows).
  6. Select the rows in the Serial Monitor, copy them, and paste them into a spreadsheet. Use Data → Split text to columns if they land in one column.

Sketch for this project

Written for the board in the kit. Copy it into the Arduino IDE; change the pin numbers if you wire it differently.

lesson5_calibrate.ino arduino
/*
  DIY KIT - Arduino Ultrasonic Distance & Parking Learning Kit
  Lesson 5 of 9: Calibrate Your Sensor

  WIRING: the sensor from Lesson 1 (TRIG pin 9, ECHO pin 10).
  The LEDs and buzzer can stay connected; this sketch does not use them.

  HOW TO USE IT
    1. Open the Serial Monitor at 9600 baud. Check the box at the bottom
       right is set to "New Line".
    2. Put a flat card at a ruler mark, for example 20 cm.
    3. Type 20 and press Enter. The UNO takes 10 readings and prints one row:
       ruler_cm, average_cm, error_cm, min_cm, max_cm, spread_cm, echoes
    4. Repeat at 10, 20, 30, 50, 75 and 100 cm. Copy the rows into a spreadsheet.
*/

const int TRIG_PIN = 9;
const int ECHO_PIN = 10;

const int SAMPLES = 10;                        // readings per row
const unsigned long ECHO_TIMEOUT_US = 30000;
const int MIN_CM = 2;
const int MAX_CM = 400;

long typedNumber = 0;     // the number being typed, digit by digit

long readOnceCm() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  unsigned long us = pulseIn(ECHO_PIN, HIGH, ECHO_TIMEOUT_US);
  if (us == 0) return 0;
  long cm = us / 58;
  if (cm < MIN_CM || cm > MAX_CM) return 0;
  return cm;
}

// Take SAMPLES readings and print one spreadsheet row.
void measureAt(long rulerCm) {
  long total = 0;
  long lowest = 9999;
  long highest = 0;
  int echoes = 0;

  for (int i = 0; i < SAMPLES; i++) {
    long cm = readOnceCm();
    if (cm > 0) {
      total = total + cm;
      echoes = echoes + 1;
      if (cm < lowest) lowest = cm;
      if (cm > highest) highest = cm;
    }
    delay(60);
  }

  Serial.print(rulerCm);
  Serial.print(",");
  if (echoes == 0) {
    Serial.println("NA,NA,NA,NA,NA,0");
    return;
  }
  long average = total / echoes;
  Serial.print(average);            Serial.print(",");
  Serial.print(average - rulerCm);  Serial.print(",");   // error: + means it reads too far
  Serial.print(lowest);             Serial.print(",");
  Serial.print(highest);            Serial.print(",");
  Serial.print(highest - lowest);   Serial.print(",");   // spread: how much it wobbles
  Serial.println(echoes);
}

void setup() {
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  Serial.begin(9600);
  Serial.println("Lesson 5: Calibrate Your Sensor");
  Serial.println("Put the card at a ruler mark, type the distance in cm and press Enter.");
  Serial.println("ruler_cm,average_cm,error_cm,min_cm,max_cm,spread_cm,echoes");
}

void loop() {
  while (Serial.available() > 0) {
    char c = Serial.read();
    if (c >= '0' && c <= '9') {
      typedNumber = typedNumber * 10 + (c - '0');   // build the number one digit at a time
    } else if (c == '\n' || c == '\r') {
      if (typedNumber > 0) measureAt(typedNumber);
      typedNumber = 0;
    }
  }
  delay(1);
}
ℹCompiler-checked for Arduino UNO (0 warnings) and run in the kit simulator. Pins match the lesson diagram. Not yet bench-tested on the shipped parts.

Upload it

  1. Click Copy (or Download .ino and open the file).
  2. In the Arduino IDE choose File → New Sketch, select everything in it and paste.
  3. Check the bottom of the window says Arduino Uno and your port (Start here, step 5).
  4. Click Upload (the → arrow) and wait for Done uploading.

How the code works

In the codeWhat it does
typedNumber = typedNumber * 10 + (c - '0');Builds the number from your digits: "2" then "0" → 2 → 20.
measureAt(rulerCm)Takes 10 readings, keeps the smallest and biggest, and prints one CSV row.
average - rulerCmThe error: positive means the sensor reads too far.
highest - lowestThe spread: how much the 10 readings wobble.

Change it and see

Change: Change SAMPLES from 10 to 30.What happens: Each row takes longer, and the average is steadier.
Change: Add Serial.print(" cm off") after the error.What happens: The row becomes easier to read, but harder to paste into a spreadsheet.

What you should see or hear

  • At start: a title line, the instruction and the header ruler_cm,average_cm,...
  • After typing 20 and Enter: one row like 20,21,1,21,22,1,10.
  • Errors of 0-2 cm and spreads of 0-2 cm up close; bigger far away.

If it doesn't work

ProblemWhat to check
Nothing happens when I press EnterChoose "New Line" in the box at the bottom right of the Serial Monitor and try again.
The row says NA and 0 echoesNothing came back: square the card up to the sensor and check the wiring from Lesson 1.
All the rows land in one spreadsheet columnUse Data → Split text to columns (Google Sheets) or Data → Text to Columns (Excel) with comma.
Nothing or strange symbols in the Serial MonitorSet the speed in the corner of the Serial Monitor to 9600 baud. Close the Serial Plotter if it is open.

Small experiment

Make a chart of error against distance in your spreadsheet. Does the error grow as the card gets further away?

Check what you learned

The ruler says 50 cm and the average is 52. What is the error?

+2 cm: the sensor reads 2 cm too far.

Readings of 30, 31, 30, 33. What is the spread?

33 − 30 = 3 cm.

Why do we compare with a ruler?

Calibration needs a reference we trust more than the sensor.

▶In the simulator: The simulator's readings are perfectly steady, so error and spread come out as 0. Do this lesson with the real sensor.

Next

  • Lesson 6 tests different targets and angles at one distance.

Stuck?

Most problems are one wire in the wrong hole. Check these first:

  1. Unplug, then compare every wire with the lesson's diagram and table. One pin off is the most common problem.
  2. Sensor: are VCC, TRIG, ECHO and GND wired by their labels, with TRIG on 9 and ECHO on 10?
  3. LEDs: is the long leg on the resistor side?
  4. Is the − rail connected to a UNO GND pin, and the + rail to 5V?
  5. Serial Monitor: is it set to 9600 baud (and "New Line" when you type commands)?
  6. Upload problems: is Tools → Board set to Arduino Uno and Tools → Port to your UNO? (Start here, step 5.)
Still stuck? Ask us on WhatsApp. Send this message with a photo of your wiring - it tells us exactly where you are.
Hi DIY KIT, I'm stuck on the Arduino Ultrasonic Distance & Parking Learning Kit.
Lesson: __
Step number: __
What should happen: __
What happens instead: __
Error message (copied exactly): __
I'll attach a photo of my wiring.
Message us on WhatsApp

More from this kit

All projects →

Bot
ECHO
Online — usually replies instantly
Catalog assistant: verify final stock/price on the product page before checkout.