Heltec-ESP32-Serial-Nano

Project : Read Serial from Nano

Nano read : RS485

Heltec-esp32

RX2 = 16

TX2 =  17

Nano

RX=10

TX=11

heltec esp32 code : โค้ดในขณะนี้ยังเป็นโหมด  esp32- ยังไม่ได้ใช้งานโหมด LoRa  ที่จะต้องกลับไปใช้งาน  ไฟล์ OLED-LoRa-Receiver

ที่ทำงานเป็น  LoRa ตัวรับและใช้ WiFi ในการส่งไปยัง  Server

/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
//Libraries 
#include <Arduino.h>
#include <Wire.h>  
#include <WiFi.h>
/*
 * There are three serial ports on the ESP known as U0UXD, U1UXD and U2UXD.
 * 
 * U0UXD is used to communicate with the ESP32 for programming and during reset/boot.
 * U1UXD is unused and can be used for your projects. Some boards use this port for SPI Flash access though
 * U2UXD is unused and can be used for your projects.
 * 
*/

#define RXD2 16
#define TXD2 17
/////
#include <math.h>
#include <ArduinoJson.h>
//======
#include <Adafruit_Sensor.h>
#include <DHT.h>  // กรณีนี้ต้องใช้คู่กันกับ  DHT_U.h
#include <DHT_U.h>

#define DHTPIN 6 // Pin which is connected to the DHT sensor.

// Uncomment the type of sensor in use:
//#define DHTTYPE           DHT11     // DHT 11 
#define DHTTYPE           DHT22     // DHT 22 (AM2302)
//#define DHTTYPE           DHT21     // DHT 21 (AM2301)

DHT_Unified dht(DHTPIN, DHTTYPE);
uint32_t delayMS;

////
String master_state;
String led1;
String led2;
String led3;
String url;

////

char* host = "xxxxx.xxx";
char* code = "SMT2xxxx-1xxxxRIX";
char* dID = "1xx";
float dustDensity = 35;
String response ="0";
String response_c = "0";
String a ;
float temp_0 = 0;
float tempF_0 = 0;
float humid_0 = 0;
float vHumidity = 0;
float vTemperature = 0;
String data1 ;
String data2 ; // standard
String data3 ; 
String data4 ;
float data5 = 0;
float data6 = 0;
float data7 = 0;
float data8 = 0;
float data9 = 0;
float data10 = 0;
float data11 = 0;
float data12 = 0;
float data13 = 0;
float data14 = 0;
float data15 = 0;
float data16 = 0;
float data17 = 0;
float data18 = 0;
float data19 = 0;
String data20 = "0";
float temperatureC = 0;
float temperatureF = 0;
int counter = 1;
int sentcount = 0;
/////////////////////////////////////////////////////////////////////////////
void master_i2c_setup() {
  Wire.begin();  
  Serial.println("I2C Master Demonstration");
}

/////////////////////////////////////////////////////////////////////////////
// Arduino setup function.

///////////////
const char* ssid      = "Arsenxxxx_2.4G";
const char* password  = "kb75xxxxx";
const char* ssid1     = "Arsenaxxxxx_2.4G";
const char* password1 = "kb7xxxxx";
const char* ssid2     = "Arsenxxxxx_2.4G";
const char* password2 = "kb75xxxxxx";

// Helper functions to print a data value to the serial monitor.

void WiFisetup()
{
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid1);
  WiFi.begin(ssid1, password1);
  delay(1000);
  if (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Failed to connected and WiFi setup ");
    WiFi.begin(ssid2, password2);
    delay(1000);
    if (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.println("Failed to connected and WiFi setup ");
    }
    else{
       ssid = ssid2;
       password = password2;
    }
  }
  else{
  ssid = ssid1;
  password = password1;
  Serial.println("");
  Serial.println("WiFi connected OK");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP()); 
  }
}
///
void AM2302_setup() {
  dht.begin();
  Serial.println("DHTxx Unified Sensor Example");
  // Print temperature sensor details.
  sensor_t sensor;
  dht.temperature().getSensor(&sensor);
  Serial.println("------------------------------------");
  Serial.println("Temperature");
  Serial.print  ("Sensor:       "); Serial.println(sensor.name);
  Serial.print  ("Driver Ver:   "); Serial.println(sensor.version);
  Serial.print  ("Unique ID:    "); Serial.println(sensor.sensor_id);
  Serial.print  ("Max Value:    "); Serial.print(sensor.max_value); Serial.println(" *C");
  Serial.print  ("Min Value:    "); Serial.print(sensor.min_value); Serial.println(" *C");
  Serial.print  ("Resolution:   "); Serial.print(sensor.resolution); Serial.println(" *C");  
  Serial.println("------------------------------------");
  // Print humidity sensor details.
  dht.humidity().getSensor(&sensor);
  Serial.println("------------------------------------");
  Serial.println("Humidity");
  Serial.print  ("Sensor:       "); Serial.println(sensor.name);
  Serial.print  ("Driver Ver:   "); Serial.println(sensor.version);
  Serial.print  ("Unique ID:    "); Serial.println(sensor.sensor_id);
  Serial.print  ("Max Value:    "); Serial.print(sensor.max_value); Serial.println("%");
  Serial.print  ("Min Value:    "); Serial.print(sensor.min_value); Serial.println("%");
  Serial.print  ("Resolution:   "); Serial.print(sensor.resolution); Serial.println("%");  
  Serial.println("------------------------------------");
  // Set delay between sensor readings based on sensor details.
  delayMS = sensor.min_delay / 1000;
}

///
void setup()
{
  delay(10000);
  //
  pinMode(23,OUTPUT);
  digitalWrite(23,HIGH);
  pinMode(21,OUTPUT);
  digitalWrite(21,LOW);
  ///
  Serial.begin(9600);
  Serial2.begin(9600, SERIAL_8N1, RXD2, TXD2); // original 8N1
  Serial.println("Serial Txd is on pin: "+String(TX));
  Serial.println("Serial Rxd is on pin: "+String(RX));

///
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFisetup();
  //WiFi.begin(ssid1, password1);
  delay(1000);
  if (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Failed connected setup ");
  }
  else{
  Serial.println("");
  Serial.println("WiFi OK connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  // We start by connecting to a WiFi network
  }
}

int value = 0;

void serverloop()
{
    delay(1000);
     ++value;
   
    data1 = String(data1);
    data2 = String(data2);
    //AM2302_loop();
    //data3 = temp_0;
    //data4 = humid_0; 
    Serial.print("data1 rain mm = ");Serial.println(data1);
    Serial.print("data2 soil    = ");Serial.println(data2);
    Serial.print("data3 temp    = ");Serial.println(data3);
    Serial.print("data4 humid   = ");Serial.println(data4);
    
    Serial.print("connecting to ");
    Serial.println(host);

    // Use WiFiClient class to create TCP connections
    WiFiClient client;
    const int httpPort = 80;
    if (!client.connect(host, httpPort)) {
        Serial.println("connection failed");
        return;
    }

    // We now create a URI for the request
     String url = "/api/insertData?device_id=" + String(dID)+"&code="+String(code)+"&data1=" +String(data1) +"&data2="
   + String(data2)+"&data3=" +String(data3)+"&data4=" +String(data4)+"&data5=" +String(data5)
   +"&data6=" +String(data6)+"&data7=" +String(data7)+"&data8=" +String(data8)+"&data9=" +String(data9)
   +"&data10=" +String(data10)+"&data11=" +String(data11)+"&data12=" +String(data12)+"&data13=" +String(data13)
   +"&data14=" +String(data14)+"&data15=" +String(data15)+"&data16=" +String(data16)+"&data17=" +String(data17)
   +"&data18=" +String(data18)+"&data19=" +String(data19)+"&data20=" +String(data20);   
 
    Serial.print("Requesting URL: ");
    Serial.println(url);

    // This will send the request to the server
    client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                 "Host: " + host + "\r\n" +
                 "Connection: close\r\n\r\n");
    //unsigned long timeout = millis();
    delay(1000);
    
    while (client.available() == 0) {
            Serial.println(">>> Client Timeout !");
            client.stop();
            return;
           }
    
     

    // Read all the lines of the reply from server and print them to Serial
    while(client.available()) {
        String line = client.readStringUntil('\r');
        //Serial.print(line);  ถอดคอมเม้น? ออก เพื่อดูการตอบสนองจาก Server
        
    }
    
    Serial.println();
    Serial.println("endloop server ");
    delay(1000);
}
//====
void loop() 
{  
    if (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.println("Failed to connected and WiFi setup ");
        WiFisetup();  
    }
  serial_loop();
  read_master_status_FromServer();
  serverloop();  
  data1 = "";
  data2 = "";
} 

void serial_loop()
{
Serial.println("Please wait Serial..");
/// #1
  while (a == "") {
    Serial2.print("Input1"); // ส่งหัวข้อคำถาม ว่า Question1 ไปยัง Arduino
    a = Serial2.readString();  // อ่าน Serial และนำไปเก็บในตัวแปร A
    delay(100);
    Serial.print(".");
  }
  Serial.print(" Answer 1 ");Serial.println(a);
  data1 = String(a);
  delay(1000);
  a="";
///#2
  while (a == "") {
    Serial2.print("Input2"); // ส่งหัวข้อคำถาม ว่า Question1 ไปยัง Arduino
    a = Serial2.readString();  // อ่าน Serial และนำไปเก็บในตัวแปร A
    delay(100);
    Serial.print(".");
  }
  Serial.print(" Answer 2 ");Serial.println(a);
  data2=String(a);
  a="";
///#3
    while (a == "") {
    Serial2.print("Input3"); // ส่งหัวข้อคำถาม ว่า Question1 ไปยัง Arduino
    a = Serial2.readString();  // อ่าน Serial และนำไปเก็บในตัวแปร A
    delay(100);
    Serial.print(".");
  }
  Serial.print(" Answer 3 ");Serial.println(a);
  data3 = String(a);
  delay(1000);
  a="";
///#4
  while (a == "") {
    Serial2.print("Input4"); // ส่งหัวข้อคำถาม ว่า Question1 ไปยัง Arduino
    a = Serial2.readString();  // อ่าน Serial และนำไปเก็บในตัวแปร A
    delay(100);
    Serial.print(".");
  }
  Serial.print(" Answer 4 ");Serial.println(a);
  data4=String(a);
  a="";
}
void read_master_status_FromServer()
{
 Serial.print("Read control command from Server ... connecting to ");
 Serial.println(host);

WiFiClient client;
if (client.connect(host, 80)) 
  {
    Serial.println("reconnecting...");
     
         //url = "/api/readLast/IOT_API_KEY_BY_ADMIN/136/PTLCB-2020";
         url = "/api/readLast/IOT_API_KEY_BY_ADMIN/"+ String(dID)+"/"+String(code);
         Serial.print("Requesting URL: ");
         Serial.println(url);
    
         client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                 "Host: " + host + "\r\n" + 
                 "Connection: close\r\n\r\n");
         delay(2000);
         
         String section="header";
         
         while(client.available())
         {
            //Serial.println("Connection available ");
            String line = client.readStringUntil('\r');
            //Serial.print(line);
            // we’ll parse the HTML body here
            if (section=="header") 
              { // headers..
           
                  if (line=="\n") 
                    { // skips the empty space at the beginning 
                      section="json";
                    }
              }
            else if (section=="json") 
              {  // print the good stuff
                  section="ignore";
                  String result = line.substring(1);
                             
                  // Parse JSON
                  int size = result.length() + 1;
                  char json[size];
                  result.toCharArray(json, size);
                  StaticJsonBuffer<1500> jsonBuffer;
                  JsonObject& json_parsed = jsonBuffer.parseObject(json);
                  if (!json_parsed.success())
                    {
                      Serial.println("parseObject() failed");
                      return;
                    }
                      Serial.println("parseObject() OK ...");
                      ///Serial.println(result); // show all json found
                      //String led = json_parsed["led"][0]["status"];
                      String master_state = json_parsed["result"]["deviceData"]["master_status"];
                      String led1 = json_parsed["result"]["deviceData"]["data18"];
                      String led2 = json_parsed["result"]["deviceData"]["data19"];
                      String led3 = json_parsed["result"]["deviceData"]["data20"];
                      data20=String(master_state);
                      // string led = json_parsed["table name""][array number]["value of field"]
                      Serial.print("Master state = ");
                      Serial.println(master_state);
                      if (master_state == "0")
                      { digitalWrite(23,LOW);
                        digitalWrite(21,HIGH);
                      }
                      else
                      {
                        digitalWrite(23,HIGH);
                        digitalWrite(21,LOW);
                      }
                      Serial.println(led1);
                      Serial.println(led2);
                      Serial.println(led3);
                   
            
             } // if found json
          } // end while client available
          
    }
    // end if host connected
   
    else 
    {
      // if you couldn't make a connection:
      ///Serial.println("connection failed read server 1");
    }
}

Nano Code

#include <EEPROM.h>
#include <SoftwareSerial.h>
SoftwareSerial chat(10, 11); // RX, TX
////////  AM2302
#include <math.h>
#include <Adafruit_Sensor.h>
#include <DHT.h>  // กรณีนี้ต้องใช้คู่กันกับ  DHT_U.h
#include <DHT_U.h>

#define DHTPIN 6 // Pin which is connected to the DHT sensor.

// Uncomment the type of sensor in use:
//#define DHTTYPE           DHT11     // DHT 11 
#define DHTTYPE           DHT22     // DHT 22 (AM2302)
//#define DHTTYPE           DHT21     // DHT 21 (AM2301)

DHT_Unified dht(DHTPIN, DHTTYPE);
uint32_t delayMS;
////////

int i;
int sensorValue;
float rainmm ;
float dustDensity = 35;
String response ="0";
String response_c = "0";
String a ;
float temp_0 = 0;
float tempF_0 = 0;
float humid_0 = 0;
float vHumidity = 0;
float vTemperature = 0;
String data1 ;
String data2 ; // standard
float data3 = 0; 
float data4 = 0;
float data5 = 0;
float data6 = 0;
float data7 = 0;
float data8 = 0;
float data9 = 0;
float data10 = 0;
float data11 = 0;
float data12 = 0;
float data13 = 0;
float data14 = 0;
float data15 = 0;
float data16 = 0;
float data17 = 0;
float data18 = 0;
float data19 = 0;
float data20 = 0;
float temperatureC = 0;
float temperatureF = 0;
int counter = 1;
int sentcount = 0;
//////////////////////////////
void AM2302_setup() {
  dht.begin();
  Serial.println("DHTxx Unified Sensor Example");
  // Print temperature sensor details.
  sensor_t sensor;
  dht.temperature().getSensor(&sensor);
  Serial.println("------------------------------------");
  Serial.println("Temperature");
  Serial.print  ("Sensor:       "); Serial.println(sensor.name);
  Serial.print  ("Driver Ver:   "); Serial.println(sensor.version);
  Serial.print  ("Unique ID:    "); Serial.println(sensor.sensor_id);
  Serial.print  ("Max Value:    "); Serial.print(sensor.max_value); Serial.println(" *C");
  Serial.print  ("Min Value:    "); Serial.print(sensor.min_value); Serial.println(" *C");
  Serial.print  ("Resolution:   "); Serial.print(sensor.resolution); Serial.println(" *C");  
  Serial.println("------------------------------------");
  // Print humidity sensor details.
  dht.humidity().getSensor(&sensor);
  Serial.println("------------------------------------");
  Serial.println("Humidity");
  Serial.print  ("Sensor:       "); Serial.println(sensor.name);
  Serial.print  ("Driver Ver:   "); Serial.println(sensor.version);
  Serial.print  ("Unique ID:    "); Serial.println(sensor.sensor_id);
  Serial.print  ("Max Value:    "); Serial.print(sensor.max_value); Serial.println("%");
  Serial.print  ("Min Value:    "); Serial.print(sensor.min_value); Serial.println("%");
  Serial.print  ("Resolution:   "); Serial.print(sensor.resolution); Serial.println("%");  
  Serial.println("------------------------------------");
  // Set delay between sensor readings based on sensor details.
  delayMS = sensor.min_delay / 1000;
}


void setup()  {
  Serial.begin(9600);
  chat.begin(9600);
}

void loop() {
  AM2302_loop();
  input1_loop();
  //input2_loop();
  if (chat.readString()){
     // chat.print(1);
     if(chat.readString()== "Input1"){ //มีการถามคำถาม Question1 ส่งข้อมูลตัวแปร a ออกไป
      chat.print(String(sensorValue));
     }
     if(chat.readString()== "Input2"){ //มีการถามคำถาม Question2 ส่งข้อมูลตัวแปร b ออกไป
     chat.print(String(rainmm));
     }
     if(chat.readString()== "Input3"){ //มีการถามคำถาม Question1 ส่งข้อมูลตัวแปร a ออกไป
      chat.print(String(data3));
     }
     if(chat.readString()== "Input4"){ //มีการถามคำถาม Question2 ส่งข้อมูลตัวแปร b ออกไป
     chat.print(String(data4));
     }     
     Serial.print("Send = ");
     Serial.println(i);
  }

  i++;
  delay(1000);

}
void input1_loop() {  
  // read the value from the sensor:
  sensorValue = analogRead(A0);
  //Serial.print(" Analog read := ");Serial.println(sensorValue);
  if (sensorValue > 580) {
    rainmm = 80.437-0.0977*sensorValue;
  }
  else {
    if (sensorValue > 509) {
      rainmm = 443.6-0.717*sensorValue;
    }
    else
    {
      if (sensorValue > 466) {
        rainmm = 903.74-1.6059*sensorValue;
      }
      else{
      rainmm = 770.06-1.3314*sensorValue;
      }
    }
  }
  delay(1000);
  //answer=String(255);
  Serial.print("A0 signal : ");Serial.println(sensorValue);
  Serial.print("Rain mm : ");Serial.println(rainmm);
}
void input2_loop() {  
  // read the value from the sensor:
  sensorValue = analogRead(A0);
  //Serial.print(" Analog read := ");Serial.println(sensorValue);
  if (sensorValue > 580) {
    rainmm = 80.437-0.0977*sensorValue;
  }
  else {
    if (sensorValue > 509) {
      rainmm = 443.6-0.717*sensorValue;
    }
    else
    {
      if (sensorValue > 466) {
        rainmm = 903.74-1.6059*sensorValue;
      }
      else{
      rainmm = 770.06-1.3314*sensorValue;
      }
    }
  }
  delay(1000);
  //answer=String(255);  
}
void AM2302_loop() {
  // Delay between measurements.
  delay(delayMS);
  // Get temperature event and print its value.
  sensors_event_t event;  
  dht.temperature().getEvent(&event);
  if (isnan(event.temperature)) {
    Serial.println("Error reading temperature!");
  }
  else {
    Serial.print("Temperature: ");
    Serial.print(event.temperature);
    Serial.println(" *C");
    temp_0 = event.temperature;
    data3 = temp_0;
  }
  // Get humidity event and print its value.
  dht.humidity().getEvent(&event);
  if (isnan(event.relative_humidity)) {
    Serial.println("Error reading humidity!");
  }
  else {
    Serial.print("Humidity: ");
    Serial.print(event.relative_humidity);
    Serial.println("%");
    humid_0 = event.relative_humidity;
    data4 = humid_0;
  }
  
}

การทำงาน  Heltec  ส่งคำขอข้อมูล ตามลำดับ  และ Nano ส่งข้อมูลกลับ

การนำไปใช้งาน

ใช้  Nano  run  Modebuslibrary อ่านค่า  RS485 และเก็บเป็นตัวแปลนำส่ง   Heltec  ทาง  Serial  ก่อนนำส่งต่อไปตามลำดับ

สิ่งที่ควรดำเนินการต่อไปคือ ให้  Heltec run Modbuslibrary โดยตรง

16,741 total views, 7 views today