Skip to content

Instantly share code, notes, and snippets.

@chut
Created October 16, 2013 16:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save chut/7011078 to your computer and use it in GitHub Desktop.
Save chut/7011078 to your computer and use it in GitHub Desktop.
An example of how to connect to the xively MQTT server using arduino. Based on the pubsub client by knolleary
/*
Xively MQTT example
-Subscribes to Xively feed
-publishes current value to serial monitor
Based on Basic MQTT Example by knolleary
By Calum Barnes, Xively (c) 2013
BSD 3 License
*/
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte server[] = { 64, 94, 18, 120 };
byte ip[] = { 192, 168, 1, 10 };
String stringone = "api.xively.com";
void callback(char* topic, byte* payload, unsigned int length) {
Serial.println(topic);
//convert byte to char
payload[length] = '\0';
String strPayload = String((char*)payload);
Serial.println(strPayload);
int valoc = strPayload.lastIndexOf(',');
String val = strPayload.substring(valoc+1);
Serial.println(val);
}
EthernetClient ethClient;
PubSubClient client(server, 1883, callback, ethClient);
void setup()
{
Serial.begin(19200);
Serial.println("==STARTING==");
// start the Ethernet connection:
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// no point in carrying on, so do nothing forevermore:
// try to congifure using IP address instead of DHCP:
Ethernet.begin(mac, ip);
}
// give the Ethernet shield a second to initialize:
delay(1000);
Serial.println("connecting...");
for (byte thisByte = 0; thisByte < 4; thisByte++) {
// print the value of each byte of the IP address:
Serial.print(Ethernet.localIP()[thisByte], DEC);
Serial.print(".");
}
//delay(500);
boolean con = client.connect("arduinoMQTT", "XIVELY_API_KEY", "");
while(con != 1){
Serial.println("no con-while");
con = client.connect("arduinoMQTT", "XIVELY_API_KEY", "");
}
//Serial.println(con);
if(con){
Serial.println("got con");
//client.publish("outTopic","hello world");
client.subscribe("/v2/feeds/FEED_ID.csv");
}else Serial.println("no con");
}
void loop()
{
client.loop();
}
@liuluqqzj
Copy link

Hello, do you send your MQTT PUBLISH and receive MQTT SUBCRIBE through HTTP or just TCP socket? Can you printf the datastream you send and receive? Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment