Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

// Developer : Asst.Prof.Dr.

Kittipong Suwannaraj ,Thailand


// ESPsendData2Sheet (Google App Scripts)
===================
function doGet(e) {
Logger.log( JSON.stringify(e) );
var result = 'Ok';
if (e.parameter == 'undefined') {
result = 'No Parameters';
}
else {
var sheet_id = 'YourGoogleSheetID'; // Spreadsheet ID
var sheet = SpreadsheetApp.openById(sheet_id).getActiveSheet();
var newRow = sheet.getLastRow() + 1;
var rowData = [];
var Curr_Date = new Date();
rowData[0] = Curr_Date; // Date in column A
var Curr_Time = Utilities.formatDate(Curr_Date, "Asia/Bangkok", 'HH:mm:ss');
rowData[1] = Curr_Time; // Time in column B
for (var param in e.parameter) {
Logger.log('In for loop, param=' + param);
var value = stripQuotes(e.parameter[param]);
Logger.log(param + ':' + e.parameter[param]);
switch (param) {
case 'temp':
rowData[2] = value; // Temperature in column C
result = 'temp Written on column C';
break;
case 'humi':
rowData[3] = value; // Temperature in column D
result = 'humidity Written on column D';
break;
}
}
Logger.log(JSON.stringify(rowData));
var newRange = sheet.getRange(newRow, 1, 1, rowData.length);
newRange.setValues([rowData]);
}
return ContentService.createTextOutput(result);
}
function stripQuotes( value ) {
return value.replace(/^["']|['"]$/g, "");
}
Arduino IDE Code (.ino)
====================

//----------------------------------------Include the NodeMCU ESP8266 Library

#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include "DHT.h"
//----------------------------------------

#define DHTTYPE DHT11 // DHT 11


//#define DHTTYPE DHT21 // DHT 21 (AM2301)
//#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321

const int DHTPin = 5;


String t;
#define ON_Board_LED 2 //--> Defining an On Board LED, used for indicators when the pro
cess of connecting to a wifi router

//----------------------------------------SSID dan Password wifi mu gan.


const char* ssid = "YourSSID"; //--> Nama Wifi / SSID.
const char* password = "YourPassword"; //--> Password wifi .
//----------------------------------------

//----------------------------------------Host & httpsPort


const char* host = "script.google.com";
const int httpsPort = 443;
//----------------------------------------
// Initialize DHT sensor.
DHT dht(DHTPin, DHTTYPE);

WiFiClientSecure client; //--> Create a WiFiClientSecure object.

// Timers auxiliar variables


long now = millis();
long lastMeasure = 0;

String GAS_ID = "Your Google App Script ID "; //--> spreadsheet script ID

//============================================ void setup


void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
delay(500);
dht.begin();

WiFi.begin(ssid, password); //--> Connect to your WiFi router


Serial.println("");

pinMode(ON_Board_LED,OUTPUT); //--> On Board LED port Direction output


digitalWrite(ON_Board_LED, HIGH); //-->

//----------------------------------------Wait for connection


Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
//----------------------------------------Make the On Board Flashing LED on the process of conne
cting to the wifi router.
digitalWrite(ON_Board_LED, LOW);
delay(250);
digitalWrite(ON_Board_LED, HIGH);
delay(250);
//----------------------------------------
}
//----------------------------------------
digitalWrite(ON_Board_LED, HIGH); //--> Turn off the On Board LED when it is connected t
o the wifi router.
//----------------------------------------If successfully connected to the wifi router, the IP Address t
hat will be visited is displayed in the serial monitor
Serial.println("");
Serial.print("Successfully connected to : ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.println();
//----------------------------------------

client.setInsecure();
}
//=====================================================================
=========
//=====================================================================
========= void loop
void loop() {

now = millis();
// Publishes new temperature and humidity every 3 seconds
if (now - lastMeasure > 3000) {
lastMeasure = now;
// 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();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}

// Computes temperature values in Celsius


float hic = dht.computeHeatIndex(t, h, false);
static char temperatureTemp[7];
dtostrf(hic, 6, 2, temperatureTemp);

// Uncomment to compute temperature values in Fahrenheit


// float hif = dht.computeHeatIndex(f, h);
// static char temperatureTemp[7];
// dtostrf(hif, 6, 2, temperatureTemp);

static char humidityTemp[7];


dtostrf(h, 6, 2, humidityTemp);

Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t Temperature: ");
Serial.print(t);
Serial.print(" *C ");
Serial.print(f);
Serial.print(" *F\t Heat index: ");
Serial.print(hic);
Serial.println(" *C ");
// Serial.print(hif);
// Serial.println(" *F");
sendData(t,h);

}
//*****
//=====================================================================
=========

void sendData(float value,float value2) {


Serial.println("==========");
Serial.print("connecting to ");
Serial.println(host);
//----------------------------------------Connect to Google host
if (!client.connect(host, httpsPort)) {
Serial.println("connection failed");
return;
}
//----------------------------------------

//----------------------------------------Proses dan kirim data

float string_temp = value;


float string_humi = value2;
String url = "/macros/s/" + GAS_ID + "/exec?temp=" + string_temp + "&humi="+string_humi
; // 2 variables
Serial.print("requesting URL: ");
Serial.println(url);

client.print(String("GET ") + url + " HTTP/1.1\r\n" +


"Host: " + host + "\r\n" +
"User-Agent: BuildFailureDetectorESP8266\r\n" +
"Connection: close\r\n\r\n");

Serial.println("request sent");
//----------------------------------------

//---------------------------------------
while (client.connected()) {
String line = client.readStringUntil('\n');
if (line == "\r") {
Serial.println("headers received");
break;
}
}
String line = client.readStringUntil('\n');
if (line.startsWith("{\"state\":\"success\"")) {
Serial.println("esp8266/Arduino CI successfull!");
} else {
Serial.println("esp8266/Arduino CI has failed");
}
Serial.print("reply was : ");
Serial.println(line);
Serial.println("closing connection");
Serial.println("==========");
Serial.println();
//----------------------------------------
}
//===============================================

You might also like