Created
January 23, 2017 16:34
-
-
Save Whizzard/9ca5caeed42c0ce7659cd98231626289 to your computer and use it in GitHub Desktop.
Simple joystick implementation with timeout for puck.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pinMode( D13, 'input_pullup' ); // up | |
pinMode( D14, 'input_pullup' ); // right | |
pinMode( D15, 'input_pullup' ); // left | |
pinMode( D16, 'input_pullup' ); // down | |
let LEFT = 1; | |
let RIGHT = 2; | |
let ROT = 3; | |
let DOWN = 4; | |
let TIMEOUT = 60000; | |
var connecting = false; | |
var device = false; | |
var timer = false; | |
var characteristic = false; | |
function disconnect() { | |
if( device ) { | |
device.disconnect(); | |
device = false; | |
} | |
LED3.reset(); | |
if( timer ) { | |
clearTimeout( timer ); | |
} | |
connecting = false; | |
} | |
function refreshTimer() { | |
if( timer ) { | |
clearTimeout( timer ); | |
} | |
timer = setTimeout( disconnect, TIMEOUT ); | |
} | |
function connect() { | |
if( device ) { | |
refreshTimer(); | |
return Promise.resolve( characteristic ); | |
} | |
else if( ! connecting ) { | |
connecting = true; | |
analogWrite(LED3, 0.02); | |
return NRF.requestDevice({filters:[{services:['FFE0']}]}).then(dev=>{ | |
console.log( "connecting " + dev.name); | |
return dev.gatt.connect(); | |
}).then(con=>{ | |
device = con; | |
console.log( "connected" ); | |
return con.getPrimaryService(0xFFE0); | |
}).then(ser=>{ | |
console.log( "service found"); | |
return ser.getCharacteristic(0xFFE1); | |
}).then(cha=>{ | |
console.log("characteristic found"); | |
characteristic = cha; | |
connecting = false; | |
refreshTimer(); | |
return cha; | |
}).catch(err=>{ | |
console.log("error", err); | |
disconnect(); | |
digitalPulse(LED1,1,200); | |
return Promise.reject(err); | |
}); | |
} | |
else { | |
return Promise.reject("connecting"); | |
} | |
} | |
function send( b ) { | |
connect().then(cha=>{ | |
cha.writeValue( b ); | |
}).catch(err=>{ | |
console.log("could not send" ); | |
}); | |
} | |
setWatch(()=>{ send( ROT ); }, D13, { repeat: true, edge: 'rising', debounce: 20 }); | |
setWatch(()=>{ send( RIGHT ); }, D14, { repeat: true, edge: 'rising', debounce: 20 }); | |
setWatch(()=>{ send( LEFT ); }, D15, { repeat: true, edge: 'rising', debounce: 20 }); | |
setWatch(()=>{ send( DOWN ); }, D16, { repeat: true, edge: 'rising', debounce: 20 }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment