刚开始学习,遇问题,求解
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>
#include <BLE2902.h>
#define OLED_RESET -1
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"
BLECharacteristic *pCharacteristic;
#define TEMPERATURE_SENSOR_PIN 34
#define LED_PIN 2
void setup() {
Serial.begin(9600);
// 初始化 OLED 显示屏
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;)
;
}
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
// 初始化蓝牙
BLEDevice::init("ESP32 BLE Server");
BLEServer *pServer = BLEDevice::createServer();
BLEService *pService = pServer->createService(SERVICE_UUID);
pCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID,
BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY);
pCharacteristic->addDescriptor(new BLE2902());
pService->start();
BLEAdvertising *pAdvertising = pServer->getAdvertising();
pAdvertising->addServiceUUID(pService->getUUID());
pAdvertising->setScanResponse(true);
pAdvertising->setMinPreferred(0x0);
pAdvertising->setMinPreferred(0x1);
BLEDevice::startAdvertising();
// 初始化温度传感器
pinMode(LED_PIN, OUTPUT);
pinMode(TEMPERATURE_SENSOR_PIN, INPUT);
}
void loop() {
float temperature = readTemperature();
display.clearDisplay();
display.setCursor(0, 0);
display.print("Temperature: ");
display.print(temperature);
display.print(" C");
display.display();
// 蓝牙传输数据
String temperatureString = String(temperature);
pCharacteristic->setValue(temperatureString.c_str());
pCharacteristic->notify();
delay(1000);
}
float readTemperature() {
int sensorValue = analogRead(TEMPERATURE_SENSOR_PIN);
float voltage