0% found this document useful (0 votes)
184 views

Esp32 Instalação e Exemplos

The document provides information about programming the ESP 32 microcontroller using Arduino IDE. It describes the ESP 32's characteristics such as its dual core processor, integrated WiFi and Bluetooth capabilities. It also provides instructions for installing the ESP 32 board in Arduino IDE on Ubuntu Linux and Windows, including downloading necessary files and adding the board in Arduino IDE. Examples of programs for inputs, outputs and sensors are listed.

Uploaded by

Paulo Galvao
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
184 views

Esp32 Instalação e Exemplos

The document provides information about programming the ESP 32 microcontroller using Arduino IDE. It describes the ESP 32's characteristics such as its dual core processor, integrated WiFi and Bluetooth capabilities. It also provides instructions for installing the ESP 32 board in Arduino IDE on Ubuntu Linux and Windows, including downloading necessary files and adding the board in Arduino IDE. Examples of programs for inputs, outputs and sensors are listed.

Uploaded by

Paulo Galvao
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
You are on page 1/ 25

ESP 32

Microcontrolador, WiFi e Bluetooth


Índice
Introdution to ESP32 Board in Arduino IDE on Ubuntu Linux...........................................................1
Pinout..........................................................................................................................................4
Programação através de Arduino IDE..................................................................................................5
Installing ESP32 Board in Arduino IDE (UBUNTU Linux)...........................................................5
Step 1: Open Terminal and execute the following command (copy->paste and hit enter):........5
Step 2: Restart Your arduino IDE................................................................................................6
Installing ESP32 Board in Arduino IDE (Windows Install)............................................................8
Exemplos de Programas.....................................................................................................................15
Exemplo 1: Efeito de Hall.............................................................................................................15
Exemplo 2: Efeito Capacitivo (Touch Sensor)..............................................................................18
Exemplo 3: Entrada Analógica......................................................................................................20
Exemplo 4: Entrada Analógica + Saída PWD...............................................................................22
Introdution to ESP32 Board in Arduino IDE on Ubuntu
Linux
ESP32 is highly-integrated with in-built antenna switches, RF balun, power amplifier, low-noise
receive amplifier, filters, and power management modules. ESP32 adds priceless functionality and
versatility to your applications with minimal Printed Circuit Board (PCB) requirements. ESP32 can
interface with other systems to provide Wi-Fi and Bluetooth functionality through its SPI / SDIO or
I2C / UART interfaces. Most of the ESP32 framework is implemented. Most noticeable is the
missing analogWrite. While analogWrite is on it’s way, there are a few other extra options that you
can use:
The ESP32 Main Characteristics

The ESP32 is an under US$10 board with great advantages over similar IoT boards in the market.
This board has a dual processed microprocessor that helps a lot, because when one processor is
handle communication, the other one is in charge of I/O control, for example. This feature will
prevent some issues that happen with ESP8266, where the sole CPU needs stop controlling I/Os
when handle with Comm. Besides, the ESP32 has integrated WIFI, BLUETOOTH, DAC, several
ADC (not only one as the ESP8266), capacitive touch sensors, etc (give a look at above block
diagram). And the good news is that Power Consumption is almost the same as ESP8266.
Bellow a chart that can show us its main characteristics, and differences when compared with
ESP8266:
Let’s point its main properties for more details:
Key Features:
• 240 MHz dual-core Tensilica LX6 microcontroller with 600 DMIPS
• Integrated 520 KB SRAM
• Integrated 802.11 b/g/n HT40 Wi-Fi transceiver, baseband, stack and LwIP
• Integrated dual mode Bluetooth (classic and BLE)
• 16 MB flash, memory-mapped to the CPU code space
• 2.3V to 3.6V operating voltage
• -40°C to +125°C operating temperature
• Onboard PCB antenna / IPEX connector for external antenna

Sensors:
• Ultra-low noise analog amplifier
• Hall sensor
• 10x capacitive touch interfaces
• 32 kHz crystal oscillator

34 x GPIO:
• 3 x UARTs, including hardware flow control
• 3 x SPI
• 2 x I2S
• 18 x ADC input channels
• 2 x DAC
• 2 x I2C
• PWM/timer input/output available on every GPIO pin
• OpenOCD debug interface with 32 kB TRAX buffer
• SDIO master/slave 50 MHz
• Supports external SPI flash up to 16 MB
• SD-card interface support

Security Related:
• WEP, WPA/WPA2 PSK/Enterprise
• Hardware accelerated encryption: AES/SHA2/Elliptical Curve Cryptography/RSA-4096

Performance:
• Supports sniffer, Station, SoftAP and Wi-Fi direct mode
• Max data rate of 150 Mbps@11n HT40, 72 Mbps@11n HT20, 54 Mbps@11g, and 11
Mbps@11b
• Maximum transmit power of 19.5 dBm@11b, 16.5 dBm@11g, 15.5 dBm@11n
• Minimum receiver sensitivity of -97 dBm
• 135 Mbps UDP sustained throughput
• 5 μA power consumption in Deep-sleep

O ESP pode ser programado nas seguintes linguagens:


• LUA

• Arduino IDE

• MicroPython

• NodeJS (JavaScript) / Node-RED

Zerynth IDE (Python):


https://docs.zerynth.com/latest/official/core.zerynth.docs/installationguide/docs/index.html

Chilipepr (LUA): http://chilipeppr.com/esp32

Micropython: https://randomnerdtutorials.com/getting-started-micropython-esp32-esp8266/
Pinout

Paǵina Oficial: https://wiki.ai-thinker.com/esp32/boards/nodemcu_32s


Especificações do Produto e Desenhos:
https://wiki.ai-thinker.com/_media/esp32/docs/nodemcu-32s_product_specification.pdf
Firmware:ai-thinker_nodemcu-32s_dio_32mbit_v1.0_20161101.7z
Hardware:nodemcu_32s_hardware_resources.7z
NodeMCU: https://github.com/nodemcu/nodemcu-firmware/tree/dev-esp32
Arduino: https://github.com/espressif/arduino-esp32
Programação através de Arduino IDE

Installing ESP32 Board in Arduino IDE (UBUNTU Linux)


In this tutorial we are installing ESP32 board in Arduino IDE. Its not same as installing ESP8266.
ESP32 is dual core CPU in arduino IDE it will not support all the functions but its enough to make
many projects.

Step 1: Open Terminal and execute the following command (copy->paste and hit
enter):
Step 1.1: Allow non root user to use tty0 (USB to Serial converter) serial communication with
ESP32
sudo usermod -a -G dialout $USER
Step 1.2: Install git. By default its installed with ubuntu linux installation
sudo apt-get install git
Step 1.3: Get repository for get–pip.py, is a bootstrapping script that enables users to install pip,
setup tools, and wheel in Python environments that don’t already have them.
wget https://bootstrap.pypa.io/get-pip.py
Step 1.4: Run python get-pip.py
sudo python get-pip.py
Step 1.5: Install pySerial is a Python API module to access the serial port. pySerial provides a
uniform API across multiple operating systems, including Windows, Linux, and BSD.
sudo pip3 install pyserial
Step 1.6: On terminal go to you Arduino installation directory using cd command

Step 1.7: Create directory espressif in arduino-1.8.3/hardware/ folder


mkdir -p ~/Arduino/hardware/espressif
Step 1.8: Change directory to espressif
cd ~/Arduino/hardware/espressif
Step 1.9: Clone esp32 core from git to esperssif directory
git clone https://github.com/espressif/arduino-esp32.git esp32
Step 1.10: After cloning you will find esp32 directory
cd esp32
Step 1.11: Update submodules of ESP32
git submodule update –init –recursive
Step 1.12: Run following final commands
cd tools
python get.py
Here is my installation Screen shot

Step 2: Restart Your arduino IDE


See in boards you will find ESP32 board. Go to Toõls (Ferramentas), Placa and choose in this case
NodeMCU-32S.
Change Upload Speed to 115200 and search for the right Porta to make the connection.
Installing ESP32 Board in Arduino IDE (Windows Install)
Driver conversor USB-Série para ESP32 e ESP8266

Após a ligação do NodeMCU-32S no computador ele será identificado e a busca por drivers de
instalação vai iniciar. Por padrão, o Windows vai procurar pelos drivers na internet e se ele
encontrar a instalação vai ocorrer de forma automática.
Caso o Windows não consiga encontrar os drivers para instalação da placa, então terá que instalar
manualmente.
Faça download do driver no link abaixo:
Driver CP2102 para Windows
Após o download faça a instalação dos drivers. Terminado a instalação, seu NodeMCU-32S já está
pronto para ser usado.

A IDE do Arduino (Programa do Arduino) é uma ferramenta multiplataforma escrita em Java


derivada dos projetos Processing e Wiring. Inclui um editor de código com recursos de realce de
sintaxe, parênteses correspondentes e identação automática, sendo capaz de compilar e carregar
programas para a placa com um único clique. Por isso não há a necessidade de editar Makefiles ou
correr programas em ambientes de linha de comando.
Através da IDE do Arduino é possível programar (utilizando a linguagem do Arduino) para o
NodeMCU-32S. Dessa forma, será possível trabalhar num ambiente mais simples, que é bastante
conhecido por quem já programa para Arduino ou C / C++.
Antes de efetuar a instalação da IDE é necessário fazer a instalação do Java. Caso já possua o Java
instalado, verifique se o mesmo está atualizado.
Para download do Java, basta aceder https://www.java.com/ e fazer o download do instalador.
Feito a instalação ou atualização do Java, já é possível fazer a instalação da IDE do Arduino.
Para fazer o download da versão atualizada da IDE do Arduino para Windows basta aceder
https://www.arduino.cc/en/Main/Software e efetuar a instalação.
Após a instalação da IDE, será necessário prepararmos os Ficheiros necessários para que a IDE do
Arduino possa reconhecer o NodeMCU-32S.
Faça o download do Git:
https://git-scm.com/download/win
Após o download, faça a instalação do programa. Terminado a instalação, acesse o caminho
“C:\Program Files\Git\cmd” e execute “git-gui”.
Com o programa aberto, clique em “Clone Existing Repository”:

Na janela que abrir, insira as informações da seguinte forma:


Source Location:
https://github.com/espressif/arduino-esp32.git
Target Directory:
C:/Users/[Utilizador-PC]/Documents/Arduino/hardware/espressif/esp32
OBS: Em “Target Directory:” apague o [USUARIO-PC] e insira o nome de utilizador do seu
computador para que o caminho possa ser válido.

Após inserir as informações, clique em “Clone” para que o processo de cópia do repositório seja
realizado:
Este processo é um pouco demorado, portanto paciência.
Finalizado a clonagem do repositório, acesse o caminho “C:/Users/[ USUARIO-
PC]/Documents/Arduino/hardware/espressif/esp32/tools” (lembre-se de mudar [USUARIO-PC]
para o nome de utilizador do seu computador) e execute o “get.exe” e aguarde:

Este processo também é demorado.


Terminado, conecte o NodeMCU-32S ao computador e abra a IDE do Arduino.
Com a IDE aberta, será mostrado algumas opções na barra de ferramentas da mesma. Abaixo é feito
um apanhado geral (das opções relevantes) do menu Ficheiro e Ferramentas:
1. Ficheiro
• Novo: abre uma nova instância da IDE.
• Abrir: carrega na IDE projetos guardados no computador.
• Exemplos: disponibiliza diversos exemplos que são separados por pastas e
bibliotecas. Os exemplos estão em submenus e para abrir algum deles, basta
selecionar e clicar.
• Fechar: fecha a instância atual.
• Guardar: guarda as últimas modificações do seu projeto.
• Guardar como: se o projeto já foi guardado, mas deseja Guardar noutro local, essa é
a opção indicada.
• Preferências: configurações gerais da IDE.
• Sair: encerra definitivamente a IDE.
2. Ferramentas
• Monitor série: executa o terminal série que auxilia no recolha e envio de dados para
a placa sem a necessidade de recorrer a uma ferramenta externa.
• Placa: possibilita selecionar o modelo da placa que está ligado ao computador.
• Porta: possibilita selecionar a porta COM em que a placa está recebendo/enviando
informações.
No menu “Ferramentas” selecione a opção “Placas”, role a lista até o final e selecione “NodeMCU-
32S”:

Ainda no menu “Ferramentas”, selecione a opção porta e marque a porta COM em que sua placa foi
alocada:
Veja que a minha placa foi alocada na COM3, porém, o seu NodemCU-32S pode ter sido alocado
em uma COM de outro valor. Caso não saiba em qual porta COM sua placa foi alocada, basta
retornar no menu Iniciar do Windows, aceder a opção Dispositivos e Impressoras e verificar a porta
em que seu NodeMCU-32S está ligado e retornar na IDE e selecionar a porta COM.
Feito essas configurações, sua IDE está pronta para enviar os códigos ao NodeMCU-32S.
Para um teste rápido, na IDE clique no menu “Ficheiro”, selecione a opção “Exemplos”, em seguida
“01.Basics” e selecione “Blink”. Uma nova janela da IDE vai abrir. Faça a conferência das
informações para garantir que nada foi alterado na placa e na porta. Se atente ao rodapé da IDE que
mostra a placa e a porta COM que está configurada na IDE:

Agora, clique no botão de upload do código para o NodeMCU-32S e aguarde o código ser
carregado na placa.
Terminado o carregamento, o LED da placa irá piscar com intervalo de 1 segundo:
Sempre que abrir a IDE, faça a conferência das informações para garantir que nada foi alterado.
Geralmente, feito a configurações a primeira vez ela vai se manter sem necessidade de fazer
alteração.
Reforçando: sem executar os passos de definição de placa e porta, caso você escreva o código ou
utilize algum exemplo de código e tente carregar no NodeMCU-32S, o carregamento do código
para a placa não será bem sucedido e um erro será mostrado na IDE.
Exemplos de Programas

Exemplo 1: Efeito de Hall


The ESP32 Hall Effect Sensor
The ESP32 features a built-in hall effect sensor located behind the metal lid of the ESP32 chip as
shown in the following figure.

A hall effect sensor can detect variations in the magnetic field in its surroundings. The greater the
magnetic field, the greater the sensor’s output voltage.

The hall effect sensor can be combined with a threshold detection to act as a switch, for example.
Additionally, hall effect sensors are mainly used to:
• Detect proximity;
• Calculate positioning;
• Count the number of revolutions of a wheel;
• Detect a door closing;
• And much more.

Read Hall Effect Sensor – Arduino IDE


Reading the hall effect sensor measurements with the ESP32 using the Arduino IDE is as simple as
using the hallRead() function.
In your Arduino IDE, go to File > Examples > ESP32 > HallSensor sketch:
// Simple sketch to access the internal hall effect detector on the esp32.
// values can be quite low.
// Brian Degger / @sctv

int val = 0;

void setup() {
Serial.begin(9600);
}

// put your main code here, to run repeatedly


void loop() {
// read hall effect sensor value
val = hallRead();
// print the results to the serial monitor
Serial.println(val);
delay(1000);
}

Hall_Effect_Sensor.ino → [email protected] curso ESP-32

This example simply reads the hall sensor measurements and displays them on the Serial monitor.
val = hallRead();
Serial.println(val);

Add a delay of one second in the loop, so that you can actually read the values.
delay(1000);

Upload the code to your ESP32 board:


Demonstration
Once the upload is finished, open the Serial Monitor at a baud rate of 9600. Approximate a magnet
to the ESP32 hall sensor and see the values increasing…
Or decreasing depending on the magnet pole that is facing the sensor:
The closer the magnet is to the sensor, the greater the absolute values are.
Exemplo 2: Efeito Capacitivo (Touch Sensor)
/*****************************************************
* ESP32 Touch Test and LED Ctrl
* Touch pin ==> Touch0 is T0 which is on GPIO 4 (D4).
* LED pin ==> D2
*
* MJRoBot.org 6Sept17
*****************************************************/

#define TOUTCH_PIN T0 // ESP32 Pin D4


#define LED_PIN 2
int touch_value = 100;

void setup()
{
Serial.begin(115200);
delay(1000); // give me time to bring up serial monitor
Serial.println("ESP32 Touch Test");
pinMode(LED_PIN, OUTPUT);
digitalWrite (LED_PIN, LOW);
}

void loop()
{
touch_value = touchRead(TOUTCH_PIN);
Serial.println(touch_value); // get value using T0
if (touch_value < 50)
{
digitalWrite (LED_PIN, HIGH);
}
else
{
digitalWrite (LED_PIN, LOW);
}
delay(1000);
}

touch.ino Mjrovai
Em vazio: >50 e led desligado
Em contacto: <10 e led ligado
Exemplo 3: Entrada Analógica
GPIO ADC Channel
• GPIO 0 ==> ADC2_CH1
• GPIO 2 ==> ADC2_CH2
• GPIO 4 ==> ADC2_CH0
• GPIO 12 => ADC2_CH5
• GPIO 13 => ADC2_CH4
• GPIO 14 => ADC2_CH6
• GPIO 15 => ADC2_CH3
• GPIO 25 => ADC2_CH8
• GPIO 26 => ADC2_CH9
• GPIO 27 => ADC2_CH7
• GPIO 32 => ADC1_CH4
• GPIO 33 => ADC1_CH5
• GPIO 34 => ADC1_CH6
• GPIO 35 => ADC1_CH7
• GPIO 36 => ADC1_CH0
• GPIO 37 => ADC1_CH1
• GPIO 38 => ADC1_CH2
• GPIO 39 => ADC1_CH3
/******************************************************
* ESP32 Analog Input Test
* Analog Input: ADC_1_0 pin ==> GPIO36 (VP).
*
* MJRoBot.org 6Sept17
*****************************************************/
//Analog Input
#define ANALOG_PIN_0 36
int analog_value = 0;

void setup()
{
Serial.begin(115200);
delay(1000); // give me time to bring up serial monitor
Serial.println("ESP32 Analog IN Test");
}

void loop()
{
analog_value = analogRead(ANALOG_PIN_0);
Serial.println(analog_value);
delay(500);
}

RTD
Com a RTD é possível ir dos 0 (luz total – telemóvel em cima sensor) aos 4095 (escuridão total –
dedo no sensor)
analog.ino
Exemplo 4: Entrada Analógica + Saída PWD

Use a mesma montagem anterior.


/*****************************************************
* ESP32 Analog Input Test
* Analog Input: ADC_1_0 pin ==> GPIO36 (VP).
*
* MJRoBot.org 6Sept17 / Paulo Glavao 28Jun19
*****************************************************/

//Analog Input
#define ANALOG_PIN_0 36
int analog_value = 0;

// PMW LED
#define LED_PIN 2
int freq = 5000;
int ledChannel = 0;
int resolution = 8;
int dutyCycle = 0;

void setup()
{
Serial.begin(115200);
delay(1000); // give me time to bring up serial monitor
Serial.println("ESP32 Analog IN/OUT Test");

ledcSetup(ledChannel, freq, resolution);


ledcAttachPin(LED_PIN, ledChannel);
ledcWrite(ledChannel, dutyCycle);
}
void loop()
{
analog_value = analogRead(ANALOG_PIN_0);
Serial.print("LDR: ");
Serial.println(analog_value);
dutyCycle = map(analog_value, 0, 4095, 0, 255);
ledcWrite(ledChannel, dutyCycle);
Serial.print("PWD: ");
Serial.println(dutyCycle);
delay(500);
}

analog_PWM.ino

You might also like