LoginSignup
6
6

More than 3 years have passed since last update.

ESP32-CAM で撮影した画像を SDカードに書き込む

Last updated at Posted at 2019-06-28

概要

Ai-ThinkerのESP32を載せたカメラモジュール
https://amzn.to/2FAvrNa

ちょっとこれを触る機会があったのですが、Arduinoサンプルを動かしている人はたくさんいたもののSDカードに画像を保存する方法がなかなか見つからなかったので、とりあえずメモしておきます。

環境

Arduino IDE を使う想定です(その辺の使い方とかは割愛しますが、、)

いきなりコード

たいした量ではないし、難しいことをやっているわけでもないので、ソースを見るのが一番早い気がするのでソース載せておきます(必要なところだけの抜粋です)。

どうやら "SD.h" ではなくて "SD_MMC.h" を使う必要があるらしい、というところだけがポイント。

sd_save.c
#include "FS.h"
#include "SD_MMC.h"
#include <time.h>

bool isSDExist = 0;

int setupSD(){
  int sdRet = SD_MMC.begin();
  Serial.printf("setupSD: SD_MMC.begin() -> %d\n", sdRet);

  uint8_t cardType = SD_MMC.cardType();
  if(cardType != CARD_NONE){
    isSDExist = 1;
  }

  switch(cardType){
    case CARD_NONE: Serial.println("setupSD: Card: None");      break;
    case CARD_MMC:  Serial.println("setupSD: Card Type: MMC");  break;
    case CARD_SD:   Serial.println("setupSD: Card Type: SDSC"); break;
    case CARD_SDHC: Serial.println("setupSD: Card Type: SDHC"); break;
    default:        Serial.println("setupSD: Card: UNKNOWN");   break;
  }
}

void takePic(camera_fb_t* fb){
  Serial.println("takePic: Start");
  if(!isSDExist){
    Serial.println("takePic: SD Card none");    
    return;
  }

  if (!fb) {
    Serial.println("takePic: image data none");
    return;
  }

  time_t t = time(NULL);
  struct tm *tm;
  tm = localtime(&t);

  char filename[32];
  sprintf(filename, "/img%04d%02d%02d%02d%02d%02d.jpg",
    tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);

  fs::FS &fs = SD_MMC;
  File imgFile = fs.open(filename, FILE_WRITE);
  if(imgFile && fb->len > 0){
    imgFile.write(fb->buf, fb->len);
    imgFile.close();
    Serial.print("takePic: ");
    Serial.println(filename);
  }else{
    Serial.println("takePic: Save file failed");
    Serial.printf("takePic: imgFile: %d\n", imgFile);
    Serial.printf("takePic: fb->len: %d\n", fb->len);
  }
}

備考

setup() あたりで setupSD() を呼んでおいて、何か画像を保存したい契機で

fb = esp_camera_fb_get();
takePic(fb);
esp_camera_fb_return(fb);

こんな感じで takePic() を呼んでもらうと "img_現在時刻.jpg" みたいなファイルが保存されます。

全ソース

こちらを使用したWebカメラ的なものを以下で公開しています。
ご参考にどうぞ。
https://github.com/manontroppo1974/MiniWebCamera

6
6
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6