#include <SPI.h>
#include <Ethernet.h>
#include "DHT.h"
// Define constants for the DHT sensor
#define DHTPIN 3 // Pin where the DHT sensor is connected
#define DHTTYPE DHT22 // DHT 22 sensor type
// Initialize DHT sensor
DHT dht(DHTPIN, DHTTYPE);
// Network settings
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // MAC address of Ethernet Shield
IPAddress ip(10, 40, 16, 23); // Static IP for the Arduino (optional)
EthernetClient influxClient; // Ethernet client object
// InfluxDB settings
int HTTP_PORT = 6100; // Port of InfluxDB server
char HOST_NAME[] = "192.168.1.99"; // InfluxDB server IP
String token = "replace_by_your_token"; // InfluxDB token
String organisation = "private"; // InfluxDB organization name
String bucket = "ArduinoTest"; // InfluxDB bucket name
void setup() {
Serial.begin(9600);
dht.begin();
// Initialize Ethernet
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to obtain an IP address using DHCP");
while (true);
}
Serial.println("Ethernet initialized");
}
// Function to send data to InfluxDB
void unfluxdb(String data) {
if (influxClient.connect(HOST_NAME, HTTP_PORT)) {
Serial.println("Connected to InfluxDB server");
// Construct HTTP POST request
influxClient.println("POST /api/v2/write?org=" + organisation + "&bucket=" + bucket + "&precision=ns HTTP/1.1");
influxClient.println("Host: " + String(HOST_NAME));
influxClient.println("Authorization: Token " + token);
influxClient.println("Content-Type: text/plain; charset=utf-8");
influxClient.println("Accept: application/json");
influxClient.println("Content-Length: " + String(data.length()));
influxClient.println();
influxClient.println(data);
// Wait for server response
while (influxClient.available()) {
char c = influxClient.read();
Serial.write(c);
}
influxClient.stop();
Serial.println("Data sent and connection closed");
} else {
Serial.println("Failed to connect to InfluxDB server");
}
}
void loop() {
// Read temperature and humidity from DHT sensor
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
// Check if sensor readings are valid
if (isnan(temperature) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Construct InfluxDB line protocol data
String data = "TFAOutDoor,sensor_id=7c temperature=" + String(temperature) + ",humidity=" + String(humidity);
// Send data to InfluxDB
unfluxdb(data);
// Delay before next read
delay(5000);
}