Escolar Documentos
Profissional Documentos
Cultura Documentos
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.
CASA TUTORIAIS DE PRODUTOS TUTORIAIS CONCEITUAIS GUIAS DE PROJETOS
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!
A câmera em ação.
CASA TUTORIAIS DE PRODUTOS TUTORIAIS CONCEITUAIS GUIAS DE PROJETOS
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
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
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
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.
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
Copy
// OTA stuff
#include <ESPmDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
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";
// 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");
});
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();
Todas essas funções são muito fáceis de fazer com a biblioteca OneButton.
Copy
// Button stuff
#include <OneButton.h>
Copy
/** GPIO for OTA request button */
int otaButton = 12;
/** Button class */
OneButton pushBt(otaButton, true, true);
Copy
// Attach the button functions
pushBt.attachClick(enableOTA);
pushBt.attachDoubleClick(resetDevice);
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
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
}
}
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
}
Copy
// Select which of the servers are active
// Select only one or the streaming will be very sl
#define ENABLE_WEBSERVER
#define ENABLE_RTSPSERVER
Copy
/** Web server class */
WebServer server(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
Copy
// Start the web server
server.begin();
E com
Copy
// Check if the server has clients
server.handleClient();
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
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
}
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
}
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);
}
}
Copy
Browser Stream Link: http://192.168.0.109
Browser Single Picture Link: http//192.168.0.109/jp
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);
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
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
}
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,
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.
CASA TUTORIAIS DE PRODUTOS TUTORIAIS CONCEITUAIS GUIAS DE PROJETOS
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
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
CASA TUTORIAIS DE PRODUTOS TUTORIAIS CONCEITUAIS GUIAS DE PROJETOS
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
CASA TUTORIAIS DE PRODUTOS TUTORIAIS CONCEITUAIS GUIAS DE PROJETOS
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
CASA TUTORIAIS DE PRODUTOS TUTORIAIS CONCEITUAIS GUIAS DE PROJETOS
Artigos relacionados