-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathMQTT_Ethernet.ino
60 lines (45 loc) · 1.44 KB
/
MQTT_Ethernet.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
Publishing in the callback
- connects to an MQTT server
- subscribes to the topic "inTopic"
- when a message is received, republishes it to "outTopic"
This example shows how to control pins using Ethernet shield via MQTT
*/
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 100);
IPAddress server(192, 168, 1, 117);
const int lightPin = 8;
// Callback function header
void callback(char* topic, byte* payload, unsigned int length);
EthernetClient ethClient;
PubSubClient client(server, 1883, callback, ethClient);
// Callback function
void callback(char* topic, byte* payload, unsigned int length) {
//turn the LED ON if the payload is '1' and publish to the MQTT server a confirmation message
if(payload[0] == '1'){
digitalWrite(lightPin, HIGH);
client.publish("outTopic", "Light On"); }
//turn the LED OFF if the payload is '0' and publish to the MQTT server a confirmation message
if (payload[0] == '0'){
digitalWrite(lightPin, LOW);
client.publish("outTopic", "Light Off");
}
} // void callback
void setup()
{
pinMode(lightPin, OUTPUT);
digitalWrite(lightPin, LOW);
Ethernet.begin(mac, ip);
if (client.connect("arduinoClient")) {
client.publish("outTopic","hello world");
client.subscribe("inTopic");
}
}
void loop()
{
client.loop();
}