This commit is contained in:
antopoid 2022-11-15 16:40:14 +01:00
parent 3a9ccfd28d
commit c17a6bb850
24 changed files with 6330 additions and 0 deletions

View File

@ -0,0 +1,118 @@
/****************************************************************************
* Copyright (C) 2021 by Fabrice Muller *
* *
* This file is useful for ESP32 Design course. *
* *
****************************************************************************/
/**
* @file main.c
* @author Fabrice Muller
* @date 31 Oct. 2021
* @brief File containing the lab1-2 of Part 4.
*
* @see https://github.com/fmuller-pns/esp32-vscode-project-template
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "freertos/FreeRTOSConfig.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_timer.h"
#include "esp_sleep.h"
#include "driver/gpio.h"
#include "driver/dac.h"
#include "driver/adc.h"
#include "driver/adc_common.h"
#include "esp_adc_cal.h"
/*
ADC : Analog to Digital Converter
Documentation:
https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/adc.html
Command to obtain Vref:
espefuse.py --port /dev/ttyUSB0 adc_info
*/
/* Default eFuse Vref in mV */
#define DEFAULT_VREF 1121
const adc_unit_t unit = ADC_UNIT_1;
const adc_channel_t channel = ADC_CHANNEL_1;
const adc_bits_width_t width = ADC_WIDTH_BIT_10;
const adc_atten_t atten = ADC_ATTEN_DB_11;
esp_adc_cal_characteristics_t *adc_chars;
/**
* @brief Print the Characterization type.
*
* @param val_type type of characterization
*/
static void print_char_val_type(esp_adc_cal_value_t val_type) {
switch (val_type) {
case ESP_ADC_CAL_VAL_EFUSE_TP:
printf("Characterized using Two Point Value\n");
break;
case ESP_ADC_CAL_VAL_EFUSE_VREF:
printf("Characterized using eFuse Vref (%d mV)\n", DEFAULT_VREF);
break;
default:
printf("Characterized using Default Vref\n");
}
}
/**
* @brief Starting point function
*
*/
void app_main(void) {
/* Configure ADC */
adc1_config_width(width);
adc1_config_channel_atten(channel, atten);
/* Characterize ADC */
adc_chars = calloc(1, sizeof(esp_adc_cal_characteristics_t));
esp_adc_cal_value_t val_type = esp_adc_cal_characterize(unit, atten, width, DEFAULT_VREF, adc_chars);
print_char_val_type(val_type);
uint16_t measuredValues;
int v;
for (;;) {
/* Get start time */
int64_t t1 = esp_timer_get_time();
/* Perform measure */
v = adc1_get_raw(channel);
measuredValues = esp_adc_cal_raw_to_voltage(v, adc_chars);
/* Get end time */
int64_t t2 = esp_timer_get_time();
/* Print time conversion and voltage */
printf("full time conversion = %lld µs\n", t2-t1);
printf("V = %d mV\n", measuredValues);
/* Every second */
vTaskDelay(pdMS_TO_TICKS(1000));
}
/* to ensure its exit is clean */
vTaskDelete(NULL);
}

View File

@ -0,0 +1,3 @@
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
CONFIG_ESPTOOLPY_FLASHSIZE="4MB"

View File

@ -0,0 +1,92 @@
/****************************************************************************
* Copyright (C) 2021 by Fabrice Muller *
* *
* This file is useful for ESP32 Design course. *
* *
****************************************************************************/
/**
* @file main.c
* @author Fabrice Muller
* @date 02 Nov. 2021
* @brief File containing the lab2 of Part 4.
*
* @see https://github.com/fmuller-pns/esp32-vscode-project-template
*/
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/ledc.h"
#include "esp_err.h"
#include "soc/ledc_reg.h"
/*
Documentation:
https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/ledc.html
*/
/**
* @brief Starting point function
*
*/
void app_main(void) {
/*
* LEDC Timer configuration
* Timer 0, Low speed mode, Auto clk, Résolution 10bits, Frequency 5 KHz
*/
ledc_timer_config_t timer = {
.speed_mode = LEDC_LOW_SPEED_MODE,
.duty_resolution = LEDC_TIMER_10_BIT,
.timer_num = LEDC_TIMER_0,
.freq_hz = 5000,
.clk_cfg = LEDC_AUTO_CLK};
ledc_timer_config(&timer);
/*
* Channel configuration
* Timer 0, Channel 0, GPIO21 pin, Low speed mode, duty=0
*/
ledc_channel_config_t channel = {
.gpio_num = 21,
.speed_mode = LEDC_LOW_SPEED_MODE,
.channel = LEDC_CHANNEL_0,
.timer_sel = LEDC_TIMER_0,
.duty = 0,
.hpoint = 0
};
ledc_channel_config(&channel);
/* Fade installation */
esp_err_t result = ledc_fade_func_install(0);
if (result != ESP_OK) {
printf("Error installing fade: %04x\n", result);
return;
}
/* First scenario */
printf("First scenario\n");
for (int i = 0; i < 1024; i++) {
ledc_set_duty_and_update(LEDC_LOW_SPEED_MODE,LEDC_CHANNEL_0,i,0);
vTaskDelay(pdMS_TO_TICKS(10));
}
/* Second scenario */
printf("Second scenario\n");
while(true) {
printf("Action 1\n");
ledc_set_fade_time_and_start(LEDC_LOW_SPEED_MODE,LEDC_CHANNEL_0, 0, 2000, LEDC_FADE_WAIT_DONE);
printf("Action 2\n");
ledc_set_fade_time_and_start(LEDC_LOW_SPEED_MODE,LEDC_CHANNEL_0, 1024, 5000, LEDC_FADE_WAIT_DONE);
}
}

View File

@ -0,0 +1,10 @@
# Configuration files
sdkconfig
sdkconfig.old
# Production folder
build/
# HTML documentation
html_doc/

View File

@ -0,0 +1,6 @@
# The following lines of boilerplate have to be in your project's
# CMakeLists in this exact order for cmake to work correctly
cmake_minimum_required(VERSION 3.5)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(main)

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,3 @@
PROJECT_NAME := main
include $(IDF_PATH)/make/project.mk

View File

@ -0,0 +1,22 @@
interface ftdi
ftdi_vid_pid 0x0403 0x6010
ftdi_layout_init 0x0038 0x003b
# The ESP32 only supports JTAG.
transport select jtag
# This can go as high as 20MHz if CPU frequency is 80MHz, or 26MHz
# if CPU frequency is 160MHz or 240MHz.
adapter_khz 20000
# If single core debugging is required, uncomment the following line
#set ESP32_ONLYCPU 1
# To disable RTOS support, uncomment the following line
# set ESP32_RTOS none
# This option defaults to 3.3v
set ESP32_FLASH_VOLTAGE 3.3
# Source the ESP32 configuration file
source [find target/esp32.cfg]

View File

@ -0,0 +1,3 @@
idf_component_register(
SRC_DIRS "."
INCLUDE_DIRS ".")

View File

@ -0,0 +1,2 @@
COMPONENT_SRCDIRS := .
COMPONENT_ADD_INCLUDEDIRS := .

View File

@ -0,0 +1,99 @@
/****************************************************************************
* Copyright (C) 2021 by Fabrice Muller *
* *
* This file is useful for ESP32 Design course. *
* *
****************************************************************************/
/**
* @file main.c
* @author Fabrice Muller
* @date 02 Nov. 2021
* @brief File containing the lab3 of Part 4.
*
* @see https://github.com/fmuller-pns/esp32-vscode-project-template
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "esp_log.h"
#include "esp_intr_alloc.h"
#include "freertos/FreeRTOSConfig.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/uart.h"
#include "driver/gpio.h"
static const char *TAG = "MAIN";
// GPIO18
#define TXD_PIN 18
// GPIO23
#define RXD_PIN 23
// Not Connected
#define RTS_PIN (UART_PIN_NO_CHANGE)
// Not Connected
#define CTS_PIN (UART_PIN_NO_CHANGE)
// Port number : 2
#define UART_PORT_NUM 2
// Rate : 115200
#define UART_BAUD_RATE 115200
#define TASK_STACK_SIZE 2048
#define BUF_SIZE (1024)
static char data[BUF_SIZE];
/**
* @brief Starting point function
*
*/
void app_main(void) {
printf("Echo UART\n");
/* Configure parameters of the UART driver,
* communication pins and install the driver.
*
* Configuration: 115000 BAUDS, 8 BITS, No Parity, 1 STOP BIT, No Flow Control, APB CLK
*/
uart_config_t uart_config = {
.baud_rate = UART_BAUD_RATE,
.data_bits = 0x3,
.parity = 0x0,
.stop_bits = 0x1,
.flow_ctrl = 0x0,
.source_clk = 0x0,
};
ESP_ERROR_CHECK(uart_driver_install(UART_PORT_NUM, BUF_SIZE * 2, 0, 0, NULL, 0));
ESP_ERROR_CHECK(uart_param_config(UART_PORT_NUM, &uart_config));
ESP_ERROR_CHECK(uart_set_pin(UART_PORT_NUM, TXD_PIN, RXD_PIN, RTS_PIN, CTS_PIN));
char text[100];
for (int iter=0; iter<10; iter++) {
sprintf(text, "(iter = %d) => HELLO, I'M TESTING UART !\r\n", iter);
// Write data back to the UART
int length = uart_write_bytes(UART_PORT_NUM, (const char *) text, strlen(text));
if (length == -1)
ESP_LOGE(TAG, "Error when writing in UART.");
vTaskDelay(pdMS_TO_TICKS(1000));
// Read data from the UART
length = uart_read_bytes(UART_PORT_NUM, data, BUF_SIZE, 20 / portTICK_RATE_MS);
if (length != 0)
printf("Read data: %s\n", data);
}
vTaskDelete(NULL);
}

View File

@ -0,0 +1,294 @@
# Visual Studio Code Template for ESP32
## Prerequisites
We consider that the Espressif IoT Development Framework (ESP-IDF), version 4.4.1, and Visual Studio Code environment is installed on the computer.
For more details, see:
- https://docs.espressif.com/projects/esp-idf/en/v4.4.1/esp32/get-started/index.html#installation-step-by-step
- https://code.visualstudio.com/
As of VS-code v1.56.1 integrated terminals require additional configuration to work correctly. see https://code.visualstudio.com/docs/getstarted/settings#_settings-file-locations to edit the `setting.json` file and add the following entry:
```bash
"terminal.integrated.allowWorkspaceConfiguration":true
```
In Linux (from Ubuntu 20.x), on connecting an ESP32 board with a CP210x USB to serial converter, there is a problem of connection. Add the following entries below that disable both parts of the brltty service and allowed the ESP32 development boards to properly connect.
```bash
sudo systemctl stop brltty-udev.service
sudo systemctl mask brltty-udev.service
sudo systemctl stop brltty.service
sudo systemctl disable brltty.service
```
Another solution is to uninstall brltty as below:
```bash
sudo apt remove brltty
```
## Getting Started
Firstly, you have to clone the `esp32-vscode-project-template` project and follow the next steps.
```bash
git clone https://github.com/fmuller-pns/esp32-vscode-project-template.git
```
#### 1. Rename the `vscode_project_template` folder
```bash
mv esp32-vscode-project-template <my_project_name>
```
#### 2. Go to the project directory
```bash
cd <my_project_name>
```
#### 3. Remove the GIT directory
```bash
rm -fR .git
```
#### 4. Open visual studio code for the new project
```bash
code .
```
#### 5. Verify paths in the `c_cpp_properties.json` file and change them if wrong.
```json
"IDF_TOOLS": "~/.espressif/tools",
"IDF_PATH": "~/esp/esp-idf"
```
#### 6. [Not required] Change the default project name called `main` in files.
This step renames the executable file. By default, the executable file is `main.elf`.
1. Open `CMakeLists.txt` and replace `main` by <my_project_name>
2. Open `Makefile` and replace `main` by <my_project_name>
3. Open `.vscode/launch.json` and replace `main` by <my_project_name> (lines 11 and 19)
#### 7. Open a terminal from Visual Studio Code to perform commands
Choose an external or internal terminal.
##### Open integrated terminal from Visual Studio Code
* using keyboard shortcut: `Ctrl+Shift+`<sup>2</sup>
* or pressing `F1` key and typing `integrated`
##### Open external terminal from Visual Studio Code
* using keyboard shortcut: `Ctrl+Shift+C`
* or pressing `F1` key and typing `external`
#### 8. Identify the USB serial port (usually `/dev/ttyUSB0`)
```bash
ls /dev/ttyUSB*
```
<span style="color:yellow">/dev/ttyUSB0</span>
#### 9. Building, flashing and running project
The serial port is `/dev/ttyUSB0` identified above.
```bash
idf.py -p /dev/ttyUSB0 flash monitor
```
##### Push the button on the ESP32 board when connecting
```bash
Serial port /dev/ttyUSB0
Connecting........_____....._
Detecting chip type... ESP32
Chip is ESP32-PICO-D4 (revision 1)
```
##### Flashing and monitoring
The message "`Hello ESP32 !`" appears.
```bash
...
W (290) spi_flash: Detected size(4096k) larger than the size in the binary image header(2048k). Using the size in the binary image header.
I (300) cpu_start: Starting scheduler on PRO CPU.
I (0) cpu_start: Starting scheduler on APP CPU.
Hello ESP32 !
```
To exit monitoring, typing `Ctrl+AltGr+]`
## Useful Commands
#### Open external terminal from vscode to perform commands
* using keyboard shortcut: `Ctrl+Shift+C`
* or pressing `F1` key and typing `external`
#### Open integrated terminal from vscode to perform commands
* using keyboard shortcut: `Ctrl+Shift+`<sup>2</sup>
* or pressing `F1` key and typing `integrated`
#### Clean project
```bash
idf.py fullclean
```
#### Configuration of the ESP32 board (only in external terminal)
```bash
idf.py menuconfig
```
#### Compile and build the executable file (`.elf` extension)
```bash
idf.py build
```
#### Identify the USB serial port (usually `/dev/ttyUSB0`)
```bash
ls /dev/ttyUSB*
```
#### Compile, build, flash
```bash
idf.py -p /dev/ttyUSB0 flash
```
#### Compile, build, flash and monitor
```bash
idf.py -p /dev/ttyUSB0 flash monitor
```
To exit monitoring, typing `Ctrl+AltGr+]`
## Using Tasks for ESP32 to run, debug Project and so on
1. In the menu, select `Run Task...`
2. Select the task you want to launch:
- `ESP32 - Build only`: just build the project
- `ESP32 - Flash and Monitor`: build (when modifications of code), flash and monitor
- `ESP32 - Clean Project`: Clean project (Full clean)
- `ESP32 - OpenOCD with FT2232`: Run in dedicated terminal the openOCD command to debug the project
- `ESP32 - Doxygen - HTML doc.`: Generate HTML documentation with Doxygen
## Configure GIT for your new project
#### Go to your new project folder
```bash
cd <project_name>
```
#### Configure name and email address
```bash
git config --global user.name "your name"
git config --global user.email "your email address"
```
#### Avoid typing your username and personal access token in vscode each time
This is useful when connecting your GIT to GitHub.
```bash
git config credential.helper store
```
## Using GITHUB with visual studio code
We consider you have followed the sections above:
* Getting Started
* Configure GIT for your new project
Now, how to communicate with GitHub ?
1. Open visual studio code.
2. Click on the `Source Control` icon on your left side or use `Ctrl+Shift+G` shortcut.
3. For the first time, click on `Initialize Repository` button
4. Enter a message for your first commit (ex: first commit) and click on Commit icon
5. Press `F1` and typing `git add remote` and entering :
* *remote name* : your github repository previously created
* *remote url* : https://github.com/xxx/your_project.git
* *username* and *password*
6. Push to the GitHub server (master branch)
See https://code.visualstudio.com/docs/editor/versioncontrol for more details.
## Debugging with JTAG FT2232
You must install FTDI FT2232 driver.
### Quick Driver installation for Linux:
1. Install USB Driver
```bash
sudo apt-get install libusb-1.0
$ lsusb
Bus 001 Device 002: ID 0403:6010 Future Technology Devices International, Ltd FT2232C Dual USB-UART/FIFO IC
```
2. Install OpenOCD rules. The path for rule copy can be different and depend on your ESP-IDF installation.
```bash
$ sudo usermod -a -G dialout $USER
$ sudo usermod -a -G plugdev $USER
$ sudo cp ~/.espressif/tools/openocd-esp32/v0.10.0-esp32-20210401/openocd-esp32/share/openocd/contrib/60-openocd.rules /etc/udev/rules.d/
$ sudo reboot
```
### Step 1: From external terminals
1. Connect the ESP32 board (USB)
2. Open an external terminal for building, flashing and running project
The serial port is `/dev/ttyUSB0` identified above.
```bash
idf.py -p /dev/ttyUSB0 flash monitor
```
3. Connect the JTAG FT2232 (USB)
4. Open another external terminal for running `openocd` with configuration file (`ftdi_ft2232.cfg`) located in the project root.
```bash
openocd -f ftdi_ft2232.cfg
```
5. Result on openocd terminal
```bash
Open On-Chip Debugger v0.10.0-esp32-20190313 (2019-03-13-09:52)
Licensed under GNU GPL v2
adapter speed: 20000 kHz
Info : Configured 2 cores
esp32 interrupt mask on
Info : Listening on port 6666 for tcl connections
Info : Listening on port 4444 for telnet connections
Info : ftdi: if you experience problems at higher adapter clocks, try the command "ftdi_tdo_sample_edge falling"
Info : clock speed 20000 kHz
Info : JTAG tap: esp32.cpu0 tap/device found: 0x120034e5 (mfg: 0x272 (Tensilica), part: 0x2003, ver: 0x1)
Info : JTAG tap: esp32.cpu1 tap/device found: 0x120034e5 (mfg: 0x272 (Tensilica), part: 0x2003, ver: 0x1)
Info : esp32: Debug controller 0 was reset (pwrstat=0x5F, after clear 0x0F).
Info : esp32: Core 0 was reset (pwrstat=0x5F, after clear 0x0F).
Info : esp32: Debug controller 1 was reset (pwrstat=0x5F, after clear 0x0F).
Info : esp32: Core 1 was reset (pwrstat=0x5F, after clear 0x0F).
Info : Detected debug stubs @ 3ffb2950 on core0 of target 'esp32'
Info : Listening on port 3333 for gdb connections
```
### Step 2: From Visual Studio Code
1. Click on the left on the line you want to set a breakpoint. A red bullet appears.
2. Click on debug Icon
3. Click on RUN `ESP32 OpenOCD`. If an error arises, click again.
4. The program stops at the breakpoint and you can see variables and more
### Step 3: When you modify the code
Do not touch the terminal with `openocd` command.
1. Stop the program into the terminal, typing `Ctrl+AltGr+]`
2. Build, flash and run program
The serial port is `/dev/ttyUSB0` identified above.
```bash
idf.py -p /dev/ttyUSB0 flash monitor
```
3. Click on RUN `ESP32 OpenOCD`. If an error arises, click again.
4. The program stops at the breakpoint and you can see variables and more
## Generate Doxygen documentation
You can use [Using Tasks for ESP32](#using-tasks-for-esp32-to-run-debug-project-and-so-on) or follow the steps below.
1. Open external terminal from vscode, using keyboard shortcut: `Ctrl+Shift+C`, or pressing `F1` key and typing `external`
2. Generate HTML documentation in `html_doc` folder
* From the User interface (allow you updating the `Doxyfile` configuration file)
```bash
doxywizard
```
* Directly from `Doxyfile` configuration file
```bash
doxygen
```
3. A new `html` folder is created, the entry file is `index.html`

View File

@ -0,0 +1,3 @@
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
CONFIG_ESPTOOLPY_FLASHSIZE="4MB"

View File

@ -0,0 +1,10 @@
# Configuration files
sdkconfig
sdkconfig.old
# Production folder
build/
# HTML documentation
html_doc/

View File

@ -0,0 +1,6 @@
# The following lines of boilerplate have to be in your project's
# CMakeLists in this exact order for cmake to work correctly
cmake_minimum_required(VERSION 3.5)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(main)

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,3 @@
PROJECT_NAME := main
include $(IDF_PATH)/make/project.mk

View File

@ -0,0 +1,22 @@
interface ftdi
ftdi_vid_pid 0x0403 0x6010
ftdi_layout_init 0x0038 0x003b
# The ESP32 only supports JTAG.
transport select jtag
# This can go as high as 20MHz if CPU frequency is 80MHz, or 26MHz
# if CPU frequency is 160MHz or 240MHz.
adapter_khz 20000
# If single core debugging is required, uncomment the following line
#set ESP32_ONLYCPU 1
# To disable RTOS support, uncomment the following line
# set ESP32_RTOS none
# This option defaults to 3.3v
set ESP32_FLASH_VOLTAGE 3.3
# Source the ESP32 configuration file
source [find target/esp32.cfg]

View File

@ -0,0 +1,3 @@
idf_component_register(
SRC_DIRS "."
INCLUDE_DIRS ".")

View File

@ -0,0 +1,2 @@
COMPONENT_SRCDIRS := .
COMPONENT_ADD_INCLUDEDIRS := .

View File

@ -0,0 +1,297 @@
/****************************************************************************
* Copyright (C) 2021 by Fabrice Muller *
* *
* This file is useful for ESP32 Design course. *
* *
****************************************************************************/
/**
* @file main.c
* @author Fabrice Muller
* @date 08 Nov. 2021
* @brief File containing the lab4 of Part 4.
*
* @see https://github.com/fmuller-pns/esp32-vscode-project-template
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "esp_log.h"
#include "esp_intr_alloc.h"
#include "freertos/FreeRTOSConfig.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "my_helper_fct.h"
#include "driver/uart.h"
#include "driver/gpio.h"
#include "driver/adc.h"
#include "driver/adc_common.h"
#include "esp_adc_cal.h"
#include "driver/ledc.h"
#include "soc/ledc_reg.h"
static const char *TAG = "MAIN";
/******************** ADC Declaration **********************/
// Vref in mV
#define DEFAULT_VREF 1100
const adc_unit_t unit = ADC_UNIT_1;
const adc_channel_t channel = ADC_CHANNEL_1;
const adc_bits_width_t width = ADC_WIDTH_BIT_10;
const adc_atten_t atten = ADC_ATTEN_DB_11;
/******************** UART Declaration **********************/
// GPIO18 / IO18
#define TXD_PIN 18
// GPIO23 / IO23
#define RXD_PIN 23
// Not Connected
#define RTS_PIN (UART_PIN_NO_CHANGE)
// Not Connected
#define CTS_PIN (UART_PIN_NO_CHANGE)
#define UART_PORT_NUM 2
#define UART_BAUD_RATE 115200
QueueHandle_t uart_queue;
#define BUF_SIZE (1024)
static char data[BUF_SIZE];
/******************** Task Declaration **********************/
/* The tasks */
void vUpdateLedTask(void *pvParameters);
void vScanTask(void *pvParameters);
/* LED constants */
static const char * WHITE_LED_CMD = "WHITE";
static const char * BLUE_LED_CMD = "BLUE";
/**
* @brief Starting point function
*
*/
void app_main(void) {
printf("Application - Photoresistance - IHM Node-RED\n");
/* Configure parameters of the UART driver,
* communication pins and install the driver.
*
* Configuration: 115000 BAUDS, 8 BITS, No Parity, 1 STOP BIT, No Flow Control, APB CLK
*/
uart_config_t uart_config = {
.baud_rate = UART_BAUD_RATE,
.data_bits = 0x3,
.parity = 0x0,
.stop_bits = 0x1,
.flow_ctrl = 0x0,
.source_clk = 0x0,
};
ESP_ERROR_CHECK(uart_driver_install(UART_PORT_NUM, BUF_SIZE * 2, BUF_SIZE * 2, 20, &uart_queue, 0));
ESP_ERROR_CHECK(uart_param_config(UART_PORT_NUM, &uart_config));
ESP_ERROR_CHECK(uart_set_pin(UART_PORT_NUM, TXD_PIN, RXD_PIN, RTS_PIN, CTS_PIN));
/* Configure ADC : ADC1, Channel 1, 10 bits, Attenuation 11dB */
/* Configure ADC */
adc1_config_width(width);
adc1_config_channel_atten(channel, atten);
/*
* LEDC Timer configuration
* Timer 0, Low speed mode, Auto clk, Résolution 10bits, Frequency 5 KHz
*/
ledc_timer_config_t timer = {
.speed_mode = LEDC_LOW_SPEED_MODE,
.duty_resolution = LEDC_TIMER_10_BIT,
.timer_num = LEDC_TIMER_0,
.freq_hz = 5000,
.clk_cfg = LEDC_AUTO_CLK};
ledc_timer_config(&timer);
/*
* Channel 0 configuration
* Timer 0, Channel 0, GPIO21 pin, Low speed mode
*/
ledc_channel_config_t channel_0 = {
.gpio_num = 21,
.speed_mode = LEDC_LOW_SPEED_MODE,
.channel = LEDC_CHANNEL_0,
.timer_sel = LEDC_TIMER_0,
.duty = 0,
.hpoint = 0
};
ledc_channel_config(&channel_0);
/*
* Channel 1 configuration
* Timer 0, Channel 1, GPIO22 pin, Low speed mode
*/
ledc_channel_config_t channel_1 = {
.gpio_num = 22,
.speed_mode = LEDC_LOW_SPEED_MODE,
.channel = LEDC_CHANNEL_1,
.timer_sel = LEDC_TIMER_0,
.duty = 0,
.hpoint = 0};
ledc_channel_config(&channel_1);
esp_err_t result = ledc_fade_func_install(0); // 0 : no interrupt
if (result != ESP_OK) {
printf("Error installing fade: %04x\n", result);
return;
}
/* Create Tasks */
xTaskCreatePinnedToCore(vUpdateLedTask, "UpdateTask", 4096, NULL, 2, NULL,CORE_1);
xTaskCreatePinnedToCore(vScanTask, "UpdateTask", 4096, NULL, 2, NULL,CORE_0);
/* Delete Main task */
vTaskDelete(NULL);
}
void vScanTask(void *pvParameters){
esp_adc_cal_characteristics_t *adc_chars;
adc_chars = calloc(1, sizeof(esp_adc_cal_characteristics_t));
esp_adc_cal_value_t val_type = esp_adc_cal_characterize(unit, atten, width, DEFAULT_VREF, adc_chars);
uint16_t measuredValues;
int v;
for (;;) {
/* Perform measure */
v = adc1_get_raw(channel);
measuredValues = esp_adc_cal_raw_to_voltage(v, adc_chars);
/* Print time conversion and voltage */
printf("V = %d mV\n", measuredValues);
// Send message
char text[100];
sprintf(text, "%d\r\n", measuredValues);
// Write data back to the UART
int length = uart_write_bytes(UART_PORT_NUM, (const char *) text, strlen(text));
if (length == -1)
ESP_LOGE(TAG, "Error when writing in UART.");
/* Every second */
vTaskDelay(pdMS_TO_TICKS(1000));
}
}
void vUpdateLedTask(void *pvParameters) {
uart_event_t event;
for (;;) {
/* Wait for message with infinite timeout */
if(xQueueReceive(uart_queue, (void * )&event, (portTickType)portMAX_DELAY)) {
switch(event.type) {
// Event of received data
case UART_DATA:
uart_read_bytes(UART_PORT_NUM, data, event.size, portMAX_DELAY);
DISPLAY("[UART DATA]: %.*s", event.size, data);
data[event.size] = 0; // Be sure the last character in NULL (end of string)
int cmp_length;
char *ptr;
/* Extract Value */
char *str_value = strrchr(data, ':');
if (str_value != NULL)
cmp_length = event.size - strlen(str_value);
else {
DISPLAYE(TAG, "[UART DATA]: Format Error");
continue;
}
uint32_t value = strtoul((str_value+1), &ptr, 10);
/* duty cycle according to the color LED */
if (strncmp(WHITE_LED_CMD, data, cmp_length) == 0) {
}
else if (strncmp(BLUE_LED_CMD, data, cmp_length) == 0) {
}
break;
// Event of HW FIFO overflow detected
case UART_FIFO_OVF:
DISPLAYE(TAG, "hw fifo overflow");
uart_flush_input(UART_PORT_NUM);
xQueueReset(uart_queue);
break;
// Event of UART ring buffer full
case UART_BUFFER_FULL:
ESP_LOGI(TAG, "ring buffer full");
uart_flush_input(UART_PORT_NUM);
xQueueReset(uart_queue);
break;
//Event of UART RX break detected
case UART_BREAK:
DISPLAYE(TAG, "uart rx break");
break;
//Event of UART parity check error
case UART_PARITY_ERR:
DISPLAYE(TAG, "uart parity error");
break;
//Event of UART frame error
case UART_FRAME_ERR:
DISPLAYE(TAG, "uart frame error");
break;
//UART_PATTERN_DET
case UART_PATTERN_DET:
DISPLAYW(TAG, "uart pattern detected");
break;
//Others
default:
DISPLAYW(TAG, "uart event type: %d", event.type);
break;
}
}
}
vTaskDelete(NULL);
}

View File

@ -0,0 +1,47 @@
#ifndef _MY_HELPER_FCT_
#define _MY_HELPER_FCT_
#include <unistd.h>
#include "esp_log.h"
/* Core constants fot xTaskCreatePinnedToCore() function */
const uint32_t CORE_0 = 0;
const uint32_t CORE_1 = 1;
const uint32_t PRO_CPU = 0;
const uint32_t APP_CPU = 1;
/**
* @brief Macro to display the buffer with arguments. msg is a formatted string as printf() function.
*
*/
#define DISPLAY(msg, ...) printf("%d:%d>\t"msg"\r\n", xTaskGetTickCount(), xPortGetCoreID(), ##__VA_ARGS__);
/**
* @brief Macro to display error/warning/info for the buffer with arguments. msg is a formatted string as printf() function.
*
*/
#define DISPLAYE(tag, msg, ...) ESP_LOGE(tag, "%d:%d>\t"msg"", xTaskGetTickCount(), xPortGetCoreID(), ##__VA_ARGS__);
#define DISPLAYW(tag, msg, ...) ESP_LOGW(tag, "%d:%d>\t"msg"", xTaskGetTickCount(), xPortGetCoreID(), ##__VA_ARGS__);
#define DISPLAYI(tag, msg, ...) ESP_LOGI(tag, "%d:%d>\t"msg"", xTaskGetTickCount(), xPortGetCoreID(), ##__VA_ARGS__);
/**
* @brief Macro to display the buffer without argument
*
*/
#define DISPLAYB(msg) printf("%d:%d>\t", xTaskGetTickCount(), xPortGetCoreID());\
printf(msg);\
printf("\r\n");
/* Consume CPU cycles. Time parameter is for the default frequency: 160MHz (ESP32_DEFAULT_CPU_FREQ_MHZ=160) */
#define COMPUTE_IN_TIME_US(time_us) {register uint32_t i=(uint32_t)time_us*5.02*100/22; while (i-- > 0) {asm(" nop");}}
#define COMPUTE_IN_TIME_MS(time_ms) {register uint32_t i=(uint32_t)time_ms*1000*5.02*100/22; while (i-- > 0) {asm(" nop");}}
#define COMPUTE_IN_TICK(tick) {register uint32_t i=(uint32_t)(tick*1000/configTICK_RATE_HZ)*1000*5.02*100/22; while (i-- > 0) {asm(" nop");}}
#endif

View File

@ -0,0 +1,294 @@
# Visual Studio Code Template for ESP32
## Prerequisites
We consider that the Espressif IoT Development Framework (ESP-IDF), version 4.4.1, and Visual Studio Code environment is installed on the computer.
For more details, see:
- https://docs.espressif.com/projects/esp-idf/en/v4.4.1/esp32/get-started/index.html#installation-step-by-step
- https://code.visualstudio.com/
As of VS-code v1.56.1 integrated terminals require additional configuration to work correctly. see https://code.visualstudio.com/docs/getstarted/settings#_settings-file-locations to edit the `setting.json` file and add the following entry:
```bash
"terminal.integrated.allowWorkspaceConfiguration":true
```
In Linux (from Ubuntu 20.x), on connecting an ESP32 board with a CP210x USB to serial converter, there is a problem of connection. Add the following entries below that disable both parts of the brltty service and allowed the ESP32 development boards to properly connect.
```bash
sudo systemctl stop brltty-udev.service
sudo systemctl mask brltty-udev.service
sudo systemctl stop brltty.service
sudo systemctl disable brltty.service
```
Another solution is to uninstall brltty as below:
```bash
sudo apt remove brltty
```
## Getting Started
Firstly, you have to clone the `esp32-vscode-project-template` project and follow the next steps.
```bash
git clone https://github.com/fmuller-pns/esp32-vscode-project-template.git
```
#### 1. Rename the `vscode_project_template` folder
```bash
mv esp32-vscode-project-template <my_project_name>
```
#### 2. Go to the project directory
```bash
cd <my_project_name>
```
#### 3. Remove the GIT directory
```bash
rm -fR .git
```
#### 4. Open visual studio code for the new project
```bash
code .
```
#### 5. Verify paths in the `c_cpp_properties.json` file and change them if wrong.
```json
"IDF_TOOLS": "~/.espressif/tools",
"IDF_PATH": "~/esp/esp-idf"
```
#### 6. [Not required] Change the default project name called `main` in files.
This step renames the executable file. By default, the executable file is `main.elf`.
1. Open `CMakeLists.txt` and replace `main` by <my_project_name>
2. Open `Makefile` and replace `main` by <my_project_name>
3. Open `.vscode/launch.json` and replace `main` by <my_project_name> (lines 11 and 19)
#### 7. Open a terminal from Visual Studio Code to perform commands
Choose an external or internal terminal.
##### Open integrated terminal from Visual Studio Code
* using keyboard shortcut: `Ctrl+Shift+`<sup>2</sup>
* or pressing `F1` key and typing `integrated`
##### Open external terminal from Visual Studio Code
* using keyboard shortcut: `Ctrl+Shift+C`
* or pressing `F1` key and typing `external`
#### 8. Identify the USB serial port (usually `/dev/ttyUSB0`)
```bash
ls /dev/ttyUSB*
```
<span style="color:yellow">/dev/ttyUSB0</span>
#### 9. Building, flashing and running project
The serial port is `/dev/ttyUSB0` identified above.
```bash
idf.py -p /dev/ttyUSB0 flash monitor
```
##### Push the button on the ESP32 board when connecting
```bash
Serial port /dev/ttyUSB0
Connecting........_____....._
Detecting chip type... ESP32
Chip is ESP32-PICO-D4 (revision 1)
```
##### Flashing and monitoring
The message "`Hello ESP32 !`" appears.
```bash
...
W (290) spi_flash: Detected size(4096k) larger than the size in the binary image header(2048k). Using the size in the binary image header.
I (300) cpu_start: Starting scheduler on PRO CPU.
I (0) cpu_start: Starting scheduler on APP CPU.
Hello ESP32 !
```
To exit monitoring, typing `Ctrl+AltGr+]`
## Useful Commands
#### Open external terminal from vscode to perform commands
* using keyboard shortcut: `Ctrl+Shift+C`
* or pressing `F1` key and typing `external`
#### Open integrated terminal from vscode to perform commands
* using keyboard shortcut: `Ctrl+Shift+`<sup>2</sup>
* or pressing `F1` key and typing `integrated`
#### Clean project
```bash
idf.py fullclean
```
#### Configuration of the ESP32 board (only in external terminal)
```bash
idf.py menuconfig
```
#### Compile and build the executable file (`.elf` extension)
```bash
idf.py build
```
#### Identify the USB serial port (usually `/dev/ttyUSB0`)
```bash
ls /dev/ttyUSB*
```
#### Compile, build, flash
```bash
idf.py -p /dev/ttyUSB0 flash
```
#### Compile, build, flash and monitor
```bash
idf.py -p /dev/ttyUSB0 flash monitor
```
To exit monitoring, typing `Ctrl+AltGr+]`
## Using Tasks for ESP32 to run, debug Project and so on
1. In the menu, select `Run Task...`
2. Select the task you want to launch:
- `ESP32 - Build only`: just build the project
- `ESP32 - Flash and Monitor`: build (when modifications of code), flash and monitor
- `ESP32 - Clean Project`: Clean project (Full clean)
- `ESP32 - OpenOCD with FT2232`: Run in dedicated terminal the openOCD command to debug the project
- `ESP32 - Doxygen - HTML doc.`: Generate HTML documentation with Doxygen
## Configure GIT for your new project
#### Go to your new project folder
```bash
cd <project_name>
```
#### Configure name and email address
```bash
git config --global user.name "your name"
git config --global user.email "your email address"
```
#### Avoid typing your username and personal access token in vscode each time
This is useful when connecting your GIT to GitHub.
```bash
git config credential.helper store
```
## Using GITHUB with visual studio code
We consider you have followed the sections above:
* Getting Started
* Configure GIT for your new project
Now, how to communicate with GitHub ?
1. Open visual studio code.
2. Click on the `Source Control` icon on your left side or use `Ctrl+Shift+G` shortcut.
3. For the first time, click on `Initialize Repository` button
4. Enter a message for your first commit (ex: first commit) and click on Commit icon
5. Press `F1` and typing `git add remote` and entering :
* *remote name* : your github repository previously created
* *remote url* : https://github.com/xxx/your_project.git
* *username* and *password*
6. Push to the GitHub server (master branch)
See https://code.visualstudio.com/docs/editor/versioncontrol for more details.
## Debugging with JTAG FT2232
You must install FTDI FT2232 driver.
### Quick Driver installation for Linux:
1. Install USB Driver
```bash
sudo apt-get install libusb-1.0
$ lsusb
Bus 001 Device 002: ID 0403:6010 Future Technology Devices International, Ltd FT2232C Dual USB-UART/FIFO IC
```
2. Install OpenOCD rules. The path for rule copy can be different and depend on your ESP-IDF installation.
```bash
$ sudo usermod -a -G dialout $USER
$ sudo usermod -a -G plugdev $USER
$ sudo cp ~/.espressif/tools/openocd-esp32/v0.10.0-esp32-20210401/openocd-esp32/share/openocd/contrib/60-openocd.rules /etc/udev/rules.d/
$ sudo reboot
```
### Step 1: From external terminals
1. Connect the ESP32 board (USB)
2. Open an external terminal for building, flashing and running project
The serial port is `/dev/ttyUSB0` identified above.
```bash
idf.py -p /dev/ttyUSB0 flash monitor
```
3. Connect the JTAG FT2232 (USB)
4. Open another external terminal for running `openocd` with configuration file (`ftdi_ft2232.cfg`) located in the project root.
```bash
openocd -f ftdi_ft2232.cfg
```
5. Result on openocd terminal
```bash
Open On-Chip Debugger v0.10.0-esp32-20190313 (2019-03-13-09:52)
Licensed under GNU GPL v2
adapter speed: 20000 kHz
Info : Configured 2 cores
esp32 interrupt mask on
Info : Listening on port 6666 for tcl connections
Info : Listening on port 4444 for telnet connections
Info : ftdi: if you experience problems at higher adapter clocks, try the command "ftdi_tdo_sample_edge falling"
Info : clock speed 20000 kHz
Info : JTAG tap: esp32.cpu0 tap/device found: 0x120034e5 (mfg: 0x272 (Tensilica), part: 0x2003, ver: 0x1)
Info : JTAG tap: esp32.cpu1 tap/device found: 0x120034e5 (mfg: 0x272 (Tensilica), part: 0x2003, ver: 0x1)
Info : esp32: Debug controller 0 was reset (pwrstat=0x5F, after clear 0x0F).
Info : esp32: Core 0 was reset (pwrstat=0x5F, after clear 0x0F).
Info : esp32: Debug controller 1 was reset (pwrstat=0x5F, after clear 0x0F).
Info : esp32: Core 1 was reset (pwrstat=0x5F, after clear 0x0F).
Info : Detected debug stubs @ 3ffb2950 on core0 of target 'esp32'
Info : Listening on port 3333 for gdb connections
```
### Step 2: From Visual Studio Code
1. Click on the left on the line you want to set a breakpoint. A red bullet appears.
2. Click on debug Icon
3. Click on RUN `ESP32 OpenOCD`. If an error arises, click again.
4. The program stops at the breakpoint and you can see variables and more
### Step 3: When you modify the code
Do not touch the terminal with `openocd` command.
1. Stop the program into the terminal, typing `Ctrl+AltGr+]`
2. Build, flash and run program
The serial port is `/dev/ttyUSB0` identified above.
```bash
idf.py -p /dev/ttyUSB0 flash monitor
```
3. Click on RUN `ESP32 OpenOCD`. If an error arises, click again.
4. The program stops at the breakpoint and you can see variables and more
## Generate Doxygen documentation
You can use [Using Tasks for ESP32](#using-tasks-for-esp32-to-run-debug-project-and-so-on) or follow the steps below.
1. Open external terminal from vscode, using keyboard shortcut: `Ctrl+Shift+C`, or pressing `F1` key and typing `external`
2. Generate HTML documentation in `html_doc` folder
* From the User interface (allow you updating the `Doxyfile` configuration file)
```bash
doxywizard
```
* Directly from `Doxyfile` configuration file
```bash
doxygen
```
3. A new `html` folder is created, the entry file is `index.html`

View File

@ -0,0 +1,3 @@
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
CONFIG_ESPTOOLPY_FLASHSIZE="4MB"