Skip to content

Instantly share code, notes, and snippets.

@chandler767
Last active November 13, 2020 10:11
Show Gist options
  • Save chandler767/472a93fac406af096d00c8377aa3fb17 to your computer and use it in GitHub Desktop.
Save chandler767/472a93fac406af096d00c8377aa3fb17 to your computer and use it in GitHub Desktop.
Pubnub Arduino SDK code sample for ESP8266. Demonstrates publish and subscribe. Get your unique PubNub keys from the PubNub Developer Portal (https://admin.pubnub.com/?devrel_gh=PubNub-UV-Index-Monitor ). If you don't have a PubNub account, you can sign up for a PubNub account for free (https://dashboard.pubnub.com/signup/?devrel_gh=PubNub-UV-In…
#include <ESP8266WiFi.h>
#define PubNub_BASE_CLIENT WiFiClient
#include <PubNub.h>
const char* ssid = "YourSSID";
const char* password = "YourPASSWORD";
const char* channelName = "hello_world";
void setup() {
Serial.begin(9600);
WiFi.begin(ssid, password);
if(WiFi.waitForConnectResult() == WL_CONNECTED){
PubNub.begin("demo", "demo");
} else {
Serial.println("Couldn't get a wifi connection");
while(1) delay(100);
}
}
void loop() {
PubNub_BASE_CLIENT *client;
Serial.println("publishing a message");
client = PubNub.publish(channelName, "\"\\\"Hello world!\\\" from Arduino.\"");
if (!client) {
Serial.println("publishing error");
delay(1000);
return;
}
while (client->connected()) {
while (client->connected() && !client->available());
char c = client->read();
Serial.print(c);
}
client->stop();
Serial.println();
Serial.println("waiting for a message (subscribe)");
PubSubClient *pclient = PubNub.subscribe(channel);
if (!pclient) {
Serial.println("subscription error");
delay(1000);
return;
}
while (pclient->wait_for_data()) {
char c = pclient->read();
Serial.print(c);
}
pclient->stop();
Serial.println();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment