0% found this document useful (0 votes)
42 views2 pages

MQTT Demo 2.ino

Coding MQTT with Arduino Uno
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views2 pages

MQTT Demo 2.ino

Coding MQTT with Arduino Uno
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <SPI.

h>
#include <Ethernet.h>
#include <PubSubClient.h>
#include <string.h>

// Update these with values suitable for your network.


byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 61);
const char* server = "192.168.1.41";
char in_message[100];
EthernetClient ethClient;
PubSubClient mqttClient(ethClient);

void callback(char* topic, byte* payload, unsigned int length) {


Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("]\n ");
for (int i=0;i<length;i++) {
//Serial.print((char)payload[i]);
in_message[i]=char(payload[i]);
}
//Serial.print(payload);
}

void setup()
{
// Open serial communications and wait for port to open:

Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Ethernet.begin(mac, ip);
// Allow the hardware to sort itself out
delay(1500);
//mqttClient.setServer(server, 1883);
mqttClient.setServer("192.168.1.41", 1883);
mqttClient.setCallback(callback);

if (mqttClient.connect("arduino-1")) {
// connection succeeded
Serial.println("Connected ");
boolean r= mqttClient.subscribe("test");
Serial.println("subscribe ");
Serial.println(r);
}
else {
// connection failed
// mqttClient.state() will provide more information
// on why it failed.
Serial.println("Connection failed ");
}

void loop()
{
//
int count=0;
while (true)
{
count+=1;
char count_string[4];
sprintf(count_string, "%d", count);
Serial.println("publishing string");
Serial.println(count_string);
char out_msg[100] ="test message count= ";
strcat(out_msg,count_string);
boolean rc = mqttClient.publish("test", out_msg );
byte outmsg[]={0xff,0xfe};
Serial.println("publishing bytes");
rc = mqttClient.publish("testbyte", outmsg,2);
Serial.print("in_message= ");
Serial.print(in_message);

delay(1000);
mqttClient.loop();
}

You might also like