Skip to content

Instantly share code, notes, and snippets.

@alanshaw
Created June 27, 2015 16:20
Show Gist options
  • Save alanshaw/1d58ffbc1d304f3e8e75 to your computer and use it in GitHub Desktop.
Save alanshaw/1d58ffbc1d304f3e8e75 to your computer and use it in GitHub Desktop.
lasercat + xbox controller
var five = require('johnny-five')
var XboxController = require('xbox-controller')
var xbox = new XboxController()
var board = new five.Board()
board.on('ready', function () {
console.log('board ready')
var pan = new five.Servo(9)
var tilt = new five.Servo(13)
var laser = new five.Led(2)
pan.step = function (degrees, time) {
var target = (this.last ? this.last.target : this.startAt) + degrees
if (target < 0) target = 0
if (target > 180) target = 180
console.log('target pan', target)
return this.to(target, time)
}
tilt.step = function (degrees, time) {
var target = (this.last ? this.last.target : this.startAt) + degrees
if (target < 0) target = 0
if (target > 180) target = 180
console.log('target tilt', target)
return this.to(target, time)
}
this.repl.inject({
pan: pan,
tilt: tilt,
laser: laser
})
xbox.on('connected', function(){
console.log('Xbox controller connected')
})
xbox.on('righttrigger', function (val) {
if (val) {
laser.on()
} else {
laser.off()
}
})
var panAvailable = true
pan.on('move:complete', function () {
console.log('move:complete')
panAvailable = true
})
var panInterval = null
var panDirection = null
var panSpeed = null
function startPan (direction, speed) {
if (!speed) {
clearInterval(panInterval)
panInterval = null
return
}
panDirection = direction
panSpeed = speed
if (!panInterval) {
panInterval = setInterval(doPan, 50)
}
}
function doPan () {
if (!panAvailable) return
panAvailable = false
if (panDirection == 'left') {
console.log('pan left -5')
pan.step(-45, panSpeed)
} else {
console.log('pan right 5')
pan.step(45, panSpeed)
}
}
var tiltAvailable = true
tilt.on('move:complete', function () {
console.log('move:complete')
tiltAvailable = true
})
var tiltInterval = null
var tiltDirection = null
var tiltSpeed = null
function startTilt (direction, speed) {
if (!speed) {
clearInterval(tiltInterval)
tiltInterval = null
return
}
tiltDirection = direction
tiltSpeed = speed
if (!tiltInterval) {
tiltInterval = setInterval(doTilt, 50)
}
}
function doTilt () {
if (!tiltAvailable) return
tiltAvailable = false
if (tiltDirection == 'up') {
console.log('tilt up -5')
tilt.step(-45, tiltSpeed)
} else {
console.log('tilt down 5')
tilt.step(45, tiltSpeed)
}
}
xbox.on('left:move', function (pos) {
console.log('left:move', pos)
if (pos.x < 0) {
startPan('left', 250)
} else if (pos.x > 0) {
startPan('right', 250)
} else {
startPan(null, 0)
}
})
xbox.on('right:move', function (pos) {
console.log('right:move', pos)
if (pos.y < 0) {
startTilt('up', 250)
} else if (pos.y > 0) {
startTilt('down', 250)
} else {
startTilt(null, 0)
}
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment