liqinliqin
ONLINE

liqinliqin

www.doit.am
🏢  深圳四博智联科技有限公司 / 研发负责人
V2EX 第 23618 号会员,加入于 2012-07-18 09:41:55 +08:00
今日活跃度排名 746
机器人、物联网
liqinliqin 最近回复了
APP+硬件原型周期一上午可以完成
这段代码实现了以下功能:

控制马达的转速,可以通过 motorSpeed 变量设置马达的转速。
检测温度传感器的数据,通过 tempSensorPin 引脚读取温度传感器的值。
通过 BLE 服务将温度数据发送给 BLE 中心设备。
检测运动传感器的状态,通过 motionSensorPin 引脚读取运动传感器的状态。
监测开关机按键状态,通过 powerButtonPin 引脚检测开关机按键的状态,并通过 BLE 服务将开关机状态发送给 BLE 中心设备。
#include <Arduino.h>
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>

// 定义 BLE 服务、特征和 UUID
BLEServer* pServer;
BLEService* pService;
BLECharacteristic* pCharacteristic;

// 定义马达控制参数
const int motorPin = 12; // 马达控制引脚
int motorSpeed = 0; // 马达转速

// 定义温度传感器引脚
const int tempSensorPin = 34; // 温度传感器引脚

// 定义运动检测参数
const int motionSensorPin = 35; // 运动传感器引脚
int motionDetected = 0; // 运动检测结果

// 定义开关机按键参数
const int powerButtonPin = 27; // 开关机按键引脚
bool powerState = false; // 开关机状态

// 定义 BLE 特征的 UUID
#define CHARACTERISTIC_UUID "1a2b3c4d-5e6f-7g8h-9i0j-1k2l3m4n5o6p"

// 回调函数,当有 BLE 中心设备连接或断开连接时调用
class MyServerCallbacks: public BLEServerCallbacks {
void onConnect(BLEServer* pServer) {
Serial.println("BLE 设备已连接");
};

void onDisconnect(BLEServer* pServer) {
Serial.println("BLE 设备已断开连接");
}
};

// 初始化 BLE 服务
void initBLE() {
BLEDevice::init("ESP32_BLE_Server");
pServer = BLEDevice::createServer();
pServer->setCallbacks(new MyServerCallbacks());

pService = pServer->createService(BLEUUID((uint16_t)0x180F));
pCharacteristic = pService->createCharacteristic(
BLEUUID((uint16_t)0x2A19),
BLECharacteristic::PROPERTY_READ
);

pCharacteristic->setValue(0); // 初始化特征值为 0
pService->start();
BLEAdvertising* pAdvertising = pServer->getAdvertising();
pAdvertising->start();
}

// 初始化硬件
void setup() {
Serial.begin(115200);
initBLE();
pinMode(motorPin, OUTPUT);
pinMode(tempSensorPin, INPUT);
pinMode(motionSensorPin, INPUT);
pinMode(powerButtonPin, INPUT_PULLUP);
}

// 主循环
void loop() {
// 读取温度传感器数据
float temperature = analogRead(tempSensorPin) * 3.3 / 4095 * 100; // 假设温度传感器为模拟传感器,实际情况请根据传感器类型调整

// 检测运动传感器
motionDetected = digitalRead(motionSensorPin);

// 检测开关机按键状态
if (digitalRead(powerButtonPin) == LOW) {
powerState = !powerState; // 切换开关机状态
}

// 发送数据到 BLE 中心设备
pCharacteristic->setValue(temperature); // 将温度值写入 BLE 特征
pCharacteristic->notify();

delay(1000); // 等待 1 秒钟
}
26 天前
回复了 SssaltedFish 创建的主题 iPhone 苹果定位漂移怎么办
推测可能把几公里外的路由拿到办公室用了,根据路由 mac 地址定位了
39 天前
回复了 LiuJiang 创建的主题 香港 香港开户
不买保险,就要找中介,是开美元的账号吗
@Ericality #19 我们主要出模组,有的工厂买过去,自己生产销售的
@Ericality #9 从什么渠道购买的
@hh4646908 #5 可以加 V andy433928 我安排一个技术一对一看下
设备 4 下短按+1 下长按 恢复出厂,手机如果已经绑定就在手机上移除,然后重启手机
关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3827 人在线   最高记录 6543   ·     Select Language
创意工作者们的社区
World is powered by solitude
VERSION: 3.9.8.5 · 21ms · UTC 00:55 · PVG 08:55 · LAX 17:55 · JFK 20:55
Developed with CodeLauncher
♥ Do have faith in what you're doing.