Page MenuHomePhabricator
Paste P274

(An Untitled Masterwork)
ActivePublic

Authored by stwalkerster on Jun 21 2020, 2:11 AM.
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_AM2320.h>
#include <SPI.h>
#include <Ethernet.h>
#include <Arduino.h>
#include <MQTT.h>
#include "credentials.h"
#define NETWORK_CONN_STATUS 13
#define NETWORK_PACKET_SEND 13
#define BROADCAST_FREQUENCY 2000
// CONSTANTS
byte mac[] = { 0x0E, 0x00, 0x00, 0x00, 0x00, 0x03 }; // temp1
// byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 }; // arduino
Adafruit_AM2320 am2320 = Adafruit_AM2320();
EthernetClient net;
MQTTClient client;
void(* resetFunc) (void) = 0;
void connect() {
Serial.print("connect()");
// net.setInsecure();
client.setWill(MQTT_MONTOPIC, "missing", true, 1);
while (!client.connect(MQTT_CLIENT, MQTT_USERNAME, MQTT_PASSWORD)) {
delay(1000);
}
client.publish(MQTT_MONTOPIC, "connected", true, 1);
digitalWrite(NETWORK_CONN_STATUS, HIGH);
Serial.println(" connected.");
}
void setup() {
Serial.begin(115200);
pinMode(NETWORK_CONN_STATUS, OUTPUT);
pinMode(NETWORK_PACKET_SEND, OUTPUT);
digitalWrite(NETWORK_CONN_STATUS, LOW);
digitalWrite(NETWORK_PACKET_SEND, HIGH);
Serial.print("Connecting to network... ");
delay(250);
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed DHCP");
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
Serial.println("Ethernet module was not found.");
} else if (Ethernet.linkStatus() == LinkOFF) {
Serial.println("Ethernet cable is not connected.");
}
delay(5000);
resetFunc();
}
Serial.println(Ethernet.localIP());
// initialise the sensor
am2320.begin();
// connect to broker
client.begin(MQTT_BROKER, MQTT_PORT, net);
connect();
}
unsigned long lastMillis = 0;
void loop() {
if (!client.connected()) {
digitalWrite(NETWORK_CONN_STATUS, LOW);
connect();
}
Ethernet.maintain();
client.loop();
delay(500);
if(millis() > (lastMillis + BROADCAST_FREQUENCY)) {
float temp = am2320.readTemperature();
float humid = am2320.readHumidity();
digitalWrite(NETWORK_PACKET_SEND, LOW);
client.publish(MQTT_TOPIC_TEMP, String(temp), true, 1);
client.publish(MQTT_TOPIC_HUMID, String(humid), true, 1);
digitalWrite(NETWORK_PACKET_SEND, HIGH);
Serial.println("T:" + String(temp) + " H:" + String(humid));
lastMillis = millis();
}
}

Event Timeline

stwalkerster created this object with visibility "Public (No Login Required)".
credentials.h
#define MQTT_BROKER      "mqttbroker.localdomain"
#define MQTT_PORT        1883
#define MQTT_USERNAME    "arduino"
#define MQTT_PASSWORD    "hunter2"
#define MQTT_CLIENT      "arduino"

#define MQTT_TOPIC_TEMP  "sensor/temperature"
#define MQTT_TOPIC_HUMID "sensor/humidity"
#define MQTT_MONTOPIC    "client/arduino/status"