Photon NFC with Threading

Hey guys, I’m trying to add support to the Photon using Threading to read RFID via I2C to a PN532. The code is:

#include "application.h"
#include "PN532.h"
#include "PN532_I2C.h"

SYSTEM_THREAD(ENABLED);

Thread* readerThread;
Thread* mainThread;

PN532_I2C pn532_i2c(Wire);
PN532 nfc(pn532_i2c);

os_thread_return_t readRFID() {
  Serial.println("Read");
  delay(1000);
}

os_thread_return_t mainLoop() {
  Serial.println("MAIN");
  delay(100);
}

void setup() {
  Serial.begin(9600);

  while(!Serial.available()) {
      SPARK_WLAN_Loop(); // Open serial terminal and Press ENTER.
  }
  Serial.println("Hello!");

  nfc.begin();

  uint32_t versiondata;
  do {
      versiondata = nfc.getFirmwareVersion();
      if (!versiondata) {
          Serial.print("Didn't find PN53x board");
          delay(1000);
          SPARK_WLAN_Loop(); // Keep connected to the Cloud while re-trying
      }
  }
  while(!versiondata);

  // Got ok data, print it out!
  Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
  Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
  Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);

  // configure board to read RFID tags
  nfc.SAMConfig();

  readerThread = new Thread("reader", readRFID);
  mainThread = new Thread("main", mainLoop);
}

void loop() {
}

But I get a problem that after the OTA update is done the Photon flashes 8 ish red blinks then 2, as far as I can read that’s Out of Heap memory?

One thing SPARK_WLAN_Loop() is deprecated, you should now use Particle.process() wherever you used the former.

to be continued … @peekay123 has said the rest :+1:

Currently (in its beta state) I’d assume you’d need to tear down your threads before system functions like OTA or Listening can take over, since they currently don’t expect other threads to be running - I guess :sunglasses:

@ekarlso, as much as threading is great on larger systems, the Photon is still memory restricted and threading is still in Beta. I suggest you stay away from creating threads for your reader and main code and use the proven loop() approach. :wink:

1 Like

Then again the below simple app too fails and blinks red.

#include "application.h"

SYSTEM_THREAD(ENABLED);

os_thread_return_t mainLoop();

Thread* mainThread;

void setup() {
  Serial.begin(9600);

  while(!Serial.available()) {
      Particle.process(); // Open serial terminal and Press ENTER.
  }
  Serial.println("Hello!");

  mainThread = new Thread("main", mainLoop);
}

os_thread_return_t mainLoop() {
  Serial.println("FOO");
  delay(500);
}

void loop() {
}

@ekarlso, just a side note. The system firmware uses main() as its primary startup entry point (like all C/C++ code). Your “main” thread may conflict with this. BTW, you already have a primary user thread called loop()!!! Try renaming your thread to see if that works.