본문 바로가기
아두이노/아두이노+ESP32

아두이노 ESP32 - USB로 Android와 데이터 주고받기, 안드로이드폰으로 간이 온도 습도 측정기 만들기

by 감자최고 2022. 7. 2.
  • ESP32 보드에 USB OTG로 전원 공급하고, ESP32 에 연결된 센서의 값을 안드로이드 화면에 출력 해보려고 함
  • 궁극적으로 안드로이드 폰을 간이 측정기로 만들어보려고 함
  • https://youtu.be/zk0xY88l6Rc 를 레퍼런스로 하려고 함
    • Android Studio 설치하고,
    • Flutter 설치하고,
    • 레퍼런스 코드를 가져왔는데 현재 Flutter 버전이 맞지 않아 빌드가 안됨
    • 코드 수정을 위해 Flutter 와 Dart 공부 중(2022/06/23)
    • 주말 포함 틈틈히 Flutter / Dart 공부해봤지만 빌드 에러 잡는데 무한의 시간이 소요될 것 같아,
    • 참고로한 유툽에서 참고한 github 에 들어가보니 main.dart 가 업데이트되서, 최신으로 엎어치고 보니,
    • https://github.com/altera2015/usbserial/blob/master/example/lib/main.dart
    • 드디어 뭔가 보이기 시작 조금 더 공부 해봐야할 것 같습니다.(6/26)
    • 주말에 다시 확인해보니 Arduino 에 프로그램을 제대로 올려서 보니
      아래 처럼 주기적인 출력과 안드로이드에서 보낸 스트링을 받아서 출력도 잘 됩니다.

 

사용된 아두이노 소스 (시리얼 입출력+DH11 센서+WiFi Simple Server)

아래 "더보기" 클릭해주세요

더보기
// Example testing sketch for various DHT humidity/temperature sensors
// Written by ladyada, public domain

#include "DHT.h"

아래 DHT11 의 센서 read 핀 값은 반드시 구성에 맞게 수정 필요
#define DHTPIN 32     // what digital pin we're connected to

// Uncomment whatever type you're using!
#define DHTTYPE DHT11   // DHT 11
//#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

// Connect pin 1 (on the left) of the sensor to +5V
// NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
// to 3.3V instead of 5V!
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

// Initialize DHT sensor.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors.  This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.
DHT dht(DHTPIN, DHTTYPE);
//+++++++++++++++++++++++++++++++++++++++++ WIFI Simple Server
#include <WiFi.h>
const char* ssid     = your Wifi AP name
const char* password = your Wifi AP password

WiFiServer server(80);
#define DOUTPIN 2
String serialIncomingString;
//-----------------------------------------
void setup() {
  Serial.begin(115200);
  Serial.println("DHTxx test!");

  dht.begin();
//+++++++++++++++++++++++++++++++++++++++++ WIFI Simple Server
    pinMode(DOUTPIN, OUTPUT);      // set the LED pin mode

    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }

    Serial.println("");
    Serial.println("WiFi connected.");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
    
    server.begin();
//-----------------------------------------
}

//+++++++++++++++++++++++++++++++++++++++++ WIFI Simple Server
int value = 0;

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

  if (client) {                             // if you get a client,
//+++++++++++++++++++++++++++++++++++++++++ DHT11 Sensor
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
//-----------------------------------------

    Serial.println("New Client.");           // print a message out 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
        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)
            // 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();

            // the content of the HTTP response follows the header:
            client.print("Click <a href=\"/H\">here</a> to turn the LED on pin 5 on.<br>");
            client.print("Click <a href=\"/L\">here</a> to turn the LED on pin 5 off.<br>");

//+++++++++++++++++++++++++++++++++++++++++ DHT11 Sensor
  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  client.print("Humidity: ");
  client.print(h);
  client.print(" %\t");
  client.print("Temperature: ");
  client.print(t);
//-----------------------------------------

            // 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
        }

        // Check to see if the client request was "GET /H" or "GET /L":
        if (currentLine.endsWith("GET /H")) {
          digitalWrite(DOUTPIN, HIGH);               // GET /H turns the LED on
        }
        if (currentLine.endsWith("GET /L")) {
          digitalWrite(DOUTPIN, LOW);                // GET /L turns the LED off
        }
      }
    }
    // close the connection:
    client.stop();
    Serial.println("\r\nClient Disconnected.");
  }
  else if(Serial.available() > 0)
  {
    serialIncomingString= Serial.readString();
    Serial.print("Serial Rcvd: ");
    Serial.print(serialIncomingString);
  }
  else
  {
//+++++++++++++++++++++++++++++++++++++++++ DHT11 Sensor
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
//-----------------------------------------
//+++++++++++++++++++++++++++++++++++++++++ DHT11 Sensor
  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print("\r\n");
//-----------------------------------------   
    delay(1000);
  }
}
//-----------------------------------------

댓글