Skip to content

Instantly share code, notes, and snippets.

@abachman
Created April 27, 2018 17:05
Show Gist options
  • Save abachman/9da5eafb2642604db73f843310177ad8 to your computer and use it in GitHub Desktop.
Save abachman/9da5eafb2642604db73f843310177ad8 to your computer and use it in GitHub Desktop.
ESP8266 Arduino sketch w/ memory tracking
// using the new Feed#get() method to trigger MQTT resending
#define IO_USERNAME "abachman"
#define IO_KEY "xxx"
#define WIFI_SSID "normalnet"
#define WIFI_PASS "xxx"
#include "AdafruitIO_WiFi.h"
AdafruitIO_WiFi io(IO_USERNAME, IO_KEY, WIFI_SSID, WIFI_PASS);
AdafruitIO_Feed *counter = io.feed("counter"); // subscribe
AdafruitIO_Feed *messages = io.feed("messages"); // pub
// user_interface.h provides the system_get_free_heap_size function
extern "C" {
#include "user_interface.h"
}
const char* device_id = "esp8266-ff2d1x29"; // randomish
void setup() {
Serial.begin(115200);
// connect to io.adafruit.com
io.connect();
// set up a message handler for the count feed.
// the handleMessage function (defined below)
// will be called whenever a message is
// received from adafruit io.
counter->onMessage(handleMessage);
// wait for a connection to WiFi
int line = 1;
Serial.print("Connecting to WiFi");
while(io.status() < AIO_NET_CONNECTED) {
Serial.print(".");
delay(500);
line = (line + 1) % 80;
if (line == 0) Serial.println(' ');
}
// wait for a connection to IO
line = 1;
Serial.print("Connecting to Adafruit IO");
while(io.status() < AIO_CONNECTED) {
Serial.print(".");
delay(500);
line = (line + 1) % 80;
if (line == 0) Serial.println(' ');
}
// we are connected
Serial.println();
Serial.println(io.statusText());
Serial.print("publish to MQTT /get topic");
if (counter->get()) {
Serial.println("get() ok");
} else {
Serial.println("get() failed");
}
messages->save("connected " + String(device_id));
}
unsigned long count = 0;
unsigned long last_send = 0;
// memory usage update interval in milliseconds
unsigned long interval = 15000;
void loop() {
io.run();
unsigned long current = millis();
if ((current - last_send) > interval) {
Serial.print("received messages -> ");
Serial.println(count);
// Publish free heap size to Serial. If the heap gets smaller while your sketch is running,
// the program will eventually crash hard.
uint32_t free_heap = system_get_free_heap_size(); // <-- provided by user_interface.h lib
Serial.print("free heap size ");
Serial.println(free_heap);
messages->save(String(device_id) + " " + String(count) +
" messages received, free heap: " + String(free_heap));
last_send = current;
}
}
void handleMessage(AdafruitIO_Data *data) {
Serial.print("got <- ");
Serial.println(data->value());
count++;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment