制作接近报警器
物体距离过近时发出蜂鸣声
制作接近报警器 是 CoddyKit 上的免费 Arduino & IoT Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Arduino & IoT Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Arduino & IoT Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Turn Range Into Action
You can read distance, so now react to it. A proximity alarm buzzes the moment something comes too close to the sensor. 🚨
Add a Buzzer
Wire a small buzzer to a digital pin and to ground. Driving that pin HIGH makes a sound, and LOW makes it stop.
const int buzzerPin = 8;Set the Buzzer Pin
In setup, mark the buzzer pin as OUTPUT so the Arduino is allowed to drive it on and off whenever you decide.
pinMode(buzzerPin, OUTPUT);Pick a Threshold
Choose a trigger distance, for example 20 cm. Anything closer than this counts as too near and should set off the alarm.
const int alarmDistance = 20;Read the Distance
Each loop, take a fresh measurement using the trigger and pulseIn steps you learned, then store the result in a distance variable.
Compare It
Use an if statement to check whether the reading is below your threshold. That comparison is the brain of the whole alarm.
if (cm < alarmDistance) {
// too close!
}Sound the Alarm
When something is too close, drive the buzzer pin HIGH. Otherwise drive it LOW so it stays silent until needed.
if (cm < alarmDistance) digitalWrite(buzzerPin, HIGH);
else digitalWrite(buzzerPin, LOW);Ignore Bad Reads
Remember pulseIn can return zero on a timeout. Skip those values so a missed echo never falsely triggers your buzzer.
Add a Warning LED
Pair the buzzer with an LED on another pin. A visible blink plus the sound makes the alert clear even in a noisy room.
Smarter Alerts
You can make the buzzer beep faster as objects get closer by mapping distance to the delay between beeps, just like a parking sensor.
Make It Yours
This pattern, sense, decide, react, is the heart of every smart device. Swap the buzzer for a relay or a message to extend it.
Quick Check
Think about what decides when the buzzer sounds.
You Built a Device
You combined a sensor, logic, and an output into a working alarm. That sense-decide-react loop is what real IoT projects are made of. ✅
常见问题解答
「制作接近报警器」课时是免费的吗?
是的 — 「制作接近报警器」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Arduino & IoT Academy 课程的其余内容,请升级到 CoddyKit PRO。 Arduino & IoT Academy 课程共包含 4 节课。
「制作接近报警器」这节课中我会学到什么?
物体距离过近时发出蜂鸣声 你通过在浏览器中直接运行的动手代码来练习 Arduino & IoT Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Arduino & IoT Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Arduino & IoT Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「制作接近报警器」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Arduino & IoT Academy 课中编写并运行代码吗?
能。每节 Arduino & IoT Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。