惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

月光博客
月光博客
Cyberwarzone
Cyberwarzone
L
LINUX DO - 最新话题
N
News and Events Feed by Topic
T
Troy Hunt's Blog
Help Net Security
Help Net Security
S
Security @ Cisco Blogs
Google DeepMind News
Google DeepMind News
Security Archives - TechRepublic
Security Archives - TechRepublic
M
MIT News - Artificial intelligence
G
Google Developers Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
V2EX - 技术
V2EX - 技术
Y
Y Combinator Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
大猫的无限游戏
大猫的无限游戏
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Microsoft Security Blog
Microsoft Security Blog
Cisco Talos Blog
Cisco Talos Blog
T
Threatpost
Recent Commits to openclaw:main
Recent Commits to openclaw:main
S
SegmentFault 最新的问题
I
InfoQ
H
Hacker News: Front Page
D
Docker
Scott Helme
Scott Helme
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Blog — PlanetScale
Blog — PlanetScale
人人都是产品经理
人人都是产品经理
博客园 - 叶小钗
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
N
Netflix TechBlog - Medium
AWS News Blog
AWS News Blog
Know Your Adversary
Know Your Adversary
博客园 - 【当耐特】
T
Tor Project blog
U
Unit 42
H
Heimdal Security Blog
Microsoft Azure Blog
Microsoft Azure Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
P
Privacy & Cybersecurity Law Blog
PCI Perspectives
PCI Perspectives
美团技术团队
O
OpenAI News
T
Tailwind CSS Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
B
Blog
GbyAI
GbyAI
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
MyScale Blog
MyScale Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
用超聲波加紅外線達成全向障礙偵測:Arduino 雙感測器整合
張旭豐 · 2026-06-28 · via DEV Community

張旭豐

Arduino 超聲波與紅外線感測器整合:打造全向障礙偵測系統

為光譜裡誰做:阿哲(想做避障小車)
Parent Gene:超聲波感測(14)、紅外線感測(09)

概念句:用超聲波加紅外線達成全向障礙偵測


想像一下:你在桌子上的小型避障小車,忽然遇到一隻手、一塊淺色保麗龍、和遠處的牆——三種不同的障礙,它都能正確停下來嗎?

單一感測器做不到。但把超聲波感測器(HC-SR04)紅外線感測器加在一起,就可以。

1. 為什麼要整合?(互補特性分析)

超音波感測器(HC-SR04)

  • 原理:發射超聲波,計算回傳時間 \text{Distance} = \frac{\text{Sonic Speed} \times \text{Time}}{2}。
  • 優點:測距範圍廣(約 2cm ~ 400cm),對物體顏色不敏感。
  • 缺點
    • 盲區:太近的物體測不准。
    • 聲波散射:面對傾斜表面或吸音材料(海綿、布料)時,聲波被散射而回傳失敗,導致「看不見」障礙物。

紅外線感測器

  • 原理:發射紅外光,偵測反射回來的光強度。
  • 優點:反應速度快,適合近距離偵測(邊緣偵測、極近障礙)。
  • 缺點
    • 深色物體吸收紅外光:黑色或深色表面會讓偵測距離大幅縮短甚至完全偵測不到。
    • 環境光干擾:強烈陽光(含紅外線成分)可能造成誤判。

整合策略:雙重驗證

情境 超音波結果 紅外線結果 系統判定
遠處有牆 \text{Distance} < 20\text{cm} 無觸發 障礙物(遠)
面對淺色保麗龍(多孔) 無回傳(散射) 觸發(吸光少) 僅超聲波(超聲波盲,IR 補上)
面前有白色牆壁 \text{Distance} < 5\text{cm} 觸發 障礙物(極近)
空曠環境 \text{Distance} > 20\text{cm} 無觸發 安全

阿哲可能遇到的問題:為什麼淺色保麗龍讓超聲波「失效」了,但紅外線卻測到了?因為保麗龍表面軟、多孔,聲波散射回不上來,但紅外光仍能反射回讀——兩種感測器的物理特性不同,剛好互補。


2. 硬體接線

元件清單

  • Arduino Uno 或 Nano × 1(約 NT200-300)
  • HC-SR04 超聲波模組 × 1(約 NT50-80)
  • 紅外線障礙偵測模組 × 1(約 NT30-50)
  • 麵包板、杜邦線

接線表

元件 引腳 Arduino 引腳 說明
HC-SR04 VCC 5V 電源
Trig D9 觸發脈衝
Echo D10 接收回傳
GND GND 接地
IR Sensor VCC 5V 電源
OUT D2 偵測訊號(Low = 偵測到)
GND GND 接地

3. 程式碼實現

// 定義引腳
const int TRIG_PIN = 9;
const int ECHO_PIN = 10;
const int IR_PIN = 2;

const long MAX_DISTANCE = 300; // sentinel 值:代表「測不到/超範圍」,不是真實可測距離(pulseIn timeout 限制實測上限約 51cm)
const int DEBOUNCE_COUNT = 3;   // 連續偵測次數

int stableCount = 0; // 紅外線穩定計數

void setup() {
  Serial.begin(9600);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  pinMode(IR_PIN, INPUT);
  digitalWrite(TRIG_PIN, LOW);
  Serial.println("System Initialized: 超聲波 + 紅外線融合");
  Serial.println(">> 校準:打開 Serial Monitor,確認數值正常 <<");
}

long getUltrasonicDistance() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  // pulseIn timeout = 3000μs → 實測上限約 51cm(來回 102cm)。超過就回傳 MAX_DISTANCE(sentinel)
  long duration = pulseIn(ECHO_PIN, HIGH, 3000);
  if (duration == 0) return MAX_DISTANCE; // 無回傳視為超範圍 / 未知
  return duration * 0.034 / 2;
}

void loop() {
  long distance = getUltrasonicDistance();
  int irDetected = digitalRead(IR_PIN);

  Serial.print("距離: ");
  Serial.print(distance);
  Serial.print(" cm | IR: ");
  Serial.println(irDetected == LOW ? "偵測到!" : "無");

  // 整合邏輯:加括號避免優先順序錯誤
  bool ultrasonicTrigger = (distance > 0 && distance < 20);
  bool irTrigger = (irDetected == LOW);

  // 防雜訊:紅外線連續 3 次偵測到才算數
  if (irTrigger) {
    stableCount++;
  } else {
    stableCount = 0;
  }

  if (ultrasonicTrigger || (stableCount >= DEBOUNCE_COUNT)) {
    Serial.println(">>> 障礙物!停車! <<<");
    // motorStop(); // 在這裡加入馬達停止指令
  } else {
    Serial.println("路徑暢通,前進中...");
    // motorForward(); // 在這裡加入馬達前進指令
  }

  delay(200);
}

技術細節:為什麼要加 timeout?

pulseIn()預設可以等很久。如果超聲波沒收到回傳(例如面對吸音海綿),它會卡住直到收到為止——這段時間小車可能已經撞上了。

加入 timeout 參數(微秒)後,3ms(= 3000 微秒)內沒收到回傳就回傳 0,我們立刻知道「這次沒測到」,而不會卡死。聲音在空氣中每秒約走 340 公尺,也就是每秒 34,000 公分,所以每微秒約 0.034 公分duration * 0.034 / 2 這個公式就是把微秒轉換成來回的距離(公分)。

MAX_DISTANCE 只是 sentinel 值,表示「測不到」,不代表真的 300cm。當超聲波完全收不到回傳時,pulseIn 回傳 0,我們回傳 MAX_DISTANCE,邏輯會走到 distance > 0 && distance < 20 這個超聲波觸發條件,結果是 false——這時候紅外線的 stableCount 就會在它感測到障礙時觸發。兩個感測器互相當作 backup。


4. 動手驗證(阿哲測試清單)

  1. 超聲波測試:拿一本書慢慢靠近,Serial Monitor 顯示的數值是否符合實際距離?
  2. 紅外線測試:用手靠近/遠離模組,觀察訊號燈和 Serial Monitor 輸出。
  3. 軟質材料測試:拿一塊白色或淺色保麗龍測試——超聲波可能失效(散射),但紅外線仍能偵測到(淺色表面反射紅外光良好),這正是兩種感測器互補的好例子。黑色海綿則是兩者的共同盲區——聲波散射 + 紅外光吸收,同時失效。
  4. 整合測試:同時觸發兩個感測器,確認「雙重驗證」邏輯正確。

5. 讓阿哲問的問答

Q:為什麼保麗龍讓超聲波測不准?
A:超聲波靠「聲波反射」回傳資訊。保麗龍、海綿等軟質/多孔材料會把聲波散射吃掉,幾乎沒有反射。紅外線靠「光反射」,如果表面是淺色,同樣能反射回讀——兩者互補。

Q:可以把這個邏輯用在循線小車上嗎?
A:可以。把紅外線模組朝下安裝,當車輪接近桌面邊緣時,紅外線訊號會從「無反射」變成「有反射」(桌面 vs. 懸空),就能及時停住。

Q:pulseIn 的 timeout 要設多少?
A:這題是物理+設定的混合問題。pulseIn() 的 timeout 參數單位是微秒(μs)。聲音在空氣中每秒約走 340 公尺(每秒 34,000 公分),所以每微秒約走 0.034 公分。來回 100cm(大約手臂伸直的距離)約需 2.9ms(= 2900 微秒)。pulseIn()3000(微秒)表示:等 3ms 還沒有回傳就放棄。實務上 3ms timeout 讓 HC-SR04 最遠約測到 51cm(單程)——超過這個距離的障礙,會被視為「無障礙」。這是超聲波感測器的物理上限,不是程式的錯。


結論

超聲波的「遠距掃描」與紅外線的「近距補完」,剛好從兩個方向覆蓋了單一感測器的盲區。

這個整合做起來不貴(全部材料約 NT300 以內),邏輯也清晰——而且讓你真正理解「感測器融合」在實務上長什麼樣子。

動手門檻:國中生程度可以接線,但程式邏輯建議有高一以上基礎。或請旭豐帶你走一遍。