使用手机应用控制 LED
通过 BLE 向开发板发送命令
使用手机应用控制 LED 是 CoddyKit 上的免费 Arduino & IoT Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Arduino & IoT Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Arduino & IoT Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Your First BLE Control
是时候将其整合在一起了:点击手机上的按钮,即可看到 LED 灯亮起。这就是 BLE 控制的实际应用。💡
The Plan
手机将一个值写入特征值(characteristic),你的开发板读取该值,随后你的程序便会切换 LED 的状态以与之匹配。简单而强大。
Prepare the LED Pin
In setup, declare the LED pin as an output so your board can drive it. This is the same pinMode you already know.
pinMode(2, OUTPUT);Make It Writable
The control characteristic needs PROPERTY_WRITE so the phone is allowed to send commands to it. Read-only would block control.
svc->createCharacteristic(uuid,
BLECharacteristic::PROPERTY_WRITE);Listen for Writes
Attach a callback so your code runs the instant the phone writes. The onWrite method becomes your command handler.
Read the Command
Inside the callback, fetch what the phone sent with getValue. Maybe it is the text 1 for on or 0 for off.
std::string v = c->getValue();Act on the Value
Compare the command, then drive the pin. A 1 turns the LED on, anything else turns it off. That is the whole logic.
digitalWrite(2, v == "1" ? HIGH : LOW);Confirm Back
It helps to send the new state back so the app stays in sync. A short Serial print also confirms the command really arrived.
Serial.println("LED set");Use a Generic App
No need to build an app yet. A tool like nRF Connect lets you connect and write values to test your control instantly.
Connect and Send
In the app, connect to your device, open the writable characteristic, and send 1. The onboard LED should light up right away.
From Here to a Real App
The same write idea powers a full custom app. Once this works, you can control motors, relays, or anything from your phone.
Quick Check
You want the phone to send an on or off command to your board.
Recap
A writable characteristic plus a callback turns phone taps into real-world action. You just built remote LED control over BLE. 🎉
常见问题解答
「使用手机应用控制 LED」课时是免费的吗?
是的 — 「使用手机应用控制 LED」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Arduino & IoT Academy 课程的其余内容,请升级到 CoddyKit PRO。 Arduino & IoT Academy 课程共包含 4 节课。
「使用手机应用控制 LED」这节课中我会学到什么?
通过 BLE 向开发板发送命令 你通过在浏览器中直接运行的动手代码来练习 Arduino & IoT Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Arduino & IoT Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Arduino & IoT Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「使用手机应用控制 LED」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Arduino & IoT Academy 课中编写并运行代码吗?
能。每节 Arduino & IoT Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。