Esp32 cam with ultrasonic sensor and Oled

Hello friends, please is it possible to use an esp32 cam board to power an ultrasonic sensor with an ssd1306 Oled, while using and ftd1 with power coming from the usb port??

:thinking:

What you suggest is reasonable.

Tried that and it's giving me all sort of errors
When I remove it works fine

Time to show us a schematic and code.


Show us a good schematic of your proposed circuit.
Show us a good image of your ‘actual’ wiring.
Give links to components.


In the Arduino IDE, use Ctrl T or CMD T to format your code then copy the complete sketch.

Use the </> icon from the ‘reply menu’ to attach the copied sketch.

#include "esp_camera.h"
#include <WiFi.h>
#include <WiFiClient.h>
#include <Wire.h>  // Only needed for Arduino 1.6.5 and earlier
#include "SSD1306Wire.h" // legacy include: `#include "SSD1306.h"`
#include "esp_system.h"
#include "Arduino.h"
#include "soc/soc.h"           // Disable brownout problems
#include "soc/rtc_cntl_reg.h"  // Disable brownout problems
#include "driver/rtc_io.h"
#include <SPIFFS.h>
#include <FS.h>
#include <Firebase_ESP_Client.h>
//Provide the token generation process info.
#include <addons/TokenHelper.h>
#include <string.h>
#include <time.h>
#define STR_SIZE 10000

//#include "time.h"
// ===================
// Select camera model
// ===================
#define CAMERA_MODEL_AI_THINKER // Has PSRAM
// ===========================
// Enter your WiFi credentials
// ===========================
#define SSID "Redmi 10"
#define PASSWORD "1favour7"

// Insert Firebase parameters
#define API_KEY "AIzaSyDc-D6UXo56aIHXEBJloHDQxM0Fta-0rvs"
#define USER_EMAIL "akpanidiong777@gmail.com"
#define USER_PASSWORD "1favour7"
#define STORAGE_BUCKET_ID "esp32-project-900f8.appspot.com"
#define FIREBASE_PROJECT_ID "esp32-project-900f8"

// Photo File Name to save in SPIFFS
#define FILE_PHOTO "/data/photo.jpg"

SSD1306Wire display(0x3c, 16, 12);

const char* ntpServer = "pool.ntp.org";
// Variable to save current epoch time
unsigned long epochTime;
char buffe [50];
char bufferr [50];
char source[] = ".jpg";
char docPath[] = "Images/";

unsigned long getTime() {
  time_t now;
  struct tm timeinfo;
  if (!getLocalTime(&timeinfo)) {
    //Serial.println("Failed to obtain time");
    return (0);
  }
  time(&now);
  return now;
}

hw_timer_t *timer = NULL;
void IRAM_ATTR resetModule() {
  ets_printf("reboot\n");
  esp_restart();
}

// Pin definition for 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

//Define Firebase Data objects
FirebaseData fbdo;
FirebaseAuth auth;
FirebaseConfig configF;

bool taskCompleted = false;

// Check if photo capture was successful
bool checkPhoto( fs::FS &fs ) {
  File f_pic = fs.open( FILE_PHOTO );
  unsigned int pic_sz = f_pic.size();
  return ( pic_sz > 100 );
}

// Capture Photo and Save it to SPIFFS
void capturePhotoSaveSpiffs( void ) {
  camera_fb_t * fb = NULL; // pointer
  bool ok = 0; // Boolean indicating if the picture has been taken correctly
  do {
    // Take a photo with the camera
    Serial.println("Taking a photo...");

    fb = esp_camera_fb_get();
    if (!fb) {
      Serial.println("Camera capture failed");
      return;
    }
    // Photo file name
    Serial.printf("Picture file name: %s\n", FILE_PHOTO);
    File file = SPIFFS.open(FILE_PHOTO, FILE_WRITE);
    // Insert the data in the photo file
    if (!file) {
      Serial.println("Failed to open file in writing mode");
    }
    else {
      file.write(fb->buf, fb->len); // payload (image), payload length
      Serial.print("The picture has been saved in ");
      Serial.print(FILE_PHOTO);
      Serial.print(" - Size: ");
      Serial.print(file.size());
      Serial.println(" bytes");
    }
    // Close the file
    file.close();
    esp_camera_fb_return(fb);

    // check if file has been correctly saved in SPIFFS
    ok = checkPhoto(SPIFFS);
  } while ( !ok );
}
void initSPIFFS() {
  if (!SPIFFS.begin(true)) {
    Serial.println("An Error has occurred while mounting SPIFFS");
    ESP.restart();
  }
  else {
    delay(500);
    Serial.println("SPIFFS mounted successfully");
  }
}

//ultransonic sensor pins
const int trigPin = 13;
const int echoPin = 15;
boolean startTimer = false;
unsigned long time_now = 0;
int counter = 0, time_capture = 0;

//other variables
long duration;
float distanceCm;
float distanceInch;

//int FirstDistance;
//int SecondDistance;
//double velocity;
//float Time = 2.0;
//float delayedtime = 1000*Time;


//define sound speed in cm/uS
#define SOUND_SPEED 0.034
#define CM_TO_INCH 0.393701


void setup() {
  Serial.begin(115200);
  while (!Serial) {
    ;
  }
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  WiFi.begin(SSID, PASSWORD);
  Serial.printf("WiFi connecting to %s\n", SSID);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(400);
  }
  Serial.printf("\nWiFi connected\nIP : ");
  Serial.println(WiFi.localIP());
  initSPIFFS();
  WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0);
  display.init();
  configTime(0, 0, ntpServer);
  //Firebase
  // Assign the api key
  configF.api_key = API_KEY;
  //Assign the user sign in credentials
  auth.user.email = USER_EMAIL;
  auth.user.password = USER_PASSWORD;
  //Assign the callback function for the long running token generation task
  configF.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h
  Firebase.begin(&configF, &auth);
  Firebase.reconnectWiFi(true);
  strcat(buffe, source);
  strcat(docPath, bufferr);
  sprintf(buffe, "%lu", epochTime);
  timer = timerBegin(0, 80, true); //timer 0, div 80Mhz
  timerAttachInterrupt(timer, &resetModule, true);
  timerAlarmWrite(timer, 20000000, false);
  timerAlarmEnable(timer); //enable interrupt

  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;

  if (psramFound()) {
    // FRAMESIZE_ +
    //QQVGA/160x120//QQVGA2/128x160//QCIF/176x144//HQVGA/240x176
    //QVGA/320x240//CIF/400x296//VGA/640x480//SVGA/800x600//XGA/1024x768
    //SXGA/1280x1024//UXGA/1600x1200//QXGA/2048*1536
    config.frame_size = FRAMESIZE_VGA;
    config.jpeg_quality = 10;
    config.fb_count = 2;
  }
  else {
    config.frame_size = FRAMESIZE_QQVGA; config.jpeg_quality = 12;
    config.fb_count = 1;
  }
  // Init Camera
  esp_err_t err = esp_camera_init(&config);
  if (err != ESP_OK) {
    Serial.printf("Camera init failed with error 0x%x", err);
    return;
  }
}

void loop() {
  timerWrite(timer, 0); //reset timer (feed watchdog)
  display.clear();
  epochTime = getTime();
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);

  // Calculate the distance
  distanceCm = duration * SOUND_SPEED / 2;

  // Convert to inches
  distanceInch = distanceCm * CM_TO_INCH;

  // Prints the distance in the Serial Monitor
  Serial.print("Distance (cm): ");
  Serial.println(distanceCm);
  Serial.print("Distance (inch): ");
  Serial.println(distanceInch);
  display.drawString(0,0, String(distanceInch));
  display.display();


  if (distanceCm <= 10 && startTimer != true) {
    Camera_capture();
    startTimer = true;
  } else if (distanceCm > 10) {
    startTimer = false;
    time_capture = 0;
  } if (distanceCm <= 10) {
    if (++time_capture > 4) {
      time_capture = 0;
      Camera_capture();
      Serial.println("Over Time");
    }
  }
  delay(500);
}
void Camera_capture() {
  capturePhotoSaveSpiffs();
  delay(1);
  if (Firebase.ready() && !taskCompleted) {
    taskCompleted = true;

    Serial.print("Uploading picture... ");
    //MIME type should be valid to avoid the download problem.
    //The file systems for flash and SD/SDMMC can be changed in FirebaseFS.h.
    if (Firebase.Storage.upload(&fbdo, STORAGE_BUCKET_ID /* Firebase Storage bucket id */, FILE_PHOTO /* path to local file */, mem_storage_type_flash /* memory storage type, mem_storage_type_flash and mem_storage_type_sd */, buffe /* path of remote file stored in the bucket */, "image/jpeg" /* mime type */)) {
      Serial.printf("\nDownload URL: %s\n", fbdo.downloadURL().c_str());
    }
    else {
      Serial.println(fbdo.errorReason());
    }
    String documentPath = docPath;
    //String documentPath = "Images/" + String(epochTime).c_str();
    FirebaseJson content;
    content.set("fields/ImgUrl/stringValue", fbdo.downloadURL().c_str());
    content.set("fields/velocity/stringValue", String(distanceCm).c_str());
    content.set("fields/ImgUrl/stringValue", String(epochTime).c_str());
    Serial.print("Uploading data... ");

    if (Firebase.Firestore.createDocument(&fbdo, FIREBASE_PROJECT_ID, "" /* databaseId can be (default) or empty */, documentPath.c_str(), content.raw())) {
      Serial.printf("ok\n%s\n\n", fbdo.payload().c_str());
    }
    else {
      Serial.println(fbdo.errorReason());
    }
    taskCompleted = false;
  }
}

As stated in the code the for the OLED display
VCC on the Oled to 3v on the esp32
Gnd on the Oled to Gnd on the esp32
SCL on the Oled to pin 12 on the esp32
SDA on the Oled to pin 16 on the esp32

For the sensor
Gnd to Gnd on the esp32
Echo to pin 15 on the esp32
Trig to pin 13 on the esp32
Vcc to 5v on the esp32

the problems/errors where

E (3873) cam_hal: cam_dma_config(292): frame buffer malloc failed 
E (3873) cam_hal: cam_config(376): cam_dma_config failed
E (3874) camera: Camera config failed with error 0xffffffff Camera init failed with error 0xffffffff
Distance (cm): 3.59
Guru Meditation Error: Core  0 panic'ed (InstrFetchProhibited). Exception was unhandled.  
Core  0 register dump: PC      : 0x00000000  PS      : 0x00060630  A0      : 0x80131ef4  
A1      : 0x3ffbd120   A2      : 0x00000001  A3      : 0x3ffccb48  A4      : 0x00000103  
A5      : 0x3ffc1788   A6      : 0x00000005  A7      : 0x00000001  A8      : 0x8016e2e6  
A9      : 0x3ffbd0f0   A10     : 0x3ff5cd0c  A11     : 0x00000000  A12     : 0x00000001 
 A13     : 0x3ffbd324   A14     : 0x00000000  A15     : 0x00000000  SAR     : 0x00000020  
EXCCAUSE: 0x00000014   EXCVADDR: 0x00000000  LBEG    : 0x40085f1d  LEND:0x40085f25  LCOUNT  : 0x00000027
E (243) psram: PSRAM ID read error: 0xffffffff 
E (243) cpu_start: Failed to init external RAM! (IDFGH-4457) #6288

The camera also failed to initialize and take a picture

Which ESP32-CAM board are you using? Most of them have very few pins available to do anything else with... they are already used for the camera, SD card, PSRAM.

Aithinker model

Hi,

This would be helpful...

Tom.... :smiley: :+1: :coffee: :australia:

...and this

Which would seem to indicate the GPIO12 is used for the SD card, and GPIO16 is used as the chip select for the PSRAM.

So... yes, you will likely have issues if you use these pins.

Oh wow
Since I don't make use of an SD card, I could use pin 12 but pin 16 is for PSRAM
I'll need to change the pin then
Thanks so much!!!!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.