Você está na página 1de 27

Loja Fórum Aprender

CASA TUTORIAIS DE PRODUTOS TUTORIAIS CONCEITUAIS GUIAS DE PROJETOS   

LEARN @ CIRCUITROCKS
SOFTWARE, FERRAMENTAS E OUTROS SERVIÇOS EM DESTAQUE
POLÍTICA DE PRIVACIDADE
Saiba mais sobre as coisas com as quais brincamos dentro da Comunidade Circuitrocks.

 ESP32, TUTORIAIS DE PRODUTOS


Procurar... 
ESP32-CAM com transmissão de vídeo RTSP

O ESP32-CAM é uma das soluções mais baratas se você quiser adicionar


gravação de vídeo ao seu projeto IoT. Neste tutorial, você aprenderá o
seguinte:

como programar o ESP32-CAM


como fazer streaming de vídeo baseado em navegador e RTSP
como usar um adaptador FTDI para programar o ESP32-CAM
como usar o OTA para programar o ESP32-CAM via WiFi


CASA TUTORIAIS DE PRODUTOS TUTORIAIS CONCEITUAIS GUIAS DE PROJETOS   

SOFTWARE, FERRAMENTAS E OUTROS SERVIÇOS EM DESTAQUE POLÍTICA DE PRIVACIDADE

Antes de começar
A placa de desenvolvimento ESP32-CAM é diferente de outras placas de
fuga ESP32 porque não há conector USB. Então programar o tabuleiro é
diferente do que você sabe. Você precisará de um CONVERSOR FTDI USB
para Serial como este para ver a saída serial de depuração e programar o
ESP32.
Você precisará, além disso, de um botão para colocar o ESP32-CAM no
modo de download. A placa ESP32-CAM está com fome de energia!

Você precisa de pelo menos uma fonte de alimentação 2A 5V ou a placa não


vai inicializar. Este com uma saída 2A é uma boa escolha.

A câmera em ação.


CASA TUTORIAIS DE PRODUTOS TUTORIAIS CONCEITUAIS GUIAS DE PROJETOS   

SOFTWARE, FERRAMENTAS E OUTROS SERVIÇOS EM DESTAQUE POLÍTICA DE PRIVACIDADE

0:00 / 0:38

A câmera em ação. Não o mais rápido, mas ei, são apenas 500 Pesos!

Credenciais
O código aqui fornecido é baseado no código de exemplo de Kevin Hestners
Micro-RTSP. Você pode encontrar a biblioteca e o código de exemplo
original em seu repo Github.
Para as funções do botão, é utilizada a biblioteca OneButton fornecida por
Matthias Hertel.

Fontes
Código-fonte no Github https://github.com/circuitrocks/ESP32-RTSP
biblioteca OneButton https://github.com/mathertel/OneButton
fontes micro-RTSP https://github.com/geeksville/Micro-RTSP
caso esp32-CAM https://circuit.rocks/product:2659
Camera como arquivo Fusion360 https://github.com/circuitrocks/ESP32-
RTSP/blob/master/3D/ESP32-CAM-Case.f3z
arquivos STL caso Camera para impressão 3D
https://github.com/circuitrocks/ESP32-RTSP/tree/master/3D

Passo 1: Ligue a placa ESP32-CAM para


testes
Como dito anteriormente, a programação do ESP32-CAM é diferente de
outras fugas EPS32.

A primeira coisa é a fonte de alimentação. Você precisa aplicar 5V


diretamente nos pinos de cabeçalho 5V e GND.

A segunda coisa é o adaptador de programação. TXD, RXD e GND do


adaptador FTDI serão conectados aos pinos de cabeçalho UOT (RXD), UOR
(TXD) e GND.

A terceira coisa é o botão para colocar o ESP32 no modo de programação.


Este botão precisa ser conectado ao IO0 e ao GND. Durante a função

normal, o IO0 é usado como um dos pinos de controle da câmera. O fio no
IO0 deve ser o mais curto possível, porque algumas das placas ESP32-CAM
CASA TUTORIAIS DE PRODUTOS TUTORIAIS CONCEITUAIS GUIAS DE PROJETOS   
são muito sensíveis ao ruído neste pino.
SOFTWARE, FERRAMENTAS E OUTROS SERVIÇOS EM DESTAQUE POLÍTICA DE PRIVACIDADE

Aqui está o esquema fritzing para fácil compreensão:

All files including this Fritzing sketch can be found on our Github repo. Check
out the link at the end of the post.


CASA TUTORIAIS DE PRODUTOS TUTORIAIS CONCEITUAIS GUIAS DE PROJETOS   

SOFTWARE, FERRAMENTAS E OUTROS SERVIÇOS EM DESTAQUE POLÍTICA DE PRIVACIDADE

E esta é a minha configuração de laboratório para o ESP32-CAM. O fio


verde, branco e preto no canto inferior direito estão indo para o adaptador
FTDI. A placa vermelha é uma fuga Micro USB semelhante a esta Placa de
Fuga Micro USB. Os dois botões são o botão momentâneo amigável da
prancha de pão da Circuitrocks

Passo 2: Teste se você pode forçar o ESP32


no modo de download
Para colocar o ESP32 no modo de programação, você precisa pressionar o
botão DOWNLOAD (o lado direito no esboço do Fritzing) e mantê-lo
pressionado enquanto você liga ou redefine a placa ESP32-CAM. O botão de
reset está no lado oposto da placa, então um pouco difícil de alcançar.

Se funcionar e seus fios FTDI estiverem corretos, você verá no monitor serial
a seguinte saída:

Copy
ets Jun 8 2016 00:22:57

rst:0x1 (POWERON_RESET),boot:0x3 (DOWNLOAD_BOOT(UAR


waiting for download

Se você não ver nada no monitor serial, ou uma mensagem que não diga
"DOWNLOAD_BOOT" e "esperando o download", verifique sua fiação FTDI
e as conexões do botão DOWNLOAD.

Passo 3: Prepare seu ambiente de


desenvolvimento
Primeiro obtenha o código-fonte do nosso repo do Github como arquivo ZIP 
e descomprima o conteúdo para o seu harddisk.
PlataformaIO
TUTORIAIS DE PRODUTOS TUTORIAIS CONCEITUAIS GUIAS DE PROJETOS   
CASA TUTORIAIS DE PRODUTOS
No PlatformIO é bastante simples, pois tudo o que você precisa fazer é
baixar o repositório
SOFTWARE, completo
FERRAMENTAS do nosso
E OUTROS Github
SERVIÇOS e abrir a pasta POLÍTICA
EM DESTAQUE no PlatformIO.
DE PRIVACIDADE
Todas as bibliotecas necessárias serão adicionadas automaticamente quando
você começar a compilar o código-fonte.

Para escolher se você deseja piscar o ESP32-CAM sobre USB ou sobre OTA,
comente/não cocompartile uma das duas entradas upload_port.

Copy
; upload_port = COM3
upload_port = 192.168.0.109

ArduinoIDE
Para compilar o código com o ArduinoIDE, você precisa instalar duas
bibliotecas. O primeiro, OneButton está disponível com a compilação no
gerenciador de bibliotecas. Abra o gerente da biblioteca e procure por
OneButton. Se ainda não estiver instalado, instale-o.


CASA TUTORIAIS DE PRODUTOS TUTORIAIS CONCEITUAIS GUIAS DE PROJETOS   

SOFTWARE, FERRAMENTAS E OUTROS SERVIÇOS EM DESTAQUE POLÍTICA DE PRIVACIDADE

A segunda biblioteca, Micro-RTSP, é um pouco mais complicada, pois não


está disponível através do gerente da biblioteca.

Incluímos a biblioteca como um arquivo ZIP em nosso repositórioDo Github .


Ao baixar os códigos-fonte, encontrará a biblioteca na subpasta ArduinoIDE.

Em ArduinoIDE vá para Sketch -> Incluir Biblioteca -> Adicionar . Biblioteca


ZIP...

Em seguida, navegue até a pasta de código-fonte ESP32-RTSP e, em


seguida, para ArduinoIDE e selecione o arquivo Micro-RTSP.zip

Depois de ter sido bem sucedido na instalação de ambas as bibliotecas, o


esboço está pronto para compilação.

Abra o arquivo src.ino com arduinoIDE. Não se surpreenda que o arquivo


esteja vazio. Está aqui apenas para compatibilidade com ArduinoIDE. As
fontes reais estão nos arquivos .cpp e .h na mesma pasta.

Configure suas credenciais WiFi



Antes de começar a compilar o código, edite o arquivo wifikeys.h e insira
CASA TUTORIAIS DE PRODUTOS TUTORIAIS CONCEITUAIS GUIAS DE PROJETOS   
suas credenciais WiFi lá.
SOFTWARE, FERRAMENTAS E OUTROS SERVIÇOS EM DESTAQUE POLÍTICA DE PRIVACIDADE
Copy
#include <Arduino.h>
// Change YOUR_AP_NAME and YOUR_AP_PASSWORD to your
const char *ssid = "YOUR_AP_NAME"; // Put you
const char *password = "YOUR_AP_PASSWORD"; // Put y

Próximo: Atualizações de OTA (Over The Air)


Como você pode ver acima, é um pouco de esforço para piscar o ESP32-
CAM sobre USB, então a primeira coisa que eu fiz adicionar ao software é
habilitar atualizações OTA. Isso facilita a atualização do módulo sem a
necessidade de uma conexão com fio.

Para implementar o OTA, precisamos de 3 inclui no arquivo principal.h

Copy
// OTA stuff
#include <ESPmDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>

UDP é o protocolo de rede usado para a atualização, mDNS é para anunciar


o nome do dispositivo na rede e ArduinoOTA é a biblioteca para OTA.

Para inicializar e iniciar o serviço OTA escrevi a função startOTA. ArduinoOTA


possui retornos de chamada, que informa o aplicativo principal sobre o
início, o fim, o progresso e os erros que ocorrem. Esses retornos de chamada
são definidos no arquivo ota.cpp.

Copy
/**
* Initialize OTA server
* and start waiting for OTA requests
*/
void startOTA(void)
{
ArduinoOTA
// OTA request received
.onStart([]() {
String type;
if (ArduinoOTA.getCommand() == U_FLASH)
type = "sketch";
else // U_SPIFFS
type = "filesystem";

// NOTE: if updating SPIFFS this would be the


Serial.println("Start updating " + type);
lastProgress = 0; 
otaStarted = true;
})
CASA TUTORIAIS DE PRODUTOS
.onEnd([]() { TUTORIAIS CONCEITUAIS GUIAS DE PROJETOS   

// OTA is finished
Serial.println("\nEnd");
SOFTWARE, FERRAMENTAS E OUTROS SERVIÇOS EM DESTAQUE POLÍTICA DE PRIVACIDADE
})
.onProgress([](unsigned int progress, unsigned
// Status report during OTA
if ((lastProgress == 0) || ((progress / (tota
{
Serial.printf("Progress: %u%%\r", (progress
lastProgress = (progress / (total / 100));
if (lastProgress == 0)
{
lastProgress = 1;
}
}
})
.onError([](ota_error_t error) {
// Error occured during OTA, report it
Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR)
Serial.println("Auth Failed");
else if (error == OTA_BEGIN_ERROR)
Serial.println("Begin Failed");
else if (error == OTA_CONNECT_ERROR)
Serial.println("Connect Failed");
else if (error == OTA_RECEIVE_ERROR)
Serial.println("Receive Failed");
else if (error == OTA_END_ERROR)
Serial.println("End Failed");
});

// Enable MDNS so device can be seen


ArduinoOTA.setMdnsEnabled(false);

// Create a unique name


IPAddress ip = WiFi.localIP();
String hostName = "ESP32-CAM-" + ip.toString();
Serial.printf("Device is advertising as %s\n", ho
// Set the MDNS advertising name
ArduinoOTA.setHostname(hostName.c_str());
// Start the OTA server
ArduinoOTA.begin();
}

Para parar o serviço OTA é necessária uma subrotina muito simples

Copy
/**
* Stop the OTA server
*/
void stopOTA(void)
{
ArduinoOTA.end();
} 
CASA TUTORIAIS DE PRODUTOS TUTORIAIS CONCEITUAIS GUIAS DE PROJETOS   
A chamada ArduinoOTA.end() interromperá o serviço que está ouvindo as
solicitações do OTA.
SOFTWARE, FERRAMENTAS E OUTROS SERVIÇOS EM DESTAQUE POLÍTICA DE PRIVACIDADE
Para lidar com as solicitações OTA na função loop() você acabou de chamar

Copy
ArduinoOTA.handle();

para verificar o serviço.

Normalmente, você iniciaria o serviço OTA a partir da função () configuração


e simplesmente a deixaria funcionar em segundo plano. Mas ao testar o
aplicativo, descobri que o serviço OTA está interferindo no streaming UDP
do vídeo. Então eu decidi iniciar o serviço OTA apenas quando o usuário
solicita, apertando um botão.

Então, em vez de chamar ArduinoOTA.handle() o tempo todo da função


loop(), adicionei um botão adicional. Pressionar o botão uma vez parar os
servidores rtsp e web streaming e iniciar o servidor OTA. Apertando o botão
uma segunda vez, para o servidor OTA e reinicia os servidores de streaming.

Além disso, adicionei a opção de reiniciar o dispositivo por um clique duplo


rápido no botão.

Todas essas funções são muito fáceis de fazer com a biblioteca OneButton.

Copy
// Button stuff
#include <OneButton.h>

Esta é a única inclusão necessária. Em seguida, o botão é definido com

Copy
/** GPIO for OTA request button */
int otaButton = 12;
/** Button class */
OneButton pushBt(otaButton, true, true);

e duas funções são anexadas como clique único e duplo

Copy
// Attach the button functions
pushBt.attachClick(enableOTA);
pushBt.attachDoubleClick(resetDevice);

E no loop principal() adicionamos

Copy
// Check the button 
pushBt.tick();
CASA TUTORIAIS DE PRODUTOS TUTORIAIS CONCEITUAIS GUIAS DE PROJETOS   
para lidar com eventos de botões.
SOFTWARE, FERRAMENTAS E OUTROS SERVIÇOS EM DESTAQUE POLÍTICA DE PRIVACIDADE
Eu realmente amo a biblioteca OneButton, porque ele faz

debounce o botão clica no fundo


tem opções para single, double click e long-press
Na função enableOTA, basta verificar se o servidor OTA está ativo agora ou
não e ligar/desligar os servidores de acordo

Copy
/**
* Handle button single click
*/
void enableOTA(void)
{
// If OTA is not enabled
if (!otaStarted)
{
// Stop the camera servers
#ifdef ENABLE_WEBSERVER
stopWebStream();
#endif
#ifdef ENABLE_RTSPSERVER
stopRTSP();
#endif
delay(100);
Serial.println("OTA enabled");
// Start the OTA server
startOTA();
otaStarted = true;
}
else
{
// If OTA was enabled
otaStarted = false;
// Stop the OTA server
stopOTA();
// Restart the camera servers
#ifdef ENABLE_WEBSERVER
initWebStream();
#endif
#ifdef ENABLE_RTSPSERVER
initRTSP();
#endif
}
}

E na segunda função iniciamos um reset SW do ESP32

Copy
/**
* Handle button double click
*/ 
void resetDevice(void)
{
CASA TUTORIAIS DE PRODUTOS
delay(100); TUTORIAIS CONCEITUAIS GUIAS DE PROJETOS   

WiFi.disconnect();
esp_restart();
SOFTWARE, FERRAMENTAS E OUTROS SERVIÇOS EM DESTAQUE POLÍTICA DE PRIVACIDADE
}

Finalmente: As funções de streaming.


O aplicativo tem duas opções de streaming de vídeo:

Streaming diretamente para um navegador da Web


Streaming como um servidor RTSP (Consulte wikipedia para uma
explicação do RTSP)
Para selecionar um dos dois servidores abra main.h e habilite o servidor que
deseja executar

Copy
// Select which of the servers are active
// Select only one or the streaming will be very sl
#define ENABLE_WEBSERVER
#define ENABLE_RTSPSERVER

Apenas um dos servidores deve ser habilitado. Se você habilitar ambos os


servidores, o streaming será muito lento.

Streaming para um navegador da Web


Esta é uma maneira bastante simples de transmitir um vídeo de uma câmera
WiFi. Basicamente, o ESP32 inicia um servidor web e em conexão por um
navegador da Web envia imagens da câmera para o navegador da Web.
Portanto, não é um fluxo de dados real da câmera, mas mais como um fluxo
de imagens.

Para habilitar o streaming do navegador da Web, usamos o servidor web a


partir da estrutura Arduino ESP32.

Copy
/** Web server class */
WebServer server(80);

inicializa o servidor web para atender às solicitações HTTP recebidas na porta


80.

Copy
// Set the function to handle stream requests
server.on("/", HTTP_GET, handle_jpg_stream);
// Set the function to handle single picture requ
server.on("/jpg", HTTP_GET, handle_jpg);
// Set the function to handle other requests 
server.onNotFound(handleNotFound);
CASA TUTORIAIS DE PRODUTOS TUTORIAIS CONCEITUAIS GUIAS DE PROJETOS   

define as ações em diferentes solicitações HTTP.


SOFTWARE, FERRAMENTAS E OUTROS SERVIÇOS EM DESTAQUE POLÍTICA DE PRIVACIDADE
Uma simples solicitação http://<IP-ADDRESS>/solicitação inicia o fluxo
contínuo de imagens para o navegador da Web.
http://<IP-ADDRESS>/jpg envia uma única imagem da câmera para o
navegador da Web E todas as outras solicitações são ignoradas.

Em seguida, o servidor web é iniciado

Copy
// Start the web server
server.begin();

E com

Copy
// Check if the server has clients
server.handleClient();

nós lidamos com os pedidos.

Para o fluxo contínuo de imagens, a subrotina handle_jpg_stream() está


fazendo duas coisas. #1 informa o navegador da Web dos dados que enviará.
E #2 ele envia imagens da câmera em um loop até que o navegador da Web
se desconecte.

Copy
/**
* Handle web stream requests
* Gives a first response to prepare the streaming
* Then runs in a loop to update the web content
* every time a new frame is available
*/
void handle_jpg_stream(void)
{
WiFiClient thisClient = server.client();
String response = "HTTP/1.1 200 OK\r\n";
response += "Content-Type: multipart/x-mixed-repl
server.sendContent(response);

while (1)
{
cam.run();
if (!thisClient.connected())
{
break;
}
response = "--frame\r\n";
response += "Content-Type: image/jpeg\r\n\r\n";
server.sendContent(response);

thisClient.write((char *)cam.getfb(), cam.getSi
server.sendContent("\r\n");
CASA TUTORIAIS DE PRODUTOS
delay(150); TUTORIAIS CONCEITUAIS GUIAS DE PROJETOS   

}
}
SOFTWARE, FERRAMENTAS E OUTROS SERVIÇOS EM DESTAQUE POLÍTICA DE PRIVACIDADE

As solicitações de imagem única são tratadas pela subrotina handle_jpg().


Ele lê uma foto da câmera e envia para o navegador da web.

Copy
/**
* Handle single picture requests
* Gets the latest picture from the camera
* and sends it to the web client
*/
void handle_jpg(void)
{
WiFiClient thisClient = server.client();

cam.run();
if (!thisClient.connected())
{
return;
}
String response = "HTTP/1.1 200 OK\r\n";
response += "Content-disposition: inline; filenam
response += "Content-type: image/jpeg\r\n\r\n";
server.sendContent(response);
thisClient.write((char *)cam.getfb(), cam.getSize
}

E para todas as outras solicitações, o handle Desendo apenas envia uma


resposta simples com instruções de volta para o navegador da Web

Copy
/**
* Handle any other request from the web client
*/
void handleNotFound()
{
IPAddress ip = WiFi.localIP();
String message = "Stream Link: rtsp://";
message += ip.toString();
message += ":8554/mjpeg/1\n";
message += "Browser Stream Link: http://";
message += ip.toString();
message += "\n";
message += "Browser Single Picture Link: http//";
message += ip.toString();
message += "/jpg\n";
message += "\n";
server.send(200, "text/plain", message);
} 
CASA TUTORIAIS DE PRODUTOS TUTORIAIS CONCEITUAIS GUIAS DE PROJETOS   
Como uma abordagem para ter streaming web e transmissão RTSP em
paralelo euFERRAMENTAS
SOFTWARE, executá-los em tarefasSERVIÇOS
E OUTROS independentes freeRTOS.POLÍTICA
EM DESTAQUE A tarefa de
DE PRIVACIDADE
streaming da Web é iniciada com uma chamada para

Copy
/**
* Initialize the web stream server by starting the
*/
void initWebStream(void)
{
#ifdef ENABLE_WEBSERVER
// Create the task for the web server
xTaskCreate(webTask, "WEB", 4096, NULL, 1, &webTa

if (webTaskHandler == NULL)
{
Serial.println("Create Webstream task failed");
}
else
{
Serial.println("Webstream task up and running")
}
#endif
}

Na tarefa recém-iniciada, fazemos então a configuração e o início do


servidor web e manuseamos em um loop infinito as solicitações http
recebidas. A tarefa é interrompida pela parada de bandeiraWeb que pode
ser definida a partir do loop principal() no caso de querermos ativar o
servidor OTA.

Copy
/**
* The task that handles web server connections
* Starts the web server
* Handles requests in an endless loop
* until a stop request is received because OTA
* starts
*/
void webTask(void *pvParameters)
{
// Set the function to handle stream requests
server.on("/", HTTP_GET, handle_jpg_stream);
// Set the function to handle single picture requ
server.on("/jpg", HTTP_GET, handle_jpg);
// Set the function to handle other requests
server.onNotFound(handleNotFound);
// Start the web server
server.begin();

while (1)

{
#ifdef ENABLE_WEBSERVER
CASA TUTORIAIS
// Check DE PRODUTOS
if the serverTUTORIAIS
has CONCEITUAIS
clients GUIAS DE PROJETOS   

server.handleClient();
#endif
SOFTWARE, FERRAMENTAS E OUTROS SERVIÇOS EM DESTAQUE POLÍTICA DE PRIVACIDADE
if (stopWeb)
{
// User requested web server stop
server.close();
// Delete this task
vTaskDelete(NULL);
}
delay(100);
}
}

Assista ao fluxo jpeg em um navegador


Para assistir ao fluxo da câmera em um navegador da Web use as urls

Copy
Browser Stream Link: http://192.168.0.109
Browser Single Picture Link: http//192.168.0.109/jp

para ver um fluxo contínuo de imagens ou um único instantâneo.

Substitua o endereço IP na URL pelo endereço IP da placa ESp32-CAM.

O servidor RTSP
O servidor RTSP usado é a biblioteca de servidores Micro-RTSP de Kevin
Hestner. Para executá-lo ao lado de um servidor é necessário um streamer
(para transmitir o vídeo) e uma sessão (para lidar com a comunicação RTP).
O cliente wi-fi é a alça para o cliente RTSP conectado.

Copy
/** WiFi server for RTSP */
WiFiServer rtspServer(8554);

/** Stream for the camera video */


CStreamer *streamer = NULL;
/** Session to handle the RTSP communication */
CRtspSession *session = NULL;
/** Client to handle the RTSP connection */
WiFiClient rtspClient;

O mesmo que para o servidor de streaming web usamos uma tarefa


freerTOS independente para lidar com solicitações. A tarefa é iniciada com
uma chamada para initRTSP()

Copy 
/**
* Starts the task that handles RTSP streaming
*/
CASA voidTUTORIAIS DE PRODUTOS
initRTSP(void) TUTORIAIS CONCEITUAIS GUIAS DE PROJETOS   

{
//FERRAMENTAS
SOFTWARE, Create the task SERVIÇOS
E OUTROS for theEMRTSP server POLÍTICA DE PRIVACIDADE
DESTAQUE
xTaskCreate(rtspTask, "RTSP", 4096, NULL, 1, &rts

// Check the results


if (rtspTaskHandler == NULL)
{
Serial.println("Create RTSP task failed");
}
else
{
Serial.println("RTSP task up and running");
}
}

Dentro da tarefa, iniciamos o servidor RTSP e iniciamos. Depois disso,


lidamos com pedidos de entrada de loop infinitos. E no caso de o servidor
OTA ser iniciado, o servidor e a tarefa podem ser interrompidos pelo flag
stopRTSPtask

Copy
/**
* The task that handles RTSP connections
* Starts the RTSP server
* Handles requests in an endless loop
* until a stop request is received because OTA
* starts
*/
void rtspTask(void *pvParameters)
{
uint32_t msecPerFrame = 200;
static uint32_t lastimage = millis();

// rtspServer.setNoDelay(true);
rtspServer.setTimeout(1);
rtspServer.begin();

while (1)
{
// If we have an active client connection, just
if (session)
{
session->handleRequests(0); // we don't use a
// instead we send only if we have new enough

uint32_t now = millis();


if (now > lastimage + msecPerFrame || now < l
{ // handle clock rollover
session->broadcastCurrentFrame(now);
lastimage = now;

// check if we are overrunning our max fram 


now = millis();
if (now > lastimage + msecPerFrame)
CASA TUTORIAISprintf("warning
DE PRODUTOS TUTORIAIS CONCEITUAIS
exceeding GUIAS
max frame DE PROJETOS
rate   

}
SOFTWARE, FERRAMENTAS E OUTROS SERVIÇOS EM DESTAQUE POLÍTICA DE PRIVACIDADE
// Handle disconnection from RTSP client
if (session->m_stopped)
{
Serial.println("RTSP client closed connecti
delete session;
delete streamer;
session = NULL;
streamer = NULL;
}
}
else
{
rtspClient = rtspServer.accept();
// Handle connection request from RTSP client
if (rtspClient)
{
Serial.println("RTSP client started connect
streamer = new OV2640Streamer(&rtspClient,

session = new CRtspSession(&rtspClient, str


delay(100);
}
}

if (stopRTSPtask)
{
// User requested RTSP server stop
if (rtspClient)
{
Serial.println("Shut down RTSP server becau
delete session;
delete streamer;
session = NULL;
streamer = NULL;
}
// Delete this task
vTaskDelete(NULL);
}
delay(10);
}
}

Inside the endless loop you can see that we initate the streaming of a image
frame every 200 ms (defined by uint32_t msecPerFrame = 200;). The time
between sending two frames defines how smooth the video is shown in the
RTSP client. How fast you can go depends basically on what your local WiFi
network (and the ESP32 processing power) can handle. For my environment
the 200ms was good value.

How to watch the RTSP stream.
To receive the RTSP stream and watch it there are several options. For all
CASA TUTORIAIS DE PRODUTOS TUTORIAIS CONCEITUAIS GUIAS DE PROJETOS   
options you need to setup the RTSP network address as
rtsp://192.168.0.109:8554/mjpeg/1
SOFTWARE, FERRAMENTAS E OUTROS SERVIÇOS EM DESTAQUE POLÍTICA DE PRIVACIDADE
and replace the IP address with the one that your ESP32 uses.
On a Windows PC you can use e.g. VLC and connect to the network

On an Android device you can use VLC as well. Or any other of the many
RTSP clients available.

Last last step: put the camera into a nice case.


Now that we have cheap web cam that can stream videos to your devices, it
would be nice to have it packaged in a protecting case. There are many
options for matching cases for the ESP32-CAM available, but we decided to
make our own.


CASA TUTORIAIS DE PRODUTOS TUTORIAIS CONCEITUAIS GUIAS DE PROJETOS   

SOFTWARE, FERRAMENTAS E OUTROS SERVIÇOS EM DESTAQUE POLÍTICA DE PRIVACIDADE

It is a quite simple case, just plugged together with access to the SD card
(that we didn’t use in this tutorial). The case has the option of vertical and
horizontal adjustment of the viewing angle.
The 3D files for all three parts are available in the 3D folder of the Github
repository. At Flarelab the cost of all 3D printed parts was just 360 Pesos.

The parts hold the ESP32-CAM board without screws. But some glue might
be required to hold the front and back part together. There is as well an
opening for a micro USB connector mounted on a breakout board.

The camera case and the foot are fixed with a 5mm screw. So once you have
the right angle you can fix the case by tightening the screw.
The footer has 4 long circled holes that allow to adjust the viewing angle
before fixing the case.


CASA TUTORIAIS DE PRODUTOS TUTORIAIS CONCEITUAIS GUIAS DE PROJETOS   

SOFTWARE, FERRAMENTAS E OUTROS SERVIÇOS EM DESTAQUE POLÍTICA DE PRIVACIDADE

Sources:
Source code on Github https://github.com/circuitrocks/ESP32-RTSP
OneButton library https://github.com/mathertel/OneButton
Micro-RTSP sources https://github.com/geeksville/Micro-RTSP
ESP32-CAM https://circuit.rocks/product:2659
Camera case as Fusion360 file https://github.com/circuitrocks/ESP32-
RTSP/blob/master/3D/ESP32-CAM-Case.f3z
Camera case STL files for 3D printing https://github.com/circuitrocks/ESP32-
RTSP/tree/master/3D

Mounting the camera in the case


CASA TUTORIAIS DE PRODUTOS TUTORIAIS CONCEITUAIS GUIAS DE PROJETOS   

SOFTWARE, FERRAMENTAS E OUTROS SERVIÇOS EM DESTAQUE POLÍTICA DE PRIVACIDADE

First step we need to solder the 5V power supply from the USB breakout
board to the pins on the ESP32-CAM board


Empurre o ESP32 suavemente para a parte frontal do caso
CASA TUTORIAIS DE PRODUTOS TUTORIAIS CONCEITUAIS GUIAS DE PROJETOS   

SOFTWARE, FERRAMENTAS E OUTROS SERVIÇOS EM DESTAQUE POLÍTICA DE PRIVACIDADE

Aperte suavemente a placa de fuga USB entre as duas pernas da parte de


trás da caixa


CASA TUTORIAIS DE PRODUTOS TUTORIAIS CONCEITUAIS GUIAS DE PROJETOS   

SOFTWARE, FERRAMENTAS E OUTROS SERVIÇOS EM DESTAQUE POLÍTICA DE PRIVACIDADE

Conserte a placa USB com uma cola quente. No próximo design vou
adicionar alguns pinos de suporte para evitar a cola quente


Agora junta todas as partes e você está pronto para ir. Esta foi a primeira
CASA TUTORIAIS DE PRODUTOS TUTORIAIS CONCEITUAIS GUIAS DE PROJETOS   
impressão, então há algumas bordas irregulares onde a caixa dianteira e
traseira se conectam. Isso será melhorado no próximo projetoPOLÍTICA
SOFTWARE, FERRAMENTAS E OUTROS SERVIÇOS EM DESTAQUE
de caso.DE PRIVACIDADE

Um pequeno lembrete onde você lê este blog LEARN


CASA TUTORIAIS DE PRODUTOS TUTORIAIS CONCEITUAIS GUIAS DE PROJETOS   

SOFTWARE, FERRAMENTAS E OUTROS SERVIÇOS EM DESTAQUE POLÍTICA DE PRIVACIDADE

A abertura para o cabo USB

Cabo USB conectado e a câmera começa a transmitir 


CASA TUTORIAIS DE PRODUTOS TUTORIAIS CONCEITUAIS GUIAS DE PROJETOS   

SOFTWARE, FERRAMENTAS E OUTROS SERVIÇOS EM DESTAQUE POLÍTICA DE PRIVACIDADE

Compartilhar:  GORJEIO  FACEBOOK  REDDIT


 Marcado ESP32, ESP32-CAM, RTSP

Artigos relacionados
   

Como usar o Interfacing RFID: Fundamentos


Usando
módulo de
comandos AT no MFRC-522 GPS com Chip
câmera Reader/Writer GPS UBLOX
ESP8266
Raspberry Pi Module NEO-6M

Você também pode gostar