Raspberry Pi Zero W and GSM SIM900 Based Ultrasonic Distance Measurement System

Raspberry Pi Zero W & GSM SIM900 Ultrasonic Distance Measurement | MakeMindz
IoT Raspberry Pi GSM / SMS Intermediate

Raspberry Pi Zero W & GSM SIM900 Ultrasonic Distance Measurement System

An IoT remote monitoring project that measures distance with a JSN-SR04T ultrasonic sensor and sends real-time SMS alerts via the SIM900 GSM module — no internet required.

📅 Feb 2026 ⏱ ~45 min build 🔧 Pi Zero W · SIM900 · JSN-SR04T
🚀

Project Overview

This project combines the compact Raspberry Pi Zero W with a SIM900 GSM/GPRS module and a JSN-SR04T waterproof ultrasonic sensor to create a fully autonomous distance monitoring system. When the measured distance crosses a set threshold, the system fires an SMS alert directly to any registered mobile number — zero Wi-Fi dependency.

📡
No Internet Needed
GSM cellular network carries all alerts, perfect for remote and rural deployments.
💧
Waterproof Sensor
JSN-SR04T is IP67-rated, ideal for water tanks, reservoirs and outdoor use.
Low Power
Pi Zero W draws under 150mA — easily solar or battery powered in the field.
📲
Instant SMS Alert
AT commands trigger real-time SMS the moment a threshold is breached.
🔩

Components Required

# Component Spec / Note Qty
1Raspberry Pi Zero WWi-Fi + BT, 40-pin GPIO, 1GHz single-core1
2SIM900 GSM/GPRS ModuleQuad-band 850/900/1800/1900MHz, UART interface1
3JSN-SR04T Ultrasonic SensorWaterproof, 25–450cm range, 5V supply1
45V Regulated Power Supply≥2A recommended (SIM900 peaks 2A)1
5Active SIM CardAny GSM carrier (voice/SMS plan)1
6Jumper WiresMale-to-female, various lengths~12
7Breadboard (optional)For prototyping connections1
🔌

Circuit Diagram & Pinout

Raspberry Pi Zero W GPIO 23 (TRIG) · GPIO 24 (ECHO) GPIO 14 (TXD) · GPIO 15 (RXD) 5V · GND JSN-SR04T Waterproof Ultrasonic VCC · TRIG · ECHO · GND SIM900 GSM GPRS Quad-band Module VCC · RX · TX · GND SIM CARD ANT 5V Power Supply (≥2A) VCC · GND External regulated TRIG ECHO TX→RX RX←TX 5V GND Circuit Diagram — Pi Zero W + SIM900 + JSN-SR04T Serial (UART) — GPIO — 5V Power TRIG/ECHO UART TX/RX 5V Power GND Dashed = optional external power run

📌 Pin Connection Reference

Pi Zero W Pin Component Component Pin Wire Color
GPIO 23 (Pin 16)JSN-SR04TTRIGYellow
GPIO 24 (Pin 18)JSN-SR04TECHOGreen
5V (Pin 2)JSN-SR04TVCCRed
GND (Pin 6)JSN-SR04TGNDBlack
GPIO 14 / TXD (Pin 8)SIM900RXPurple
GPIO 15 / RXD (Pin 10)SIM900TXBlue
External 5VSIM900VCCRed
Common GNDSIM900GNDBlack
⚠️ Voltage Warning: The SIM900 module can surge to 2A during GSM transmission. Always use a dedicated external 5V/2A supply for it — do NOT power it from the Pi's 5V rail.
🛠

Step-by-Step Instructions

1

Set Up Raspberry Pi Zero W

Flash Raspberry Pi OS Lite onto a microSD card using Raspberry Pi Imager. Enable SSH and configure Wi-Fi in the imager settings (Advanced Options). Boot, then SSH in and run:

bash
sudo apt update && sudo apt upgrade -y
sudo raspi-config   # Enable Serial (Interface Options → Serial Port)
# Disable serial console, enable serial hardware
ℹ️ When asked "Would you like a login shell accessible over serial?" select No. When asked "Would you like the serial port hardware to be enabled?" select Yes.
2

Install Required Python Libraries

Install the GPIO and serial communication libraries on the Pi:

bash
sudo apt install python3-pip python3-rpi.gpio -y
pip3 install pyserial RPi.GPIO
3

Wire the JSN-SR04T Ultrasonic Sensor

  • Connect TRIG → GPIO 23 (Pin 16) via a yellow wire
  • Connect ECHO → GPIO 24 (Pin 18) via a green wire
  • Connect VCC → 5V (Pin 2) via a red wire
  • Connect GND → GND (Pin 6) via a black wire
⚠️ The JSN-SR04T outputs 5V logic on the ECHO pin. The Pi's GPIO is 3.3V tolerant only. Add a simple voltage divider (1kΩ + 2kΩ) on the ECHO line to protect your Pi.
4

Wire the SIM900 GSM Module

  • Insert an active SIM card into the SIM900 slot
  • Connect SIM900 RX → GPIO 14 / TXD (Pin 8) via purple wire
  • Connect SIM900 TX → GPIO 15 / RXD (Pin 10) via blue wire
  • Connect SIM900 VCC → External 5V supply (red)
  • Connect SIM900 GND → Common GND (black)
⚠️ SIM900 operates at 5V logic but many modules include onboard level shifters. Confirm your module's RX pin voltage tolerance before connecting directly to Pi's 3.3V TX. When in doubt, use a level shifter.
5

Test the Ultrasonic Sensor

Create a quick test script to verify distance readings before integrating GSM:

Python
import RPi.GPIO as GPIO, time
TRIG, ECHO = 23, 24
GPIO.setmode(GPIO.BCM)
GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)
GPIO.output(TRIG, False)
time.sleep(0.5)
GPIO.output(TRIG, True)
time.sleep(0.00001)
GPIO.output(TRIG, False)
while GPIO.input(ECHO) == 0: pulse_start = time.time()
while GPIO.input(ECHO) == 1: pulse_end   = time.time()
distance = (pulse_end - pulse_start) * 17150
print(f"Distance: {distance:.1f} cm")
GPIO.cleanup()

Run with python3 test_sensor.py and verify you see accurate readings.

6

Test the SIM900 GSM Module

Use minicom to verify AT command communication:

bash
sudo apt install minicom -y
minicom -b 9600 -o -D /dev/ttyS0

Type AT and press Enter. You should receive OK. Type AT+CSQ to check signal strength (values 10–31 are good).

ℹ️ The red LED on the SIM900 should blink every ~3 seconds when registered to a network. Rapid blinking = no network. Slow blink every 3s = registered.
7

Upload and Run the Main Python Script

Create the main script (see full code below), set your phone number and threshold, then run it:

bash
nano distance_monitor.py
# Paste the full code, edit PHONE_NUMBER and THRESHOLD_CM
python3 distance_monitor.py
⚠️ To run at startup, add to crontab -e: @reboot python3 /home/pi/distance_monitor.py &
💻

Full Source Code

Production-ready Python script with threshold alerts, cooldown logic, and clean GPIO handling:

Python 3 — distance_monitor.py
#!/usr/bin/env python3
"""
Raspberry Pi Zero W + GSM SIM900 + JSN-SR04T
Ultrasonic Distance Measurement & SMS Alert System
MakeMindz.com – makemindz.com/2026/02/raspberry-pi-zero-w-and-gsm-sim900.html
"""

import RPi.GPIO as GPIO
import serial, time, logging

# ─── Configuration ────────────────────────────────────────────────────────────
TRIG_PIN      = 23          # GPIO 23 → JSN-SR04T TRIG
ECHO_PIN      = 24          # GPIO 24 ← JSN-SR04T ECHO
SERIAL_PORT   = "/dev/ttyS0" # UART serial port
BAUD_RATE     = 9600
PHONE_NUMBER  = "+91XXXXXXXXXX" # ← Replace with your number
THRESHOLD_CM  = 30           # Alert if distance < this (cm)
MEASURE_DELAY = 2.0         # Seconds between readings
ALERT_COOLDOWN= 60          # Seconds between repeated SMS alerts
# ──────────────────────────────────────────────────────────────────────────────

logging.basicConfig(level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
    datefmt="%H:%M:%S")

def setup_gpio():
    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(False)
    GPIO.setup(TRIG_PIN, GPIO.OUT)
    GPIO.setup(ECHO_PIN, GPIO.IN)
    GPIO.output(TRIG_PIN, False)
    time.sleep(0.5)   # sensor settle time

def measure_distance() -> float:
    # Trigger 10µs pulse
    GPIO.output(TRIG_PIN, True)
    time.sleep(0.00001)
    GPIO.output(TRIG_PIN, False)

    pulse_start = pulse_end = time.time()
    timeout = pulse_start + 0.04   # 40ms timeout

    while GPIO.input(ECHO_PIN) == 0:
        pulse_start = time.time()
        if pulse_start > timeout:
            return -1   # no echo

    while GPIO.input(ECHO_PIN) == 1:
        pulse_end = time.time()
        if pulse_end > timeout:
            return -1

    return (pulse_end - pulse_start) * 17150  # cm

def send_sms(gsm: serial.Serial, number: str, message: str) -> bool:
    try:
        gsm.write(b"AT+CMGF=1\r")
        time.sleep(1)
        gsm.write(f'AT+CMGS="{number}"\r'.encode())
        time.sleep(1)
        gsm.write(message.encode() + bytes([26]))  # Ctrl+Z
        time.sleep(3)
        response = gsm.read(gsm.in_waiting).decode(errors='ignore')
        if "+CMGS" in response:
            logging.info(f"SMS sent to {number}")
            return True
    except Exception as e:
        logging.error(f"SMS error: {e}")
    return False

def main():
    setup_gpio()
    last_alert_time = 0

    with serial.Serial(SERIAL_PORT, BAUD_RATE, timeout=1) as gsm:
        logging.info("System started. Monitoring distance...")

        try:
            while True:
                dist = measure_distance()

                if dist < 0:
                    logging.warning("Sensor timeout – no echo received")
                else:
                    logging.info(f"Distance: {dist:.1f} cm")

                    now = time.time()
                    if dist < THRESHOLD_CM and (now - last_alert_time) > ALERT_COOLDOWN:
                        msg = (f"[MakeMindz Alert]\n"
                               f"Distance: {dist:.1f} cm\n"
                               f"Threshold: {THRESHOLD_CM} cm\n"
                               f"Status: THRESHOLD BREACHED")
                        if send_sms(gsm, PHONE_NUMBER, msg):
                            last_alert_time = now

                time.sleep(MEASURE_DELAY)

        except KeyboardInterrupt:
            logging.info("Stopped by user.")
        finally:
            GPIO.cleanup()

if __name__ == "__main__":
    main()
ℹ️ The original project description references Arduino-style C++ code. This Python implementation is the recommended approach for Raspberry Pi — it uses proper GPIO libraries, timeout handling, and SMS cooldown to prevent alert flooding.
🔬

Simulation & Testing Tools

Simulate and prototype this project online before building the hardware:

📦

Applications & Benefits

🚰
Water Tank Monitoring
Alert when tank reaches critical low or overflow level without manual checks.
🌊
Reservoir & Dam Alerts
Monitor flood levels and send emergency SMS to authorities automatically.
🏭
Industrial Safety
Detect objects or materials crossing safety perimeters in manufacturing lines.
🅿️
Smart Parking
Detect vehicle presence in parking bays and report occupancy remotely.
🔐
Intrusion Detection
Trigger SMS alerts when an object breaches a defined proximity threshold.
🌱
Agricultural Water Mgmt
Monitor irrigation tank levels and automate pump-on alerts via SMS.

Related MakeMindz Projects

Comments

try for free