ESP32 Cam with Telegram App, Send images to Telegram
Table of Contents
ESP32 Cam with Telegram:
ESP32 Cam with Telegram App, Send images to Telegram- Today, we are going to make an IoT based Security Camera using ESP32 Cam Module and Telegram application.
But this is not just another security camera. It’s a camera with a twist. With a simple command, like ‘/flash,’ you can illuminate the night, ensuring you have a clear view of your surroundings whenever you need it.
And that’s not all. A tap on your Smartphone, using the command ‘/photo,’ unleashes the power of this incredible ESP32 Camera module, capturing high-quality images and instantly sending them to your Telegram app, right at your fingertips
This is a brilliant combination of hardware and software, unlocking a new level of control and security. It’s all about making your life safer and more convenient, 24/7. And since, this project is based on the IoT “Internet of things” so, you can request images from any part of the world provided if the internet connection is available.
This security camera is designed with portability in mind. You have the flexibility to power it using a single-cell lithium-ion battery, a LiPo battery, or a 4S lithium-ion battery pack, just like the one I’m using here with a 5V and 3A power supply. This setup has been invaluable for me, not only for this project but also for powering my Arduino-based projects that demand higher current.
For the sake of simplicity, I’ve opted not to include sensors like PIR motion sensors, microwave sensors, or ultrasonic sensors in this version. This way, beginners can dive right in and get started without any complexity.
But, stay tuned for my upcoming video and article where I’ll take this project to the next level by integrating one of these sensors, making it fully automatic. If you’re eager not to miss any of my future videos and project updates, don’t forget to hit that subscribe button!
So, without any further delay, let’s get started.
Amazon Links:
Disclosure: These are affiliate links. As an Amazon Associate I earn from qualifying purchases.
As I explained earlier, in this project, we are not using any sensors so there is no circuit diagram. All you need is the ESP32 Cam module and this ESP32 Camera development board for uploading the program. But, if you don’t have this development board then you can use the Arduino Uno for uploading the program. For this, you can read my getting started article on the ESP32 Camera module. But, I highly recommend, get yourself this ESP32 Camera development board, and trust me it will save a lot of your time. Now, let’s go ahead and setup the Arduino IDE.
ESP32 CAM in the Arduino IDE:
First of all, we will need to add the ESP32 Cam module in the Arduino IDE. Because, by default no ESP32 board is installed in the Arduino IDE and you can confirm this by going to the Tools Menu, then to Board, and you can see there is no ESP32 board.
So, first we will need to add it in the boards list, for this copy this Board Manager URL link;
https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json
Then go back to the Arduino IDE, go to the File Menu, then preferences, and paste this link in the Additional Boards Manager URLs and click the Ok button.
Next, go to the Tools Menu, then Board and click on the Boards Manager. Search for the ESP32. You can see we have Arduino ESP32 Boards and ESP32 by Espressif Systems.
So, make sure you install this one and don’t forget to select the latest version. Finally, the board installation has been completed and now we can confirm this by going to the boards list.
You can see all the different variants of the ESP32 Boards have been added. Now, let’s go ahead and open the program.
Install the required libraries:
Before, you start the programming, first of all, make sure you install the required libraries in the Arduino IDE. For this, simply copy the library name > then go to the Sketch Menu > then to Include Library > and click on the manage libraries. Paste the library name in the search box and install it. As you can see in the image down below, I have already installed the UniversalTelegramBot library.
Follow the same exact steps for the other library.
It’s already installed but needs an update so let’s update it. It’s good to keep all your libraries updated. Anyway, after installing the ESP32 Board in the Arduino IDE and after installing all the required libraries then you can congratulate yourself, because you are done with the hard work. Let’s go ahead and take a look the programming.
ESP32 CAM with Telegram Programming:
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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 |
#include <Arduino.h> #include <WiFi.h> #include <WiFiClientSecure.h> #include "soc/soc.h" #include "soc/rtc_cntl_reg.h" #include "esp_camera.h" #include <UniversalTelegramBot.h> #include <ArduinoJson.h> const char* ssid = "AndroidAP3DEC"; const char* password = "electroniclinic"; // Initialize Telegram BOT String BOTtoken = "6869476801:AAEOcKK7JYWUEkJkW4P5qomsQLbziHUKX4s"; // your Bot Token (Get from Botfather) // Use @myidbot to find out the chat ID of an individual or a group // Also note that you need to click "start" on a bot before it can // message you String CHAT_ID = "6213458614"; bool sendPhoto = false; WiFiClientSecure clientTCP; UniversalTelegramBot bot(BOTtoken, clientTCP); #define FLASH_LED_PIN 4 bool flashState = LOW; //Checks for new messages every 1 second. int botRequestDelay = 1000; unsigned long lastTimeBotRan; //CAMERA_MODEL_AI_THINKER #define PWDN_GPIO_NUM 32 #define RESET_GPIO_NUM -1 #define XCLK_GPIO_NUM 0 #define SIOD_GPIO_NUM 26 #define SIOC_GPIO_NUM 27 #define Y9_GPIO_NUM 35 #define Y8_GPIO_NUM 34 #define Y7_GPIO_NUM 39 #define Y6_GPIO_NUM 36 #define Y5_GPIO_NUM 21 #define Y4_GPIO_NUM 19 #define Y3_GPIO_NUM 18 #define Y2_GPIO_NUM 5 #define VSYNC_GPIO_NUM 25 #define HREF_GPIO_NUM 23 #define PCLK_GPIO_NUM 22 void configInitCamera(){ camera_config_t config; config.ledc_channel = LEDC_CHANNEL_0; config.ledc_timer = LEDC_TIMER_0; config.pin_d0 = Y2_GPIO_NUM; config.pin_d1 = Y3_GPIO_NUM; config.pin_d2 = Y4_GPIO_NUM; config.pin_d3 = Y5_GPIO_NUM; config.pin_d4 = Y6_GPIO_NUM; config.pin_d5 = Y7_GPIO_NUM; config.pin_d6 = Y8_GPIO_NUM; config.pin_d7 = Y9_GPIO_NUM; config.pin_xclk = XCLK_GPIO_NUM; config.pin_pclk = PCLK_GPIO_NUM; config.pin_vsync = VSYNC_GPIO_NUM; config.pin_href = HREF_GPIO_NUM; config.pin_sscb_sda = SIOD_GPIO_NUM; config.pin_sscb_scl = SIOC_GPIO_NUM; config.pin_pwdn = PWDN_GPIO_NUM; config.pin_reset = RESET_GPIO_NUM; config.xclk_freq_hz = 20000000; config.pixel_format = PIXFORMAT_JPEG; //init with high specs to pre-allocate larger buffers if(psramFound()){ config.frame_size = FRAMESIZE_UXGA; config.jpeg_quality = 10; //0-63 lower number means higher quality config.fb_count = 2; } else { config.frame_size = FRAMESIZE_SVGA; config.jpeg_quality = 12; //0-63 lower number means higher quality config.fb_count = 1; } // camera init esp_err_t err = esp_camera_init(&config); if (err != ESP_OK) { Serial.printf("Camera init failed with error 0x%x", err); delay(1000); ESP.restart(); } // Drop down frame size for higher initial frame rate sensor_t * s = esp_camera_sensor_get(); s->set_framesize(s, FRAMESIZE_CIF); // UXGA|SXGA|XGA|SVGA|VGA|CIF|QVGA|HQVGA|QQVGA } void handleNewMessages(int numNewMessages) { Serial.print("Handle New Messages: "); Serial.println(numNewMessages); for (int i = 0; i < numNewMessages; i++) { String chat_id = String(bot.messages[i].chat_id); if (chat_id != CHAT_ID){ bot.sendMessage(chat_id, "Unauthorized user", ""); continue; } // Print the received message String text = bot.messages[i].text; Serial.println(text); String from_name = bot.messages[i].from_name; if (text == "/start") { String welcome = "Welcome , " + from_name + "\n"; welcome += "Use the following commands to interact with the ESP32-CAM \n"; welcome += "/photo : takes a new photo\n"; welcome += "/flash : toggles flash LED \n"; bot.sendMessage(CHAT_ID, welcome, ""); } if (text == "/flash") { flashState = !flashState; digitalWrite(FLASH_LED_PIN, flashState); Serial.println("Change flash LED state"); } if (text == "/photo") { sendPhoto = true; Serial.println("New photo request"); } } } String sendPhotoTelegram() { const char* myDomain = "api.telegram.org"; String getAll = ""; String getBody = ""; camera_fb_t * fb = NULL; fb = esp_camera_fb_get(); if(!fb) { Serial.println("Camera capture failed"); delay(1000); ESP.restart(); return "Camera capture failed"; } Serial.println("Connect to " + String(myDomain)); if (clientTCP.connect(myDomain, 443)) { Serial.println("Connection successful"); String head = "--electroniclinic\r\nContent-Disposition: form-data; name=\"chat_id\"; \r\n\r\n" + CHAT_ID + "\r\n--electroniclinic\r\nContent-Disposition: form-data; name=\"photo\"; filename=\"esp32-cam.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n"; String tail = "\r\n--electroniclinic--\r\n"; uint16_t imageLen = fb->len; uint16_t extraLen = head.length() + tail.length(); uint16_t totalLen = imageLen + extraLen; clientTCP.println("POST /bot"+BOTtoken+"/sendPhoto HTTP/1.1"); clientTCP.println("Host: " + String(myDomain)); clientTCP.println("Content-Length: " + String(totalLen)); clientTCP.println("Content-Type: multipart/form-data; boundary=electroniclinic"); clientTCP.println(); clientTCP.print(head); uint8_t *fbBuf = fb->buf; size_t fbLen = fb->len; for (size_t n=0;n<fbLen;n=n+1024) { if (n+1024<fbLen) { clientTCP.write(fbBuf, 1024); fbBuf += 1024; } else if (fbLen%1024>0) { size_t remainder = fbLen%1024; clientTCP.write(fbBuf, remainder); } } clientTCP.print(tail); esp_camera_fb_return(fb); int waitTime = 10000; // timeout 10 seconds long startTimer = millis(); boolean state = false; while ((startTimer + waitTime) > millis()){ Serial.print("."); delay(100); while (clientTCP.available()) { char c = clientTCP.read(); if (state==true) getBody += String(c); if (c == '\n') { if (getAll.length()==0) state=true; getAll = ""; } else if (c != '\r') getAll += String(c); startTimer = millis(); } if (getBody.length()>0) break; } clientTCP.stop(); Serial.println(getBody); } else { getBody="Connected to api.telegram.org failed."; Serial.println("Connected to api.telegram.org failed."); } return getBody; } void setup(){ WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); // Init Serial Monitor Serial.begin(115200); // Set LED Flash as output pinMode(FLASH_LED_PIN, OUTPUT); digitalWrite(FLASH_LED_PIN, flashState); // Config and init the camera configInitCamera(); // Connect to Wi-Fi WiFi.mode(WIFI_STA); Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); clientTCP.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(500); } Serial.println(); Serial.print("ESP32-CAM IP Address: "); Serial.println(WiFi.localIP()); } void loop() { if (sendPhoto) { Serial.println("Preparing photo"); sendPhotoTelegram(); sendPhoto = false; } if (millis() > lastTimeBotRan + botRequestDelay) { int numNewMessages = bot.getUpdates(bot.last_message_received + 1); while (numNewMessages) { Serial.println("got response"); handleNewMessages(numNewMessages); numNewMessages = bot.getUpdates(bot.last_message_received + 1); } lastTimeBotRan = millis(); } } |
Make sure you change the SSID and Password.
You will also need to change the BOTtoken and CHAT_ID. You will get it from the Telegram App which I will explain in a minute. So, when your code is ready then all you need is to connect your ESP32 Camera module to your Laptop or PC.
Select the ESP32 Wrover Module.
Upload speed: 921600
Flash frequency: 80Mhz
Flash Mode: “QIO”
Partition Scheme: Huge APP (3MB No OTA) and
Finally, select the port and upload the program.
I have already uploaded this program. Now, let’s setup the Telegram Application.
Telegram App Setup:
Open the Telegram application on your cell phone, click the search button, and then click on the BotFather.
Click on the Restart.
Click on the /newbot to create a new bot.
First choose a name for your bot and then press enter and then choose a username for your bot. it must end in ‘bot’. if incase you have any confusion, you can watch the video tutorial given at the end of this article.
When you press enter, you will get the congratulation message along with the BOTtoken.
6869476801:AAEOcKK7JYWUEkJkW4P5qomsQLbziHUKX4s this is the BOTtoken, simply copy it and paste in the programming next to the BOTtoken.
Click the back button. This time search for the idbot.
Click the IDBot and then press the /start.
Next, write the /getid
You will get the Chat ID, simply copy it and paste it next to the CHAT_ID in the programming and that’s it.
Click the back button, then click on the BotFather, and finally, click on your bot link and start controlling and monitoring your ESP32 Camera module.
Let me remind you one more time, for any confusion, you can watch the video tutorial given below. If you liked the video; don’t forget to subscribe my YouTube channel.