Firmware Tips and Tricks

##sprintf() consumes 20KB of FLASH memory!##
Here is a small work around for that which won’t eat up all of your FLASH memory, effectively costing you nothing, with an useful example:

// The following two lines are for Local Builds, 
// but work fine in the Sparkulator (web IDE)
#include "application.h"
const char* myIpAddress(void);

// allow us to use itoa() in this scope
extern char* itoa(int a, char* buffer, unsigned char radix);

const char* myIpAddress(void)
{
  IPAddress myIp = WiFi.localIP();
  static char buf[24] = "";
  //sprintf(buf, "%d.%d.%d.%d", myIp[0], myIp[1], myIp[2], myIp[3]);
  // The following code does the same thing as the above sprintf()
  // but uses 20KB less flash!
  char num[4];
  itoa(myIp[0],num,10);
  strcat(buf,num); strcat(buf,".");
  itoa(myIp[1],num,10);
  strcat(buf,num); strcat(buf,".");
  itoa(myIp[2],num,10);
  strcat(buf,num); strcat(buf,".");
  itoa(myIp[3],num,10);
  strcat(buf,num);
  return buf;
}

void setup() {
  // Make sure your serial terminal is closed before starting your Core.
  // Start up your Spark Core, you should hear a USB driver connection
  // being made after the following line runs.
  Serial.begin(115200);
  // Now it's ok to open your serial terminal software, and connect to the
  // available COM port.  The following line effectively pauses your
  // application waiting for a character to be received from the serial
  // terminal.  While it's waiting it processes the background tasks to
  // keep your Core connected to the Cloud.  Press ENTER in your 
  // serial terminal to start your application.
  while(!Serial.available()) Spark.process();

  // Print out the IP address the Spark Core is connected to
  Serial.print("Spark Core connected to IP: ");
  Serial.println(myIpAddress());
}

void loop() {
  // do nothing
}
4 Likes