-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathESP32cam-demo.ino
1868 lines (1526 loc) · 82.1 KB
/
ESP32cam-demo.ino
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*******************************************************************************************************************
*
* ESP32Cam development board demo sketch using Arduino IDE or PlatformIO
* Github: https://github.com/alanesq/ESP32Cam-demo
*
* Tested with ESP32 board manager version 3.0.7
*
* Starting point sketch for projects using the esp32cam development board with the following features
* web server with live video streaming and RGB data from camera demonstrated.
* sd card support using 1-bit mode (data pins are usually 2,4,12&13 but using 1bit mode only uses pin 2)
* flash led is still available for use (pin 4) and does not flash when accessing sd card
* Stores image in Spiffs if no sd card present
* PWM control of the illumination/flash LED
*
* If ota.h file is in the sketch folder you can enable OTA updating of this sketch by setting '#define ENABLE_OTA 1'
* in settings section. You can then update the sketch with a BIN file via OTA by accessing page http://x.x.x.x/ota
* This can make updating the sketch more convenient, especially if you have installed the camera in a case etc.
*
* GPIO:
* You can use io pins 13 and 12 for input or output (but 12 must not be high at boot)
* You could also use pins 1 & 3 if you do not use Serial (disable serialDebug in the settings below)
* Pins 14, 2 & 15 should be ok to use if you are not using an SD Card
* More info: https://randomnerdtutorials.com/esp32-cam-ai-thinker-pinout/
*
* You can use a MCP23017 io expander chip to give 16 gpio lines by enabling 'useMCP23017' in the setup section and connecting
* the i2c pins to 12 and 13 on the esp32cam module. Note: this requires the adafruit MCP23017 library to be installed.
*
* Created using the Arduino IDE with ESP32 module installed, no additional libraries required
* ESP32 support for Arduino IDE: https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json
*
* Info on the esp32cam board: https://randomnerdtutorials.com/esp32-cam-video-streaming-face-recognition-arduino-ide/
* https://github.com/espressif/esp32-camera
*
* To see a more advanced sketch along the same format as this one have a look at https://github.com/alanesq/CameraWifiMotion
* which includes email support, FTP, OTA updates and motion detection
*
* esp32cam-demo is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* https://alanesq.github.io/
*
*******************************************************************************************************************/
#if !defined ESP32
#error This sketch is only for an ESP32 Camera module
#endif
#include "esp_camera.h" // https://github.com/espressif/esp32-camera
#include <Arduino.h>
#include <esp_task_wdt.h> // watchdog timer - see: https://iotassistant.io/esp32/enable-hardware-watchdog-timer-esp32-arduino-ide/
// ---------------------------------------------------------------------------------------------------------
// ======================================
// Enter your wifi settings
// ======================================
#define SSID_NAME "<WIFI SSID HERE>"
#define SSID_PASWORD "<WIFI PASSWORD HERE>"
#define ENABLE_OTA 0 // If OTA updating of this sketch is enabled (requires ota.h file)
const String OTAPassword = "password"; // Password for performing OTA update (i.e. http://x.x.x.x/ota)
// ---------------------------------------------------------------------------------------------------------
// Required by PlatformIO
// forward declarations
bool initialiseCamera(bool); // this sets up and enables the camera (if bool=1 standard settings are applied but 0 allows you to apply custom settings)
bool cameraImageSettings(); // this applies the image settings to the camera (brightness etc.)
void changeResolution(framesize_t); // change camera resolution
String localTime(); // returns the current time as a String
void flashLED(int); // flashes the onboard indicator led
byte storeImage(); // stores an image in Spiffs or SD card
void handleRoot(); // the root web page
void handlePhoto(); // web page to capture an image from camera and save to spiffs or sd card
bool handleImg(); // Display a previously stored image
void handleNotFound(); // if invalid web page is requested
void readRGBImage(); // demo capturing an image and reading its raw RGB data
bool getNTPtime(int); // handle the NTP real time clock
bool handleJPG(); // display a raw jpg image
void handleJpeg(); // display a raw jpg image which periodically refreshes
void handleStream(); // stream live video (note: this can get the camera very hot)
int requestWebPage(String*, String*, int); // procedure allowing the sketch to read a web page its self
void handleTest(); // test procedure for experimenting with bits of code etc.
void handleReboot(); // handle request to restart device
void handleData(); // the root web page requests this periodically via Javascript in order to display updating information
void readGrayscaleImage(); // demo capturing a grayscale image and reading its raw RGB data
void resize_esp32cam_image_buffer(uint8_t*, int, int, uint8_t*, int, int); // this resizes a captured grayscale image (used by above)
// ---------------------------------------------------------------
// -SETTINGS
// ---------------------------------------------------------------
char* stitle = "ESP32Cam"; // title of this sketch
char* sversion = "10Dec24"; // Sketch version
framesize_t FRAME_SIZE_IMAGE = FRAMESIZE_SVGA; // default camera resolution
// Resolutions available:
// 160x120 (QQVGA), 128x160 (QQVGA2), 176x144 (QCIF), 240x176 (HQVGA), 240X240,
// 320x240 (QVGA), 400x296 (CIF), 640x480 (VGA default), 800x600 (SVGA),
// 1024x768 (XGA), 1280x1024 (SXGA), 1600x1200 (UXGA)
#define WDT_TIMEOUT 60 // timeout of watchdog timer (seconds)
const bool sendRGBfile = 0; // if set to 1 '/rgb' will just return raw rgb data which can then be saved as a file rather than display a HTML pag
uint16_t dataRefresh = 2; // how often to refresh data on root web page (seconds)
uint16_t imagerefresh = 2; // how often to refresh the image on root web page (seconds)
const bool serialDebug = 1; // show debug info. on serial port (1=enabled, disable if using pins 1 and 3 as gpio)
const int serialSpeed = 115200; // Serial data speed to use
#define useMCP23017 0 // set if MCP23017 IO expander chip is being used (on pins 12 and 13)
// Camera related
bool flashRequired = 0; // If flash to be used when capturing image (1 = yes)
int cameraImageExposure = 0; // Camera exposure (0 - 1200) If gain and exposure both set to zero then auto adjust is enabled
int cameraImageGain = 0; // Image gain (0 - 30)
int cameraImageBrightness = 0; // Image brightness (-2 to +2)
const int camChangeDelay = 200; // delay when deinit camera executed
const int TimeBetweenStatus = 600; // speed of flashing system running ok status light (milliseconds)
const int indicatorLED = 33; // onboard small LED pin (33)
// Bright LED (Flash)
const int brightLED = 4; // onboard Illumination/flash LED pin (4)
int brightLEDbrightness = 0; // initial brightness (0 - 255)
const int ledFreq = 5000; // PWM settings
const int ledChannel = 15; // camera uses timer1
const int ledRresolution = 8; // resolution (8 = from 0 to 255)
const int iopinA = 13; // general io pin 13
const int iopinB = 12; // general io pin 12 (must not be high at boot)
// camera settings (for the standard - OV2640 - CAMERA_MODEL_AI_THINKER)
// see: https://randomnerdtutorials.com/esp32-cam-camera-pin-gpios/
// set camera resolution etc. in 'initialiseCamera()' and 'cameraImageSettings()'
#define CAMERA_MODEL_AI_THINKER
#define PWDN_GPIO_NUM 32 // power to camera (on/off)
#define RESET_GPIO_NUM -1 // -1 = not used
#define XCLK_GPIO_NUM 0
#define SIOD_GPIO_NUM 26 // i2c sda
#define SIOC_GPIO_NUM 27 // i2c scl
#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 // vsync_pin
#define HREF_GPIO_NUM 23 // href_pin
#define PCLK_GPIO_NUM 22 // pixel_clock_pin
camera_config_t config; // camera settings
// ******************************************************************************************************************
//#include "esp_camera.h" // https://github.com/espressif/esp32-camera
// #include "camera_pins.h"
#include <WString.h> // this is required for base64.h otherwise get errors with esp32 core 1.0.6 - jan23
#include <base64.h> // for encoding buffer to display image on page
#include <WiFi.h>
#include <WebServer.h>
#include <HTTPClient.h>
#include "driver/ledc.h" // used to configure pwm on illumination led
// NTP - Internet time - see - https://randomnerdtutorials.com/esp32-ntp-timezones-daylight-saving/
#include "time.h"
struct tm timeinfo;
const char* ntpServer = "pool.ntp.org";
const char* TZ_INFO = "GMT+0BST-1,M3.5.0/01:00:00,M10.5.0/02:00:00"; // enter your time zone (https://remotemonitoringsystems.ca/time-zone-abbreviations.php)
long unsigned lastNTPtime;
time_t now;
// spiffs used to store images if no sd card present
#include <SPIFFS.h>
#include <FS.h> // gives file access on spiffs
WebServer server(80); // serve web pages on port 80
// Used to disable brownout detection
#include "soc/soc.h"
#include "soc/rtc_cntl_reg.h"
// sd-card
#include "SD_MMC.h" // sd card - see https://randomnerdtutorials.com/esp32-cam-take-photo-save-microsd-card/
#include <SPI.h>
#include <FS.h> // gives file access
#define SD_CS 5 // sd chip select pin = 5
// MCP23017 IO expander on pins 12 and 13 (optional)
#if useMCP23017 == 1
#include <Wire.h>
#include "Adafruit_MCP23017.h"
Adafruit_MCP23017 mcp;
// Wire.setClock(1700000); // set frequency to 1.7mhz
#endif
// Define some global variables:
uint32_t lastStatus = millis(); // last time status light changed status (to flash all ok led)
bool sdcardPresent; // flag if an sd card is detected
int imageCounter; // image file name on sd card counter
const String spiffsFilename = "/image.jpg"; // image name to use when storing in spiffs
String ImageResDetails = "Unknown"; // image resolution info
int currentRes = 0; // current selected camera resolution
// OTA Stuff
bool OTAEnabled = 0; // flag to show if OTA has been enabled (via supply of password in http://x.x.x.x/ota)
#if ENABLE_OTA
void sendHeader(WiFiClient &client, char* hTitle); // forward declarations
void sendFooter(WiFiClient &client);
#include "ota.h" // Over The Air updates (OTA)
#endif
// ---------------------------------------------------------------
// -SETUP SETUP SETUP SETUP SETUP SETUP
// ---------------------------------------------------------------
void setup() {
if (serialDebug) {
Serial.begin(serialSpeed); // Start serial communication
// Serial.setDebugOutput(true);
Serial.println("\n\n\n"); // line feeds
Serial.println("-----------------------------------");
Serial.printf("Starting - %s - %s \n", stitle, sversion);
Serial.println("-----------------------------------");
// Serial.print("Reset reason: " + ESP.getResetReason());
}
WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); // Turn-off the 'brownout detector'
// small indicator led on rear of esp32cam board
pinMode(indicatorLED, OUTPUT);
digitalWrite(indicatorLED,HIGH);
// Connect to wifi
digitalWrite(indicatorLED,LOW); // small indicator led on
if (serialDebug) {
Serial.print("\nConnecting to ");
Serial.print(SSID_NAME);
Serial.print("\n ");
}
WiFi.begin(SSID_NAME, SSID_PASWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
if (serialDebug) Serial.print(".");
}
if (serialDebug) {
Serial.print("\nWiFi connected, ");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
server.enableCORS(); // allow html to request pages without it being blocked
server.begin(); // start web server
digitalWrite(indicatorLED,HIGH); // small indicator led off
// define the web pages (i.e. call these procedures when url is requested)
server.on("/", handleRoot); // root page
server.on("/data", handleData); // suplies data to periodically update root (AJAX)
server.on("/jpg", handleJPG); // capture image and send as jpg
server.on("/jpeg", handleJpeg); // show updating image
server.on("/stream", handleStream); // stream live video
server.on("/photo", handlePhoto); // save image to sd card
server.on("/img", handleImg); // show image from sd card
server.on("/rgb", readRGBImage); // demo converting image to RGB
server.on("/graydata", readGrayscaleImage); // look at grayscale image data
server.on("/test", handleTest); // Testing procedure
server.on("/reboot", handleReboot); // restart device
server.onNotFound(handleNotFound); // invalid url requested
#if ENABLE_OTA
server.on("/ota", handleOTA); // ota updates web page
#endif
// NTP - internet time
if (serialDebug) Serial.println("\nGetting real time (NTP)");
configTime(0, 0, ntpServer);
setenv("TZ", TZ_INFO, 1);
if (getNTPtime(10)) { // wait up to 10 sec to sync
} else {
if (serialDebug) Serial.println("Time not set");
}
lastNTPtime = time(&now);
// set up camera
if (serialDebug) Serial.print(("\nInitialising camera: "));
if (initialiseCamera(1)) { // apply settings from 'config' and start camera
if (serialDebug) Serial.println("OK");
}
else {
if (serialDebug) Serial.println("failed");
}
// Spiffs - for storing images without an sd card
// see: https://circuits4you.com/2018/01/31/example-of-esp8266-flash-file-system-spiffs/
if (!SPIFFS.begin(true)) {
if (serialDebug) Serial.println(("An Error has occurred while mounting SPIFFS - restarting"));
delay(5000);
ESP.restart(); // restart and try again
delay(5000);
} else {
// SPIFFS.format(); // wipe spiffs
delay(5000);
if (serialDebug) {
Serial.print(("SPIFFS mounted successfully: "));
Serial.printf("total bytes: %d , used: %d \n", SPIFFS.totalBytes(), SPIFFS.usedBytes());
}
}
// SD Card - if one is detected set 'sdcardPresent' High
if (!SD_MMC.begin("/sdcard", true)) { // if loading sd card fails
// note: ('/sdcard", true)' = 1bit mode - see: https://dr-mntn.net/2021/02/using-the-sd-card-in-1-bit-mode-on-the-esp32-cam-from-ai-thinker
if (serialDebug) Serial.println("No SD Card detected");
sdcardPresent = 0; // flag no sd card available
} else {
uint8_t cardType = SD_MMC.cardType();
if (cardType == CARD_NONE) { // if invalid card found
if (serialDebug) Serial.println("SD Card type detect failed");
sdcardPresent = 0; // flag no sd card available
} else {
// valid sd card detected
uint16_t SDfreeSpace = (uint64_t)(SD_MMC.totalBytes() - SD_MMC.usedBytes()) / (1024 * 1024);
if (serialDebug) Serial.printf("SD Card found, free space = %dmB \n", SDfreeSpace);
sdcardPresent = 1; // flag sd card available
}
}
fs::FS &fs = SD_MMC; // sd card file system
// discover the number of image files already stored in '/img' folder of the sd card and set image file counter accordingly
imageCounter = 0;
if (sdcardPresent) {
int tq=fs.mkdir("/img"); // create the '/img' folder on sd card (in case it is not already there)
if (!tq) {
if (serialDebug) Serial.println("Unable to create IMG folder on sd card");
}
// open the image folder and step through all files in it
File root = fs.open("/img");
while (true)
{
File entry = root.openNextFile(); // open next file in the folder
if (!entry) break; // if no more files in the folder
imageCounter ++; // increment image counter
entry.close();
}
root.close();
if (serialDebug) Serial.printf("Image file count = %d \n",imageCounter);
}
// define i/o pins
pinMode(indicatorLED, OUTPUT); // defined again as sd card config can reset it
digitalWrite(indicatorLED,HIGH); // led off = High
pinMode(iopinA, INPUT); // pin 13 - free io pin, can be used for input or output
pinMode(iopinB, OUTPUT); // pin 12 - free io pin, can be used for input or output (must not be high at boot)
// MCP23017 io expander (requires adafruit MCP23017 library)
#if useMCP23017 == 1
Wire.begin(12,13); // use pins 12 and 13 for i2c
mcp.begin(&Wire); // use default address 0
mcp.pinMode(0, OUTPUT); // Define GPA0 (physical pin 21) as output pin
mcp.pinMode(8, INPUT); // Define GPB0 (physical pin 1) as input pin
mcp.pullUp(8, HIGH); // turn on a 100K pullup internally
// change pin state with mcp.digitalWrite(0, HIGH);
// read pin state with mcp.digitalRead(8)
#endif
// configure PWM for the illumination LED
pinMode(brightLED, OUTPUT);
analogWrite(brightLED, brightLEDbrightness);
// ESP32 Watchdog timer - Note: esp32 board manager v3.x.x requires different code
#if defined ESP32
esp_task_wdt_deinit(); // ensure a watchdog is not already configured
#if defined(ESP_ARDUINO_VERSION_MAJOR) && ESP_ARDUINO_VERSION_MAJOR == 3
// v3 board manager detected
if (serialDebug) Serial.println("Watchdog timer: v3 esp32 board manager detected");
esp_task_wdt_config_t wdt_config = {
.timeout_ms = WDT_TIMEOUT * 1000, // Convert seconds to milliseconds
.idle_core_mask = 1 << 0, // Which core to monitor
.trigger_panic = true // Enable panic
};
// Initialize the WDT with the configuration structure
esp_task_wdt_init(&wdt_config); // Pass the pointer to the configuration structure
esp_task_wdt_add(NULL); // Add current thread to WDT watch
esp_task_wdt_reset(); // reset timer
if (serialDebug) Serial.println("Watchdog Timer initialized");
#else
// pre v3 board manager assumed
if (serialDebug) Serial.println("Watchdog timer: Older esp32 board manager detected");
esp_task_wdt_init(WDT_TIMEOUT, true); //enable panic so ESP32 restarts
esp_task_wdt_add(NULL); //add current thread to WDT watch
#endif
#endif
// startup complete
if (serialDebug) Serial.println("\nStarted...");
flashLED(2); // flash the onboard indicator led
analogWrite(brightLED, 64); // change bright LED
delay(200);
analogWrite(brightLED, 0); // change bright LED
} // setup
// ----------------------------------------------------------------
// -LOOP LOOP LOOP LOOP LOOP LOOP LOOP
// ----------------------------------------------------------------
void loop() {
server.handleClient(); // handle any incoming web page requests
// <<< YOUR CODE HERE >>>
// // Capture an image and save to sd card every 5 seconds (i.e. time lapse)
// static uint32_t lastCamera = millis();
// if ( ((unsigned long)(millis() - lastCamera) >= 5000) && sdcardPresent ) {
// lastCamera = millis(); // reset timer
// storeImage(); // save an image to sd card
// if (serialDebug) Serial.println("Time lapse image captured");
// }
// flash status LED to show sketch is running ok
if ((unsigned long)(millis() - lastStatus) >= TimeBetweenStatus) {
lastStatus = millis(); // reset timer
esp_task_wdt_reset(); // reset watchdog timer (to prevent system restart)
digitalWrite(indicatorLED,!digitalRead(indicatorLED)); // flip indicator led status
}
} // loop
// ----------------------------------------------------------------
// Initialise the camera
// ----------------------------------------------------------------
// returns TRUE if successful
// reset - if set to 1 all settings are reconfigured
// if set to zero you can change the settings and call this procedure to apply them
bool initialiseCamera(bool reset) {
// set the camera parameters in 'config'
if (reset) {
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;
// variations in version of esp32 board manager (v3 changed the names for some reason)
#if defined(ESP_ARDUINO_VERSION_MAJOR) && ESP_ARDUINO_VERSION_MAJOR == 3
config.pin_sccb_sda = SIOD_GPIO_NUM; // v3.x
config.pin_sccb_scl = SIOC_GPIO_NUM;
#else
config.pin_sscb_sda = SIOD_GPIO_NUM; // pre v3
config.pin_sscb_scl = SIOC_GPIO_NUM;
#endif
config.pin_pwdn = PWDN_GPIO_NUM;
config.pin_reset = RESET_GPIO_NUM;
config.pin_pwdn = PWDN_GPIO_NUM;
config.pin_reset = RESET_GPIO_NUM;
config.xclk_freq_hz = 10000000; // XCLK 20MHz or 10MHz for OV2640 double FPS (Experimental)
config.pixel_format = PIXFORMAT_JPEG; // colour jpg format
config.frame_size = FRAME_SIZE_IMAGE; // Image sizes: 160x120 (QQVGA), 128x160 (QQVGA2), 176x144 (QCIF), 240x176 (HQVGA), 320x240 (QVGA),
// 400x296 (CIF), 640x480 (VGA, default), 800x600 (SVGA), 1024x768 (XGA), 1280x1024 (SXGA),
// 1600x1200 (UXGA)
config.jpeg_quality = 10; // 0-63 lower number means higher quality (can cause failed image capture if set too low at higher resolutions)
config.grab_mode = CAMERA_GRAB_WHEN_EMPTY;
//config.fb_location = CAMERA_FB_IN_PSRAM; // store the captured frame in PSRAM
config.fb_count = 1; // if more than one, i2s runs in continuous mode. Use only with JPEG
}
// check the esp32cam board has a psram chip installed (extra memory used for storing captured images)
// Note: if not using "AI thinker esp32 cam" in the Arduino IDE, PSRAM must be enabled
if (!psramFound()) {
if (serialDebug) Serial.println("Warning: No PSRam found so defaulting to image size 'CIF'");
config.frame_size = FRAMESIZE_SVGA;
config.fb_location = CAMERA_FB_IN_DRAM;
}
esp_err_t camerr = esp_camera_init(&config); // initialise the camera
if (camerr != ESP_OK) {
if (serialDebug) Serial.printf("ERROR: Camera init failed with error 0x%x", camerr);
}
cameraImageSettings(); // apply the camera image settings
return (camerr == ESP_OK); // return boolean result of camera initialisation
}
// ----------------------------------------------------------------
// -Change camera image settings
// ----------------------------------------------------------------
// Adjust image properties (brightness etc.)
// Defaults to auto adjustments if exposure and gain are both set to zero
// - Returns TRUE if successful
// More info: https://randomnerdtutorials.com/esp32-cam-ov2640-camera-settings/
// interesting info on exposure times here: https://github.com/raduprv/esp32-cam_ov2640-timelapse
bool cameraImageSettings() {
if (serialDebug) Serial.println("Applying camera settings");
sensor_t *s = esp_camera_sensor_get();
// something to try?: if (s->id.PID == OV3660_PID)
if (s == NULL) {
if (serialDebug) Serial.println("Error: problem reading camera sensor settings");
return 0;
}
// if both set to zero enable auto adjust
if (cameraImageExposure == 0 && cameraImageGain == 0) {
// enable auto adjust
s->set_gain_ctrl(s, 1); // auto gain on
s->set_exposure_ctrl(s, 1); // auto exposure on
s->set_saturation(s, -1); // Slightly decrease saturation
s->set_contrast(s, -1); // Slightly decrease contrast
s->set_whitebal(s, 1); // Enable auto white balanc
s->set_awb_gain(s, 1); // Auto White Balance enable (0 or 1)
s->set_brightness(s, cameraImageBrightness); // (-2 to 2) - set brightness
} else {
// Apply manual settings
s->set_gain_ctrl(s, 0); // auto gain off
s->set_awb_gain(s, 1); // Auto White Balance enable (0 or 1)
s->set_saturation(s, -1); // Slightly decrease saturation
s->set_contrast(s, -1); // Slightly decrease contrast
s->set_whitebal(s, 1); // Enable auto white balanc
s->set_exposure_ctrl(s, 0); // auto exposure off
s->set_brightness(s, cameraImageBrightness); // (-2 to 2) - set brightness
s->set_agc_gain(s, cameraImageGain); // set gain manually (0 - 30)
s->set_aec_value(s, cameraImageExposure); // set exposure manually (0-1200)
}
//s->set_vflip(s, 1); // flip image vertically
//s->set_hmirror(s, 1); // flip image horizontally
return 1;
} // cameraImageSettings
// // More camera settings available:
// // If you enable gain_ctrl or exposure_ctrl it will prevent a lot of the other settings having any effect
// // more info on settings here: https://randomnerdtutorials.com/esp32-cam-ov2640-camera-settings/
// s->set_gain_ctrl(s, 0); // auto gain off (1 or 0)
// s->set_exposure_ctrl(s, 0); // auto exposure off (1 or 0)
// s->set_agc_gain(s, 1); // set gain manually (0 - 30)
// s->set_aec_value(s, 1); // set exposure manually (0-1200)
// s->set_vflip(s, 1); // Invert image (0 or 1)
// s->set_quality(s, 10); // (0 - 63)
// s->set_gainceiling(s, GAINCEILING_32X); // Image gain (GAINCEILING_x2, x4, x8, x16, x32, x64 or x128)
// s->set_brightness(s, 0); // (-2 to 2) - set brightness
// s->set_lenc(s, 1); // lens correction? (1 or 0)
// s->set_saturation(s, 0); // (-2 to 2)
// s->set_contrast(s, 0); // (-2 to 2)
// s->set_sharpness(s, 0); // (-2 to 2)
// s->set_hmirror(s, 0); // (0 or 1) flip horizontally
// s->set_colorbar(s, 0); // (0 or 1) - show a testcard
// s->set_special_effect(s, 0); // (0 to 6?) apply special effect
// s->set_whitebal(s, 0); // white balance enable (0 or 1)
// s->set_awb_gain(s, 1); // Auto White Balance enable (0 or 1)
// s->set_wb_mode(s, 0); // 0 to 4 - if awb_gain enabled (0 - Auto, 1 - Sunny, 2 - Cloudy, 3 - Office, 4 - Home)
// s->set_dcw(s, 0); // downsize enable? (1 or 0)?
// s->set_raw_gma(s, 1); // (1 or 0)
// s->set_aec2(s, 0); // automatic exposure sensor? (0 or 1)
// s->set_ae_level(s, 0); // auto exposure levels (-2 to 2)
// s->set_bpc(s, 0); // black pixel correction
// s->set_wpc(s, 0); // white pixel correction
// ----------------------------------------------------------------
// returns the current time as a String
// ----------------------------------------------------------------
// see: https://randomnerdtutorials.com/esp32-date-time-ntp-client-server-arduino/
String localTime() {
struct tm timeinfo;
char ttime[40];
if(!getLocalTime(&timeinfo)) return"Failed to obtain time";
strftime(ttime,40, "%A %B %d %Y %H:%M:%S", &timeinfo);
return ttime;
}
// ----------------------------------------------------------------
// flash the indicator led 'reps' number of times
// ----------------------------------------------------------------
void flashLED(int reps) {
for(int x=0; x < reps; x++) {
digitalWrite(indicatorLED,LOW);
delay(1000);
digitalWrite(indicatorLED,HIGH);
delay(500);
}
}
// ----------------------------------------------------------------
// send standard html header (i.e. start of web page)
// ----------------------------------------------------------------
void sendHeader(WiFiClient &client, char* hTitle) {
// Start page
client.write("HTTP/1.1 200 OK\r\n");
client.write("Content-Type: text/html\r\n");
client.write("Connection: close\r\n");
client.write("\r\n");
client.write("<!DOCTYPE HTML><html lang='en'>\n");
// HTML / CSS
client.printf(R"=====(
<head>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<title>%s</title>
<style>
body {
color: black;
background-color: #FFFF00;
text-align: center;
}
input, select {
background-color: #FF9900;
border: 2px #FF9900;
color: blue;
padding: 3px 6px;
margin: 3px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
border-radius: 7px;
}
input:hover {
background-color: #FF4400;
}
</style>
</head>
<body>
<h1 style='color:red;'>%s</H1>
)=====", hTitle, hTitle);
}
// ----------------------------------------------------------------
// send a standard html footer (i.e. end of web page)
// ----------------------------------------------------------------
void sendFooter(WiFiClient &client) {
client.write("</body></html>\n");
delay(3);
client.stop();
}
// ----------------------------------------------------------------
// send line of text to both serial port and web page - used by readRGBImage
// ----------------------------------------------------------------
void sendText(WiFiClient &client, String theText) {
if (!sendRGBfile) client.print(theText + "<br>\n");
if (serialDebug || theText.indexOf("error") > 0) Serial.println(theText); // if text contains "error"
}
// ----------------------------------------------------------------
// reset the camera
// ----------------------------------------------------------------
// either hardware(1) or software(0)
void resetCamera(bool type = 0) {
if (type == 1) {
// power cycle the camera module (handy if camera stops responding)
digitalWrite(PWDN_GPIO_NUM, HIGH); // turn power off to camera module
delay(300);
digitalWrite(PWDN_GPIO_NUM, LOW);
delay(300);
initialiseCamera(1);
} else {
// reset via software (handy if you wish to change resolution or image type etc. - see test procedure)
esp_camera_deinit();
delay(camChangeDelay);
initialiseCamera(1);
}
}
// ----------------------------------------------------------------
// -change image resolution
// ----------------------------------------------------------------
// Change camera resolution
// Resolutions: 160x120 (QQVGA), 128x160 (QQVGA2), 176x144 (QCIF), 240x176 (HQVGA),
// 320x240 (QVGA), 400x296 (CIF), 640x480 (VGA, default), 800x600 (SVGA),
// 1024x768 (XGA), 1280x1024 (SXGA), 1600x1200 (UXGA)
void changeResolution(framesize_t newRes) {
esp_camera_deinit(); // disable camera
delay(camChangeDelay);
FRAME_SIZE_IMAGE = newRes;
initialiseCamera(1);
if (serialDebug) Serial.println("Camera resolution changed");
ImageResDetails = "Unknown"; // set next time image captured
}
// ----------------------------------------------------------------
// Capture image from camera and save to spiffs or sd card
// ----------------------------------------------------------------
// returns 0 if failed, 1 if stored in spiffs, 2 if stored on sd card
byte storeImage() {
byte sRes = 0; // result flag
fs::FS &fs = SD_MMC; // sd card file system
// capture the image from camera
int currentBrightness = brightLEDbrightness;
if (flashRequired) {
analogWrite(brightLED, 255); // change LED brightness (0 - 255)
delay(100);
}
camera_fb_t * fb = NULL;
fb = esp_camera_fb_get();
// there is a bug where this buffer can be from previous capture so as workaround it is discarded and captured again
esp_camera_fb_return(fb); // dispose the buffered image
fb = NULL; // reset to capture errors
fb = esp_camera_fb_get(); // get fresh image
if (flashRequired){
delay(100);
analogWrite(brightLED, currentBrightness); // change LED brightness back to previous state
}
if (!fb) {
if (serialDebug) Serial.println("Error: Camera capture failed");
return 0;
}
// save image to Spiffs
if (!sdcardPresent) {
if (serialDebug) Serial.println("Storing image to spiffs only");
SPIFFS.remove(spiffsFilename); // if file name already exists delete it
File file = SPIFFS.open(spiffsFilename, FILE_WRITE); // create new file
if (!file) {
if (serialDebug) Serial.println("Failed to create file in Spiffs - will format and try again");
if (!SPIFFS.format()) { // format spiffs
if (serialDebug) Serial.println("Spiffs format failed");
} else {
file = SPIFFS.open(spiffsFilename, FILE_WRITE); // try again to create new file
if (!file) {
if (serialDebug) Serial.println("Still unable to create file in spiffs");
}
}
}
if (file) { // if file has been created ok write image data to it
if (file.write(fb->buf, fb->len)) {
sRes = 1; // flag as saved ok
} else {
if (serialDebug) Serial.println("Error: failed to write image data to spiffs file");
}
}
esp_camera_fb_return(fb); // return camera frame buffer
if (sRes == 1 && serialDebug) {
Serial.print("The picture has been saved to Spiffs as " + spiffsFilename);
Serial.print(" - Size: ");
Serial.print(file.size());
Serial.println(" bytes");
}
file.close();
}
// save the image to sd card
if (sdcardPresent) {
if (serialDebug) Serial.printf("Storing image #%d to sd card \n", imageCounter);
String SDfilename = "/img/" + String(imageCounter + 1) + ".jpg"; // build the image file name
File file = fs.open(SDfilename, FILE_WRITE); // create file on sd card
if (!file) {
if (serialDebug) Serial.println("Error: Failed to create file on sd-card: " + SDfilename);
} else {
if (file.write(fb->buf, fb->len)) { // File created ok so save image to it
if (serialDebug) Serial.println("Image saved to sd card");
imageCounter ++; // increment image counter
sRes = 2; // flag as saved ok
} else {
if (serialDebug) Serial.println("Error: failed to save image data file on sd card");
}
file.close(); // close image file on sd card
}
}
esp_camera_fb_return(fb); // return frame so memory can be released
return sRes;
} // storeImage
// ----------------------------------------------------------------
// -Action any user input on root web page
// ----------------------------------------------------------------
void rootUserInput(WiFiClient &client) {
// if button1 was pressed (toggle io pin A)
// Note: if using an input box etc. you would read the value with the command: String Bvalue = server.arg("demobutton1");
// if image resultion was selected
if (server.hasArg("submit")) { // only if submit button was pressed
if (serialDebug) Serial.println("SUBMIT has been clicked");
if (server.hasArg("resolution")) {
String option = server.arg("resolution");
if (serialDebug) Serial.println("camera resolution selected = " + option);
framesize_t qres = FRAMESIZE_SVGA; // default
if (option == "QVGA") qres = FRAMESIZE_QVGA;
if (option == "VGA") qres = FRAMESIZE_VGA;
if (option == "SVGA") qres = FRAMESIZE_SVGA;
if (option == "XGA") qres = FRAMESIZE_XGA;
if (option == "SXGA") qres = FRAMESIZE_SXGA;
if (qres != FRAME_SIZE_IMAGE) changeResolution(qres); // change cameras resolution
}
}
// if button1 was pressed (toggle io pin B)
if (server.hasArg("button1")) {
if (serialDebug) Serial.println("Button 1 pressed");
digitalWrite(iopinB,!digitalRead(iopinB)); // toggle output pin on/off
}
// if button2 was pressed (Cycle illumination LED)
if (server.hasArg("button2")) {
if (serialDebug) Serial.println("Button 2 pressed");
if (brightLEDbrightness == 0) brightLEDbrightness = 10; // turn led on dim
else if (brightLEDbrightness == 10) brightLEDbrightness = 40; // turn led on medium
else if (brightLEDbrightness == 40) brightLEDbrightness = 255; // turn led on full
else brightLEDbrightness = 0; // turn led off
analogWrite(brightLED, brightLEDbrightness);
}
// if button3 was pressed (toggle flash)
if (server.hasArg("button3")) {
if (serialDebug) Serial.println("Button 3 pressed");
flashRequired = !flashRequired;
}
// if button3 was pressed (format SPIFFS)
if (server.hasArg("button4")) {
if (serialDebug) Serial.println("Button 4 pressed");
if (!SPIFFS.format()) {
if (serialDebug) Serial.println("Error: Unable to format Spiffs");
} else {
if (serialDebug) Serial.println("Spiffs memory has been formatted");
}
}
// if brightness was adjusted - cameraImageBrightness
if (server.hasArg("bright")) {
String Tvalue = server.arg("bright"); // read value
if (Tvalue != NULL) {
int val = Tvalue.toInt();
if (val >= -2 && val <= 2 && val != cameraImageBrightness) {
if (serialDebug) Serial.printf("Brightness changed to %d\n", val);
cameraImageBrightness = val;
cameraImageSettings(); // Apply camera image settings
}
}
}
// if exposure was adjusted - cameraImageExposure
if (server.hasArg("exp")) {
if (serialDebug) Serial.println("Exposure has been changed");
String Tvalue = server.arg("exp"); // read value
if (Tvalue != NULL) {
int val = Tvalue.toInt();
if (val >= 0 && val <= 1200 && val != cameraImageExposure) {
if (serialDebug) Serial.printf("Exposure changed to %d\n", val);
cameraImageExposure = val;
cameraImageSettings(); // Apply camera image settings
}
}
}
// if image gain was adjusted - cameraImageGain
if (server.hasArg("gain")) {
if (serialDebug) Serial.println("Gain has been changed");
String Tvalue = server.arg("gain"); // read value
if (Tvalue != NULL) {
int val = Tvalue.toInt();
if (val >= 0 && val <= 31 && val != cameraImageGain) {
if (serialDebug) Serial.printf("Gain changed to %d\n", val);
cameraImageGain = val;
cameraImageSettings(); // Apply camera image settings
}
}
}
}
// ----------------------------------------------------------------
// -root web page requested i.e. http://x.x.x.x/
// ----------------------------------------------------------------
// web page with control buttons, links etc.
void handleRoot() {
getNTPtime(2); // refresh current time from NTP server
WiFiClient client = server.client(); // open link with client
rootUserInput(client); // Action any user input from this web page
// html header
sendHeader(client, stitle);
client.write("<FORM action='/' method='post'>\n"); // used by the buttons in the html (action = the web page to send it to
// --------------------------------------------------------------------
// html main body
// Info on the arduino ethernet library: https://www.arduino.cc/en/Reference/Ethernet
// Info in HTML: https://www.w3schools.com/html/
// Info on Javascript (can be inserted in to the HTML): https://www.w3schools.com/js/default.asp
// Verify your HTML is valid: https://validator.w3.org/
// ---------------------------------------------------------------------------------------------
// info which is periodically updated using AJAX - https://www.w3schools.com/xml/ajax_intro.asp
// empty lines which are populated via vbscript with live data from http://x.x.x.x/data in the form of comma separated text
int noLines = 6; // number of text lines to be populated by javascript
for (int i = 0; i < noLines; i++) {
client.println("<span id='uline" + String(i) + "'></span><br>");
}
// Javascript - to periodically update the above info lines from http://x.x.x.x/data
// Note: You can compact the javascript to save flash memory via https://www.textfixer.com/html/compress-html-compression.php
// The below = client.printf(R"=====( <script> function getData() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var receivedArr = this.responseText.split(','); for (let i = 0; i < receivedArr.length; i++) { document.getElementById('uline' + i).innerHTML = receivedArr[i]; } } }; xhttp.open('GET', 'data', true); xhttp.send();} getData(); setInterval(function() { getData(); }, %d); </script> )=====", dataRefresh * 1000);
// get a comma seperated list from http://x.x.x.x/data and populate the blank lines in html above
client.printf(R"=====(
<script>
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var receivedArr = this.responseText.split(',');
for (let i = 0; i < receivedArr.length; i++) {
document.getElementById('uline' + i).innerHTML = receivedArr[i];
}
}
};
xhttp.open('GET', 'data', true);
xhttp.send();}
getData();
setInterval(function() { getData(); }, %d);
</script>
)=====", dataRefresh * 1000);
// ---------------------------------------------------------------------------------------------
// // touch input on the two gpio pins
// client.printf("<p>Touch on pin 12: %d </p>\n", touchRead(T5) );
// client.printf("<p>Touch on pin 13: %d </p>\n", touchRead(T4) );
// OTA
if (OTAEnabled) client.write("<br>OTA IS ENABLED!");
// Control buttons
client.write("<br><br>");
client.write("<input style='height: 35px;' name='button1' value='Toggle pin 12' type='submit'> \n");
client.write("<input style='height: 35px;' name='button2' value='Cycle illumination LED' type='submit'> \n");
client.write("<input style='height: 35px;' name='button3' value='Toggle Flash' type='submit'> \n");
client.write("<input style='height: 35px;' name='button4' value='Wipe SPIFFS memory' type='submit'> \n");