#include<Wire.h>
#include <LiquidCrystal_I2C.h>
#include <WiFi.h>
#include <HTTPClient.h>
#define VOLTAGE_SENSOR_PIN 39
LiquidCrystal_I2C lcd(0x27, 16, 2);
#define ACS712_PIN 34
#define ACS712_ADDRESS 0x40
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* webAppUrl = "https://script.google.com/macros/s/AKfycbwQzykQXNt8x80u-UaSXp0PqijP_yi6E6gl73QCBgW20m0R--eAF2Ed1Pie_5GDUNbkaw/exec";
unsigned long lastSendTime = 0; // ตัวแปรเก็บเวลาครั้งล่าสุดที่ส่งข้อมูล
const unsigned long interval = 300000; // 5 นาที
int sendCount = 0; // นับจำนวนรอบการส่งข้อมูล
void setup()
{
pinMode(VOLTAGE_SENSOR_PIN, INPUT);
pinMode(ACS712_PIN, INPUT);
lcd.init();
lcd.backlight();
Serial.begin(115200);
delay(100);
Serial.println("009");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
}
void loop() {
unsigned long currentTime = millis(); // เวลาปัจจุบัน
// อ่านค่าแรงดันแบตเตอรี่
int sensorValueVoltage = analogRead(VOLTAGE_SENSOR_PIN);
float voltageBattery = (sensorValueVoltage / 1023.0) * 5.0;
// อ่านค่ากระแสไฟฟ้า
int sensorValueACS = analogRead(ACS712_PIN);
float voltageCurrent = sensorValueACS * (5.0 / 1023.0);
float current = voltageCurrent / 0.1;
lcd.setCursor(0, 0);
lcd.print("Batt_Vtg: ");
lcd.print(voltageBattery, 2);
lcd.print(" V");
Serial.print("Batt_Voltage: ");
Serial.print(voltageBattery, 2);
Serial.println(" V ");
lcd.setCursor(0, 1);
lcd.print("Current: ");
lcd.print(current, 2);
lcd.print(" A");
Serial.print("Current: ");
Serial.print(current);
Serial.println(" A");
if (currentTime - lastSendTime >= interval) {
lastSendTime = currentTime; // อัปเดตเวลาครั้งล่าสุด
sendCount++; // เพิ่ม sendCount
// ดีบักแสดงจำนวนการส่ง
Serial.print("Total sends: ");
Serial.println(sendCount);
// ส่งข้อมูลไปยัง Google Sheets
sendDataToScript(voltageBattery, current, sendCount);
}
// ระยะเวลาเล็กน้อยเพื่อไม่ให้การอ่านข้อมูลเกิดบ่อยเกินไป
delay(1000);
}
void sendDataToScript(float voltageBattery, float current, int sendCount) {
HTTPClient http;
String serverPath = String(webAppUrl) + "?voltageBattery=" + String(voltageBattery) + "¤t=" + String(current) + "&totalsent=" + String(sendCount);
Serial.print("Sending data to: ");
Serial.println(serverPath);
if(http.begin(serverPath)){
int httpCode = http.GET();
if(httpCode > 0){
Serial.print("Server response code: ");
Serial.println(httpCode);
Serial.println("Status : SentSuccess");
}else{
Serial.print("HTTP GET request failed with error code: ");
Serial.println(httpCode);
Serial.println("Status : SentError");
}
http.end();
}else{
Serial.println("Unable to connect to the server");
}
}