写一段代码,esp32每10秒采集一次adc的电压,并通过BLE发送,其余时间处于deep-sleep模式
时间: 2023-12-22 11:05:13 浏览: 91
以下是一个简单的示例代码,用于esp32每10秒采集一次ADC电压,并通过BLE发送,其余时间处于deep-sleep模式。需要使用Arduino IDE和ESP32开发板。
```C++
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>
#include <BLE2902.h>
#include <esp_adc_cal.h>
#define ADC_PIN 32 //ADC输入引脚
#define ADC_VREF 1100 //ADC参考电压(mV)
#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b" //自定义GATT服务UUID
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8" //自定义GATT特征UUID
BLECharacteristic *pCharacteristic;
bool deviceConnected = false;
float adc_voltage = 0;
class MyServerCallbacks: public BLEServerCallbacks {
void onConnect(BLEServer* pServer) {
deviceConnected = true;
};
void onDisconnect(BLEServer* pServer) {
deviceConnected = false;
}
};
void setup() {
Serial.begin(115200);
BLEDevice::init("ESP32_ADC_BLE");
BLEServer *pServer = BLEDevice::createServer(); //创建BLE服务
pServer->setCallbacks(new MyServerCallbacks());
BLEService *pService = pServer->createService(SERVICE_UUID); //创建自定义GATT服务
pCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID,
BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY
); //创建自定义GATT特征
pCharacteristic->addDescriptor(new BLE2902()); //添加BLE描述符
pService->start(); //开始GATT服务
//配置ADC
adc1_config_width(ADC_WIDTH_BIT_12);
adc1_config_channel_atten(ADC1_CHANNEL_4, ADC_ATTEN_DB_11);
//设置定时器,每10秒触发一次
esp_sleep_enable_timer_wakeup(10 * 1000000);
}
void loop() {
if (deviceConnected) {
//获取ADC电压
int adc_raw = adc1_get_raw(ADC1_CHANNEL_4);
esp_adc_cal_characteristics_t characteristics;
esp_adc_cal_get_characteristics(VREF_ADC1_GPIO25, ADC_ATTEN_DB_11, ADC_WIDTH_BIT_12, ADC_VREF, &characteristics);
adc_voltage = esp_adc_cal_raw_to_voltage(adc_raw, &characteristics);
//将ADC电压转换为字符串并通过BLE发送
String voltage_str = String(adc_voltage, 3);
pCharacteristic->setValue(voltage_str.c_str());
pCharacteristic->notify();
delay(100); //等待BLE发送完成
}
//进入deep-sleep模式
esp_deep_sleep_start();
}
```
注意:在使用此代码之前,需要在Arduino IDE中安装ESP32开发板支持和BLE库。另外,需要在BLE客户端上扫描并连接到ESP32设备,才能接收到ADC电压数据。
阅读全文