HMI web de máquina en un Ardbox Q Lite: ejemplo completo
Una página web local, servida desde la parte Linux del Ardbox Q Lite, muestra las entradas en directo y activa una salida, sin PC ni panel adicional.
Qué hace
El microcontrolador lee las entradas y gobierna la salida. La app de Linux pide los valores con Arduino Bridge cada segundo y sirve una página web en el puerto 5001. Ábrela desde cualquier navegador de la misma red.
Qué necesitas
- Ardbox Q Lite AD o ADR con alimentación de 12 a 24 Vdc.
- Arduino IDE 2.0+ con el paquete de placas de Industrial Shields (placa: Ardbox Q, tu versión).
- Arduino App Lab para ejecutar la app de Linux.
Cómo ponerlo en marcha
- Carga sketch/sketch.ino con Arduino IDE.
- Crea una app en Arduino App Lab con app.yaml y python/main.py de esta página, y ejecútala.
- Abre http://IP-DEL-ARDBOX:5001 en un navegador de la misma red.
sketch/sketch.ino
/*
Ardbox Q Lite example 03: microcontroller side
Gives the Linux app access to the inputs and one output through Arduino Bridge.
Output: Q0.0 on Ardbox Q Lite AD, relay R1 on Ardbox Q Lite ADR.
Upload with Arduino IDE 2.0+ or arduino-cli, board Ardbox Q, your version.
*/
#include <Arduino_RouterBridge.h>
#if defined(IS_ARDBOX_Q_RELAY)
const pin_size_t OUT = R1; // Ardbox Q Lite ADR: relay R1
#else
const pin_size_t OUT = Q0_0; // Ardbox Q Lite AD: digital output Q0.0
#endif
const pin_size_t DIGITAL_IN[] = { I0_0, I0_1, I0_2, I0_3 };
const pin_size_t ANALOG_IN[] = { I0_4, I0_5, I0_6, I0_7, I0_8, I0_9 };
// Digital input 0 to 3 (I0.0 to I0.3). Returns -1 if the channel does not exist.
int readDigital(int ch) {
if (ch < 0 || ch > 3) return -1;
return digitalRead(DIGITAL_IN[ch]);
}
// Analog input 0 to 5 (I0.4 to I0.9), raw value 0 to 1023 (10 bits by default).
int readAnalog(int ch) {
if (ch < 0 || ch > 5) return -1;
return analogRead(ANALOG_IN[ch]);
}
bool setOutput(bool on) {
digitalWrite(OUT, on ? HIGH : LOW);
return on;
}
void setup() {
for (pin_size_t p : DIGITAL_IN) pinMode(p, INPUT);
pinMode(OUT, OUTPUT);
Bridge.begin();
Bridge.provide_safe("read_digital", readDigital);
Bridge.provide_safe("read_analog", readAnalog);
Bridge.provide_safe("set_output", setOutput);
}
void loop() {}
python/main.py
"""
Ardbox Q Lite example 03: machine HMI
A local web page, served from the Linux side, shows the four digital inputs
and the six analog inputs, with a button to switch the output.
Open http://<ardbox-ip>:5001 from a browser on the same network.
1. Upload sketch/sketch.ino with Arduino IDE (board Ardbox Q, your version).
2. Run this app from Arduino App Lab.
"""
import json
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from arduino.app_utils import *
PAGE = """<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width">
<title>Ardbox Q Lite</title>
<style>body{font-family:sans-serif;margin:24px;background:#141414;color:#fafafa}
td{padding:6px 14px;border-bottom:1px solid #444}button{font-size:20px;padding:10px 24px;background:#ffd915;border:0}</style>
<h1>Ardbox Q Lite</h1><table id="t"></table><p><button onclick="toggle()">Output on/off</button> <span id="o"></span></p>
<script>
async function refresh(){const s=await (await fetch('/state')).json();
let h='';s.digital.forEach((v,i)=>h+=`<tr><td>I0.${i}</td><td>${v?'ON':'off'}</td></tr>`);
s.analog.forEach((v,i)=>h+=`<tr><td>I0.${i+4}</td><td>${v}</td></tr>`);
document.getElementById('t').innerHTML=h;document.getElementById('o').textContent='Output: '+(s.output?'ON':'off');}
async function toggle(){await fetch('/toggle',{method:'POST'});refresh();}
setInterval(refresh,1000);refresh();
</script>"""
output_on = False
lock = threading.Lock()
def read_state():
with lock:
return {
"digital": [Bridge.call("read_digital", ch) for ch in range(4)],
"analog": [Bridge.call("read_analog", ch) for ch in range(6)],
"output": output_on,
}
class Handler(BaseHTTPRequestHandler):
def _send(self, body, ctype):
data = body.encode()
self.send_response(200)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def do_GET(self):
if self.path == "/state":
self._send(json.dumps(read_state()), "application/json")
else:
self._send(PAGE, "text/html; charset=utf-8")
def do_POST(self):
global output_on
if self.path == "/toggle":
with lock:
output_on = not output_on
Bridge.call("set_output", output_on)
self._send("{}", "application/json")
def log_message(self, *args):
pass
server = ThreadingHTTPServer(("0.0.0.0", 5001), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
App.run()
app.yaml
name: Ardbox Q Lite machine HMI
description: Local web page with the inputs and a button for the output
icon: "🖥️"
ports: [5001]
bricks: []