Skip to content

Instantly share code, notes, and snippets.

@don
Created September 21, 2014 01:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save don/7f77f54cc7e9d1140936 to your computer and use it in GitHub Desktop.
Save don/7f77f54cc7e9d1140936 to your computer and use it in GitHub Desktop.
Receive a NDEF message from a Peer & Light NeoPixel LEDs http://makerfaire.com/makers/arduino-nfc-3/
// Receive a NDEF message from a Peer
// Requires SPI. Tested with Seeed Studio NFC Shield v2
#include "SPI.h"
#include "PN532_SPI.h"
#include "snep.h"
#include "NdefMessage.h"
PN532_SPI pn532spi(SPI, 10);
SNEP nfc(pn532spi);
uint8_t ndefBuf[128];
#include <Adafruit_NeoPixel.h>
// Parameter 1 = number of pixels in strip
// Parameter 2 = pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
Adafruit_NeoPixel strip = Adafruit_NeoPixel(16, 6, NEO_GRB + NEO_KHZ800);
uint32_t color;
int wait = 15;
void setup() {
Serial.begin(9600);
Serial.println("NFC Peer to Peer Example - Receive Message");
strip.begin();
strip.show();
}
void loop() {
Serial.println("Waiting for message from peer");
int msgSize = nfc.read(ndefBuf, sizeof(ndefBuf));
if (msgSize > 0) {
NdefMessage msg = NdefMessage(ndefBuf, msgSize);
msg.print(); // debugging
Serial.println("\nSuccess");
// get the first record
NdefRecord record = msg.getRecord(0);
// check to make sure this a record we care about
if (record.getTnf() == TNF_MIME_MEDIA && record.getType() == "text/led") {
String payload = getPayloadAsString(record);
color = parseColor(payload);
for (int i = 0; i < strip.numPixels(); i++) {
strip.setPixelColor(i, color);
delay(wait); // animates the fill a bit
strip.show();
}
}
} else {
Serial.println("Failed to read message from peer");
}
delay(3000);
}
// The payload is a byte array. We are expecting a string.
String getPayloadAsString(NdefRecord record) {
int payloadLength = record.getPayloadLength();
byte payloadBytes[payloadLength];
record.getPayload(payloadBytes);
// cast because we *think* the payload is a String
String payloadString = String((char*)payloadBytes);
return payloadString;
}
// return a color from comma separated string
// expecting red,green,blue
// example 0,0,255
uint32_t parseColor(String s) {
int firstComma = s.indexOf(',');
int lastComma = s.lastIndexOf(',');
int red = s.substring(0, firstComma).toInt();
int green = s.substring(firstComma+1, lastComma).toInt();
int blue = s.substring(lastComma+1).toInt();
return strip.Color(red, green, blue);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment