esp32cam-demo/esp32cam-demo.ino

885 wiersze
38 KiB
Arduino
Czysty Zwykły widok Historia

2020-09-26 14:35:33 +00:00
/*******************************************************************************************************************
*
* ESP32Cam development board demo sketch using Arduino IDE
* Github: https://github.com/alanesq/ESP32Cam-demo
*
* Starting point sketch for projects using the esp32cam development board with the following features
* web server with live video streaming
* sd card support (using 1bit mode to free some io pins)
2020-09-27 06:21:17 +00:00
* io pins available for use are 13 and 12 (12 must be low at boot)
* flash led is still available for use on pin 4 and does not flash when accessing sd card
2020-09-26 14:35:33 +00:00
*
*
2020-11-13 15:17:38 +00:00
* 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
2020-09-26 14:35:33 +00:00
*
* Info on the esp32cam board: https://randomnerdtutorials.com/esp32-cam-video-streaming-face-recognition-arduino-ide/
*
2020-09-27 06:21:17 +00:00
* 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, time from NTP servers and motion detection
2020-10-18 13:26:49 +00:00
*
2020-09-26 14:35:33 +00:00
*
2020-10-18 13:26:49 +00:00
* esp32cam-demo is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
2020-10-01 15:49:36 +00:00
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
2020-10-18 13:26:49 +00:00
*
2020-09-26 14:35:33 +00:00
*******************************************************************************************************************/
#include "esp_camera.h" // https://github.com/espressif/esp32-camera
#include <WiFi.h>
#include <WebServer.h>
// ---------------------------------------------------------------
// -SETTINGS
// ---------------------------------------------------------------
// Wifi settings (enter your wifi network details)
2020-11-11 15:59:03 +00:00
const char* ssid = "<your wifi network name here>";
const char* password = "<your wifi password here>";
2020-09-26 14:35:33 +00:00
2020-11-13 15:17:38 +00:00
const char* stitle = "ESP32Cam-demo"; // title of this sketch
2020-11-13 09:22:50 +00:00
const char* sversion = "13Nov20"; // Sketch version
2020-09-26 14:35:33 +00:00
const bool debugInfo = 1; // show additional debug info. on serial port (1=enabled)
// Camera related
const bool flashRequired = 1; // If flash to be used when capturing image (1 = yes)
2020-11-11 21:52:26 +00:00
const framesize_t FRAME_SIZE_IMAGE = FRAMESIZE_VGA; // Image resolution:
2020-11-13 15:17:38 +00:00
// default = "const framesize_t FRAME_SIZE_IMAGE = FRAMESIZE_VGA"
2020-09-26 14:35:33 +00:00
// 160x120 (QQVGA), 128x160 (QQVGA2), 176x144 (QCIF), 240x176 (HQVGA),
// 320x240 (QVGA), 400x296 (CIF), 640x480 (VGA, default), 800x600 (SVGA),
// 1024x768 (XGA), 1280x1024 (SXGA), 1600x1200 (UXGA)
2020-11-13 15:17:38 +00:00
int cameraImageExposure = 0; // Camera exposure (0 - 1200) If gain and exposure both set to zero then auto adjust is enabled
2020-10-01 15:49:36 +00:00
int cameraImageGain = 0; // Image gain (0 - 30)
2020-09-26 14:35:33 +00:00
2020-11-13 15:17:38 +00:00
const int TimeBetweenStatus = 600; // speed of system running ok status light (milliseconds)
2020-09-26 14:35:33 +00:00
const int indicatorLED = 33; // onboard status LED pin (33)
const int brightLED = 4; // onboard flash LED pin (4)
2020-11-13 15:17:38 +00:00
const int iopinA = 13; // general io pin 13
const int iopinB = 12; // general io pin 12 (must not be high at boot)
2020-09-27 14:59:29 +00:00
const int serialSpeed = 115200; // Serial data speed to use
2020-09-27 07:38:25 +00:00
2020-09-26 14:35:33 +00:00
// ******************************************************************************************************************
WebServer server(80); // serve web pages on port 80
2020-09-27 06:21:17 +00:00
#include "soc/soc.h" // Used to disable brownout detection
2020-09-26 14:35:33 +00:00
#include "soc/rtc_cntl_reg.h"
#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
// Define global variables:
uint32_t lastStatus = millis(); // last time status light changed status (to flash all ok led)
2020-09-27 07:38:25 +00:00
uint32_t lastCamera = millis(); // timer for periodic image capture
2020-09-26 14:35:33 +00:00
bool sdcardPresent; // flag if an sd card is detected
2020-09-27 06:21:17 +00:00
int imageCounter; // image file name on sd card counter
2020-09-26 14:35:33 +00:00
2020-10-01 06:39:39 +00:00
// camera settings (for the standard - OV2640 - CAMERA_MODEL_AI_THINKER)
2020-10-18 13:26:49 +00:00
// see: https://randomnerdtutorials.com/esp32-cam-camera-pin-gpios/
2020-09-26 14:35:33 +00:00
#define CAMERA_MODEL_AI_THINKER
2020-11-13 15:17:38 +00:00
#define PWDN_GPIO_NUM 32 // power to camera (on/off)
2020-09-26 14:35:33 +00:00
#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
2020-11-11 15:59:03 +00:00
camera_config_t config;
2020-09-26 14:35:33 +00:00
// ******************************************************************************************************************
// ---------------------------------------------------------------
// -SETUP SETUP SETUP SETUP SETUP SETUP
// ---------------------------------------------------------------
void setup() {
2020-10-01 06:39:39 +00:00
Serial.begin(serialSpeed); // Start serial communication
2020-09-26 14:35:33 +00:00
2020-10-01 06:39:39 +00:00
Serial.println("\n\n\n"); // line feeds
2020-09-30 10:50:35 +00:00
Serial.println("-----------------------------------");
2020-10-01 06:39:39 +00:00
Serial.printf("Starting - %s - %s \n", stitle, sversion);
2020-09-30 10:50:35 +00:00
Serial.println("-----------------------------------");
2020-09-26 14:35:33 +00:00
2020-10-01 06:39:39 +00:00
WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); // Turn-off the 'brownout detector'
2020-09-26 14:35:33 +00:00
2020-10-01 06:39:39 +00:00
// Define small indicator led
2020-09-27 06:21:17 +00:00
pinMode(indicatorLED, OUTPUT);
digitalWrite(indicatorLED,HIGH);
2020-09-26 14:35:33 +00:00
// Connect to wifi
2020-09-27 06:21:17 +00:00
digitalWrite(indicatorLED,LOW); // small indicator led on
2020-09-27 14:59:29 +00:00
Serial.print("\nConnecting to ");
2020-10-01 06:39:39 +00:00
Serial.print(ssid);
Serial.print("\n ");
2020-09-26 14:35:33 +00:00
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
2020-10-01 06:39:39 +00:00
Serial.print("\nWiFi connected, ");
Serial.print("IP address: ");
2020-09-26 14:35:33 +00:00
Serial.println(WiFi.localIP());
2020-11-13 15:17:38 +00:00
server.begin(); // start web server
2020-10-01 06:39:39 +00:00
digitalWrite(indicatorLED,HIGH); // small indicator led off
2020-09-26 14:35:33 +00:00
2020-10-01 06:39:39 +00:00
// define the web pages (i.e. call these procedures when url is requested)
server.on("/", handleRoot); // root page
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
2020-11-13 15:17:38 +00:00
server.on("/rgb", readRGBImage); // demo converting image to RGB
2020-10-01 06:39:39 +00:00
server.onNotFound(handleNotFound); // invalid url requested
2020-09-26 14:35:33 +00:00
// set up camera
2020-09-30 10:50:35 +00:00
Serial.print(("\nInitialising camera: "));
2020-09-26 14:35:33 +00:00
if (setupCameraHardware()) Serial.println("OK");
else {
Serial.println("Error!");
2020-10-01 06:39:39 +00:00
showError(2); // critical error so stop and flash led
2020-09-26 14:35:33 +00:00
}
2020-10-01 06:39:39 +00:00
// SD Card - if one is detected set 'sdcardPresent' High
if (!SD_MMC.begin("/sdcard", true)) { // if loading sd card fails
2020-09-30 10:50:35 +00:00
// note: ('/sdcard", true)' = 1bit mode - see: https://www.reddit.com/r/esp32/comments/d71es9/a_breakdown_of_my_experience_trying_to_talk_to_an/
2020-09-26 14:35:33 +00:00
Serial.println("No SD Card detected");
2020-10-01 06:39:39 +00:00
sdcardPresent = 0; // flag no sd card available
2020-09-26 14:35:33 +00:00
} else {
uint8_t cardType = SD_MMC.cardType();
2020-10-01 06:39:39 +00:00
if (cardType == CARD_NONE) { // if invalid card found
2020-09-26 14:35:33 +00:00
Serial.println("SD Card type detect failed");
2020-10-01 06:39:39 +00:00
sdcardPresent = 0; // flag no sd card available
2020-09-26 14:35:33 +00:00
} else {
2020-09-27 06:21:17 +00:00
// valid sd card detected
2020-09-26 14:35:33 +00:00
uint16_t SDfreeSpace = (uint64_t)(SD_MMC.totalBytes() - SD_MMC.usedBytes()) / (1024 * 1024);
2020-09-30 10:50:35 +00:00
Serial.printf("SD Card found, free space = %dMB \n", SDfreeSpace);
2020-10-01 06:39:39 +00:00
sdcardPresent = 1; // flag sd card available
2020-09-26 14:35:33 +00:00
}
}
2020-10-01 06:39:39 +00:00
fs::FS &fs = SD_MMC; // sd card file system
2020-09-26 14:35:33 +00:00
2020-09-30 10:50:35 +00:00
// discover the number of image files stored in '/img' folder of the sd card and set image file counter accordingly
imageCounter = 0;
2020-09-26 14:35:33 +00:00
if (sdcardPresent) {
2020-10-01 06:39:39 +00:00
int tq=fs.mkdir("/img"); // create the '/img' folder on sd card (in case it is not already there)
2020-09-26 14:35:33 +00:00
if (!tq) Serial.println("Unable to create IMG folder on sd card");
2020-09-30 10:50:35 +00:00
// 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();
Serial.printf("Image file count = %d",imageCounter);
2020-09-26 14:35:33 +00:00
}
2020-09-27 07:38:25 +00:00
// define io pins
2020-10-01 06:39:39 +00:00
pinMode(indicatorLED, OUTPUT); // defined again as sd card config can reset it
digitalWrite(indicatorLED,HIGH); // led off = High
pinMode(brightLED, OUTPUT); // flash LED
digitalWrite(brightLED,LOW); // led off = Low
pinMode(iopinA, OUTPUT); // pin 13 - free io pin, can be input or output
pinMode(iopinB, OUTPUT); // pin 12 - free io pin, can be input or output (must be low at boot)
2020-09-26 14:35:33 +00:00
if (!psramFound()) {
Serial.println("Warning: No PSRam found so defaulting to image size 'CIF'");
framesize_t FRAME_SIZE_IMAGE = FRAMESIZE_CIF;
}
2020-10-01 06:39:39 +00:00
Serial.println("\n\nStarted...");
2020-09-26 14:35:33 +00:00
} // setup
// ******************************************************************************************************************
// ----------------------------------------------------------------
// -LOOP LOOP LOOP LOOP LOOP LOOP LOOP
// ----------------------------------------------------------------
void loop() {
2020-09-27 07:38:25 +00:00
server.handleClient(); // handle any incoming web page requests
2020-09-26 14:35:33 +00:00
2020-09-27 06:21:17 +00:00
2020-09-26 14:35:33 +00:00
2020-09-27 07:38:25 +00:00
// <<< your code here >>>
2020-11-13 15:17:38 +00:00
// // Capture an image and save to sd card every 5 seconds (i.e. time lapse)
2020-09-27 07:38:25 +00:00
// if ((unsigned long)(millis() - lastCamera) >= 5000) {
// lastCamera = millis(); // reset timer
// storeImage(); // save an image to sd card
// }
2020-09-26 14:35:33 +00:00
2020-11-13 15:17:38 +00:00
// flash status LED to show sketch is running ok
2020-09-26 14:35:33 +00:00
if ((unsigned long)(millis() - lastStatus) >= TimeBetweenStatus) {
lastStatus = millis(); // reset timer
digitalWrite(indicatorLED,!digitalRead(indicatorLED)); // flip indicator led status
}
} // loop
// ******************************************************************************************************************
// ----------------------------------------------------------------
2020-09-30 10:50:35 +00:00
// Configure the camera
// ----------------------------------------------------------------
2020-10-01 06:39:39 +00:00
// returns TRUE if sucessful
2020-09-30 10:50:35 +00:00
bool setupCameraHardware() {
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; // XCLK 20MHz or 10MHz for OV2640 double FPS (Experimental)
config.pixel_format = PIXFORMAT_JPEG; // Options = YUV422, GRAYSCALE, RGB565, JPEG, RGB888
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 = 5; // 0-63 lower number means higher quality
config.fb_count = 1; // if more than one, i2s runs in continuous mode. Use only with JPEG
2020-11-11 16:43:18 +00:00
2020-09-30 10:50:35 +00:00
esp_err_t camerr = esp_camera_init(&config); // initialise the camera
if (camerr != ESP_OK) Serial.printf("ERROR: Camera init failed with error 0x%x", camerr);
2020-11-11 16:43:18 +00:00
cameraImageSettings(); // apply custom camera settings
2020-09-30 10:50:35 +00:00
return (camerr == ESP_OK); // return boolean result of camera initialisation
}
// ******************************************************************************************************************
// ----------------------------------------------------------------
2020-11-11 16:32:05 +00:00
// -Change camera settings
2020-09-26 14:35:33 +00:00
// ----------------------------------------------------------------
2020-11-11 16:32:05 +00:00
// Adjust image properties (e.g. brightness)
// Defaults to auto adjustments if exposure and gain are both set to zero
// Note: White balance is disabled when manual settings applied to assist when using RGB data to compare colours
// Returns TRUE if successful
bool cameraImageSettings() {
sensor_t *s = esp_camera_sensor_get();
if (s == NULL) {
Serial.println("Error: problem getting camera sensor settings");
return 0;
}
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_awb_gain(s, 1); // Auto White Balance enable (0 or 1)
} else {
// Apply manual settings
s->set_gain_ctrl(s, 0); // auto gain off
s->set_awb_gain(s, 0); // Auto White Balance enable (0 or 1)
s->set_exposure_ctrl(s, 0); // auto exposure off
s->set_agc_gain(s, cameraImageGain); // set gain manually (0 - 30)
s->set_aec_value(s, cameraImageExposure); // set exposure manually (0-1200)
}
2020-09-26 14:35:33 +00:00
2020-11-11 16:32:05 +00:00
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, cameraImageGain); // set gain manually (0 - 30)
// s->set_aec_value(s, cameraImageExposure); // set exposure manually (0-1200)
// s->set_vflip(s, cameraImageInvert); // 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, cameraImageBrightness); // (-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, cameraImageContrast); // (-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
// ******************************************************************************************************************
// ----------------------------------------------------------------
// Misc small procedures
// ----------------------------------------------------------------
2020-09-26 14:35:33 +00:00
2020-10-01 06:39:39 +00:00
// flash the indicator led 'reps' number of times
2020-09-26 14:35:33 +00:00
void flashLED(int reps) {
for(int x=0; x < reps; x++) {
digitalWrite(indicatorLED,LOW);
delay(1000);
digitalWrite(indicatorLED,HIGH);
delay(500);
}
}
2020-09-27 06:21:17 +00:00
2020-10-01 06:39:39 +00:00
// critical error - stop sketch and continually flash error code on indicator led
2020-09-26 14:35:33 +00:00
void showError(int errorNo) {
while(1) {
flashLED(errorNo);
delay(4000);
}
}
2020-09-30 10:50:35 +00:00
2020-09-26 14:35:33 +00:00
// ******************************************************************************************************************
// ----------------------------------------------------------------
2020-09-27 06:21:17 +00:00
// Capture image from camera and save to sd card
2020-09-26 14:35:33 +00:00
// ----------------------------------------------------------------
2020-10-01 06:39:39 +00:00
// returns TRUE if sucessful
2020-09-26 14:35:33 +00:00
2020-09-27 09:20:51 +00:00
bool storeImage() {
2020-09-26 14:35:33 +00:00
2020-09-27 09:20:51 +00:00
if (sdcardPresent) {
2020-09-30 10:50:35 +00:00
if (debugInfo) Serial.printf("Storing image #%d to sd card \n", imageCounter);
2020-09-27 09:20:51 +00:00
} else {
if (debugInfo) Serial.println("Storing image requested but there is no sd card");
return 0; // no sd card available so exit procedure
}
2020-09-26 14:35:33 +00:00
fs::FS &fs = SD_MMC; // sd card file system
2020-09-27 09:20:51 +00:00
bool tResult = 0; // result flag
2020-09-26 14:35:33 +00:00
// capture live image from camera
if (flashRequired) digitalWrite(brightLED,HIGH); // turn flash on
camera_fb_t *fb = esp_camera_fb_get(); // capture image frame from camera
digitalWrite(brightLED,LOW); // turn flash off
if (!fb) {
Serial.println("Error: Camera capture failed");
flashLED(3);
}
// save the image to sd card
2020-09-27 09:20:51 +00:00
String SDfilename = "/img/" + String(imageCounter + 1) + ".jpg"; // build the image file name
2020-09-26 14:35:33 +00:00
File file = fs.open(SDfilename, FILE_WRITE); // create file on sd card
if (!file) {
Serial.println("Error: Failed to create file on sd-card: " + SDfilename);
flashLED(4);
} else {
if (file.write(fb->buf, fb->len)) { // File created ok so save image to it
if (debugInfo) Serial.println("Image saved to sd card");
2020-09-27 09:20:51 +00:00
tResult = 1; // set sucess flag
imageCounter ++; // increment image counter
2020-09-26 14:35:33 +00:00
} else {
Serial.println("Error: failed to save image to sd card");
flashLED(4);
}
file.close(); // close image file on sd card
}
esp_camera_fb_return(fb); // return frame so memory can be released
2020-09-27 09:20:51 +00:00
return tResult; // return image save sucess flag
2020-09-26 14:35:33 +00:00
} // storeImage
// ******************************************************************************************************************
// ----------------------------------------------------------------
// -root web page requested i.e. http://x.x.x.x/
// ----------------------------------------------------------------
2020-11-13 15:17:38 +00:00
// Control buttons, links etc.
2020-09-26 14:35:33 +00:00
void handleRoot() {
2020-09-30 10:50:35 +00:00
WiFiClient client = server.client(); // open link with client
2020-09-26 14:35:33 +00:00
2020-10-01 06:39:39 +00:00
// log the page request including clients IP address
2020-09-30 10:50:35 +00:00
if (debugInfo) {
2020-09-26 14:35:33 +00:00
IPAddress cip = client.remoteIP();
2020-10-01 06:39:39 +00:00
Serial.printf("Root page requested from: %d.%d.%d.%d \n", cip[0], cip[1], cip[2], cip[3]);
2020-09-30 10:50:35 +00:00
}
2020-09-26 14:35:33 +00:00
2020-10-01 06:39:39 +00:00
2020-10-01 15:49:36 +00:00
// Action any button presses or settings entered on web page
2020-09-27 07:38:25 +00:00
2020-09-30 10:50:35 +00:00
// 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 (server.hasArg("button1")) {
digitalWrite(iopinA,!digitalRead(iopinA)); // toggle output pin on/off
if (debugInfo) Serial.println("Button 1 pressed");
}
// if button2 was pressed (toggle io pin B)
if (server.hasArg("button2")) {
digitalWrite(iopinB,!digitalRead(iopinB)); // toggle output pin on/off
if (debugInfo) Serial.println("Button 2 pressed");
}
// if button3 was pressed (toggle flash LED)
if (server.hasArg("button3")) {
digitalWrite(brightLED,!digitalRead(brightLED)); // toggle flash LED on/off
if (debugInfo) Serial.println("Button 3 pressed");
}
2020-09-26 14:35:33 +00:00
2020-10-01 15:49:36 +00:00
// if exposure was adjusted - cameraImageExposure
if (server.hasArg("exp")) {
String Tvalue = server.arg("exp"); // read value
if (Tvalue != NULL) {
int val = Tvalue.toInt();
if (val >= 0 && val <= 1200 && val != cameraImageExposure) {
if (debugInfo) 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")) {
String Tvalue = server.arg("gain"); // read value
if (Tvalue != NULL) {
int val = Tvalue.toInt();
if (val >= 0 && val <= 31 && val != cameraImageGain) {
if (debugInfo) Serial.printf("Gain changed to %d\n", val);
cameraImageGain = val;
cameraImageSettings(); // Apply camera image settings
}
}
}
2020-09-27 07:38:25 +00:00
2020-09-30 10:50:35 +00:00
// html header
client.write("<!DOCTYPE html> <html lang='en'> <head> <title>root</title> </head> <body>\n"); // basic html header
2020-10-01 15:49:36 +00:00
client.write("<FORM action='/' method='post'>\n"); // used by the buttons in the html (action = the web page to send it to
2020-09-30 10:50:35 +00:00
2020-09-27 07:38:25 +00:00
// --------------------------------------------------------------------
// html main body
2020-09-30 10:50:35 +00:00
// Info on the arduino ethernet library: https://www.arduino.cc/en/Reference/Ethernet
// Info in HTML: https://www.w3schools.com/html/
2020-09-27 07:38:25 +00:00
// Info on Javascript (can be inserted in to the HTML): https://www.w3schools.com/js/default.asp
2020-09-30 10:50:35 +00:00
// Verify your HTML is valid: https://validator.w3.org/
2020-09-27 07:38:25 +00:00
client.write("<h1>Hello from ESP32Cam</h1>\n");
2020-09-26 14:35:33 +00:00
2020-09-27 09:20:51 +00:00
// sd card details
2020-09-30 10:50:35 +00:00
if (sdcardPresent) client.printf("<p>SD Card detected - %d images stored</p>\n", imageCounter);
2020-09-27 09:20:51 +00:00
else client.write("<p>No SD Card detected</p>\n");
// io pin details
if (digitalRead(iopinA) == LOW) client.write("<p>Pin 13 is Low</p>\n");
else client.write("<p>Pin 13 is High</p>\n");
if (digitalRead(iopinB) == LOW) client.write("<p>Pin 12 is Low</p>\n");
else client.write("<p>Pin 12 is High</p>\n");
2020-09-27 07:38:25 +00:00
2020-11-11 09:19:52 +00:00
// // 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) );
2020-09-27 07:38:25 +00:00
// Control bottons
client.write("<input style='height: 35px;' name='button1' value='Toggle pin 13' type='submit'> \n");
client.write("<input style='height: 35px;' name='button2' value='Toggle pin 12' type='submit'> \n");
2020-11-11 09:19:52 +00:00
client.write("<input style='height: 35px;' name='button3' value='Toggle Flash' type='submit'><br> \n");
2020-09-27 07:38:25 +00:00
2020-10-01 15:49:36 +00:00
// Image setting controls
2020-11-11 09:19:52 +00:00
client.write("<br>CAMERA SETTINGS: \n");
2020-10-01 15:49:36 +00:00
client.printf("Exposure: <input type='number' style='width: 50px' name='exp' min='0' max='1200' value='%d'> \n", cameraImageExposure);
client.printf("Gain: <input type='number' style='width: 50px' name='gain' min='0' max='30' value='%d'>\n", cameraImageGain);
client.write(" - Set both to zero for auto adjust<br>\n");
2020-11-11 09:19:52 +00:00
// links to the other pages available
client.write("<br>LINKS: \n");
client.write("<a href='/photo'>Capture an image</a> - \n");
2020-11-11 10:18:52 +00:00
client.write("<a href='/img'>View stored images</a> - \n");
client.write("<a href='/rgb'>Access Image as RGB data</a> - \n");
2020-11-11 09:19:52 +00:00
client.write("<a href='/stream'>Live stream</a><br>\n");
2020-10-01 15:49:36 +00:00
2020-09-27 07:38:25 +00:00
// --------------------------------------------------------------------
2020-09-26 14:35:33 +00:00
// end html
2020-09-27 14:14:03 +00:00
client.write("</form></body></html>\n");
2020-09-26 14:35:33 +00:00
delay(3);
client.stop();
} // handleRoot
// ******************************************************************************************************************
// ----------------------------------------------------------------
// -photo save to sd card i.e. http://x.x.x.x/photo
// ----------------------------------------------------------------
void handlePhoto() {
WiFiClient client = server.client(); // open link with client
// log page request including clients IP address
2020-09-30 10:50:35 +00:00
if (debugInfo) {
2020-09-26 14:35:33 +00:00
IPAddress cip = client.remoteIP();
2020-10-01 06:39:39 +00:00
Serial.printf("Photo requested from: %d.%d.%d.%d \n", cip[0], cip[1], cip[2], cip[3]);
2020-09-30 10:50:35 +00:00
}
2020-09-26 14:35:33 +00:00
// save an image to sd card
2020-09-27 09:20:51 +00:00
bool sRes = storeImage(); // save an image to sd card (store sucess or failed flag)
2020-09-26 14:35:33 +00:00
// html header
2020-09-30 10:50:35 +00:00
client.write("<!DOCTYPE html> <html lang='en'> <head> <title>photo</title> </head> <body>\n"); // basic html header
2020-09-26 14:35:33 +00:00
// html body
2020-10-18 13:26:49 +00:00
if (sRes == 1) {
client.printf("<p>Image saved to sd card as image number %d </p>\n", imageCounter);
client.write("<a href='/img'>View Image</a>\n"); // link to the image
} else {
client.write("<p>Error: Failed to save image to sd card</p>\n");
}
2020-09-26 14:35:33 +00:00
// end html
2020-09-30 10:50:35 +00:00
client.write("</body></html>\n");
2020-09-26 14:35:33 +00:00
delay(3);
client.stop();
} // handlePhoto
2020-09-27 06:21:17 +00:00
// ----------------------------------------------------------------
2020-11-13 15:17:38 +00:00
// -show images stored on sd card i.e. http://x.x.x.x/img?img=x
2020-09-27 06:21:17 +00:00
// ----------------------------------------------------------------
// default image = most recent
2020-09-27 09:20:51 +00:00
// returns 1 if image displayed ok
bool handleImg() {
2020-09-27 06:21:17 +00:00
WiFiClient client = server.client(); // open link with client
2020-09-30 10:50:35 +00:00
// log page request including clients IP address
if (debugInfo) {
IPAddress cip = client.remoteIP();
2020-10-01 06:39:39 +00:00
Serial.printf("Image display requested from: %d.%d.%d.%d \n", cip[0], cip[1], cip[2], cip[3]);
2020-09-30 10:50:35 +00:00
if (imageCounter == 0) Serial.println("Error: no images to display");
}
2020-09-27 06:21:17 +00:00
int imgToShow = imageCounter; // default to showing most recent file
// get image number from url parameter
if (server.hasArg("img")) {
String Tvalue = server.arg("img"); // read value
imgToShow = Tvalue.toInt(); // convert string to int
if (imgToShow < 1 || imgToShow > imageCounter) imgToShow = imageCounter; // validate image number
}
2020-09-30 10:50:35 +00:00
if (debugInfo) Serial.printf("Displaying image #%d from sd card", imgToShow);
2020-09-27 06:21:17 +00:00
String tFileName = "/img/" + String(imgToShow) + ".jpg";
2020-09-27 09:20:51 +00:00
fs::FS &fs = SD_MMC; // sd card file system
2020-09-27 06:21:17 +00:00
File timg = fs.open(tFileName, "r");
if (timg) {
2020-09-27 09:20:51 +00:00
size_t sent = server.streamFile(timg, "image/jpeg"); // send the image
2020-09-27 06:21:17 +00:00
timg.close();
} else {
if (debugInfo) Serial.println("Error: image file not found");
2020-09-27 09:20:51 +00:00
WiFiClient client = server.client(); // open link with client
client.write("<!DOCTYPE html> <html> <body>\n");
client.write("<p>Error: Image not found</p?\n");
delay(3);
client.stop();
2020-09-27 06:21:17 +00:00
}
} // handleImg
2020-09-26 14:35:33 +00:00
// ******************************************************************************************************************
// ----------------------------------------------------------------
// -invalid web page requested
// ----------------------------------------------------------------
2020-11-13 15:17:38 +00:00
// Note: shows a different way to send the HTML reply
2020-09-26 14:35:33 +00:00
void handleNotFound() {
2020-10-01 06:39:39 +00:00
2020-11-13 15:17:38 +00:00
String tReply;
2020-10-01 06:39:39 +00:00
// log page request
if (debugInfo) {
Serial.print("Invalid page requested");
}
2020-09-26 14:35:33 +00:00
2020-11-13 09:22:50 +00:00
tReply = "File Not Found\n\n";
tReply += "URI: ";
tReply += server.uri();
tReply += "\nMethod: ";
tReply += ( server.method() == HTTP_GET ) ? "GET" : "POST";
tReply += "\nArguments: ";
tReply += server.args();
tReply += "\n";
2020-09-26 14:35:33 +00:00
for ( uint8_t i = 0; i < server.args(); i++ ) {
2020-11-13 09:22:50 +00:00
tReply += " " + server.argName ( i ) + ": " + server.arg ( i ) + "\n";
2020-09-26 14:35:33 +00:00
}
2020-11-13 09:22:50 +00:00
server.send ( 404, "text/plain", tReply );
tReply = ""; // clear variable
2020-09-26 14:35:33 +00:00
} // handleNotFound
2020-11-11 09:19:52 +00:00
// ******************************************************************************************************************
2020-11-11 10:18:52 +00:00
// ----------------------------------------------------------------
2020-11-13 15:17:38 +00:00
// -access image data as RGB - i.e. http://x.x.x.x/rgb
2020-11-11 10:18:52 +00:00
// ----------------------------------------------------------------
2020-11-12 12:08:08 +00:00
// Info. from: https://github.com/Makerfabs/Project_Touch-Screen-Camera/blob/master/Camera_v2/Camera_v2.ino
// note: Will fail on the highest resolution as it requires more than 4mb to store the data (in psram)
2020-11-11 09:19:52 +00:00
void readRGBImage() {
2020-11-13 09:22:50 +00:00
WiFiClient client = server.client(); // open link with client
2020-11-13 08:24:20 +00:00
2020-11-13 09:22:50 +00:00
// log page request including clients IP address
if (debugInfo) {
IPAddress cip = client.remoteIP();
Serial.printf("RGB requested from: %d.%d.%d.%d \n", cip[0], cip[1], cip[2], cip[3]);
2020-11-12 12:08:08 +00:00
}
2020-11-13 08:24:20 +00:00
2020-11-13 09:22:50 +00:00
// html header
client.write("<!DOCTYPE html> <html lang='en'> <head> <title>photo</title> </head> <body>\n"); // basic html header
2020-11-11 10:18:52 +00:00
2020-11-13 15:17:38 +00:00
MessageRGB(client,"LIVE IMAGE AS RGB DATA"); // 'MessageRGB' sends the String to both serial port and web page
MessageRGB(client,"Starting RGB procedure at millis=" + String(millis())); // so you can see how long it takes to execute this code
2020-11-13 09:22:50 +00:00
2020-11-13 08:24:20 +00:00
2020-11-11 09:19:52 +00:00
2020-11-13 09:22:50 +00:00
// ****** main code for converting captured image to RGB *****
// capture a live image from camera (jpg)
camera_fb_t * fb = NULL;
fb = esp_camera_fb_get();
if (!fb) MessageRGB(client," -error capturing image from camera- ");
MessageRGB(client,"Image resolution=" + String(fb->width) + "x" + String(fb->height)); // display image resolution
// allocate memory to store rgb data (in psram)
if (!psramFound()) MessageRGB(client," -error no psram found- ");
MessageRGB(client,"Free psram before rgb data stored = " + String(heap_caps_get_free_size(MALLOC_CAP_SPIRAM)));
void *ptrVal = NULL; // create a pointer for memory location to store the data
uint32_t ARRAY_LENGTH = fb->width * fb->height * 3; // calculate memory required to store the RGB data (i.e. number of pixels in the jpg image x 3)
if (heap_caps_get_free_size( MALLOC_CAP_SPIRAM) < ARRAY_LENGTH) MessageRGB(client," -error: not enough free psram to store the rgb data- ");
ptrVal = heap_caps_malloc(ARRAY_LENGTH, MALLOC_CAP_SPIRAM); // allocate memory space for the rgb data
uint8_t *rgb = (uint8_t *)ptrVal; // create the 'rgb' array pointer to the allocated memory space
MessageRGB(client,"Free psram after rgb data stored = " + String(heap_caps_get_free_size(MALLOC_CAP_SPIRAM)));
// convert the captured jpg image (fb) to rgb data (stored in 'rgb' array)
bool jpeg_converted = fmt2rgb888(fb->buf, fb->len, PIXFORMAT_JPEG, rgb);
if (!jpeg_converted) MessageRGB(client," -error converting image to RGB- ");
2020-11-11 09:19:52 +00:00
2020-11-13 08:24:20 +00:00
2020-11-13 09:22:50 +00:00
// ****** examples of reading the resulting RGB data *****
2020-11-13 15:17:38 +00:00
// Note: You can send the entire image with the command: client.write(rgb, ARRAY_LENGTH);
// If this is all that is sent then it will download to the client as a raw RGB file which you can then view using this
// Processing sketch: https://github.com/alanesq/esp32cam-demo/blob/master/Misc/displayRGB.pde
2020-11-13 08:24:20 +00:00
// display some of the resulting data
2020-11-13 15:17:38 +00:00
uint32_t resultsToShow = 50; // how much data to display
2020-11-13 09:22:50 +00:00
MessageRGB(client,"R , G , B");
for (uint32_t i = 0; i < resultsToShow-2; i+=3) {
MessageRGB(client,String(rgb[i+2]) + "," + String(rgb[i+1]) + "," + String(rgb[i+0])); // Red , Green , Blue
2020-11-13 08:24:20 +00:00
// // how to calculate the x and y coordinate of the pixel
// uint16_t x = i % fb->width;
// uint16_t y = floor(i / fb->width);
}
// find the average values for each colour over entire image
uint32_t aRed = 0;
uint32_t aGreen = 0;
uint32_t aBlue = 0;
for (uint32_t i = 0; i < (ARRAY_LENGTH - 2); i+=3) { // go through all data and add up totals
aBlue+=rgb[i];
aGreen+=rgb[i+1];
aRed+=rgb[i+2];
}
aRed = aRed / (fb->width * fb->height); // divide total by number of pixels to give the average value
aGreen = aGreen / (fb->width * fb->height);
aBlue = aBlue / (fb->width * fb->height);
2020-11-13 09:22:50 +00:00
MessageRGB(client,"Average Blue = " + String(aBlue));
MessageRGB(client,"Average Green = " + String(aGreen));
2020-11-13 15:17:38 +00:00
MessageRGB(client,"Average Red = " + String(aRed));
2020-11-13 08:24:20 +00:00
2020-11-13 09:22:50 +00:00
// *******************************************************
MessageRGB(client,"Finishing RGB procedure at millis=" + String(millis()));
// end html
client.write("</body></html>\n");
delay(3);
client.stop();
2020-11-13 08:24:20 +00:00
// finished with the data so free up the space used in psram
2020-11-11 09:19:52 +00:00
esp_camera_fb_return(fb);
heap_caps_free(ptrVal);
2020-11-11 16:32:05 +00:00
} // readRGBImage
2020-11-11 09:19:52 +00:00
2020-11-13 09:22:50 +00:00
// send line of text to both serial port and web page
void MessageRGB(WiFiClient &client, String theText) {
client.print(theText + "<br>\n");
2020-11-13 15:17:38 +00:00
if (debugInfo || theText.indexOf('error') > 0) Serial.println(theText);
2020-11-13 09:22:50 +00:00
}
2020-09-26 14:35:33 +00:00
// ******************************************************************************************************************
// ----------------------------------------------------------------
// -stream requested i.e. http://x.x.x.x/stream
// ----------------------------------------------------------------
2020-11-11 16:32:05 +00:00
// Sends cam stream - thanks to Uwe Gerlach for the code showing me how to do this
2020-09-26 14:35:33 +00:00
void handleStream(){
WiFiClient client = server.client(); // open link with client
// log page request including clients IP address
2020-09-30 10:50:35 +00:00
if (debugInfo) {
2020-09-26 14:35:33 +00:00
IPAddress cip = client.remoteIP();
2020-10-01 06:39:39 +00:00
Serial.printf("Video stream requested from: %d.%d.%d.%d \n", cip[0], cip[1], cip[2], cip[3]);
2020-09-30 10:50:35 +00:00
}
2020-09-26 14:35:33 +00:00
// HTML used in the web page
const char HEADER[] = "HTTP/1.1 200 OK\r\n" \
"Access-Control-Allow-Origin: *\r\n" \
"Content-Type: multipart/x-mixed-replace; boundary=123456789000000000000987654321\r\n";
const char BOUNDARY[] = "\r\n--123456789000000000000987654321\r\n"; // marks end of each image frame
const char CTNTTYPE[] = "Content-Type: image/jpeg\r\nContent-Length: "; // marks start of image data
const int hdrLen = strlen(HEADER); // length of the stored text, used when sending to web page
const int bdrLen = strlen(BOUNDARY);
const int cntLen = strlen(CTNTTYPE);
// temp stores
char buf[32];
int s;
camera_fb_t * fb = NULL;
// send html header
client.write(HEADER, hdrLen);
client.write(BOUNDARY, bdrLen);
// send live images until client disconnects
while (true)
{
if (!client.connected()) break;
2020-10-01 06:39:39 +00:00
fb = esp_camera_fb_get(); // capture live image
2020-09-26 14:35:33 +00:00
s = fb->len; // store size of image (i.e. buffer length)
client.write(CTNTTYPE, cntLen); // send content type html (i.e. jpg image)
2020-10-01 06:39:39 +00:00
sprintf( buf, "%d\r\n\r\n", s ); // format the image's size as html and put in to 'buf'
client.write(buf, strlen(buf)); // send result (image size)
2020-09-26 14:35:33 +00:00
client.write((char *)fb->buf, s); // send the image data
client.write(BOUNDARY, bdrLen); // send html boundary see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
2020-10-01 06:39:39 +00:00
esp_camera_fb_return(fb); // return image so memory can be released
2020-09-26 14:35:33 +00:00
}
if (debugInfo) Serial.println("Video stream stopped");
delay(3);
client.stop();
} // handleStream
// ******************************************************************************************************************
// end