1_bluetooth


Android APP Production

https://app.wxbit.com/
Copy the code

The code address

https://github.com/modi12jin/arduino-ESP32-Tutorial
Copy the code

1.1_ Bluetooth light

// Load libraries
#include "BluetoothSerial.h"

// Check if Bluetooth configs are enabled
#if! defined(CONFIG_BT_ENABLED) || ! defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

// Bluetooth Serial object
BluetoothSerial SerialBT;

// GPIO where LED is connected to
const int pinout =4;

char inputdata = 0;  //Variable for storing received data


void setup(a) {
  pinMode(pinout, OUTPUT);
  Serial.begin(115200);
  // Bluetooth device name
  SerialBT.begin("ESP32");
  Serial.println("The device started, now you can pair it with bluetooth!");
}

void loop(a) {
    if(SerialBT.available() > 0)      // Send data only when you receive data:
   {
      inputdata = SerialBT.read();        //Read the incoming data & store into data
           
      if(inputdata == '1') 
      {
         digitalWrite(pinout, HIGH); 
         //SerialBT.print("LED ON\n");
      }
         
      else if(inputdata == '0')  
      {      
         digitalWrite(pinout, LOW);  
         //SerialBT.print("LED OFF\n");  }}}Copy the code

1.2 bluetooth BME280 _

#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include "BluetoothSerial.h"

// Check if Bluetooth configs are enabled
#if! defined(CONFIG_BT_ENABLED) || ! defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

// Bluetooth Serial object
BluetoothSerial SerialBT;

#define SEALEVELPRESSURE_HPA (1013.25)

Adafruit_BME280  bme280;

char inputdata = 0; 

void setup(a) {
  Serial.begin(115200);

   // Initialize the BME280 sensor
  if( bme280.begin(0x76) = =0 )
  {  // Connection error or device address error!
    while(1);                 // stay here
  }

  // Bluetooth device name
  SerialBT.begin("ESP32");
  Serial.println("The device started, now you can pair it with bluetooth!");

}

void loop(a) {
    // Read temperature, humidity, air pressure, altitude from BME280 sensor
  float temp = bme280.readTemperature();    / / temperature
  float humi = bme280.readHumidity();       / / humidity
  float pres = bme280.readPressure();       / / pressure
  float altitude =bme280.readAltitude(SEALEVELPRESSURE_HPA); / / altitude

    if(SerialBT.available() > 0)     
   {
      inputdata = SerialBT.read();
           
       if(inputdata == '0') 
      {
         SerialBT.print(
          String("Temperature.")+ temp+String("Celsius")
         +String("The humidity.")+humi+String("%")
         +String(Atmospheric pressure:)+pres+String("pa")
         +String("Altitude :")+altitude+String("米")); }}}Copy the code

2_BLE


2.1 _ble lamps

#include<Arduino.h>
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>

BLECharacteristic *pCharacteristic;
bool deviceConnected = false;
float txValue = 0;
const int LED = 2; 

#define SERVICE_UUID           "6E400001-B5A3-F393-E0A9-E50E24DCCA9E" // UART service UUID
#define CHARACTERISTIC_UUID_RX "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
#define CHARACTERISTIC_UUID_TX "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"

class MyServerCallbacks: public BLEServerCallbacks {
    void onConnect(BLEServer* pServer) {
      deviceConnected = true;
    };

    void onDisconnect(BLEServer* pServer) {
      deviceConnected = false; }};class MyCallbacks: public BLECharacteristicCallbacks {
    void onWrite(BLECharacteristic *pCharacteristic) {
      std: :string rxValue = pCharacteristic->getValue();

      if (rxValue.length() > 0) {
        Serial.println("* * * * * * * * *");
        Serial.print("Received Value: ");

        for (int i = 0; i < rxValue.length(); i++) {
          Serial.print(rxValue[i]);
        }

        Serial.println();

        // Do stuff based on the command received from the app
        if (rxValue.find("1") != - 1) { 
          Serial.print("Turning ON!");
          digitalWrite(LED, HIGH);
        }
        else if (rxValue.find("0") != - 1) {
          Serial.print("Turning OFF!");
          digitalWrite(LED, LOW);
        }

        Serial.println();
        Serial.println("* * * * * * * * *"); }}};void setup(a) {
  Serial.begin(115200);

  pinMode(LED, OUTPUT);

  // Create the BLE Device
  BLEDevice::init("ESP32 UART Test"); // Give it a name

  // Create the BLE Server
  BLEServer *pServer = BLEDevice::createServer();
  pServer->setCallbacks(new MyServerCallbacks());

  // Create the BLE Service
  BLEService *pService = pServer->createService(SERVICE_UUID);

  // Create a BLE Characteristic
  pCharacteristic = pService->createCharacteristic(
                      CHARACTERISTIC_UUID_TX,
                      BLECharacteristic::PROPERTY_NOTIFY
                    );
                      
  pCharacteristic->addDescriptor(new BLE2902());

  BLECharacteristic *pCharacteristic = pService->createCharacteristic(
                                         CHARACTERISTIC_UUID_RX,
                                         BLECharacteristic::PROPERTY_WRITE
                                       );

  pCharacteristic->setCallbacks(new MyCallbacks());

  // Start the service
  pService->start();

  // Start advertising
  pServer->getAdvertising()->start();
  Serial.println("Waiting a client connection to notify...");
}

void loop(a) {}Copy the code

2.1 _ble_BME280

#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>

#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

BLECharacteristic *pCharacteristic;

bool deviceConnected = false;

# define SEALEVELPRESSURE_HPA (1013.25)Adafruit_BME280 bme280; / / the link - o seguinte se quiser gerar seus proprios UUIDs: / / https://www.uuidgenerator.net/#define SERVICE_UUID "6E400001-B5A3-F393-E0A9-E50E24DCCA9E" // UART service UUID
#define CHARACTERISTIC_UUID_RX "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
#define DHTDATA_CHAR_UUID "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"


class MyServerCallbacks: public BLEServerCallbacks {
    void onConnect(BLEServer* pServer) {
      deviceConnected = true;
    };

    void onDisconnect(BLEServer* pServer) {
      deviceConnected = false; }}; class MyCallbacks: public BLECharacteristicCallbacks { void onWrite(BLECharacteristic *pCharacteristic) { std::string rxValue = pCharacteristic->getValue(); Serial.println(rxValue[0]);if (rxValue.length() > 0) {
        Serial.println("* * * * * * * * *");
        Serial.print("Received Value: ");

        for (int i = 0; i < rxValue.length(); i++) {
          Serial.print(rxValue[i]);
        }
        Serial.println();
        Serial.println("* * * * * * * * *");
      }

      // Processa o caracter recebido do aplicativo. Se for A acende o LED. B apaga o LED
      if (rxValue.find("1") != -1) { 
        Serial.println("Turning ON!");
      }
      else if (rxValue.find("0") != -1) {
        Serial.println("Turning OFF!"); }}}; voidsetup() { Serial.begin(9600); // Initialize the BME280 sensorif(bme280.begin(0x76) == 0) {// Connection error or device address error!while(1);                 // stay here
  }

  // Create the BLE Device
  BLEDevice::init("ESP32 BME280"); // Give it a name

  // Configura o dispositivo como Servidor BLE
  BLEServer *pServer = BLEDevice::createServer();
  pServer->setCallbacks(new MyServerCallbacks());

  // Cria o servico UART
  BLEService *pService = pServer->createService(SERVICE_UUID);

  // Cria uma Característica BLE para envio dos dados
  pCharacteristic = pService->createCharacteristic(
                      DHTDATA_CHAR_UUID,
                      BLECharacteristic::PROPERTY_NOTIFY
                    );
                      
  pCharacteristic->addDescriptor(new BLE2902());

  // cria uma característica BLE para recebimento dos dados
  BLECharacteristic *pCharacteristic = pService->createCharacteristic(
                                         CHARACTERISTIC_UUID_RX,
                                         BLECharacteristic::PROPERTY_WRITE
                                       );

  pCharacteristic->setCallbacks(new MyCallbacks());

  // Inicia o serviço
  pService->start();

  // Inicia a descoberta do ESP32
  pServer->getAdvertising()->start();
  Serial.println("Esperando um cliente se conectar...");
}

void loop() {
  ifInt temp = BME280. ReadTemperature (); Int humi = bme280. ReadHumidity (); // humidity int pres = bme280.readPressure(); Int altitude =bme280.readAltitude(SEALEVELPRESSURE_HPA); Testa se Retorno e valido, Caso Contrario algo esta errado.if (isnan(temp) || isnan(humi) || isnan(pres) || isnan(altitude)) 
    {
      Serial.println("Failed to read from BME280");
    }
    else 
    {
      Serial.print("Umidade: ");
      Serial.print(humi);
      Serial.print("%");
      Serial.print("Temperatura: ");
      Serial.print(temp);
      Serial.println(" *C");
      Serial.print("Pressure: ");
      Serial.print(pres);
      Serial.println("hpa");
      Serial.print("Altitude: ");
      Serial.print(altitude);
      Serial.println("m");
    }
    
    char humidityString[2];
    char temperatureString[2];
    char presString[2];
    char altitudeString[2];
    dtostrf(humi, 1, 2, humidityString);
    dtostrf(temp, 1, 2, temperatureString);
    dtostrf(pres, 1, 2, presString);
    dtostrf(altitude, 1, 2, altitudeString);

    char dhtDataString[16];
    sprintf(dhtDataString, "%d,%d,%d,%d", temp, humi,pres,altitude);

    pCharacteristic->setValue(dhtDataString);
    
    pCharacteristic->notify(); // Envia o valor para o aplicativo!
    Serial.print("*** Dado enviado: ");
    Serial.print(dhtDataString);
    Serial.println("* * *");
  }
  delay(1000);
}
Copy the code

3_WIFI


3.1 _WIFI lamps

Set the WIFI name and password

/********* Rui Santos Complete project details at http://randomnerdtutorials.com *********/

// Load Wi-Fi library
#include <WiFi.h>

// Replace with your network credentials
const char* ssid     = "";
const char* password = "";

// Set web server port number to 80
WiFiServer server(80);

// Variable to store the HTTP request
String header;

// Auxiliar variables to store the current output state
String output26State = "off";
String output27State = "off";

// Assign output variables to GPIO pins
const int output26 = 26;
const int output27 = 27;

void setup(a) {
  Serial.begin(115200);
  // Initialize the output variables as outputs
  pinMode(output26, OUTPUT);
  pinMode(output27, OUTPUT);
  // Set outputs to LOW
  digitalWrite(output26, LOW);
  digitalWrite(output27, LOW);

  // Connect to Wi-Fi network with SSID and password
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while(WiFi.status() ! = WL_CONNECTED) { delay(500);
    Serial.print(".");
  }
  // Print local IP address and start web server
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  server.begin();
}

void loop(a){
  WiFiClient client = server.available();   // Listen for incoming clients

  if (client) {                             // If a new client connects,
    Serial.println("New Client.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected()) {            // loop while the client's connected
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP / 1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();
            
            // turns the GPIOs on and off
            if (header.indexOf("GET /26/on") > =0) {
              Serial.println("GPIO 26 on");
              output26State = "on";
              digitalWrite(output26, HIGH);
            } else if (header.indexOf("GET /26/off") > =0) {
              Serial.println("GPIO 26 off");
              output26State = "off";
              digitalWrite(output26, LOW);
            } else if (header.indexOf("GET /27/on") > =0) {
              Serial.println("GPIO 27 on");
              output27State = "on";
              digitalWrite(output27, HIGH);
            } else if (header.indexOf("GET /27/off") > =0) {
              Serial.println("GPIO 27 off");
              output27State = "off";
              digitalWrite(output27, LOW);
            }
            
            // Display the HTML web page
            client.println("
      ");
            client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.println("<link rel=\"icon\" href=\"data:,\">");
            // CSS to style the on/off buttons 
            // Feel free to change the background-color and font-size attributes to fit your preferences
            client.println(");
            client.println(".button { background-color: #4CAF50; border: none; color: white; padding: 16px 40px;");
            client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer; }");
            client.println(".button2 {background-color: #555555; }");
            
            // Web Page Heading
            client.println("<body><h1>ESP32 Web Server</h1>");
            
            // Display current state, and ON/OFF buttons for GPIO 26  
            client.println("<p>GPIO 26 - State " + output26State + "</p>");
            // If the output26State is off, it displays the ON button       
            if (output26State=="off") {
              client.println("<p><a href=\"/26/on\"><button class=\"button\">ON</button></a></p>");
            } else {
              client.println("<p><a href=\"/26/off\"><button class=\"button button2\">OFF</button></a></p>");
            } 
               
            // Display current state, and ON/OFF buttons for GPIO 27  
            client.println("<p>GPIO 27 - State " + output27State + "</p>");
            // If the output27State is off, it displays the ON button       
            if (output27State=="off") {
              client.println("<p><a href=\"/27/on\"><button class=\"button\">ON</button></a></p>");
            } else {
              client.println("<p><a href=\"/27/off\"><button class=\"button button2\">OFF</button></a></p>");
            }
            client.println("</body></html>");
            
            // The HTTP response ends with another blank line
            client.println();
            // Break out of the while loop
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = ""; }}else if(c ! ='\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine}}}// Clear the header variable
    header = "";
    // Close the connection
    client.stop();
    Serial.println("Client disconnected.");
    Serial.println(""); }}Copy the code

3.2 _WIFI_BME280

// Load Wi-Fi library
#include <WiFi.h>
#include <Wire.h>
#include <Adafruit_BME280.h>
#include <Adafruit_Sensor.h>

//uncomment the following lines if you're using SPI /*#include 
      
        #define BME_SCK 18 #define BME_MISO 19 #define BME_MOSI 23 #define BME_CS 5*/ #define SEALEVELPRESSURE_HPA (1013.25) Adafruit_BME280 bme; // I2C //Adafruit_BME280 bme(BME_CS); // hardware SPI //Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI // Replace with your network credentials const char* ssid = ""; const char* password = ""; // Set web server port number to 80 WiFiServer server(80); // Variable to store the HTTP request String header; void setup() { Serial.begin(115200); bool status; // default settings // (you can also pass in a Wire library object like &Wire2) //status = bme.begin(); if (! bme.begin(0x76)) { Serial.println("Could not find a valid BME280 sensor, check wiring!" ); while (1); } // Connect to Wi-Fi network with SSID and password Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() ! = WL_CONNECTED) { delay(500); Serial.print("."); } // Print local IP address and start web server Serial.println(""); Serial.println("WiFi connected."); Serial.println("IP address: "); Serial.println(WiFi.localIP()); server.begin(); } void loop(){ WiFiClient client = server.available(); // Listen for incoming clients if (client) { // If a new client connects, Serial.println("New Client."); // print a message out in the serial port String currentLine = ""; // make a String to hold incoming data from the client while (client.connected()) { // loop while the client'
      s connected
      if (client.available()) {             // if there's bytes to read from the client, char c = client.read(); // read a byte, then Serial.write(c); // print it out the serial monitor header += c; if (c == '\n') { // if the byte is a newline character // if the current line is blank, you got two newline characters in a row. // that's the end of the client HTTP request, so send a response:
          if(currentline.length () == 0) {// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK) // content-type so the client knows what's coming, then a blank line: client.println("HTTP/1.1 200 OK"); client.println("Content-type:text/html"); client.println("Connection: close"); client.println(); // Display the HTML web page client.println("
      "); client.println("
      "); client.println("
      "); // CSS to style the table client.println("

ESP32 with BME280

"); client.println(" "); client.println(" "); client.println(" "); client.println(" "); client.println(" "); client.println(" "); client.println(""); // The HTTP response ends with another blank line client.println(); // Break out of the while loop break; } else { // if you got a newline, then clear currentLine currentLine = ""; } } else if (c ! = '
MEASUREMENT VALUE
Temp. Celsius "); client.println(bme.readTemperature()); client.println(" *C
Temp. Fahrenheit "); Client.println (1.8 * bme.readTemperature() + 32); client.println(" *F
Pressure "); Client. Println (bme) readPressure () / 100.0 F); client.println(" hPa
Approx. Altitude "); client.println(bme.readAltitude(SEALEVELPRESSURE_HPA)); client.println(" m
Humidity "); client.println(bme.readHumidity()); client.println(" %
\r') { // if you got anything else but a carriage return character, currentLine += c; // add it to the end of the currentLine } } } // Clear the header variable header = ""; // Close the connection client.stop(); Serial.println("Client disconnected."); Serial.println(""); }}Copy the code