Arduino-Pubnub-P5JS

From Digipool-Wiki
Revision as of 17:29, 2 January 2024 by WikiSysop (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Using a real-time communication platform PubNub, data can be exchanged relatively easily between the Arduino and the P5JS via WLAN and the Internet. For example, the following code below switches the Arduino's on-board LED on and off via a cell phone or other device with an Internet browser.

Example
For this purpose, the P5JS code with the "myButton" DOM object has a "Submit" button that calls the "sendMessage" function. If the button is pressed, the ASCII character "1" is sent via the variable "x". The Arduino first establishes a WLAN connection and then a connection to Pubnub, and immediately receives all new messages that arrive there. If the message at character number 19 consists of the character "1", the LED is switched.

Pubnub vs Arduino-Cloud
The advantage for IOT projects that are realized in this way is that they can be shared with others free of charge and without restrictions. With services such as the Arduino Cloud or Blynk, a monthly fee would be due.


Board

This example works with most ESP8266 boards. If necessary, only the LED pin would have to be adapted.

It was tested with the following hardware:

  • AZDelivery D1 Mini — (LOLIN (WEMOS) D1 R2 & Mini)


PubNub

Register for a free PubNub account and create a new application by simply clicking on the "CREATE NEW APP" button.

There you will find the two PUBkey and SUBkey codes. That's all!

www.pubnub.com



Arduino


Arduino-Libraries


Arduino-Code

// Arduino + PubNub + P5JS
// pubnub to arduino example: https://github.com/pubnub/arduino-pubnub
// or: https://github.com/pubnub/arduino

#include <SPI.h>
#include <ESP8266WiFi.h>
#include <PubNub.h>

const char* ssid = "myWlanName"; // Add your WlanName here!
const char* password = "myWlanPassWord"; // // Add your WlanPassWord here!

char pubkey[] = "pub-c-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; // Add your pubkey here!
char subkey[] = "sub-c-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; // Add your subkey here!
char channel[] = "P1"; 
char uuid[] = "xxxxxxxx-xxxx-4444-9999-xxxxxxxxxxxx";

int ledPin = 2;  // D4
int keyVal = 0;

void setup() {
  Serial.begin(9600);
  delay(10);
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, HIGH);

  // Connecting with Wifi
  Serial.println("");
  Serial.print("Connecting with: ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("Wifi is successfully connected");
  flash(ledPin, 12);

  PubNub.begin(pubkey, subkey);
  random_uuid();
  PubNub.set_uuid(uuid);
  Serial.println("PubNub set up");
}

void loop() {

  Serial.println("Waiting for a message (subscribe)");
  PubSubClient* client = PubNub.subscribe(channel);
  if (!client) {
    Serial.println("Subscription error");
    delay(1000);
    return;
  }

  String msg;
  SubscribeCracker ritz(client);
  while (!ritz.finished()) {
    ritz.get(msg);
    if (msg.length() > 0) {
      Serial.print("Received: ");
      Serial.println(msg);
      keyVal = int(msg[19]); 
      Serial.println(keyVal);
      if (keyVal == '1') {
        Serial.println("LED is on");
        digitalWrite(ledPin, LOW);
        delay(5000);
        digitalWrite(ledPin, HIGH);
        delay(100);
        Serial.println("LED is off");
      }
    }
  }

  client->stop();

  delay(1500);

  digitalWrite(ledPin, HIGH);  // turn the LED off by making the voltage LOW
}

void random_uuid() {
  randomSeed(analogRead(4) + millis() * 1024);
  snprintf(uuid,
           sizeof(uuid),
           "%04lx%04lx-%04lx-4444-9999-%04lx%04lx%04lx",
           random(0x10000),
           random(0x10000),
           random(0x10000),
           random(0x10000),
           random(0x10000),
           random(0x10000));
}

void flash(int _ledPin, int times) {
  for (int i = 0; i < times; i++) {
    digitalWrite(_ledPin, LOW);
    delay(100);
    digitalWrite(_ledPin, HIGH);
    delay(100);
  }
}


P5JS


P5JS-Library

<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.4.28.0.js"></script>


P5JS-Code

// Arduino+PubNub+P5JS
// Based on "PubNub setup" by DigitalFuturesOCADU

let signalTime = 500;
let dataServer;
const pubKey = "pub-c-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; // Add your pubkey here!
const subKey = "sub-c-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; // Add your subkey here!
const channelName = "P1";
const publisherId = "boo";
const dataReceived = [];
const presenceUpdates = [];

let mx = 100;
let my = 50;

let myButton;
let fSize;
let bPro = 0;
let bTimer = 0;

let photo;

const myMessage = {
  messageId: 1,
  x: 0,
  y: 0,
  token: 0,
  text: "psssst here is a secret message",
  recipient: "crush",
};

function setup() {
  frameRate(15);
  createCanvas(windowWidth, windowHeight);
  fSize = width / 20;
  textSize(fSize);
  textAlign(CENTER, CENTER);
  fill(255);

  myToken = round(random(10000));

  // initialize PubNub
  dataServer = new PubNub({
    publish_key: pubKey,
    subscribe_key: subKey,
    ssl: true,
    uuid: publisherId,
  });

  dataServer.addListener({
    message: readIncoming,
  });
  dataServer.subscribe({
    channels: [channelName],
    withPresence: true,
  });

  window.onbeforeunload = function () {
    dataServer.unsubscribeAll();
    return null;
  };

  myButton = createButton("submit");
  myButton.position(width / 2 - fSize * 6, (height / 10) * 8);
  myButton.size(fSize * 12, fSize * 2);
  myButton.mousePressed(sendMessage);
  myButton.style("opacity", 0.0);
  myButton.show();
}

function draw() {
  background(20, 90, 90);

  fill(255);
  text("Arduino+Pubnub+P5JS", windowWidth / 2, (height / 10) * 2);

  showButton();
}

function showButton() {
  if (bPro == 0) {
    fill(255);
  } else {
    fill(0);
  }
  rect(
    width / 2 - fSize * 6,
    (height / 10) * 8,
    fSize * 12,
    fSize * 2,
    fSize / 2
  );
  if (bPro == 0) {
    fill(0);
  } else {
    fill(255);
  }
  text("Signal", windowWidth / 2, (height / 10) * 8 + fSize);
  if (millis() > bTimer + signalTime) {
    bPro = 0;
  }
}

function readIncoming(inMessage) {
  console.log(inMessage);
  mx = inMessage.message.x;
  my = inMessage.message.y;
  inToken = inMessage.message.token;
}

function sendMessage() {
  bPro = 1;
  bTimer = millis();
  showButton();
  myMessage.x = 1;
  myMessage.token = myToken;

  dataServer.publish({
    channel: channelName,
    message: myMessage,
  });
}