Arduino MKR WiFi 1010 - Ultrasonic Sensor

Measure distances without contact! The HC-SR04 ultrasonic sensor enables your Arduino MKR WiFi 1010 to detect objects and measure distances up to 4 meters using sound waves. This tutorial teaches you how to connect an HC-SR04 ultrasonic sensor to your Arduino MKR WiFi 1010 and program it to measure accurate distances.

What You'll Learn:

Real-World Applications:

Arduino MKR WiFi 1010 ultrasonic sensor

Hardware Preparation

1×Arduino MKR WiFi 1010
1×Micro USB Cable
1×Ultrasonic Sensor
1×Breadboard
1×Jumper Wires
1×Optionally, DC Power Jack

Or you can buy the following kits:

1×DIYables Sensor Kit (30 sensors/displays)
1×DIYables Sensor Kit (18 sensors/displays)
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you.
Additionally, some of these links are for products from our own brand, DIYables .

Overview of Ultrasonic Sensor

What is the HC-SR04 Ultrasonic Sensor?

The HC-SR04 is a popular ultrasonic distance sensor that uses sound waves beyond human hearing range to measure distances accurately and without physical contact.

How Ultrasonic Sensing Works:

Ultrasonic Distance Measurement Process: Step 1: Trigger → Arduino sends 10µs pulse to TRIG pin → Sensor prepares to emit sound Step 2: Transmit → Sensor emits 8 pulses of 40kHz ultrasound → Sound travels toward object → Speed: 343 m/s (at 20°C) Step 3: Reflect → Sound waves bounce off object → Echo returns to sensor Step 4: Receive → Sensor detects echo → ECHO pin goes HIGH → Duration = time sound traveled Step 5: Calculate → Distance = (Time × Speed) / 2 → Divide by 2 (sound travels there and back) → Arduino measures ECHO pulse width

Key Specifications:

  • Operating voltage: 5V DC
  • Measuring range: 2cm to 400cm (0.8" to 157")
  • Accuracy: ±3mm (±0.12")
  • Ultrasound frequency: 40kHz (inaudible to humans)
  • Measuring angle: 15° cone
  • Trigger pulse: 10µs minimum
  • Echo pulse: 150µs to 25ms (proportional to distance)
  • Current consumption: 15mA typical

Distance Calculation:

Distance (cm) = Echo Time (µs) × 0.017 Why 0.017? Sound speed: 343 m/s = 0.0343 cm/µs Divide by 2: 0.0343 / 2 = 0.01715 ≈ 0.017

Pinout

Ultrasonic Sensor Pinout
image source: diyables.io

The HC-SR04 ultrasonic sensor has four pins:

Power Pins:

  • VCC pin: Connect to 5V power supply
    • Sensor requires 5V for proper operation
    • Current consumption: ~15mA
  • GND pin: Connect to ground (0V)
    • Common ground with Arduino

    Signal Pins:

    • TRIG pin (Trigger Input): Arduino → Sensor
      • Receives start signal from Arduino
      • Arduino sends 10µs HIGH pulse to trigger measurement
      • Connect to any Arduino digital pin (e.g., D11)
      • 5V tolerant input
    • ECHO pin (Echo Output): Sensor → Arduino
      • Sends distance data back to Arduino
      • Outputs HIGH pulse with duration proportional to distance
      • Arduino measures pulse width using pulseIn()
      • Connect to any Arduino digital pin (e.g., D10)
      • 5V output (safe for Arduino MKR WiFi 1010 3.3V inputs)

      Operating Sequence:

      Timing Diagram: TRIG pin: ____┌──┐____________________________________ (10µs pulse from Arduino) ECHO pin: ________┌─────────────────────┐____________ (Duration = distance measurement) Measurement: ..*i. Arduino: Set TRIG HIGH for 10µs ..*i. Sensor: Emit 8 ultrasonic bursts ..*i. Sensor: Wait for echo ..*i. Sensor: Set ECHO HIGH when received ..*i. Arduino: Measure ECHO pulse duration ..*i. Arduino: Calculate distance

      Range Limitations:

      • Minimum distance: 2cm (closer objects not detected)
      • Maximum distance: 400cm (beyond this returns 0 or timeout)
      • Detection angle: 15° cone (narrow beam)
      • Best results: Hard, flat surfaces perpendicular to sensor
      • Poor results: Soft, angled, or sound-absorbing materials

      How Ultrasonic Sensor Works:

      For detailed operation principles, see how an ultrasonic sensor works.

Wiring Diagram between Ultrasonic Sensor and Arduino MKR WiFi 1010

The wiring diagram between Arduino MKR WiFi 1010 ultrasonic sensor

This image is created using Fritzing. Click to enlarge image

Wiring Table

Ultrasonic Sensor Arduino MKR WiFi 1010
VCC 5V
GND GND
TRIG D11
ECHO D10

How To Program Ultrasonic Sensor

  • To create a 10-microsecond pulse on a pin of the Arduino MKR WiFi 1010, use the digitalWrite() function followed by the delayMicroseconds() function. For example, you can use pin D11.
digitalWrite(11, HIGH); delayMicroseconds(10); digitalWrite(11, LOW);
  • It checks how long the pulse lasts (in microseconds) on a pin of the Arduino MKR WiFi 1010 using the pulseIn() function. For example, use it on pin D10.
duration_us = pulseIn(D10, HIGH);
  • Find distance in centimeters:
distance_cm = 0.017 * duration_us;

Arduino MKR WiFi 1010 Code

/* * This Arduino MKR WiFi 1010 code was developed by newbiely.com * * This Arduino MKR WiFi 1010 code is made available for public use without any restriction * * For comprehensive instructions and wiring diagrams, please visit: * https://newbiely.com/tutorials/arduino-mkr/arduino-mkr-wifi-1010-ultrasonic-sensor */ // constants won't change const int TRIG_PIN = 11; // Arduino MKR WiFi 1010 pin connected to Ultrasonic Sensor's TRIG pin const int ECHO_PIN = 10; // Arduino MKR WiFi 1010 pin connected to Ultrasonic Sensor's ECHO pin // variables will change: float duration_us, distance_cm; void setup() { Serial.begin (9600); // initialize serial port pinMode(TRIG_PIN, OUTPUT); // set arduino pin to output mode pinMode(ECHO_PIN, INPUT); // set arduino pin to input mode } void loop() { // generate 10-microsecond pulse to TRIG pin digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10); digitalWrite(TRIG_PIN, LOW); // measure duration of pulse from ECHO pin duration_us = pulseIn(ECHO_PIN, HIGH); // calculate the distance distance_cm = 0.017 * duration_us; // print the value to Serial Monitor Serial.print("distance: "); Serial.print(distance_cm); Serial.println(" cm"); delay(500); }

Detailed Instructions

New to Arduino MKR WiFi 1010? Complete our Getting Started with Arduino MKR WiFi 1010 tutorial first to set up your development environment.

  • Connect the components to the Arduino MKR WiFi 1010 board as depicted in the diagram
  • Plug your Arduino MKR WiFi 1010 into your computer's USB port
  • Launch the Arduino IDE on your computer
  • Select the Arduino MKR WiFi 1010 board and its COM port
  • Copy the code above and paste it into the Arduino IDE
  • Click the Upload button to compile and upload the code
How to upload Arduino MKR WiFi 1010 code on Arduino IDE
  • Open the Serial Monitor
How to open serial monitor on Arduino IDE
  • Place your hand at different distances in front of the ultrasonic sensor
  • Watch the distance measurements update in real-time
COM6
Send
distance: 19.4 cm distance: 17.6 cm distance: 16.9 cm distance: 27.4 cm distance: 26.9 cm distance: 24.3 cm distance: 25.6 cm distance: 23.1 cm
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

Line-by-line Code Explanation

The Arduino MKR WiFi 1010 code shown above has a simple explanation for each line. Please read the notes in the code.

Troubleshooting

Problem: Sensor always reads 0 cm or no reading

  • Check 5V power: HC-SR04 requires 5V. Connect VCC to 5V pin, not 3.3V
  • Verify wiring: Confirm TRIG and ECHO pins are connected correctly
  • Test distance: Move object to 5-50cm range (minimum 2cm, but more reliable at 5cm+)
  • Check timeout: Add timeout to pulseIn() to prevent infinite wait:
duration_us = pulseIn(ECHO_PIN, HIGH, 30000); // 30ms timeout if (duration_us == 0) { Serial.println("No echo received - check sensor and distance"); }

Problem: Readings are erratic or jump around

  • Use median filter: Take multiple readings and use the middle value:
const int numReadings = 5; float getMedianDistance() { float readings[numReadings]; for (int i = 0; i < numReadings; i++) { digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10); digitalWrite(TRIG_PIN, LOW); long duration = pulseIn(ECHO_PIN, HIGH); readings[i] = 0.017 * duration; delay(10); } // Simple bubble sort for (int i = 0; i < numReadings - 1; i++) { for (int j = 0; j < numReadings - i - 1; j++) { if (readings[j] > readings[j + 1]) { float temp = readings[j]; readings[j] = readings[j + 1]; readings[j + 1] = temp; } } } return readings[numReadings / 2]; // Return median }
  • Add delay: Wait 60ms between measurements to let sensor settle
  • Check physical obstacles: Ensure clear line of sight to target surface

Problem: Maximum reading is only 50-100 cm instead of 400 cm

  • Surface reflection: Hard, flat surfaces perpendicular to sensor work best
  • Soft materials: Curtains, carpet, clothing absorb sound waves poorly
  • Angled surfaces: Sound bounces away instead of returning to sensor
  • Small objects: May be outside the 15° detection cone
  • Test with cardboard: Use a large, flat cardboard sheet at different distances

Problem: Getting readings even when no object is present

  • Add minimum threshold: Ignore distances below 2cm and above 400cm:
float distance_cm = 0.017 * duration_us; if (distance_cm < 2 || distance_cm > 400) { Serial.println("Out of range"); } else { Serial.print("distance: "); Serial.print(distance_cm); Serial.println(" cm"); }
  • Electromagnetic interference: Keep away from motors, relays during measurement

Problem: Distance readings affected by temperature

  • Temperature compensation: Sound speed changes with temperature (343 m/s at 20°C):
// Speed of sound = 331.3 + (0.606 * temperature_C) m/s float temperature = 25.0; // Get from DHT sensor if available float speedOfSound = (331.3 + (0.606 * temperature)) / 10000.0; // cm/µs float distance_cm = (speedOfSound / 2.0) * duration_us;

How to Filter Noise from Distance Measurements of Ultrasonic Sensor

Check out this guide on how to remove unwanted errors from the distance readings of an ultrasonic sensor

Challenge Extensions

Ready to take your ultrasonic sensor project to the next level? Try these challenges:

Challenge 1: Parking Assistant with LED Indicators

Create a parking distance system with LED feedback:

const int GREEN_LED = 4; const int YELLOW_LED = 5; const int RED_LED = 6; float distance_cm = 0.017 * duration_us; // Turn off all LEDs digitalWrite(GREEN_LED, LOW); digitalWrite(YELLOW_LED, LOW); digitalWrite(RED_LED, LOW); // Distance-based LED control if (distance_cm > 50) { digitalWrite(GREEN_LED, HIGH); // Safe distance } else if (distance_cm > 20) { digitalWrite(YELLOW_LED, HIGH); // Caution } else if (distance_cm >= 5) { digitalWrite(RED_LED, HIGH); // Stop } else { // Blink red for too close digitalWrite(RED_LED, !digitalRead(RED_LED)); }

Challenge 2: Proximity Buzzer

Add a buzzer that beeps faster as objects get closer:

const int BUZZER_PIN = 7; int beepDelay = map(distance_cm, 5, 100, 50, 1000); // Closer = faster beeps beepDelay = constrain(beepDelay, 50, 1000); digitalWrite(BUZZER_PIN, HIGH); delay(50); digitalWrite(BUZZER_PIN, LOW); delay(beepDelay);

Challenge 3: Servo Angle Indicator

Use a servo motor to show distance visually (like a gauge):

#include <Servo.h> Servo gaugeServo; void setup() { gaugeServo.attach(9); } void loop() { float distance_cm = getDistance(); int angle = map(distance_cm, 0, 100, 0, 180); angle = constrain(angle, 0, 180); gaugeServo.write(angle); }

Challenge 4: LCD Distance Display with Bar Graph

Show distance with text and a visual bar graph on LCD:

#include <LiquidCrystal.h> LiquidCrystal lcd(12, 11, 5, 4, 3, 2); lcd.setCursor(0, 0); lcd.print("Dist: "); lcd.print(distance_cm, 1); lcd.print(" cm "); // Bar graph on second row int bars = map(distance_cm, 0, 100, 0, 16); lcd.setCursor(0, 1); for (int i = 0; i < 16; i++) { lcd.print(i < bars ? (char)255 : ' '); // Filled or empty }

Challenge 5: Object Counter

Count objects passing in front of sensor (like people or products):

int objectCount = 0; bool objectPresent = false; float distance_cm = getDistance(); if (distance_cm < 30 && !objectPresent) { objectCount++; objectPresent = true; Serial.print("Object detected! Count: "); Serial.println(objectCount); } else if (distance_cm >= 30) { objectPresent = false; }

Challenge 6: Water Level Monitor

Mount sensor above water tank to measure fill level:

const int TANK_HEIGHT_CM = 100; // Distance from sensor to tank bottom float distance_cm = getDistance(); float waterLevel_cm = TANK_HEIGHT_CM - distance_cm; float percentage = (waterLevel_cm / TANK_HEIGHT_CM) * 100.0; Serial.print("Water Level: "); Serial.print(waterLevel_cm); Serial.print(" cm ("); Serial.print(percentage, 1); Serial.println("%)");

Challenge 7: Multi-Sensor Array

Use multiple sensors for wide-area coverage or 2D mapping:

const int TRIG_PINS[] = {2, 4, 6}; const int ECHO_PINS[] = {3, 5, 7}; for (int i = 0; i < 3; i++) { digitalWrite(TRIG_PINS[i], HIGH); delayMicroseconds(10); digitalWrite(TRIG_PINS[i], LOW); long duration = pulseIn(ECHO_PINS[i], HIGH); float distance = 0.017 * duration; Serial.print("Sensor "); Serial.print(i + 1); Serial.print(": "); Serial.print(distance); Serial.println(" cm"); }

Challenge 8: Speed Measurement

Calculate speed of moving objects:

float previousDistance = 0; unsigned long previousTime = 0; float distance_cm = getDistance(); unsigned long currentTime = millis(); if (previousTime > 0) { float distanceChange = previousDistance - distance_cm; float timeChange = (currentTime - previousTime) / 1000.0; // seconds float speed_cmps = distanceChange / timeChange; Serial.print("Speed: "); Serial.print(speed_cmps); Serial.println(" cm/s"); } previousDistance = distance_cm; previousTime = currentTime;

Challenge 9: Automatic Light Controller

Turn lights on when someone approaches:

const int LIGHT_PIN = 8; const int DETECTION_DISTANCE = 100; // cm const unsigned long TIMEOUT = 30000; // 30 seconds unsigned long lastDetectionTime = 0; if (distance_cm < DETECTION_DISTANCE) { digitalWrite(LIGHT_PIN, HIGH); lastDetectionTime = millis(); } else if (millis() - lastDetectionTime > TIMEOUT) { digitalWrite(LIGHT_PIN, LOW); }

Challenge 10: Distance Data Logger

Log measurements to SD card with timestamps:

#include <SD.h> #include <SPI.h> const int CS_PIN = 10; File dataFile; void setup() { SD.begin(CS_PIN); } void loop() { float distance_cm = getDistance(); dataFile = SD.open("distances.txt", FILE_WRITE); if (dataFile) { dataFile.print(millis()); dataFile.print(","); dataFile.println(distance_cm); dataFile.close(); } delay(1000); }

Video Tutorial

Learn More

※ OUR MESSAGES

  • As freelancers, We are AVAILABLE for HIRE. See how to outsource your project to us
  • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!