Skip to content

Instantly share code, notes, and snippets.

@naokisekiguchi
Created December 1, 2016 01:20
Show Gist options
  • Save naokisekiguchi/139b0ecb0ad87828044e55f8d82f94b2 to your computer and use it in GitHub Desktop.
Save naokisekiguchi/139b0ecb0ad87828044e55f8d82f94b2 to your computer and use it in GitHub Desktop.
CHIRIMENでタッチセンサ
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="js/task.js"></script>
<script src="js/webgpioi2c.js"></script>
<script src="js/main.js"></script>
</head>
<body>
</body>
</html>
// task.js ライブラリ
const { spawn, sleep } = task;
// document 内のリソースが読み終わるのを待つ
document.addEventListener("DOMContentLoaded", () => {
// task.js の spawn 関数内では Promise が同期的に記述できる
spawn(function() {
// I2C へのアクセサを取得
const accessor = yield navigator.requestI2CAccess();
// I2C 0 ポートを使うので、0 を指定してポートを取得
const port = accessor.ports.get(0);
yield groveTouchInit(port,0x5a);
setInterval( ()=>{
spawn(function(){
const touch = yield getTouch(port,0x5a);
// 確認用に console.log に表示
console.log("touch: "+touch);
});
},1000);
});
});
function getTouch(port,addr){
return new Promise(function(resolve,reject){
spawn(function(){
const slave = yield port.open(addr);
const lowBit = yield slave.read8(0x00, true);
const highBit = yield slave.read8(0x01, true);
const touch = ((highBit << 8) + lowBit);
const array = arrayFromMask(touch);
resolve(array);
});
});
}
function arrayFromMask (nMask) {
if (nMask > 0x7fffffff || nMask < -0x80000000) { throw new TypeError("arrayFromMask - out of range"); }
for (var nShifted = nMask, aFromMask = []; nShifted; aFromMask.push(Boolean(nShifted & 1)), nShifted >>>= 1);
return aFromMask;
}
function groveTouchInit(port,addr){
return new Promise(function(resolve,reject){
spawn(function(){
const slave = yield port.open(addr);
yield slave.write8(0x2b,0x01);
yield sleep(1);
yield slave.write8(0x2c,0x01);
yield sleep(1);
yield slave.write8(0x2d,0x01);
yield sleep(1);
yield slave.write8(0x2e,0x01);
yield sleep(1);
yield slave.write8(0x2f,0x01);
yield sleep(1);
yield slave.write8(0x30,0x01);
yield sleep(1);
yield slave.write8(0x31,0xff);
yield sleep(1);
yield slave.write8(0x32,0x02);
yield sleep(1);
for(let i=0;i<12*2;i+=2){
spawn(function(){
let address = 0x41+i;
console.log("address"+address);
yield slave.write8(address,0x0f);
yield sleep(1);
yield slave.write8(address+1,0x0a);
yield sleep(1);
});
}
yield slave.write8(0x5d,0x04);
yield sleep(1);
yield slave.write8(0x5e,0x0c);
yield sleep(1);
resolve();
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment