#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
// WiFi credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// Google Apps Script details
const char* SCRIPT_ID = "AKfycbw5jKRp5pnjxrI77Ht81HyOt2CDEkgM-jBQvVOO31GhqHn7FpStIM0LyQiDViz7UsZb/exec"; // Get this from your deployed script
const char* API_ENDPOINT = "https://script.google.com/macros/s/";
const char* API_URL = "https://script.google.com/macros/s/AKfycbw5jKRp5pnjxrI77Ht81HyOt2CDEkgM-jBQvVOO31GhqHn7FpStIM0LyQiDViz7UsZb/exec";
// Gas sensor pin
const int gasSensorPin = 34;
int gasValue = 0;
void setup() {
Serial.begin(115200);
delay(1000);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
gasValue = analogRead(34);
Serial.print("Gas Value: ");
Serial.println(gasValue);
// Prepare JSON data
String jsonData = "{\"value\": " + String(gasValue) + "}";
// Send data to Google Sheets
sendDataToGoogleSheets(jsonData);
delay(5000); // Send data every 5 seconds
}
void sendDataToGoogleSheets(String jsonData) {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(API_URL);
http.addHeader("Content-Type", "application/json");
int httpResponseCode = http.POST(jsonData);
if (httpResponseCode > 0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
String payload = http.getString();
Serial.println(payload);
} else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
http.end();
} else {
Serial.println("WiFi Disconnected");
}
}
// Google Apps Script (deploy as web app, anyone can execute)
/*
function doPost(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var data = JSON.parse(e.postData.contents);
var value = data.value;
var timestamp = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "yyyy-MM-dd HH:mm:ss");
sheet.appendRow([timestamp, value]);
return ContentService.createTextOutput(JSON.stringify({"result": "success"}));
}
*/