Exemplo de Pinos Digitais Bluetooth para Arduino Nano ESP32 - Tutorial de Controle de Pinos GPIO via BLE

Visão Geral

Este exemplo oferece controle e monitoramento remoto de pinos GPIO no Arduino Nano ESP32 usando BLE (Bluetooth Low Energy) por meio do aplicativo DIYables Bluetooth STEM. Controle pinos de saída e monitore pinos de entrada sem fio a partir de um smartphone. Adequado para controle de relé, monitoramento de botões, acionamento de LEDs e qualquer aplicação que exija acesso remoto a pinos.

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 Pinos Digitais Bluetooth para Arduino Nano ESP32 - Tutorial de Controle de Pinos GPIO via BLE

Recursos

  • Controle de Saída: Defina pinos digitais como HIGH ou LOW remotamente
  • Monitoramento de Entrada: Leia o estado de pinos digitais e analógicos
  • Pinos com Nome: Atribua rótulos descritivos a cada pino (por exemplo, "LED", "Relay")
  • Atualizações em Tempo Real: Envie as mudanças de estado dos pinos para o aplicativo
  • Até 16 Pinos: Controle vários pinos ao mesmo tempo
  • 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×Protoboard
1×Fios Jumper
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.

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_PinControl, ou cole o código no editor.
/* * DIYables Bluetooth Library - ESP32 BLE Pin Control/Monitor Example * Works with DIYables Bluetooth STEM app on Android and iOS * * This example demonstrates the Bluetooth Pin Control/Monitor feature: * - Control digital output pins via Bluetooth * - Monitor digital input pins * - Monitor analog input pins * - Configure pin modes (INPUT/OUTPUT) * * Tutorial: https://diyables.io/bluetooth-app * Author: DIYables */ #include <DIYables_BluetoothServer.h> #include <DIYables_BluetoothPinControl.h> #include <platforms/DIYables_Esp32BLE.h> // BLE Configuration const char* DEVICE_NAME = "ESP32BLE_Pins"; 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 Pin Control/Monitor app instance DIYables_BluetoothPinControl bluetoothPins; // Pin configuration (ESP32 GPIOs) const int LED_PIN = LED_BUILTIN; // Built-in LED const int OUTPUT_PIN_1 = D6; const int OUTPUT_PIN_2 = D7; const int INPUT_PIN_1 = D4; const int INPUT_PIN_2 = D5; const int ANALOG_PIN_1 = A0; // Input-only ADC pin const int ANALOG_PIN_2 = A1; // Input-only ADC pin void setup() { Serial.begin(115200); delay(1000); Serial.println("DIYables Bluetooth - ESP32 BLE Pin Control/Monitor Example"); // Initialize pins pinMode(LED_PIN, OUTPUT); pinMode(OUTPUT_PIN_1, OUTPUT); pinMode(OUTPUT_PIN_2, OUTPUT); pinMode(INPUT_PIN_1, INPUT_PULLUP); pinMode(INPUT_PIN_2, INPUT_PULLUP); // Initialize Bluetooth server with platform-specific implementation bluetoothServer.begin(); // Add digital pins app to server bluetoothServer.addApp(&bluetoothPins); // Configure which pins are accessible via Bluetooth with custom names bluetoothPins.enablePin(LED_PIN, BT_PIN_OUTPUT, "LED"); bluetoothPins.enablePin(OUTPUT_PIN_1, BT_PIN_OUTPUT, "Out1"); bluetoothPins.enablePin(OUTPUT_PIN_2, BT_PIN_OUTPUT, "Out2"); bluetoothPins.enablePin(INPUT_PIN_1, BT_PIN_INPUT, "Btn1"); bluetoothPins.enablePin(INPUT_PIN_2, BT_PIN_INPUT, "Btn2"); bluetoothPins.enablePin(ANALOG_PIN_1, BT_PIN_INPUT, "A34"); bluetoothPins.enablePin(ANALOG_PIN_2, BT_PIN_INPUT, "A35"); // Set up connection event callbacks bluetoothServer.setOnConnected([]() { Serial.println("Bluetooth connected!"); }); bluetoothServer.setOnDisconnected([]() { Serial.println("Bluetooth disconnected!"); }); // Set up callback for pin write commands bluetoothPins.onPinWrite([](int pin, int state) { digitalWrite(pin, state); Serial.print("Pin "); Serial.print(pin); Serial.print(" set to "); Serial.println(state ? "HIGH" : "LOW"); }); // Set up callback for pin read commands bluetoothPins.onPinRead([](int pin) -> int { int state; if (pin == ANALOG_PIN_1 || pin == ANALOG_PIN_2) { state = analogRead(pin); Serial.print("Analog pin "); Serial.print(pin); Serial.print(" read: "); Serial.println(state); } else { state = digitalRead(pin); Serial.print("Digital pin "); Serial.print(pin); Serial.print(" read: "); Serial.println(state ? "HIGH" : "LOW"); } return state; }); // Set up callback for pin mode changes bluetoothPins.onPinModeChange([](int pin, int mode) { pinMode(pin, mode == BT_PIN_OUTPUT ? OUTPUT : INPUT_PULLUP); Serial.print("Pin "); Serial.print(pin); Serial.print(" mode changed to "); Serial.println(mode == BT_PIN_OUTPUT ? "OUTPUT" : "INPUT"); }); Serial.println("Waiting for Bluetooth connection..."); Serial.print("Enabled pins: "); Serial.println(bluetoothPins.getEnabledPinCount()); } void loop() { bluetoothServer.loop(); static unsigned long lastInputCheck = 0; static int lastInputState1 = HIGH; static int lastInputState2 = HIGH; static int lastAnalogState1 = 0; static int lastAnalogState2 = 0; if (millis() - lastInputCheck >= 100) { lastInputCheck = millis(); int currentState1 = digitalRead(INPUT_PIN_1); if (currentState1 != lastInputState1) { lastInputState1 = currentState1; bluetoothPins.updatePinState(INPUT_PIN_1, currentState1); Serial.print("Input pin "); Serial.print(INPUT_PIN_1); Serial.print(" changed to "); Serial.println(currentState1 ? "HIGH" : "LOW"); } int currentState2 = digitalRead(INPUT_PIN_2); if (currentState2 != lastInputState2) { lastInputState2 = currentState2; bluetoothPins.updatePinState(INPUT_PIN_2, currentState2); Serial.print("Input pin "); Serial.print(INPUT_PIN_2); Serial.print(" changed to "); Serial.println(currentState2 ? "HIGH" : "LOW"); } // ESP32 has 12-bit ADC (0-4095) int currentAnalog1 = analogRead(ANALOG_PIN_1); if (abs(currentAnalog1 - lastAnalogState1) > 40) { // ~1% of 4095 lastAnalogState1 = currentAnalog1; bluetoothPins.updatePinState(ANALOG_PIN_1, currentAnalog1); Serial.print("Analog pin "); Serial.print(ANALOG_PIN_1); Serial.print(" changed to "); Serial.println(currentAnalog1); } int currentAnalog2 = analogRead(ANALOG_PIN_2); if (abs(currentAnalog2 - lastAnalogState2) > 40) { lastAnalogState2 = currentAnalog2; bluetoothPins.updatePinState(ANALOG_PIN_2, currentAnalog2); Serial.print("Analog pin "); Serial.print(ANALOG_PIN_2); Serial.print(" changed to "); Serial.println(currentAnalog2); } } 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 - Pin Control/Monitor Example Waiting for Bluetooth connection... Enabled pins: 7
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_Pins" nos resultados da busca.
  • Depois de conectar, volte à tela inicial e abra o aplicativo Digital Pins.
DIYables Bluetooth App - Tela Inicial com o Aplicativo Digital Pins

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.

  • Os pinos habilitados são listados com seus nomes e estados atuais.
  • Toque nos pinos de saída para alternar entre HIGH/LOW e observe os valores dos pinos de entrada serem atualizados em tempo real.
DIYables Bluetooth App - Tela do Digital Pins

Agora volte ao Serial Monitor na Arduino IDE. Você verá:

∞
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! Pin 13 set to HIGH Pin 13 set to LOW Digital pin 7 read: HIGH
Ln 11, Col 1
Arduino Nano ESP32 on COM15
2

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

Habilitar Pinos

// Enable pins with mode and friendly name bluetoothPins.enablePin(13, BT_PIN_OUTPUT, "LED"); bluetoothPins.enablePin(12, BT_PIN_OUTPUT, "Relay"); bluetoothPins.enablePin(7, BT_PIN_INPUT, "Button"); bluetoothPins.enablePin(A0, BT_PIN_INPUT, "Sensor"); // Check enabled pin count int count = bluetoothPins.getEnabledPinCount();

Tratar Escrita/Leitura/Modo do Pino

bluetoothPins.onPinWrite([](int pin, int state) { digitalWrite(pin, state); Serial.print("Pin "); Serial.print(pin); Serial.println(state ? " ? HIGH" : " ? LOW"); }); bluetoothPins.onPinRead([](int pin) -> int { if (pin >= A0) { return analogRead(pin); } return digitalRead(pin); }); bluetoothPins.onPinModeChange([](int pin, int mode) { pinMode(pin, mode == BT_PIN_OUTPUT ? OUTPUT : INPUT_PULLUP); });

Enviar Mudanças de Estado

// Notify the app when a pin state changes bluetoothPins.updatePinState(7, digitalRead(7)); bluetoothPins.updatePinState(A0, analogRead(A0));

Exemplos de Programação

Controle de Relé com Monitoramento de Botão

const int RELAY_PIN = 12; const int BUTTON_PIN = 7; void setup() { pinMode(RELAY_PIN, OUTPUT); pinMode(BUTTON_PIN, INPUT_PULLUP); bluetoothPins.enablePin(RELAY_PIN, BT_PIN_OUTPUT, "Relay"); bluetoothPins.enablePin(BUTTON_PIN, BT_PIN_INPUT, "Button"); bluetoothPins.onPinWrite([](int pin, int state) { digitalWrite(pin, state); }); } void loop() { bluetoothServer.loop(); // Monitor button and push changes static int lastState = HIGH; int state = digitalRead(BUTTON_PIN); if (state != lastState) { lastState = state; bluetoothPins.updatePinState(BUTTON_PIN, state); } delay(10); }

Controlador de Vários LEDs

const int LED_PINS[] = {8, 9, 10, 11, 12, 13}; const char* LED_NAMES[] = {"Red", "Green", "Blue", "Yellow", "White", "Built-in"}; const int NUM_LEDS = 6; void setup() { for (int i = 0; i < NUM_LEDS; i++) { pinMode(LED_PINS[i], OUTPUT); bluetoothPins.enablePin(LED_PINS[i], BT_PIN_OUTPUT, LED_NAMES[i]); } bluetoothPins.onPinWrite([](int pin, int state) { digitalWrite(pin, state); }); }

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 alternância do pino não funciona

  • Confirme que o pino está habilitado no modo BT_PIN_OUTPUT
  • Verifique se o callback onPinWrite está registrado
  • Verifique as conexões da ligação

3. Os pinos de entrada não são atualizados

  • Garanta que updatePinState() seja chamado quando o estado do pino mudar
  • Verifique a frequência de leitura no loop

4. Os valores analógicos não aparecem

  • Use analogRead() no callback onPinRead para pinos analógicos
  • Os pinos analógicos retornam valores na faixa de 0–1023

5. A conexão cai com frequência

  • Reduza a distância até o Arduino
  • Garanta uma alimentação USB estável

6. 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

  • Painel de controle de vários relés
  • Monitor de botões e interruptores
  • Controlador de iluminação LED
  • Painel de interruptores para automação residencial
  • Painel de entradas de sensores

Próximos Passos

Depois de concluir o exemplo do Bluetooth Digital Pins, explore:

  1. Bluetooth Slider — Controle de valores analógicos
  2. Bluetooth Monitor — Retorno de status em texto
  3. Bluetooth Table — Exibição estruturada do status dos pinos
  4. Multiple Bluetooth Apps — Combine o controle de pinos 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!