Exemplo de Medidor de Temperatura Bluetooth para Arduino Nano ESP32 - Tutorial de Exibição de Temperatura via BLE

Visão Geral

Este exemplo implementa um medidor de temperatura visual no Arduino Nano ESP32 usando BLE (Bluetooth Low Energy) por meio do aplicativo DIYables Bluetooth STEM. Exiba leituras de temperatura com faixa e unidade configuráveis em um smartphone. Adequado para monitoramento de temperatura, estações meteorológicas, projetos de climatização (HVAC) e sensoriamento ambiental.

Observação: O Arduino Nano ESP32 suporta apenas BLE — o Bluetooth Clássico não é suportado. O DIYables Bluetooth App funciona em Android e iOS com BLE.

Exemplo de Medidor de Temperatura Bluetooth para Arduino Nano ESP32 - Tutorial de Exibição de Temperatura via BLE

Recursos

  • Medidor Visual: Medidor de temperatura exibido no smartphone
  • Faixa Configurável: Defina os valores mínimo e máximo de temperatura
  • Unidade Personalizada: Exiba °C, °F ou qualquer unidade personalizada
  • Atualizações em Tempo Real: Envie as mudanças de temperatura em intervalos configuráveis
  • Solicitação sob Demanda: O aplicativo pode solicitar a temperatura atual
  • Suporte a Android e iOS: O BLE é compatível com as duas plataformas
  • Sem Necessidade de Pareamento: O BLE conecta sem pareamento manual

Hardware Necessário

1×Arduino Nano ESP32
1×Cabo USB Tipo-A para Tipo-C (para PC com USB-A)
1×Cabo USB Tipo-C para Tipo-C (para PC com USB-C)
1×(Opcional) DS18B20 Temperature Sensor
1×(Opcional) DHT11 Módulo Sensor de Temperatura e Umidade
1×(Alternativa) DHT11 Sensor
1×(Opcional) DHT22 Módulo Sensor de Temperatura e Umidade
1×(Alternativa) DHT22 Sensor
1×(Recomendado) Placa de Expansão com Bornes de Parafuso para Arduino Nano
1×(Recomendado) Placa de Expansão Breakout para Arduino Nano
1×(Recomendado) Divisor de Alimentação para Arduino Nano ESP32

Or you can buy the following kits:

1×DIYables Sensor Kit (18 sensors/displays)
Divulgação: Alguns dos links desta seção são links de afiliado da Amazon. Podemos receber uma comissão pelas compras feitas por meio desses links, sem custo adicional para você. Agradecemos o seu apoio.

Buy Note: Many DS18B20 sensors available in the market are unreliable. We strongly recommend buying the sensor from the DIYables brand using the link provided above. We tested it, and it worked reliably.

Código Arduino Nano ESP32

Passos Rápidos

  • Novo no Arduino Nano ESP32? Comece pelo guia de primeiros passos do Arduino Nano ESP32.
  • Conecte o Arduino Nano ESP32 ao seu computador via USB.
  • Abra a Arduino IDE.
  • Selecione a placa Arduino Nano ESP32 e a porta COM correta.
  • Clique no ícone Libraries na barra lateral esquerda.
  • Pesquise por "DIYables Bluetooth" e selecione a biblioteca DIYables Bluetooth da DIYables.
  • Clique em Install.
Biblioteca DIYables Bluetooth para Arduino Nano ESP32
  • Quando for solicitado a instalar as dependências, clique em Install All.
Dependência do DIYables Bluetooth para Arduino Nano ESP32

Código BLE

  • Na Arduino IDE, abra File Examples DIYables Bluetooth ArduinoBLE_Temperature, ou cole o código no editor.
/* * DIYables Bluetooth Library - ESP32 BLE Temperature Example * Works with DIYables Bluetooth STEM app on Android and iOS * * This example demonstrates the Bluetooth Temperature feature: * - Display temperature sensor readings * - Configurable temperature range and unit * - Real-time temperature updates * * Tutorial: https://diyables.io/bluetooth-app * Author: DIYables */ #include <DIYables_BluetoothServer.h> #include <DIYables_BluetoothTemperature.h> #include <platforms/DIYables_Esp32BLE.h> // BLE Configuration const char* DEVICE_NAME = "ESP32BLE_Temp"; const char* SERVICE_UUID = "19B10000-E8F2-537E-4F6C-D104768A1214"; const char* TX_UUID = "19B10001-E8F2-537E-4F6C-D104768A1214"; const char* RX_UUID = "19B10002-E8F2-537E-4F6C-D104768A1214"; // Create Bluetooth instances DIYables_Esp32BLE bluetooth(DEVICE_NAME, SERVICE_UUID, TX_UUID, RX_UUID); DIYables_BluetoothServer bluetoothServer(bluetooth); // Create Temperature app instance (min=-10°C, max=50°C, unit="°C") DIYables_BluetoothTemperature bluetoothTemperature(-10.0, 50.0, "°C"); // Variables for temperature simulation float currentTemperature = 25.0; unsigned long lastTempUpdate = 0; const unsigned long TEMP_UPDATE_INTERVAL = 2000; // Simulated temperature sensor reading float readTemperature() { // TODO: Replace with actual sensor reading static float offset = 0; offset += random(-10, 11) / 10.0; if (offset > 5.0) offset = 5.0; if (offset < -5.0) offset = -5.0; return 25.0 + offset; } void setup() { Serial.begin(115200); delay(1000); Serial.println("DIYables Bluetooth - ESP32 BLE Temperature Example"); // Initialize Bluetooth server with platform-specific implementation bluetoothServer.begin(); // Add temperature app to server bluetoothServer.addApp(&bluetoothTemperature); // Set up connection event callbacks bluetoothServer.setOnConnected([]() { Serial.println("Bluetooth connected!"); float temp = readTemperature(); bluetoothTemperature.send(temp); Serial.print("Initial temperature sent: "); Serial.print(temp); Serial.println("°C"); }); bluetoothServer.setOnDisconnected([]() { Serial.println("Bluetooth disconnected!"); }); bluetoothTemperature.onTemperatureRequest([]() { float temp = readTemperature(); bluetoothTemperature.send(temp); Serial.print("Temperature requested - Sent: "); Serial.print(temp); Serial.println("°C"); }); Serial.println("Waiting for Bluetooth connection..."); } void loop() { bluetoothServer.loop(); if (bluetooth.isConnected() && millis() - lastTempUpdate >= TEMP_UPDATE_INTERVAL) { lastTempUpdate = millis(); currentTemperature = readTemperature(); bluetoothTemperature.send(currentTemperature); Serial.print("Temperature: "); Serial.print(currentTemperature); Serial.println("°C"); } delay(10); }
  • Clique em Upload para gravar o sketch na placa.
  • Abra o Serial Monitor.
  • A saída do Serial Monitor deve ficar assim:
∞
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
Arduino Nano ESP32
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Nano ESP32' on 'COM15')
New Line
9600 baud
DIYables Bluetooth - Temperature Example Waiting for Bluetooth connection...
Ln 11, Col 1
Arduino Nano ESP32 on COM15
2

Aplicativo Móvel

  • Instale o DIYables Bluetooth App no seu smartphone: Android | iOS

Observação: O DIYables Bluetooth App funciona em Android e iOS com BLE. Não é necessário fazer pareamento manual.

  • Abra o DIYables Bluetooth App.
  • Na primeira abertura, conceda as seguintes permissões:
    • Dispositivos Próximos (Android 12+) / Bluetooth (iOS) — necessário para procurar e conectar a dispositivos Bluetooth
    • Localização (somente Android 11 e anteriores) — exigida pelas versões mais antigas do Android para procurar dispositivos BLE
  • Verifique se o Bluetooth está ativado no seu dispositivo.
  • Toque em Connect na tela inicial. O aplicativo vai procurar dispositivos BLE.
DIYables Bluetooth App - Tela Inicial com Botão de Busca
  • Toque em "Arduino_Temp" nos resultados da busca.
  • Depois de conectar, volte à tela inicial e abra o aplicativo Temperature.
DIYables Bluetooth App - Tela Inicial com o Aplicativo Temperature

Toque no ícone de configurações na tela inicial para mostrar ou ocultar aplicativos. Veja o Manual do Usuário do DIYables Bluetooth App para mais detalhes.

  • Um medidor de temperatura exibe a leitura atual com a faixa e a unidade configuradas.
DIYables Bluetooth App - Tela do Medidor de Temperatura

Agora olhe para o Serial Monitor. A saída vai mostrar:

∞
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
Arduino Nano ESP32
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Nano ESP32' on 'COM15')
New Line
9600 baud
Bluetooth connected! Temperature: 24.50 °C Temperature: 24.80 °C Temperature: 25.10 °C
Ln 11, Col 1
Arduino Nano ESP32 on COM15
2

Personalização Criativa - Adapte o Código ao Seu Projeto

Configurar a Faixa e a Unidade de Temperatura

// Celsius: -10 to 50 DIYables_BluetoothTemperature bluetoothTemp(bluetoothServer, -10.0, 50.0, "°C"); // Fahrenheit: 0 to 120 DIYables_BluetoothTemperature bluetoothTemp(bluetoothServer, 0.0, 120.0, "°F"); // Custom range for industrial use DIYables_BluetoothTemperature bluetoothTemp(bluetoothServer, -40.0, 200.0, "°C");

Enviar Atualizações de Temperatura

// Send temperature value to the app bluetoothTemp.send(25.5); // Read from a real sensor and send float temp = readTemperatureSensor(); bluetoothTemp.send(temp);

Tratar Solicitações de Temperatura

bluetoothTemp.onTemperatureRequest([]() { float temp = readTemperatureSensor(); bluetoothTemp.send(temp); Serial.print("Requested: "); Serial.println(temp); });

Exemplos de Programação

Sensor de Temperatura DS18B20

#include <OneWire.h> #include <DallasTemperature.h> OneWire oneWire(2); DallasTemperature sensors(&oneWire); DIYables_BluetoothTemperature bluetoothTemp(bluetoothServer, -10.0, 50.0, "°C"); void setup() { sensors.begin(); bluetoothTemp.onTemperatureRequest([]() { sensors.requestTemperatures(); float temp = sensors.getTempCByIndex(0); bluetoothTemp.send(temp); }); } void loop() { bluetoothServer.loop(); static unsigned long lastTime = 0; if (millis() - lastTime >= 2000) { lastTime = millis(); sensors.requestTemperatures(); float temp = sensors.getTempCByIndex(0); bluetoothTemp.send(temp); } }

Sensor DHT22 com Fahrenheit

#include <DHT.h> DHT dht(2, DHT22); DIYables_BluetoothTemperature bluetoothTemp(bluetoothServer, 0.0, 120.0, "°F"); void setup() { dht.begin(); bluetoothTemp.onTemperatureRequest([]() { float temp = dht.readTemperature(true); // Fahrenheit if (!isnan(temp)) { bluetoothTemp.send(temp); } }); } void loop() { bluetoothServer.loop(); static unsigned long lastTime = 0; if (millis() - lastTime >= 2000) { lastTime = millis(); float temp = dht.readTemperature(true); if (!isnan(temp)) { bluetoothTemp.send(temp); } } }

Solução de Problemas

Problemas Comuns

1. Dispositivo não aparece no aplicativo

  • Confirme que a placa está ligada e que o sketch foi carregado
  • Verifique se o Bluetooth está ativado no seu celular
  • No Android 11 e anteriores, ative também os serviços de localização

2. A temperatura não é atualizada

  • Verifique se send() está sendo chamado no loop
  • Verifique a temporização do intervalo de atualização
  • Garanta que bluetoothServer.loop() seja chamado

3. A temperatura mostra a faixa errada

  • Verifique os valores mínimo/máximo no construtor
  • Verifique se o texto da unidade está correto
  • O valor da temperatura deve estar dentro da faixa configurada

4. A leitura do sensor é NaN

  • Verifique as conexões da ligação do sensor
  • Verifique a alimentação do sensor
  • Adicione uma verificação com isnan() antes de enviar

5. O upload falha ou a placa não é reconhecida

  • Instale o pacote de placa Arduino Nano ESP32 mais recente pelo Board Manager
  • Tente outro cabo ou outra porta USB

Ideias de Projetos

  • Monitor de temperatura ambiente
  • Controlador de clima para estufa
  • Termômetro para geladeira/freezer
  • Display de estação meteorológica
  • Monitor de temperatura de aquário

Próximos Passos

Depois de concluir o exemplo do Bluetooth Temperature, explore:

  1. Bluetooth Analog Gauge — Exibição de medidor de uso geral
  2. Bluetooth Plotter — Registro da temperatura ao longo do tempo
  3. Bluetooth Table — Exibição de vários sensores
  4. Multiple Bluetooth Apps — Combine a temperatura com outros widgets do aplicativo

Suporte

Para obter mais ajuda:

  • Consulte a documentação de referência da API
  • Fóruns da comunidade Arduino

※ NOSSAS MENSAGENS

  • Fique à vontade para compartilhar o link deste tutorial. Porém, por favor, não use nosso conteúdo em outros sites. Investimos muito esforço e tempo para criar este conteúdo, por favor respeite nosso trabalho!