Я пытался запрограммировать свой ESP32-S3 так, чтобы, когда он воссоединен, он начинает счет, откуда он остался. Я пытаюсь войти в систему данных в листе Google, и это счетчик, где количество увеличивает счет на 1. Для этого я использовал Google App-Script и регистрировал данные в электронном таблице Google. Я делюсь тем, что я попробовал в коде Arduino и коде приложения.#include
#include
const char* ssid = "";
const char* password = "";
// Web App URL (for GET and POST)
const char* baseURL = "";
int count = 0;
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi...");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nConnected to WiFi");
// Fetch last count from Google Sheets
HTTPClient http;
String getURL = String(baseURL) + "?getCount=true";
http.begin(getURL);
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
String response = http.getString();
Serial.print("Last count from Google Sheets: ");
Serial.println(response);
count = response.toInt(); // Update count to last known value
} else {
Serial.print("GET Error code: ");
Serial.println(httpResponseCode);
}
http.end();
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(baseURL);
http.addHeader("Content-Type", "application/json");
// JSON payload
String jsonPayload = "{\"count\":" + String(count) + "}";
int httpResponseCode = http.POST(jsonPayload);
if (httpResponseCode > 0) {
String response = http.getString();
Serial.print("POST Response code: ");
Serial.println(httpResponseCode);
Serial.print("Response: ");
Serial.println(response);
} else {
Serial.print("POST Error code: ");
Serial.println(httpResponseCode);
}
http.end();
count++;
delay(2000); // Send every 2 seconds
} else {
Serial.println("WiFi Disconnected. Reconnecting...");
WiFi.reconnect();
}
}
// код приложения-сценария
function doGet(e) {
if (e && e.parameter && e.parameter.getCount === "true") {
const sheet = SpreadsheetApp.openById("").getSheetByName("Sheet1");
const lastCount = sheet.getRange("B38").getValue();
return ContentService.createTextOutput(String(lastCount)).setMimeType(ContentService.MimeType.TEXT);
}
return ContentService.createTextOutput("Invalid Request").setMimeType(ContentService.MimeType.TEXT);
}
function doPost(e) {
try {
const data = JSON.parse(e.postData.contents);
const sheet = SpreadsheetApp.openById("").getSheetByName("Sheet1");
sheet.getRange("B38").setValue(data.count);
return ContentService.createTextOutput("Success").setMimeType(ContentService.MimeType.TEXT);
} catch (error) {
Logger.log("Error: " + error.message);
return ContentService.createTextOutput("Error: " + error.message).setMimeType(ContentService.MimeType.TEXT);
}
}
Подробнее здесь: https://stackoverflow.com/questions/795 ... om-0-again
ESP32-S3 сбрасывает счет и снова начинается с 0 ⇐ C++
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение