Skip to content

Instantly share code, notes, and snippets.

@McOrLi1
Created October 8, 2015 17:41
Show Gist options
  • Save McOrLi1/f2969863a1eb05de7039 to your computer and use it in GitHub Desktop.
Save McOrLi1/f2969863a1eb05de7039 to your computer and use it in GitHub Desktop.
#include <SPI.h>
#include <Bounce2.h>
#include <Ethernet.h>
#include <PubSubClient.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(8, 7, 6, 5, 4, 3, 2);
int backLight = 9; // pin 13 will control the backlight
void callback(char* topic, byte* payload, unsigned int length);
char* inTopic = "1";
char* OutTopic = "ArduinoButton";
char message_buff[100];
byte mac[] = { 0x26, 0x9E, 0x05, 0xE2, 0x59, 0xA0 };
byte server[] = { 192, 168, 0, 50 };
int port = 1883;
EthernetClient ethClient;
PubSubClient mqttClient(server, port, callback, ethClient);
void setup() {
Serial.begin(9600);
pinMode(backLight, OUTPUT);
digitalWrite(backLight, HIGH); // turn backlight on. Replace 'HIGH' with 'LOW' to turn it off.
lcd.begin(16, 2); // columns, rows. use 16,2 for a 16x2 LCD, etc.
lcd.clear(); // start with a blank screen
lcd.setCursor(0, 0); // set cursor to column 0, row 0 (the first row)
lcd.print("waiting"); // change this text to whatever you like. keep it clean.
lcd.setCursor(0, 1); // set cursor to column 0, row 1
lcd.print("...");
Serial.print("start");
if (!Ethernet.begin(mac)) {
Serial.println(F("Failed to configure Ethernet using DHCP"));
for (;;)
;
} else {
Serial.print(F("Arduino IP address: "));
Serial.print(Ethernet.localIP());
}
Serial.println();
}
void loop() {
mqttConnection();
}
void mqttConnection() {
Ethernet.maintain();
// add reconnection logics
if (!mqttClient.connected()) {
// connection to MQTT server
if (mqttClient.connect("1")) {
Serial.println(F("Successfully connected with MQTT"));
mqttSubscribe(); // topic subscription
}
}
mqttClient.loop();
}
void mqttSubscribe() {
mqttClient.subscribe("1/#");
}
void callback(char* topic, byte* payload, unsigned int length) {
int i = 0;
Serial.println("Message arrived: topic: " + String(topic));
for(i=0; i < length; i++) {
message_buff[i] = payload[i];
}
message_buff[i] = '\0';
String msgString = String(message_buff);
Serial.println("Payload: " + msgString);
if (msgString[0] == 0)
{
lcd.clear();
lcd.setCursor(0, 0); // set cursor to column 0, row 0 (the first row)
lcd.print("access"); // change this text to whatever you like. keep it clean.
lcd.setCursor(0, 1); // set cursor to column 0, row 1
lcd.print("denied");
}
else if (msgString[0] == 1) {
lcd.clear();
lcd.setCursor(0, 0); // set cursor to column 0, row 0 (the first row)
lcd.print("access"); // change this text to whatever you like. keep it clean.
lcd.setCursor(0, 1); // set cursor to column 0, row 1
lcd.print("granted");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment