超音波を利用した距離センサーをGoogle siteで動かします。
Gnd → 0
Echo → 1
Trig → 2
Vcc → 3
obniz距離センサ測定<br />
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://unpkg.com/obniz@3.x/obniz.js" crossorigin="anonymous" ></script>
obniz ID:<input type="text" id="oid" style="width: 100px;"><br />
<button onClick="init();">実行</button><br />
<span id="val" style="display: inline-block; border: 1px solid blue; width: 70px; height: 25px; text-align: right;"></span>mm
<script>
var obniz;
function init() {
obniz = new Obniz($("#oid").val());
obniz.onconnect = async function () {
const hcsr04 = obniz.wired("HC-SR04", {gnd:0, echo:1, trigger:2, vcc:3});
while(true) {
let avg = 0;
let count = 0;
for (let i=0; i<3; i++) { // measure three time. and calculate average
const val = await hcsr04.measureWait();
if (val) {
count++;
avg += val;
}
}
if (count > 1) {
avg /= count;
}
$("#val").html(Math.floor(avg));
await obniz.wait(100);
}
};
}
</script>
ワーキングモデル