#include <WiFi.
h>
#include <PubSubClient.h>
#include <DHT.h>
#include <esp_camera.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
// Replace with your network credentials
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";
// ThingsBoard information
const char* thingsboardServer = "YOUR_THINGSBOARD_SERVER";
const int thingsboardPort = 1883;
const char* thingsboardAccessToken = "YOUR_THINGSBOARD_ACCESS_TOKEN";
// PIR sensor pin
#define PIR_PIN 14
// Buzzer pin
#define BUZZER_PIN 15
// LED pin
#define LED_PIN 16
// DHT sensor pin
#define DHT_PIN 4
// MQTT client object
WiFiClient espClient;
PubSubClient client(espClient);
// DHT sensor object
DHT dht(DHT_PIN, DHT22);
// Timer variables
unsigned long lastCaptureTime = 0;
const unsigned long captureInterval = 5000; // 5 seconds
// Forward declarations
void camera_init();
esp_err_t camera_capture();
void captureAndSendData();
void reconnectToMQTT();
void mqttCallback(char* topic, byte* payload, unsigned int length);
void process_image(int width, int height, pixformat_t format, uint8_t *buffer,
size_t size);
// Camera configuration
#define CAM_PIN_PWDN -1 // Power-down pin (not used)
#define CAM_PIN_RESET -1 // Software reset pin (not used)
#define CAM_PIN_XCLK 21 // External clock pin
#define CAM_PIN_SIOD 26 // I2C SDA pin
#define CAM_PIN_SIOC 27 // I2C SCL pin
#define CAM_PIN_D7 35 // Data pin 7
#define CAM_PIN_D6 34 // Data pin 6
#define CAM_PIN_D5 39 // Data pin 5
#define CAM_PIN_D4 36 // Data pin 4
#define CAM_PIN_D3 19 // Data pin 3
#define CAM_PIN_D2 18 // Data pin 2
#define CAM_PIN_D1 5 // Data pin 1
#define CAM_PIN_D0 4 // Data pin 0
#define CAM_PIN_VSYNC 25 // Vertical sync pin
#define CAM_PIN_HREF 23 // Horizontal reference pin
#define CAM_PIN_PCLK 22 // Pixel clock pin
static camera_config_t camera_config = {
.pin_pwdn = CAM_PIN_PWDN,
.pin_reset = CAM_PIN_RESET,
.pin_xclk = CAM_PIN_XCLK,
.pin_sccb_sda = CAM_PIN_SIOD,
.pin_sccb_scl = CAM_PIN_SIOC,
.pin_d7 = CAM_PIN_D7,
.pin_d6 = CAM_PIN_D6,
.pin_d5 = CAM_PIN_D5,
.pin_d4 = CAM_PIN_D4,
.pin_d3 = CAM_PIN_D3,
.pin_d2 = CAM_PIN_D2,
.pin_d1 = CAM_PIN_D1,
.pin_d0 = CAM_PIN_D0,
.pin_vsync = CAM_PIN_VSYNC,
.pin_href = CAM_PIN_HREF,
.pin_pclk = CAM_PIN_PCLK,
.xclk_freq_hz = 20000000, // External clock frequency
.ledc_timer = LEDC_TIMER_0,
.ledc_channel = LEDC_CHANNEL_0,
.pixel_format = PIXFORMAT_JPEG, // JPEG image format
.frame_size = FRAMESIZE_UXGA, // Frame size UXGA (1600x1200)
.jpeg_quality = 12, // JPEG quality (0-63)
.fb_count = 1, // Frame buffer count
.grab_mode = CAMERA_GRAB_WHEN_EMPTY, // Grab mode
};
void setup() {
Serial.begin(115200);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Initialize DHT sensor
dht.begin();
// Set PIR pin as input
pinMode(PIR_PIN, INPUT);
// Set buzzer pin as output
pinMode(BUZZER_PIN, OUTPUT);
digitalWrite(BUZZER_PIN, LOW);
// Set LED pin as output
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
// Initialize the camera
camera_init();
// Connect to ThingsBoard
client.setServer(thingsboardServer, thingsboardPort);
client.setCallback(mqttCallback);
if (!client.connected()) {
reconnectToMQTT();
}
}
void loop() {
// Check PIR sensor
int pirValue = digitalRead(PIR_PIN);
// Read temperature from DHT22 sensor
float temperatureDHT = dht.readTemperature();
// Check if either PIR or DHT22 conditions are met
if (pirValue == HIGH || temperatureDHT > 34.0) {
Serial.println("Motion detected or temperature above 34 degrees Celsius!
Activating buzzer and LED...");
digitalWrite(BUZZER_PIN, HIGH); // Activate the buzzer
digitalWrite(LED_PIN, HIGH); // Turn on the LED
delay(5000); // Buzzer and LED active for 5 seconds
digitalWrite(BUZZER_PIN, LOW); // Turn off the buzzer
digitalWrite(LED_PIN, LOW); // Turn off the LED
// Capture and send data to ThingsBoard
captureAndSendData();
Serial.println("Data sent to ThingsBoard");
} else if (pirValue == HIGH) {
Serial.println("Motion detected!");
} else if (temperatureDHT > 34.0) {
Serial.println("Temperature above 34 degrees Celsius!");
}
// Check time to capture data
if (millis() - lastCaptureTime >= captureInterval) {
// Capture and send data to ThingsBoard
captureAndSendData();
}
// Reconnect to MQTT broker if disconnected
if (!client.connected()) {
reconnectToMQTT();
}
// Maintain MQTT client
client.loop();
}
void camera_init() {
// Power up the camera if PWDN pin is defined
if (CAM_PIN_PWDN != -1) {
pinMode(CAM_PIN_PWDN, OUTPUT);
digitalWrite(CAM_PIN_PWDN, LOW);
}
// Initialize the camera module
esp_err_t err = esp_camera_init(&camera_config);
if (err != ESP_OK) {
Serial.println("Camera Init Failed");
}
}
esp_err_t camera_capture() {
//acquire a frame
camera_fb_t * fb = esp_camera_fb_get();
if (!fb) {
Serial.println("Camera Capture Failed");
return ESP_FAIL;
}
//replace this with your own function
process_image(fb->width, fb->height, fb->format, fb->buf, fb->len);
//return the frame buffer back to the driver for reuse
esp_camera_fb_return(fb);
return ESP_OK;
}
void process_image(int width, int height, pixformat_t format, uint8_t *buffer,
size_t size) {
// Here you can process the captured image before sending it to ThingsBoard.
// For example, you can convert the image to Base64 or resize it before sending.
// For demonstration purposes, let's just print the image size.
Serial.printf("Image size: %dx%d, format: %d, size: %d\n", width, height, format,
size);
}
// Capture and send data to ThingsBoard
captureAndSendData ();
Serial.println("Data sent to ThingsBoard");
} else if (pirValue == HIGH) {
Serial.println("Motion detected!");
} else if (temperatureDHT > 34.0) {
Serial.println("Temperature above 34 degrees Celsius!");
}
// Check time to capture data
if (millis() - lastCaptureTime >= captureInterval) {
// Capture and send data to ThingsBoard
captureAndSendData();
}
// Reconnect to MQTT broker if disconnected
if (!client.connected()) {
reconnectToMQTT();
}
// Maintain MQTT client
client.loop();
}
void captureAndSendData() {
// Capture a photo
camera_fb_t* fb = esp_camera_fb_get();
if (!fb) {
Serial.println("Camera capture failed");
return;
}
// Send photo to ThingsBoard as telemetry data
if (client.publish("v1/devices/me/telemetry", reinterpret_cast<const
uint8_t*>(fb->buf), fb->len)) {
Serial.println("Photo sent to ThingsBoard");
} else {
Serial.println("Failed to send photo to ThingsBoard");
}
esp_camera_fb_return(fb);
// Read temperature and humidity from DHT22 sensor
float temperatureDHT = dht.readTemperature();
float humidity = dht.readHumidity();
// Create JSON payload for sending telemetry data
StaticJsonDocument<256> jsonPayload;
jsonPayload["temperature_dht"] = temperatureDHT;
jsonPayload["humidity"] = humidity;
// Convert JSON to string
String payloadString;
serializeJson(jsonPayload, payloadString);
// Send telemetry data to ThingsBoard
if (client.publish("v1/devices/me/telemetry", payloadString.c_str())) {
Serial.println("Telemetry data sent to ThingsBoard");
} else {
Serial.println("Failed to send telemetry data to ThingsBoard");
}
// Update last capture time
lastCaptureTime = millis();
}
void reconnectToMQTT() {
while (!client.connected()) {
Serial.println("Attempting MQTT connection...");
if (client.connect("ESP32Client", thingsboardAccessToken, nullptr)) {
Serial.println("Connected to ThingsBoard");
} else {
Serial.print("Failed to connect to ThingsBoard, rc=");
Serial.print(client.state());
Serial.println(" Retrying in 5 seconds...");
delay(5000);
}
}
}
void mqttCallback(char* topic, byte* payload, unsigned int length) {
// You can add code to handle incoming MQTT messages here
// For example, you can parse JSON payload and take specific actions based on the
received data
// For this example, we're not implementing any specific actions for incoming
MQTT messages
}