Web NFC (and writing to NFC tags)

Posted on
  • Hi, I'll try and turn this into a tutorial at some point, but it turns out you can now use 'Web NFC' on Android to read and write NFC tags including Puck.js/Pixl.js.

    HTML looks like this:

    <html>
    <body>
    <script>
    /* Starting a scan at startup stops Android from
    moving away from the Chrome window when a tag is found*/
    const reader = new NDEFReader();
    const writer = new NDEFWriter();
    reader.scan();
    
    function send(msg) {
      writer.write(msg).then(_=>console.log("W­ritten ",msg));
    }
    </script>
    <button onclick="send('red')">Red</button>
    <button onclick="send('green')">Green</button>
    <button onclick="send('blue')">Blue</button>
    </body>
    </html>
    

    Puck.js/Pixl.js code is a bit more complex as right now it's emulating an NFC tag in JS:

    var data = new Uint8Array(10+64);
    var header = NRF.nfcStart();
    var written = false;
    data.set(header,0); // NFC device header
    data.set([0,0,0xE1,0x10,(data.length-10)­/8,0,0,3,0,0xFe], 0x0A); // NDEF tag header
    // 0,0,e1
    NRF.on('NFCrx', function(rx) {
      var idx = rx[1]*4;
      switch(rx[0]) {
        case 0x30: //command: READ
          NRF.nfcSend(new Uint8Array(data.buffer, idx, 16));
          break;
        case 0xa2: //command: WRITE
          written = true;
          if(idx > data.length) {
            NRF.nfcSend(0x0);
          } else {
            data.set(new Uint8Array(rx, 2, 4), idx);
            NRF.nfcSend(0xA);
          }
          break;
        default:   //just, re-enable rx
          NRF.nfcSend();
          break;
        }
    });
    NRF.on("NFCoff",function() {
      if (written) 
        onWritten(E.toString(new Uint8Array(data.buffer,26,data[21]-3)));­
      written = false;
    });
    
    function onWritten(data) {
      console.log("NFC written", data);
      var colors = {
        red : 1,
        green : 2,
        blue : 4,
      };
      if (colors[data]) {
        digitalWrite([LED3,LED2,LED1], colors[data]); //  onwards
        setTimeout(function() {
          digitalWrite([LED3,LED2,LED1], 0);
        },1000);
      }
    }
    

    But basically this lets you send strings of data over NFC (no bluetooth connection needed). You just hold the phone near, tap 'red/green/blue' and then when you move the phone away Puck.js reads the text in the tag and decides what colour to make itself...

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

Web NFC (and writing to NFC tags)

Posted by Avatar for Gordon @Gordon

Actions