Created
          March 8, 2016 01:46 
        
      - 
      
 - 
        
Save mmckegg/9404105b265a3755cfeb to your computer and use it in GitHub Desktop.  
  
    
      This file contains hidden or 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
    
  
  
    
  | var SerialPort = require('serialport').SerialPort | |
| var bl = require('bl') | |
| module.exports = connect | |
| function connect (device, cb) { | |
| var port = new SerialPort(device, { baudrate: 115200, highWaterMark: 1 }) | |
| var timer = null | |
| var initialized = false | |
| var queue = [] | |
| port.on('open', function () { | |
| reset() | |
| timer = setInterval(tryToEnterBinMode, 20) | |
| port.on('data', checkForBinMode) | |
| }) | |
| function reset () { | |
| port.write([0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x0d, 0x23]) | |
| } | |
| function tryToEnterBinMode () { | |
| port.write([0x00]) | |
| } | |
| function checkForBinMode (data) { | |
| if (data.toString() === 'BBIO1') { | |
| clearInterval(timer) | |
| port.removeListener('data', checkForBinMode) | |
| startSPI() | |
| } | |
| } | |
| function startSPI () { | |
| port.write([0x01]) // SPI mode | |
| port.write([0b01000000]) // disable power supplies | |
| port.write([0b10001010]) // 3.3v pin mode | |
| port.write([0b01100111]) // 8 MHz clock | |
| setTimeout(function () { | |
| port.write([0b01001000]) // wait 1 second then enable power to avoid spike | |
| }, 1000) | |
| initialized = true | |
| while (queue.length) { | |
| write(queue.shift()) | |
| } | |
| } | |
| function write (data) { | |
| if (initialized) { | |
| var output = bl() | |
| output.append(data) | |
| for (var i = 0; i < output.length; i += 16) { | |
| var chunk = output.slice(i, i + 16) | |
| port.write([0b00010000 + chunk.length - 1]) | |
| port.write(chunk) | |
| } | |
| } else { | |
| queue.push(data) | |
| } | |
| } | |
| return write | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment