Hackster is hosting Hackster Holidays, Ep. 6: Livestream & Giveaway Drawing. Watch previous episodes or stream live on Monday!Stream Hackster Holidays, Ep. 6 on Monday!
Alex JonssonJohan Risch
Published © MIT

Visualize realtime MQTT feeds in your browser

A how-to article on getting started with MQTT using the free tier SA Studio, for graphing and analysing sensor data in the web browser

IntermediateProtip2 hours1,546
Visualize realtime MQTT feeds in your browser

Things used in this project

Hardware components

Arduino MKR1000
Arduino MKR1000
×1

Software apps and online services

SA Studio
SA Studio
Stream Analyze SA Studio

Story

Read more

Code

MQTT client for generating waves on the Arduino

Arduino
(example #1)
/*
  ArduinoMqttClient - WiFi Simple Sender
  -For the Arduino MKR 1000, MKR 1010 or Uno WiFi Rev.2 board
*/

#include <ArduinoMqttClient.h>
#include <WiFi101_Generic.h>

#include "arduino_secrets.h"
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = SECRET_SSID;        // your network SSID (name)
char pass[] = SECRET_PASS;    // your network password (use for WPA, or use as key for WEP)

// To connect with SSL/TLS:
// 1) Change WiFiClient to WiFiSSLClient.
// 2) Change port value from 1883 to 8883.
// 3) Change broker value to a server with a known SSL/TLS root certificate 
//    flashed in the WiFi module.

WiFiClient wifiClient;
MqttClient mqttClient(wifiClient);

const char broker[] = "YOUR-MQTT-BROKER-HERE"; // e.g. mqtt.mosquitto.org
int port     = 1883;
const char topic[]  = "YOUR-TOPIC-HERE"; // e.g. "test/values"

const long interval = 1000;
unsigned long previousMillis = 0;
const float pi=3.14159;
int analogValue = 0;

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // attempt to connect to Wifi network:
  Serial.print("Attempting to connect to WPA SSID: ");
  Serial.println(ssid);
  while (WiFi.begin(ssid, pass) != WL_CONNECTED) {
    // failed, retry
    Serial.print(".");
    delay(5000);
  }

  Serial.println("You're connected to the network");
  Serial.println();

  // You can provide a unique client ID, if not set the library uses Arduino-millis()
  // Each client must have a unique client ID
  // mqttClient.setId("clientId");

  // You can provide a username and password for authentication
  // mqttClient.setUsernamePassword("username", "password");

  Serial.print("Attempting to connect to the MQTT broker: ");
  Serial.println(broker);

  if (!mqttClient.connect(broker, port)) {
    Serial.print("MQTT connection failed! Error code = ");
    Serial.println(mqttClient.connectError());

    while (1);  // Goes on forever until connected
  }

  Serial.println("You're connected to the MQTT broker!");
  Serial.println();
}

void loop() {
  // call poll() regularly to allow the library to send MQTT keep alives which
  // avoids being disconnected by the broker
  mqttClient.poll();

  // avoid having delays in loop, we'll use the strategy from BlinkWithoutDelay
  // see: File -> Examples -> 02.Digital -> BlinkWithoutDelay for more info
  unsigned long currentMillis = millis();
  
  if (currentMillis - previousMillis >= interval) {
    // save the last time a message was sent
    previousMillis = currentMillis;

    static uint8_t pkt[8];
  
  static int i = 0;
  static int j = 0;
  static int x = 0;
  static float y = 0;
  static uint8_t square = 60;
  static uint8_t height = -1; 
   
  y=20*sin(x*pi/180);   //calculate sine, transform deg->rad 

  pkt[0] = 0x55; //Startbyte
  pkt[1] = 0x00; // Not in use
  pkt[2] = 0x00; // Not in use
  pkt[3] = square+height*20; //square wave
  pkt[4] = 97+i; //sawtooth wave
  *((int16_t *)&pkt[5]) = (int16_t)(y); //Sine wave
  pkt[7] = 0xAA; //Stopbyte
  
  
  i++;
  if(i>20)
  {
    i=0;
    height *=-1;
  }
  x=x+5;// increase the angle

  
  // Serial.write(pkt,8);  // send package

    Serial.print("Sending message to topic: ");
    Serial.println(topic);
    char serialString[16] = {0};
    sprintf(serialString,"%02X%02X%02X%02X%02X%02X%02X%02X",pkt[0],pkt[1],pkt[2],pkt[3],pkt[4],pkt[5],pkt[6],pkt[7]);
    Serial.print(serialString);
    Serial.println();

    // send message, the Print interface can be used to set the message contents
    mqttClient.beginMessage(topic);
    char dataString[16] = {0};
    sprintf(dataString,"%02X%02X%02X%02X%02X%02X%02X%02X",pkt[0],pkt[1],pkt[2],pkt[3],pkt[4],pkt[5],pkt[6],pkt[7]);
    mqttClient.print(dataString);
     
    mqttClient.endMessage();
    Serial.println();
  }
}

arduino_secrets.h

Arduino
Companion file for wifi settings
#define SECRET_SSID "YOUR-SSID-GOES-HERE"
#define SECRET_PASS "YOUR-SECRET-PASSWORD-GOES-HERE"

MQTT client for reading the analog port, and publishing the values on MQTT

Arduino
(example #2)
/*
  ArduinoMqttClient - WiFi Simple Sender
  -For the Arduino MKR 1000, MKR 1010 or Uno WiFi Rev.2 board
  This example code is in the public domain.
*/

#include <ArduinoMqttClient.h>
#include <WiFi101_Generic.h>

#include "arduino_secrets.h"
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = SECRET_SSID;        // your network SSID (name)
char pass[] = SECRET_PASS;    // your network password (use for WPA, or use as key for WEP)

// To connect with SSL/TLS:
// 1) Change WiFiClient to WiFiSSLClient.
// 2) Change port value from 1883 to 8883.
// 3) Change broker value to a server with a known SSL/TLS root certificate 
//    flashed in the WiFi module.

WiFiClient wifiClient;
MqttClient mqttClient(wifiClient);

const char broker[] = "op-en.se";
int port     = 1883;
const char topic[]  = "YOUR-MQTT-TOPIC-HERE";

const long interval = 1000;
unsigned long previousMillis = 0;
const float pi=3.14159;
int analogValue = 0;

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // attempt to connect to Wifi network:
  Serial.print("Attempting to connect to WPA SSID: ");
  Serial.println(ssid);
  while (WiFi.begin(ssid, pass) != WL_CONNECTED) {
    // failed, retry
    Serial.print(".");
    delay(5000);
  }

  Serial.println("You're connected to the network");
  Serial.println();

  // You can provide a unique client ID, if not set the library uses Arduino-millis()
  // Each client must have a unique client ID
  // mqttClient.setId("clientId");

  // You can provide a username and password for authentication
  // mqttClient.setUsernamePassword("username", "password");

  Serial.print("Attempting to connect to the MQTT broker: ");
  Serial.println(broker);

  if (!mqttClient.connect(broker, port)) {
    Serial.print("MQTT connection failed! Error code = ");
    Serial.println(mqttClient.connectError());

    while (1);  // Goes on forever until connected
  }

  Serial.println("You're connected to the MQTT broker!");
  Serial.println();
}

void loop() {
  // call poll() regularly to allow the library to send MQTT keep alives which
  // avoids being disconnected by the broker
  mqttClient.poll();

  // avoid having delays in loop, we'll use the strategy from BlinkWithoutDelay
  // see: File -> Examples -> 02.Digital -> BlinkWithoutDelay for more info
  unsigned long currentMillis = millis();
  
  if (currentMillis - previousMillis >= interval) {
    // save the last time a message was sent
    previousMillis = currentMillis;

    analogValue = analogRead(A0);

    Serial.print("Sending message to topic: ");
    Serial.println(topic);
    Serial.println(analogValue);

    // send message, the Print interface can be used to set the message contents
    mqttClient.beginMessage(topic);
    
    mqttClient.print(analogValue);
    mqttClient.endMessage();
    Serial.println();
  }
}

Credits

Alex Jonsson

Alex Jonsson

5 projects • 0 followers
Johan Risch

Johan Risch

3 projects • 0 followers

Comments