Myu
2025年11月1日土曜日
ESP32 DEVKIT_Cで容量をWIFIでロギング
間欠動作で12時間ごとにGPIO4を容量センサとして使い、ロギングしてみた。raspiにGETでデータを保存し、スマホ等で取り出すアプリを作れば完成の予定。 はたして、灯油タンク残量が容量センサで計測実用なるか、テスト予定。(PICのCPSも検討したが、かえって複雑になりそうなので、このパターンにしてみた。)
*********esp32 code*********** #include
#include
#include "esp_sleep.h" #define TOUCH_PIN 4 // GPIO4 #define SLEEP_SECONDS 43200 // 12時間 (12 × 60 × 60) //#define SLEEP_SECONDS 15 // --- Wi-Fi 設定 --- const char* ssid = "***"; const char* password = "***"; // --- サーバ設定 --- // サーバ設定 const char* host = "*.*.*.*"; // Raspberry Pi IP const int port = 8888; const char* path = "/***/***"; String url; String cprint; volatile bool sendFlag = false; // ISR用フラグ // ISR: フラグを立てるだけ void IRAM_ATTR touch_isr() { sendFlag = true; } void setup() { Serial.begin(115200); delay(100); // Touch割り込みは不要ならコメント // attachInterrupt(digitalPinToInterrupt(TOUCH_PIN), touch_isr, FALLING); // Wi-Fi接続 WiFi.begin(ssid, password); Serial.print("Connecting to WiFi"); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("\nWiFi connected"); // Touch値測定 uint16_t capValue = touchRead(TOUCH_PIN); Serial.print("Touch value: "); Serial.println(capValue); // HTTP送信 WiFiClient client; if (client.connect(host, port)) { url = String(path) + "?cap=" + String(capValue); cprint=String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n"; client.print(cprint); // サーバ応答を表示(任意) while (client.connected() || client.available()) { if (client.available()) { String line = client.readStringUntil('\n'); Serial.println(line); } } client.stop(); } else { Serial.println("Connection failed url="+url+" clientPrint="+cprint); } Serial.println("Going to sleep..."); delay(100); // Serial出力待ち // Deep Sleep esp_sleep_enable_timer_wakeup(SLEEP_SECONDS * 1000000ULL); esp_deep_sleep_start(); } void loop() { // Deep Sleepを使う場合はここは何もしない // 必須なので空の関数を置く } *********raspi bottle code********** from bottle import Bottle, request, response import json from datetime import datetime import os app = Bottle() latest_cap = None LOG_FILE = "cap_log.txt" MAX_LINES = 200 def read_log(): if not os.path.exists(LOG_FILE): return [] with open(LOG_FILE, "r") as f: return f.readlines() def write_log(lines): with open(LOG_FILE, "w") as f: f.writelines(lines) @app.route('/py/cap') def cap_handler(): global latest_cap cap_value = request.query.cap # ?cap=123 または ?cap=list10 list10は最新の10行表示 if cap_value: if cap_value.startswith("list"): # ?cap=listN の場合 try: n = int(cap_value[4:]) lines = read_log() latest_lines = lines[-n:] if n > 0 else [] response.content_type = 'application/json' # JSON形式で返す result = [] for line in latest_lines: dt_str, value_str = line.strip().split(',', 1) result.append({"datetime": dt_str, "cap": int(value_str)}) return json.dumps(result) except ValueError: response.status = 400 return "Invalid list parameter" else: # 数値の場合 try: latest_cap = int(cap_value) now_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S") line = f"{now_str},{latest_cap}\n" # ログを読み込んで追記 lines = read_log() lines.append(line) # 最大行数を維持 if len(lines) > MAX_LINES: lines = lines[-MAX_LINES:] write_log(lines) return f"Cap value {latest_cap} saved.\n" except ValueError: response.status = 400 return "Invalid value" else: # パラメータなし → 最新値返す if latest_cap is not None: response.content_type = 'application/json' return json.dumps({"latest_cap": latest_cap}) else: response.status = 404 return "No data yet" ***等で表したアドレス、パスは書き換え必要
PICに比べると、至れり尽くせりでesp32は開発しやすい。それでも、ネットワークがからむとプロトコルやポートとかいろいろ調整が必要になってくるので、それはそれで、手間がかかる。
0 件のコメント:
コメントを投稿
前の投稿
ホーム
登録:
コメントの投稿 (Atom)
0 件のコメント:
コメントを投稿