#001

Váha pro RC modely

Průjezdná váha navržená přímo pro RC modely traktorů, náklaďáků a zemědělské techniky. Celou váhu řídí ESP32-WROOM-32, které vyčítá data z osmi snímačů přes dva moduly HX711, výsledek posílá na odnímatelný červený 8×32 LED maticový displej a zároveň hostuje vlastní Wi-Fi webové rozhraní s historií vážení.


📸 Váha v akci na RC ploše

RC traktor na váze

Traktor s vlekem na váze – na displeji aktuální hmotnost 4,7 kg.

Pohled shora na RC areál

Celkový pohled na zapojení váhy přímo v RC areálu.

🧱 Konstrukce a mechanika

• Sendvičová konstrukce: Spodní i horní dřevěná deska jsou po bocích vyztužené hliníkovými profily, aby se dřevo nekroutilo. Boční profily zároveň fungují jako vedení/závora pro horní vážicí desku.
• 8 tenzometrů mezi deskami: V rozích a po délce mezi oběma deskami je rozmístěno celkem 8 snímačů zatížení.
• Nájezdy: Dva samostatné dřevěné nájezdy s protiskluzovým povrchem a vodicími čepy pro pohodlné najetí modelů.

Nájezdy k váze

Dva odnímatelné nájezdy s protiskluzovým povrchem.

Vnitřek váhy s 8 senzory

Všech 8 snímačů svedených do středu desky k ESP32 a dvěma HX711.

Spodní rám s hliníkovými profily

Spodní strana s hliníkovou výztuhou a gumovými nožičkami.

⚡ Elektronika, zapojení a napájení

• Mozek: ESP32-WROOM-32 uprostřed spodní desky.
• 2× HX711 (4+4 senzory): Z ESP32 vedou kabely do stran na dva převodníky HX711, ze kterých jsou do „X“ zapojené vždy 4 tenzometrické senzory.
• Rozsah a přesnost: Teoretický limit je až 100 kg, reálně otestováno až do 88 kg (při takto velkém rozsahu už na horní hranici vychází odchylka zhruba ±20 kg, pro běžné RC modely po kalibraci ale funguje spolehlivě).
• Odnímatelný displej: Maticový LED displej MAX7219 8×32 (4× 8×8 modul FC16_HW) na konektoru – dá se kdykoli odpojit.
• Ovládání & Napájení: Tlačítko na GPIO 4 (krátký stisk = TARE, dlouhý stisk = kalibrace na 1,5 kg). Dříve napájeno přes 3A UBEC, nově pohodlně přímo z USB powerbanky.

MAX7219 8x32 LED displej

Odnímatelný 8×32 LED displej v 3D tištěném krytu.

USB napájení a konektor displeje

Vývod USB napájení, konektoru displeje a tlačítka.

🌐 Wi-Fi & Webové rozhraní: ESP32 vysílá vlastní Wi-Fi síť ESP32_Weight s webovým rozhraním, kde zobrazuje živou váhu (kg i raw hodnotu), posledních 10 ustálených měření a diagnostický Admin log.

💻 Kód pro ESP32 (Arduino / C++)

#include <HX711_ADC.h>
#include <WiFi.h>
#include <WebServer.h>
#include <MD_Parola.h>
#include <MD_MAX72xx.h>
#include <SPI.h>

// ----------- HX711 1 + 2 -----------
const int HX711_dout1 = 15;
const int HX711_sck1  = 5;
const int HX711_dout2 = 27;
const int HX711_sck2  = 26;

HX711_ADC LoadCell1(HX711_dout1, HX711_sck1);
HX711_ADC LoadCell2(HX711_dout2, HX711_sck2);

float rawEmpty1 = 0, rawEmpty2 = 0;
float calFactor1 = 0, calFactor2 = 0;
bool tareDone = false;
bool calDone = false;
const float deadbandRaw = 50;
const float deadbandKg  = 0.05;

// ----------- WiFi / WebServer -----------
const char* ssid = "ESP32_Weight";
const char* password = "Rc Domažlice";
WebServer server(80);
float lastKg = 0;
float lastRaw = 0;

// ----------- MAX7219 / MD_Parola -----------
#define HARDWARE_TYPE MD_MAX72XX::FC16_HW
#define MAX_DEVICES 4
#define CS_PIN 18
#define CLK_PIN 14
#define DATA_PIN 13
MD_Parola mx = MD_Parola(HARDWARE_TYPE, DATA_PIN, CLK_PIN, CS_PIN, MAX_DEVICES);

// ----------- Tlačítko -----------
const int BUTTON = 4;
unsigned long pressStart = 0;
bool buttonWasPressed = false;

// ----------- Historie vážení -----------
#define HISTORY_SIZE 10
float weightHistory[HISTORY_SIZE] = {0};
unsigned long stableStart = 0;
float stableKg = 0;

// ----------- Admin log buffer -----------
String adminLog = "";

// --- Web handlers ---
void handleRoot();
void handleWeight();
void handleAdminLog();

void handleRoot() {
  String html = "<!DOCTYPE html><html><head><meta charset='UTF-8'><title>ESP32 Váha</title>";
  html += "<meta name='viewport' content='width=device-width, initial-scale=1.0'>";

  // CSS
  html += "<style>";
  html += "body{font-family:Arial,sans-serif;margin:0;padding:0;min-height:100vh;}";
  html += ".topbar{position:fixed;top:10px;width:100%;display:flex;justify-content:space-between;padding:0 10px;}";
  html += ".topbar-left{display:flex;gap:10px;}";
  html += ".topbar-right{display:flex;gap:10px;}";
  html += ".btn{padding:6px 12px;border:none;border-radius:8px;cursor:pointer;font-size:0.9em;}";
  html += ".btn-login{background:#444;color:#fff;}";
  html += ".btn-logout{background:#2ecc71;color:white;display:none;}";
  html += ".card{padding:20px;border-radius:20px;text-align:center;margin:10px;transition:0.3s;}";
  html += ".container{display:flex;flex-wrap:wrap;justify-content:center;width:100%;max-width:1000px;margin:80px auto 20px auto;}";
  html += "#historyCard{flex:0 0 300px;}";
  html += "#adminCard{flex:1;min-width:300px;display:none;text-align:left;}";
  html += "table{border-collapse:collapse;width:100%;margin-top:10px;}";
  html += "th, td{padding:8px;text-align:center;}";
  html += "pre{background:rgba(0,0,0,0.6);padding:10px;border-radius:10px;white-space:pre-wrap;word-wrap:break-word;max-height:400px;overflow-y:auto;}";
  html += "body.light-mode{background:#f0f2f5;color:#000;}";
  html += "body.light-mode .card{background:#dcdcdc;box-shadow:0 8px 16px rgba(0,0,0,0.3);}";
  html += "body.light-mode table th, body.light-mode table td{color:#000;background:#e5e5e5;border:1px solid #ccc;}";
  html += "body.light-mode pre{background:#fff;color:#000;}";
  html += "body.dark-mode{background:#121212;color:#fff;}";
  html += "body.dark-mode .card{background:#1e1e1e;box-shadow:0 8px 16px rgba(0,0,0,0.7);}";
  html += "body.dark-mode table th, body.dark-mode table td{color:#fff;background:#1e1e1e;border:1px solid #555;}";
  html += "body.dark-mode pre{background:#000;color:#fff;}";
  html += "</style>";

  // JS
  html += "<script>";
  html += "function updateThemeIcon(){let btn=document.getElementById('themeBtn'); if(document.body.classList.contains('dark-mode')){btn.textContent='🌙';} else {btn.textContent='☀️';}}";
  html += "function toggleTheme(){if(document.body.classList.contains('dark-mode')){document.body.classList.remove('dark-mode');document.body.classList.add('light-mode');localStorage.setItem('theme','light-mode');}else{document.body.classList.remove('light-mode');document.body.classList.add('dark-mode');localStorage.setItem('theme','dark-mode');}updateThemeIcon();}";
  html += "function updateWeight(){fetch('/weight').then(resp=>resp.json()).then(data=>{document.getElementById('raw').textContent=data.raw.toFixed(2);document.getElementById('kg').textContent=data.kg.toFixed(1)+' kg';let historyTable='';data.history.forEach((w,i)=>{historyTable+='<tr><td>'+(i+1)+'</td><td>'+w.toFixed(1)+' kg</td></tr>';});document.getElementById('history').innerHTML=historyTable;});}";
  html += "function updateLog(){fetch('/adminlog').then(resp=>resp.text()).then(data=>{let logElem=document.getElementById('adminLog'); logElem.textContent=data; logElem.scrollTop = logElem.scrollHeight;});}";
  html += "function checkLogin(){let u=document.getElementById('username').value;let p=document.getElementById('password').value;if(u=='admin'&&p=='1234'){document.getElementById('adminCard').style.display='block';document.getElementById('loginDiv').style.display='none';document.getElementById('logoutBtn').style.display='inline-block';setInterval(updateLog,1000);}}";
  html += "function logout(){document.getElementById('adminCard').style.display='none';document.getElementById('loginDiv').style.display='flex';document.getElementById('logoutBtn').style.display='none';}";
  html += "window.onload=function(){if(localStorage.getItem('theme')){document.body.className=localStorage.getItem('theme');} else if(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches){document.body.className='dark-mode';}updateThemeIcon();updateWeight();setInterval(updateWeight,1000);};";
  html += "</script>";

  html += "</head><body class='light-mode'>";
  html += "<div class='topbar'>";
  html += "<div class='topbar-left' id='loginDiv'><input id='username' placeholder='Username'><input id='password' type='password' placeholder='Password'><button class='btn btn-login' onclick='checkLogin()'>Login</button></div>";
  html += "<div class='topbar-right'><button class='btn' id='themeBtn' onclick='toggleTheme()'>☀️</button><button class='btn btn-logout' id='logoutBtn' onclick='logout()'>Logout</button></div>";
  html += "</div>";
  html += "<div class='card'><h1>ESP32 Váha</h1><p>Raw: <span id='raw'>" + String(lastRaw,2) + "</span></p><p>Kg: <span id='kg'>" + String(lastKg,1) + " kg</span></p></div>";
  html += "<div class='container'><div class='card' id='historyCard'><h2>Historie vážení</h2><table><tr><th>#</th><th>Kg</th></tr><tbody id='history'></tbody></table></div><div class='card' id='adminCard'><h2>Admin log</h2><pre id='adminLog'></pre></div></div>";
  html += "</body></html>";

  server.send(200,"text/html",html);
}

void handleWeight() {
  String json="{\"raw\":"+String(lastRaw,2)+",\"kg\":"+String(lastKg,1)+",\"history\":[";
  for(int i=0;i<HISTORY_SIZE;i++){
    json+=String(weightHistory[i],1);
    if(i<HISTORY_SIZE-1) json+=",";
  }
  json+="]}";
  server.send(200,"application/json",json);
}

void handleAdminLog() {
  server.send(200,"text/plain",adminLog);
}

void setup() {
  Serial.begin(115200);
  delay(100);
  LoadCell1.begin();
  LoadCell2.begin();
  LoadCell1.start(2000, true);
  LoadCell2.start(2000, true);
  delay(2000);

  Serial.println("Short press = TARE, Long press = CALIBRATION (both cells)");

  WiFi.softAP(ssid,password);
  Serial.println("WiFi AP started with password: Rc Domažlice");

  server.on("/", handleRoot);
  server.on("/weight", handleWeight);
  server.on("/adminlog", handleAdminLog);
  server.begin();

  mx.begin();
  mx.displayClear();
  mx.setIntensity(5);
  pinMode(BUTTON, INPUT_PULLUP);
}

void loop() {
  LoadCell1.update();
  LoadCell2.update();
  server.handleClient();

  // --- tlačítko ---
  bool pressed = digitalRead(BUTTON) == LOW;
  if(pressed && !buttonWasPressed){ pressStart = millis(); buttonWasPressed = true; }
  else if(!pressed && buttonWasPressed){
    unsigned long pressDuration = millis() - pressStart;
    if(pressDuration < 1000){
      rawEmpty1 = LoadCell1.getData();
      rawEmpty2 = LoadCell2.getData();
      tareDone = true;
      adminLog += "TARE done (both)\n";
      Serial.println("Tare done (both)");
      mx.displayClear(); mx.displayText("TARE", PA_CENTER, 50, 0, PA_PRINT, PA_NO_EFFECT); delay(1000); mx.displayClear();
    } else if(pressDuration >= 1000 && tareDone){
      float rawKnown1 = LoadCell1.getData();
      float rawKnown2 = LoadCell2.getData();
      float knownWeightKg = 1.5; // kalibrace na 1.5 kg
      calFactor1 = knownWeightKg / (rawKnown1 - rawEmpty1);
      calFactor2 = knownWeightKg / (rawKnown2 - rawEmpty2);
      calDone = true;
      adminLog += "CAL done (both, 1.5kg)\n";
      Serial.println("Calibration done (both, 1.5kg)");
      mx.displayClear(); mx.displayText("CAL", PA_CENTER, 50, 0, PA_PRINT, PA_NO_EFFECT); delay(1000); mx.displayClear();
    }
    buttonWasPressed = false;
  }

  // --- vážení ---
  if(tareDone && calDone){
    float raw1 = LoadCell1.getData();
    float raw2 = LoadCell2.getData();
    float rawTotal = raw1 + raw2;

    static float lastValRaw = 0;
    if(abs(rawTotal - lastValRaw) < deadbandRaw) rawTotal = lastValRaw;
    lastValRaw = rawTotal;

    float kg = ((raw1 - rawEmpty1) * calFactor1) + ((raw2 - rawEmpty2) * calFactor2);
    if(abs(kg) < deadbandKg) kg = 0.0;

    lastKg = kg;
    lastRaw = rawTotal;

    String logLine = "raw1 " + String(raw1,2) + " raw2 " + String(raw2,2) + " total kg " + String(kg,1);
    Serial.println(logLine);
    adminLog += logLine + "\n";
    if(adminLog.length() > 5000) adminLog.remove(0, 1000);

    String kgStr = String(kg,1) + " kg";
    if(mx.displayAnimate()) mx.displayText(kgStr.c_str(), PA_CENTER, 50, 0, PA_PRINT, PA_NO_EFFECT);

    if(kg > 0){
      if(abs(kg - stableKg) < deadbandKg){
        if(stableStart == 0) stableStart = millis();
        else if(millis() - stableStart >= 5000){
          for(int i = HISTORY_SIZE - 1; i > 0; i--) weightHistory[i] = weightHistory[i - 1];
          weightHistory[0] = kg;
          stableStart = millis();
        }
      } else {
        stableKg = kg;
        stableStart = millis();
      }
    } else {
      stableStart = 0;
      stableKg = 0;
    }
  }

  delay(100);
}