Add support for IDF v5.0

Resolves #979
This commit is contained in:
Valerii Koval
2023-01-04 20:05:31 +02:00
parent 8b5e233994
commit ecc617e341
36 changed files with 529 additions and 336 deletions
+39 -5
View File
@@ -576,6 +576,15 @@ def generate_project_ld_script(sdk_config, ignore_targets=None):
) )
# A temporary workaround to avoid modifying CMake mainly for the "heap" library.
# The "tlsf.c" source file in this library has an include flag relative
# to CMAKE_CURRENT_SOURCE_DIR which breaks PlatformIO builds that have a
# different working directory
def _fix_component_relative_include(config, build_flags, source_index):
source_file_path = config["sources"][source_index]["path"]
build_flags = build_flags.replace("..", os.path.dirname(source_file_path) + "/..")
return build_flags
def prepare_build_envs(config, default_env, debug_allowed=True): def prepare_build_envs(config, default_env, debug_allowed=True):
build_envs = [] build_envs = []
target_compile_groups = config.get("compileGroups") target_compile_groups = config.get("compileGroups")
@@ -597,6 +606,10 @@ def prepare_build_envs(config, default_env, debug_allowed=True):
for cc in compile_commands: for cc in compile_commands:
build_flags = cc.get("fragment") build_flags = cc.get("fragment")
if not build_flags.startswith("-D"): if not build_flags.startswith("-D"):
if build_flags.startswith("-include") and ".." in build_flags:
source_index = cg.get("sourceIndexes")[0]
build_flags = _fix_component_relative_include(
config, build_flags, source_index)
build_env.AppendUnique(**build_env.ParseFlags(build_flags)) build_env.AppendUnique(**build_env.ParseFlags(build_flags))
build_env.AppendUnique(CPPDEFINES=defines, CPPPATH=includes) build_env.AppendUnique(CPPDEFINES=defines, CPPPATH=includes)
if sys_includes: if sys_includes:
@@ -639,9 +652,17 @@ def compile_source_files(
else: else:
obj_path = os.path.join(obj_path, os.path.basename(src_path)) obj_path = os.path.join(obj_path, os.path.basename(src_path))
preserve_source_file_extension = board.get(
"build.esp-idf.preserve_source_file_extension", False
)
objects.append( objects.append(
build_envs[compile_group_idx].StaticObject( build_envs[compile_group_idx].StaticObject(
target=os.path.splitext(obj_path)[0] + ".o", target=(
obj_path
if preserve_source_file_extension
else os.path.splitext(obj_path)[0]
) + ".o",
source=os.path.realpath(src_path), source=os.path.realpath(src_path),
) )
) )
@@ -1029,7 +1050,14 @@ def install_python_deps():
result = {} result = {}
packages = {} packages = {}
pip_output = subprocess.check_output( pip_output = subprocess.check_output(
[env.subst("$PYTHONEXE"), "-m", "pip", "list", "--format=json"] [
env.subst("$PYTHONEXE"),
"-m",
"pip",
"list",
"--format=json",
"--disable-pip-version-check",
]
) )
try: try:
packages = json.loads(pip_output) packages = json.loads(pip_output)
@@ -1045,9 +1073,13 @@ def install_python_deps():
# https://github.com/platformio/platform-espressif32/issues/635 # https://github.com/platformio/platform-espressif32/issues/635
"cryptography": ">=2.1.4,<35.0.0", "cryptography": ">=2.1.4,<35.0.0",
"future": ">=0.15.2", "future": ">=0.15.2",
"pyparsing": ">=2.0.3,<2.4.0", "pyparsing": ">=3"
if platform.get_package_version("framework-espidf")
.split(".")[1]
.startswith("5")
else ">=2.0.3,<2.4.0",
"kconfiglib": "==13.7.1", "kconfiglib": "==13.7.1",
"idf-component-manager": "~=1.0" "idf-component-manager": "~=1.0",
} }
installed_packages = _get_installed_pip_packages() installed_packages = _get_installed_pip_packages()
@@ -1471,4 +1503,6 @@ env.Replace(
) )
# Propagate application offset to debug configurations # Propagate application offset to debug configurations
env["INTEGRATION_EXTRA_DATA"].update({"application_offset": env.subst("$ESP32_APP_OFFSET")}) env["INTEGRATION_EXTRA_DATA"].update(
{"application_offset": env.subst("$ESP32_APP_OFFSET")}
)
@@ -1,3 +1,4 @@
idf_component_register(SRCS "esp_eddystone_api.c" idf_component_register(SRCS "esp_eddystone_api.c"
"esp_eddystone_demo.c" "esp_eddystone_demo.c"
INCLUDE_DIRS "") INCLUDE_DIRS "")
target_compile_options(${COMPONENT_LIB} PRIVATE "-Wno-format")
@@ -1,10 +1,8 @@
/* /*
This example code is in the Public Domain (or CC0 licensed, at your option.) * SPDX-FileCopyrightText: 2021 Espressif Systems (Shanghai) CO LTD
*
Unless required by applicable law or agreed to in writing, this * SPDX-License-Identifier: Unlicense OR CC0-1.0
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR */
CONDITIONS OF ANY KIND, either express or implied.
*/
/**************************************************************************** /****************************************************************************
@@ -62,21 +60,21 @@ Byte offset Field Description
0 Frame Type Value = 0x00 0 Frame Type Value = 0x00
1 Ranging Data Calibrated Tx power at 0 m 1 Ranging Data Calibrated Tx power at 0 m
2 NID[0] 10-byte Namespace 2 NID[0] 10-byte Namespace
3 NID[1] 3 NID[1]
4 NID[2] 4 NID[2]
5 NID[3] 5 NID[3]
6 NID[4] 6 NID[4]
7 NID[5] 7 NID[5]
8 NID[6] 8 NID[6]
9 NID[7] 9 NID[7]
10 NID[8] 10 NID[8]
11 NID[9] 11 NID[9]
12 BID[0] 6-byte Instance 12 BID[0] 6-byte Instance
13 BID[1] 13 BID[1]
14 BID[2] 14 BID[2]
15 BID[3] 15 BID[3]
16 BID[4] 16 BID[4]
17 BID[5] 17 BID[5]
18 RFU Reserved for future use, must be0x00 18 RFU Reserved for future use, must be0x00
19 RFU Reserved for future use, must be0x00 19 RFU Reserved for future use, must be0x00
*********************************************/ *********************************************/
@@ -135,7 +133,7 @@ static esp_err_t esp_eddystone_url_received(const uint8_t* buf, uint8_t len, esp
//ERROR:too long url //ERROR:too long url
return -1; return -1;
} }
res->inform.url.tx_power = buf[pos++]; res->inform.url.tx_power = buf[pos++];
url_res = esp_eddystone_resolve_url_scheme(buf+pos, buf+len-1); url_res = esp_eddystone_resolve_url_scheme(buf+pos, buf+len-1);
memcpy(&res->inform.url.url, url_res, strlen(url_res)); memcpy(&res->inform.url.url, url_res, strlen(url_res));
res->inform.url.url[strlen(url_res)] = '\0'; res->inform.url.url[strlen(url_res)] = '\0';
@@ -148,17 +146,17 @@ Byte offset Field Description
0 Frame Type Value = 0x20 0 Frame Type Value = 0x20
1 Version TLM version, value = 0x00 1 Version TLM version, value = 0x00
2 VBATT[0] Battery voltage, 1 mV/bit 2 VBATT[0] Battery voltage, 1 mV/bit
3 VBATT[1] 3 VBATT[1]
4 TEMP[0] Beacon temperature 4 TEMP[0] Beacon temperature
5 TEMP[1] 5 TEMP[1]
6 ADV_CNT[0] Advertising PDU count 6 ADV_CNT[0] Advertising PDU count
7 ADV_CNT[1] 7 ADV_CNT[1]
8 ADV_CNT[2] 8 ADV_CNT[2]
9 ADV_CNT[3] 9 ADV_CNT[3]
10 SEC_CNT[0] Time since power-on or reboot 10 SEC_CNT[0] Time since power-on or reboot
11 SEC_CNT[1] 11 SEC_CNT[1]
12 SEC_CNT[2] 12 SEC_CNT[2]
13 SEC_CNT[3] 13 SEC_CNT[3]
************************************************/ ************************************************/
/* decode and store received TLM */ /* decode and store received TLM */
static esp_err_t esp_eddystone_tlm_received(const uint8_t* buf, uint8_t len, esp_eddystone_result_t* res) static esp_err_t esp_eddystone_tlm_received(const uint8_t* buf, uint8_t len, esp_eddystone_result_t* res)
@@ -211,14 +209,14 @@ esp_err_t esp_eddystone_decode(const uint8_t* buf, uint8_t len, esp_eddystone_re
return -1; return -1;
} }
uint8_t pos=0; uint8_t pos=0;
while(res->common.srv_data_type != EDDYSTONE_SERVICE_UUID) while(res->common.srv_data_type != EDDYSTONE_SERVICE_UUID)
{ {
pos++; pos++;
if(pos >= len ) { if(pos >= len ) {
return -1; return -1;
} }
uint8_t ad_type = buf[pos++]; uint8_t ad_type = buf[pos++];
switch(ad_type) switch(ad_type)
{ {
case ESP_BLE_AD_TYPE_FLAG: { case ESP_BLE_AD_TYPE_FLAG: {
res->common.flags = buf[pos++]; res->common.flags = buf[pos++];
@@ -227,7 +225,7 @@ esp_err_t esp_eddystone_decode(const uint8_t* buf, uint8_t len, esp_eddystone_re
case ESP_BLE_AD_TYPE_16SRV_CMPL: { case ESP_BLE_AD_TYPE_16SRV_CMPL: {
uint16_t uuid = little_endian_read_16(buf, pos); uint16_t uuid = little_endian_read_16(buf, pos);
if(uuid != EDDYSTONE_SERVICE_UUID) { if(uuid != EDDYSTONE_SERVICE_UUID) {
return -1; return -1;
} }
res->common.srv_uuid = uuid; res->common.srv_uuid = uuid;
pos += 2; pos += 2;
@@ -237,7 +235,7 @@ esp_err_t esp_eddystone_decode(const uint8_t* buf, uint8_t len, esp_eddystone_re
uint16_t type = little_endian_read_16(buf, pos); uint16_t type = little_endian_read_16(buf, pos);
pos += 2; pos += 2;
uint8_t frame_type = buf[pos++]; uint8_t frame_type = buf[pos++];
if(type != EDDYSTONE_SERVICE_UUID || !(frame_type == EDDYSTONE_FRAME_TYPE_UID || frame_type == EDDYSTONE_FRAME_TYPE_URL || if(type != EDDYSTONE_SERVICE_UUID || !(frame_type == EDDYSTONE_FRAME_TYPE_UID || frame_type == EDDYSTONE_FRAME_TYPE_URL ||
frame_type == EDDYSTONE_FRAME_TYPE_TLM)) { frame_type == EDDYSTONE_FRAME_TYPE_TLM)) {
return -1; return -1;
} }
@@ -251,4 +249,3 @@ esp_err_t esp_eddystone_decode(const uint8_t* buf, uint8_t len, esp_eddystone_re
} }
return esp_eddystone_get_inform(buf+pos, len-pos, res); return esp_eddystone_get_inform(buf+pos, len-pos, res);
} }
@@ -1,10 +1,8 @@
/* /*
This example code is in the Public Domain (or CC0 licensed, at your option.) * SPDX-FileCopyrightText: 2021 Espressif Systems (Shanghai) CO LTD
*
Unless required by applicable law or agreed to in writing, this * SPDX-License-Identifier: Unlicense OR CC0-1.0
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR */
CONDITIONS OF ANY KIND, either express or implied.
*/
#ifndef __ESP_EDDYSTONE_API_H__ #ifndef __ESP_EDDYSTONE_API_H__
@@ -57,8 +55,8 @@ static inline uint32_t big_endian_read_32(const uint8_t *buffer, uint8_t pos)
} }
/* /*
* The esp eddystone API. * The esp eddystone API.
* This function is called to decode eddystone information from adv_data. * This function is called to decode eddystone information from adv_data.
* The res points to the result struct. * The res points to the result struct.
* *
*/ */
@@ -67,4 +65,3 @@ esp_err_t esp_eddystone_decode(const uint8_t* buf, uint8_t len, esp_eddystone_re
//bool esp_eddystone_is_eddystone_packet(.....); //bool esp_eddystone_is_eddystone_packet(.....);
#endif /* __ESP_EDDYSTONE_API_H__ */ #endif /* __ESP_EDDYSTONE_API_H__ */
@@ -1,10 +1,8 @@
/* /*
This example code is in the Public Domain (or CC0 licensed, at your option.) * SPDX-FileCopyrightText: 2021 Espressif Systems (Shanghai) CO LTD
*
Unless required by applicable law or agreed to in writing, this * SPDX-License-Identifier: Unlicense OR CC0-1.0
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR */
CONDITIONS OF ANY KIND, either express or implied.
*/
/**************************************************************************** /****************************************************************************
@@ -110,7 +108,7 @@ static void esp_gap_cb(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t* par
// error:The received data is not an eddystone frame packet or a correct eddystone frame packet. // error:The received data is not an eddystone frame packet or a correct eddystone frame packet.
// just return // just return
return; return;
} else { } else {
// The received adv data is a correct eddystone frame packet. // The received adv data is a correct eddystone frame packet.
// Here, we get the eddystone infomation in eddystone_res, we can use the data in res to do other things. // Here, we get the eddystone infomation in eddystone_res, we can use the data in res to do other things.
// For example, just print them: // For example, just print them:
@@ -143,7 +141,7 @@ static void esp_gap_cb(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t* par
void esp_eddystone_appRegister(void) void esp_eddystone_appRegister(void)
{ {
esp_err_t status; esp_err_t status;
ESP_LOGI(DEMO_TAG,"Register callback"); ESP_LOGI(DEMO_TAG,"Register callback");
/*<! register the scan callback function to the gap module */ /*<! register the scan callback function to the gap module */
@@ -160,14 +158,14 @@ void esp_eddystone_init(void)
esp_eddystone_appRegister(); esp_eddystone_appRegister();
} }
void app_main() void app_main(void)
{ {
ESP_ERROR_CHECK(nvs_flash_init()); ESP_ERROR_CHECK(nvs_flash_init());
ESP_ERROR_CHECK(esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT)); ESP_ERROR_CHECK(esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT));
esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT(); esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
esp_bt_controller_init(&bt_cfg); esp_bt_controller_init(&bt_cfg);
esp_bt_controller_enable(ESP_BT_MODE_BLE); esp_bt_controller_enable(ESP_BT_MODE_BLE);
esp_eddystone_init(); esp_eddystone_init();
/*<! set scan parameters */ /*<! set scan parameters */
@@ -1,10 +1,8 @@
/* /*
This example code is in the Public Domain (or CC0 licensed, at your option.) * SPDX-FileCopyrightText: 2021 Espressif Systems (Shanghai) CO LTD
*
Unless required by applicable law or agreed to in writing, this * SPDX-License-Identifier: Unlicense OR CC0-1.0
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR */
CONDITIONS OF ANY KIND, either express or implied.
*/
#ifndef __ESP_EDDYSTONE_PROTOCOL_H__ #ifndef __ESP_EDDYSTONE_PROTOCOL_H__
#define __ESP_EDDYSTONE_PROTOCOL_H__ #define __ESP_EDDYSTONE_PROTOCOL_H__
@@ -32,7 +30,7 @@
#define EDDYSTONE_TLM_ADV_COUNT_LEN 4 #define EDDYSTONE_TLM_ADV_COUNT_LEN 4
#define EDDYSTONE_TLM_TIME_LEN 4 #define EDDYSTONE_TLM_TIME_LEN 4
#define EDDYSTONE_TLM_DATA_LEN (EDDYSTONE_TLM_VERSION_LEN + EDDYSTONE_TLM_BATTERY_VOLTAGE_LEN + \ #define EDDYSTONE_TLM_DATA_LEN (EDDYSTONE_TLM_VERSION_LEN + EDDYSTONE_TLM_BATTERY_VOLTAGE_LEN + \
EDDYSTONE_TLM_TEMPERATURE_LEN + EDDYSTONE_TLM_ADV_COUNT_LEN + EDDYSTONE_TLM_TIME_LEN) EDDYSTONE_TLM_TEMPERATURE_LEN + EDDYSTONE_TLM_ADV_COUNT_LEN + EDDYSTONE_TLM_TIME_LEN)
//URL //URL
#define EDDYSTONE_URL_SCHEME_LEN 1 #define EDDYSTONE_URL_SCHEME_LEN 1
#define EDDYSTONE_URL_ENCODED_MAX_LEN 17 #define EDDYSTONE_URL_ENCODED_MAX_LEN 17
@@ -49,8 +47,8 @@ typedef struct {
} __attribute__((packed))esp_eddystone_uid_t; } __attribute__((packed))esp_eddystone_uid_t;
/* Eddystone URL frame */ /* Eddystone URL frame */
typedef struct { typedef struct {
int8_t tx_power; /*<! calibrated Tx power at 0m */ int8_t tx_power; /*<! calibrated Tx power at 0m */
uint8_t url_scheme; /*<! encoded scheme prefix */ uint8_t url_scheme; /*<! encoded scheme prefix */
uint8_t encoded_url[0]; /*<! length 1-17 */ uint8_t encoded_url[0]; /*<! length 1-17 */
} __attribute__((packed))esp_eddystone_url_t; } __attribute__((packed))esp_eddystone_url_t;
@@ -98,9 +96,9 @@ typedef struct {
esp_eddystone_frame_t frame; esp_eddystone_frame_t frame;
} __attribute__((packed)) esp_eddystone_packet_t; } __attribute__((packed)) esp_eddystone_packet_t;
/* /*
* URLs are written only with the graphic printable characters of the US-ASCII coded character set. * URLs are written only with the graphic printable characters of the US-ASCII coded character set.
* The octets 00-20 and 7F-FF hexadecimal are not used. * The octets 00-20 and 7F-FF hexadecimal are not used.
* See “Excluded US-ASCII Characters” in RFC 2936. * See “Excluded US-ASCII Characters” in RFC 2936.
* *
*/ */
@@ -1,2 +1,3 @@
idf_component_register(SRCS "coap_server_example_main.c" idf_component_register(SRCS "coap_server_example_main.c"
INCLUDE_DIRS ".") INCLUDE_DIRS "."
EMBED_TXTFILES certs/coap_ca.pem certs/coap_server.crt certs/coap_server.key)
@@ -31,6 +31,10 @@
#include "coap3/coap.h" #include "coap3/coap.h"
#ifndef CONFIG_COAP_SERVER_SUPPORT
#error COAP_SERVER_SUPPORT needs to be enabled
#endif /* COAP_SERVER_SUPPORT */
/* The examples use simple Pre-Shared-Key configuration that you can set via /* The examples use simple Pre-Shared-Key configuration that you can set via
'idf.py menuconfig'. 'idf.py menuconfig'.
@@ -187,6 +191,7 @@ static void coap_example_server(void *p)
while (1) { while (1) {
coap_endpoint_t *ep = NULL; coap_endpoint_t *ep = NULL;
unsigned wait_ms; unsigned wait_ms;
int have_dtls = 0;
/* Prepare the CoAP server socket */ /* Prepare the CoAP server socket */
coap_address_init(&serv_addr); coap_address_init(&serv_addr);
@@ -258,16 +263,18 @@ static void coap_example_server(void *p)
ESP_LOGE(TAG, "udp: coap_new_endpoint() failed"); ESP_LOGE(TAG, "udp: coap_new_endpoint() failed");
goto clean_up; goto clean_up;
} }
ep = coap_new_endpoint(ctx, &serv_addr, COAP_PROTO_TCP); if (coap_tcp_is_supported()) {
if (!ep) { ep = coap_new_endpoint(ctx, &serv_addr, COAP_PROTO_TCP);
ESP_LOGE(TAG, "tcp: coap_new_endpoint() failed"); if (!ep) {
goto clean_up; ESP_LOGE(TAG, "tcp: coap_new_endpoint() failed");
goto clean_up;
}
} }
#if defined(CONFIG_COAP_MBEDTLS_PSK) || defined(CONFIG_COAP_MBEDTLS_PKI) #if defined(CONFIG_COAP_MBEDTLS_PSK) || defined(CONFIG_COAP_MBEDTLS_PKI)
if (coap_dtls_is_supported()) { if (coap_dtls_is_supported()) {
#ifndef CONFIG_MBEDTLS_TLS_SERVER #ifndef CONFIG_MBEDTLS_TLS_SERVER
/* This is not critical as unencrypted support is still available */ /* This is not critical as unencrypted support is still available */
ESP_LOGI(TAG, "MbedTLS (D)TLS Server Mode not configured"); ESP_LOGI(TAG, "MbedTLS DTLS Server Mode not configured");
#else /* CONFIG_MBEDTLS_TLS_SERVER */ #else /* CONFIG_MBEDTLS_TLS_SERVER */
serv_addr.addr.sin6.sin6_port = htons(COAPS_DEFAULT_PORT); serv_addr.addr.sin6.sin6_port = htons(COAPS_DEFAULT_PORT);
ep = coap_new_endpoint(ctx, &serv_addr, COAP_PROTO_DTLS); ep = coap_new_endpoint(ctx, &serv_addr, COAP_PROTO_DTLS);
@@ -275,8 +282,23 @@ static void coap_example_server(void *p)
ESP_LOGE(TAG, "dtls: coap_new_endpoint() failed"); ESP_LOGE(TAG, "dtls: coap_new_endpoint() failed");
goto clean_up; goto clean_up;
} }
have_dtls = 1;
#endif /* CONFIG_MBEDTLS_TLS_SERVER */ #endif /* CONFIG_MBEDTLS_TLS_SERVER */
} else { }
if (coap_tls_is_supported()) {
#ifndef CONFIG_MBEDTLS_TLS_SERVER
/* This is not critical as unencrypted support is still available */
ESP_LOGI(TAG, "MbedTLS TLS Server Mode not configured");
#else /* CONFIG_MBEDTLS_TLS_SERVER */
serv_addr.addr.sin6.sin6_port = htons(COAPS_DEFAULT_PORT);
ep = coap_new_endpoint(ctx, &serv_addr, COAP_PROTO_TLS);
if (!ep) {
ESP_LOGE(TAG, "tls: coap_new_endpoint() failed");
goto clean_up;
}
#endif /* CONFIG_MBEDTLS_TLS_SERVER */
}
if (!have_dtls) {
/* This is not critical as unencrypted support is still available */ /* This is not critical as unencrypted support is still available */
ESP_LOGI(TAG, "MbedTLS (D)TLS Server Mode not configured"); ESP_LOGI(TAG, "MbedTLS (D)TLS Server Mode not configured");
} }
@@ -1,2 +1,2 @@
idf_component_register(SRCS "exception_example_main.cpp" idf_component_register(SRCS "exception_example_main.cpp"
INCLUDE_DIRS ".") INCLUDE_DIRS ".")
@@ -1,2 +1,4 @@
idf_component_register(SRCS "hello_world_main.c" idf_component_register(SRCS "hello_world_main.c"
INCLUDE_DIRS "") INCLUDE_DIRS "")
target_compile_options(${COMPONENT_LIB} PRIVATE "-Wno-format")
@@ -1,34 +1,42 @@
/* Hello World Example /*
* SPDX-FileCopyrightText: 2010-2022 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: CC0-1.0
*/
This example code is in the Public Domain (or CC0 licensed, at your option.)
Unless required by applicable law or agreed to in writing, this
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied.
*/
#include <stdio.h> #include <stdio.h>
#include "sdkconfig.h"
#include "freertos/FreeRTOS.h" #include "freertos/FreeRTOS.h"
#include "freertos/task.h" #include "freertos/task.h"
#include "esp_system.h" #include "esp_chip_info.h"
#include "esp_spi_flash.h" #include "esp_flash.h"
void app_main(void)
void app_main()
{ {
printf("Hello world!\n"); printf("Hello world!\n");
/* Print chip information */ /* Print chip information */
esp_chip_info_t chip_info; esp_chip_info_t chip_info;
uint32_t flash_size;
esp_chip_info(&chip_info); esp_chip_info(&chip_info);
printf("This is ESP32 chip with %d CPU cores, WiFi%s%s, ", printf("This is %s chip with %d CPU core(s), WiFi%s%s, ",
chip_info.cores, CONFIG_IDF_TARGET,
(chip_info.features & CHIP_FEATURE_BT) ? "/BT" : "", chip_info.cores,
(chip_info.features & CHIP_FEATURE_BLE) ? "/BLE" : ""); (chip_info.features & CHIP_FEATURE_BT) ? "/BT" : "",
(chip_info.features & CHIP_FEATURE_BLE) ? "/BLE" : "");
printf("silicon revision %d, ", chip_info.revision); unsigned major_rev = chip_info.revision / 100;
unsigned minor_rev = chip_info.revision % 100;
printf("silicon revision v%d.%d, ", major_rev, minor_rev);
if(esp_flash_get_size(NULL, &flash_size) != ESP_OK) {
printf("Get flash size failed");
return;
}
printf("%dMB %s flash\n", spi_flash_get_chip_size() / (1024 * 1024), printf("%uMB %s flash\n", flash_size / (1024 * 1024),
(chip_info.features & CHIP_FEATURE_EMB_FLASH) ? "embedded" : "external"); (chip_info.features & CHIP_FEATURE_EMB_FLASH) ? "embedded" : "external");
printf("Minimum free heap size: %d bytes\n", esp_get_minimum_free_heap_size());
for (int i = 10; i >= 0; i--) { for (int i = 10; i >= 0; i--) {
printf("Restarting in %d seconds...\n", i); printf("Restarting in %d seconds...\n", i);
@@ -1,2 +1,2 @@
idf_component_register(SRCS "http_request_example_main.c" idf_component_register(SRCS "http_request_example_main.c"
INCLUDE_DIRS ".") INCLUDE_DIRS ".")
@@ -21,6 +21,7 @@
#include "lwip/sys.h" #include "lwip/sys.h"
#include "lwip/netdb.h" #include "lwip/netdb.h"
#include "lwip/dns.h" #include "lwip/dns.h"
#include "sdkconfig.h"
/* Constants that aren't configurable in menuconfig */ /* Constants that aren't configurable in menuconfig */
#define WEB_SERVER "example.com" #define WEB_SERVER "example.com"
@@ -1,2 +1,2 @@
idf_component_register(SRCS "uart_echo_example_main.c" idf_component_register(SRCS "uart_echo_example_main.c"
INCLUDE_DIRS ".") INCLUDE_DIRS ".")
@@ -11,23 +11,31 @@
#include "freertos/task.h" #include "freertos/task.h"
#include "driver/uart.h" #include "driver/uart.h"
#include "driver/gpio.h" #include "driver/gpio.h"
#include "sdkconfig.h"
#include "esp_log.h"
/** /**
* This is an example which echos any data it receives on UART1 back to the sender, * This is an example which echos any data it receives on configured UART back to the sender,
* with hardware flow control turned off. It does not use UART driver event queue. * with hardware flow control turned off. It does not use UART driver event queue.
* *
* - Port: UART1 * - Port: configured UART
* - Receive (Rx) buffer: on * - Receive (Rx) buffer: on
* - Transmit (Tx) buffer: off * - Transmit (Tx) buffer: off
* - Flow control: off * - Flow control: off
* - Event queue: off * - Event queue: off
* - Pin assignment: see defines below * - Pin assignment: see defines below (See Kconfig)
*/ */
#define ECHO_TEST_TXD (GPIO_NUM_4) #define ECHO_TEST_TXD (CONFIG_EXAMPLE_UART_TXD)
#define ECHO_TEST_RXD (GPIO_NUM_5) #define ECHO_TEST_RXD (CONFIG_EXAMPLE_UART_RXD)
#define ECHO_TEST_RTS (UART_PIN_NO_CHANGE) #define ECHO_TEST_RTS (UART_PIN_NO_CHANGE)
#define ECHO_TEST_CTS (UART_PIN_NO_CHANGE) #define ECHO_TEST_CTS (UART_PIN_NO_CHANGE)
#define ECHO_UART_PORT_NUM (CONFIG_EXAMPLE_UART_PORT_NUM)
#define ECHO_UART_BAUD_RATE (CONFIG_EXAMPLE_UART_BAUD_RATE)
#define ECHO_TASK_STACK_SIZE (CONFIG_EXAMPLE_TASK_STACK_SIZE)
static const char *TAG = "UART TEST";
#define BUF_SIZE (1024) #define BUF_SIZE (1024)
@@ -36,29 +44,39 @@ static void echo_task(void *arg)
/* Configure parameters of an UART driver, /* Configure parameters of an UART driver,
* communication pins and install the driver */ * communication pins and install the driver */
uart_config_t uart_config = { uart_config_t uart_config = {
.baud_rate = 115200, .baud_rate = ECHO_UART_BAUD_RATE,
.data_bits = UART_DATA_8_BITS, .data_bits = UART_DATA_8_BITS,
.parity = UART_PARITY_DISABLE, .parity = UART_PARITY_DISABLE,
.stop_bits = UART_STOP_BITS_1, .stop_bits = UART_STOP_BITS_1,
.flow_ctrl = UART_HW_FLOWCTRL_DISABLE, .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
.source_clk = UART_SCLK_APB, .source_clk = UART_SCLK_DEFAULT,
}; };
uart_driver_install(UART_NUM_1, BUF_SIZE * 2, 0, 0, NULL, 0); int intr_alloc_flags = 0;
uart_param_config(UART_NUM_1, &uart_config);
uart_set_pin(UART_NUM_1, ECHO_TEST_TXD, ECHO_TEST_RXD, ECHO_TEST_RTS, ECHO_TEST_CTS); #if CONFIG_UART_ISR_IN_IRAM
intr_alloc_flags = ESP_INTR_FLAG_IRAM;
#endif
ESP_ERROR_CHECK(uart_driver_install(ECHO_UART_PORT_NUM, BUF_SIZE * 2, 0, 0, NULL, intr_alloc_flags));
ESP_ERROR_CHECK(uart_param_config(ECHO_UART_PORT_NUM, &uart_config));
ESP_ERROR_CHECK(uart_set_pin(ECHO_UART_PORT_NUM, ECHO_TEST_TXD, ECHO_TEST_RXD, ECHO_TEST_RTS, ECHO_TEST_CTS));
// Configure a temporary buffer for the incoming data // Configure a temporary buffer for the incoming data
uint8_t *data = (uint8_t *) malloc(BUF_SIZE); uint8_t *data = (uint8_t *) malloc(BUF_SIZE);
while (1) { while (1) {
// Read data from the UART // Read data from the UART
int len = uart_read_bytes(UART_NUM_1, data, BUF_SIZE, 20 / portTICK_RATE_MS); int len = uart_read_bytes(ECHO_UART_PORT_NUM, data, (BUF_SIZE - 1), 20 / portTICK_PERIOD_MS);
// Write data back to the UART // Write data back to the UART
uart_write_bytes(UART_NUM_1, (const char *) data, len); uart_write_bytes(ECHO_UART_PORT_NUM, (const char *) data, len);
if (len) {
data[len] = '\0';
ESP_LOGI(TAG, "Recv str: %s", (char *) data);
}
} }
} }
void app_main(void) void app_main(void)
{ {
xTaskCreate(echo_task, "uart_echo_task", 1024, NULL, 10, NULL); xTaskCreate(echo_task, "uart_echo_task", ECHO_TASK_STACK_SIZE, NULL, 10, NULL);
} }
@@ -1,5 +1 @@
CONFIG_TINYUSB=y CONFIG_TINYUSB_CDC_ENABLED=y
CONFIG_TINYUSB_DESC_USE_ESPRESSIF_VID=n
CONFIG_TINYUSB_DESC_CUSTOM_VID=0x303A
CONFIG_TINYUSB_DESC_USE_DEFAULT_PID=n
CONFIG_TINYUSB_DESC_CUSTOM_PID=0x3000
@@ -1,2 +1,2 @@
idf_component_register(SRCS "tusb_sample_descriptor_main.c" idf_component_register(SRCS "tusb_serial_device_main.c"
INCLUDE_DIRS .) INCLUDE_DIRS .)
@@ -1,10 +0,0 @@
menu "Example Configuration"
config EXAMPLE_MANUAL_DESC
bool "Set up a USB descriptor manually in code"
default y
help
You can set up a descriptor using Menuconfig or independently of
your project configuration - manually in code
endmenu
@@ -1,71 +0,0 @@
/* USB Example
This example code is in the Public Domain (or CC0 licensed, at your option.)
Unless required by applicable law or agreed to in writing, this
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied.
*/
#include <stdlib.h>
#include "esp_log.h"
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "tinyusb.h"
#include "sdkconfig.h"
static const char *TAG = "example";
void app_main(void)
{
ESP_LOGI(TAG, "USB initialization");
#if CONFIG_EXAMPLE_MANUAL_DESC
// Setting of descriptor. You can use descriptor_tinyusb and
// descriptor_str_tinyusb as a reference
tusb_desc_device_t my_descriptor = {
.bLength = sizeof(my_descriptor),
.bDescriptorType = TUSB_DESC_DEVICE,
.bcdUSB = 0x0200, // USB version. 0x0200 means version 2.0
.bDeviceClass = TUSB_CLASS_UNSPECIFIED,
.bMaxPacketSize0 = CFG_TUD_ENDPOINT0_SIZE,
.idVendor = 0x303A,
.idProduct = 0x3000,
.bcdDevice = 0x0101, // Device FW version
.iManufacturer = 0x01, // see string_descriptor[1] bellow
.iProduct = 0x02, // see string_descriptor[2] bellow
.iSerialNumber = 0x03, // see string_descriptor[3] bellow
.bNumConfigurations = 0x01
};
tusb_desc_strarray_device_t my_string_descriptor = {
// array of pointer to string descriptors
(char[]){0x09, 0x04}, // 0: is supported language is English (0x0409)
"I", // 1: Manufacturer
"My Custom Device", // 2: Product
"012-345", // 3: Serials, should use chip ID
};
tinyusb_config_t tusb_cfg = {
.descriptor = &my_descriptor,
.string_descriptor = my_string_descriptor,
.external_phy = false // In the most cases you need to use a `false` value
};
#else
tinyusb_config_t tusb_cfg = {
.descriptor = NULL,
.string_descriptor = NULL,
.external_phy = false // In the most cases you need to use a `false` value
};
#endif
ESP_ERROR_CHECK(tinyusb_driver_install(&tusb_cfg));
ESP_LOGI(TAG, "USB initialization DONE");
}
@@ -0,0 +1,83 @@
/*
* SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Unlicense OR CC0-1.0
*/
#include <stdint.h>
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "tinyusb.h"
#include "tusb_cdc_acm.h"
#include "sdkconfig.h"
static const char *TAG = "example";
static uint8_t buf[CONFIG_TINYUSB_CDC_RX_BUFSIZE + 1];
void tinyusb_cdc_rx_callback(int itf, cdcacm_event_t *event)
{
/* initialization */
size_t rx_size = 0;
/* read */
esp_err_t ret = tinyusb_cdcacm_read(itf, buf, CONFIG_TINYUSB_CDC_RX_BUFSIZE, &rx_size);
if (ret == ESP_OK) {
ESP_LOGI(TAG, "Data from channel %d:", itf);
ESP_LOG_BUFFER_HEXDUMP(TAG, buf, rx_size, ESP_LOG_INFO);
} else {
ESP_LOGE(TAG, "Read error");
}
/* write back */
tinyusb_cdcacm_write_queue(itf, buf, rx_size);
tinyusb_cdcacm_write_flush(itf, 0);
}
void tinyusb_cdc_line_state_changed_callback(int itf, cdcacm_event_t *event)
{
int dtr = event->line_state_changed_data.dtr;
int rts = event->line_state_changed_data.rts;
ESP_LOGI(TAG, "Line state changed on channel %d: DTR:%d, RTS:%d", itf, dtr, rts);
}
void app_main(void)
{
ESP_LOGI(TAG, "USB initialization");
const tinyusb_config_t tusb_cfg = {
.device_descriptor = NULL,
.string_descriptor = NULL,
.external_phy = false,
.configuration_descriptor = NULL,
};
ESP_ERROR_CHECK(tinyusb_driver_install(&tusb_cfg));
tinyusb_config_cdcacm_t acm_cfg = {
.usb_dev = TINYUSB_USBDEV_0,
.cdc_port = TINYUSB_CDC_ACM_0,
.rx_unread_buf_sz = 64,
.callback_rx = &tinyusb_cdc_rx_callback, // the first way to register a callback
.callback_rx_wanted_char = NULL,
.callback_line_state_changed = NULL,
.callback_line_coding_changed = NULL
};
ESP_ERROR_CHECK(tusb_cdc_acm_init(&acm_cfg));
/* the second way to register a callback */
ESP_ERROR_CHECK(tinyusb_cdcacm_register_callback(
TINYUSB_CDC_ACM_0,
CDC_EVENT_LINE_STATE_CHANGED,
&tinyusb_cdc_line_state_changed_callback));
#if (CONFIG_TINYUSB_CDC_COUNT > 1)
acm_cfg.cdc_port = TINYUSB_CDC_ACM_1;
ESP_ERROR_CHECK(tusb_cdc_acm_init(&acm_cfg));
ESP_ERROR_CHECK(tinyusb_cdcacm_register_callback(
TINYUSB_CDC_ACM_1,
CDC_EVENT_LINE_STATE_CHANGED,
&tinyusb_cdc_line_state_changed_callback));
#endif
ESP_LOGI(TAG, "USB initialization DONE");
}
@@ -1,2 +1,2 @@
idf_component_register(SRCS "sd_card_example_main.c" idf_component_register(SRCS "sd_card_example_main.c"
INCLUDE_DIRS ".") INCLUDE_DIRS ".")
@@ -0,0 +1,57 @@
menu "SD/MMC Example Configuration"
config EXAMPLE_FORMAT_IF_MOUNT_FAILED
bool "Format the card if mount failed"
default n
help
If this config item is set, format_if_mount_failed will be set to true and the card will be formatted if
the mount has failed.
choice EXAMPLE_SDMMC_BUS_WIDTH
prompt "SD/MMC bus width"
default EXAMPLE_SDMMC_BUS_WIDTH_4
help
Select the bus width of SD or MMC interface.
Note that even if 1 line mode is used, D3 pin of the SD card must have a pull-up resistor connected.
Otherwise the card may enter SPI mode, the only way to recover from which is to cycle power to the card.
config EXAMPLE_SDMMC_BUS_WIDTH_4
bool "4 lines (D0 - D3)"
config EXAMPLE_SDMMC_BUS_WIDTH_1
bool "1 line (D0)"
endchoice
if SOC_SDMMC_USE_GPIO_MATRIX
config EXAMPLE_PIN_CMD
int "CMD GPIO number"
default 35 if IDF_TARGET_ESP32S3
config EXAMPLE_PIN_CLK
int "CLK GPIO number"
default 36 if IDF_TARGET_ESP32S3
config EXAMPLE_PIN_D0
int "D0 GPIO number"
default 37 if IDF_TARGET_ESP32S3
if EXAMPLE_SDMMC_BUS_WIDTH_4
config EXAMPLE_PIN_D1
int "D1 GPIO number"
default 38 if IDF_TARGET_ESP32S3
config EXAMPLE_PIN_D2
int "D2 GPIO number"
default 33 if IDF_TARGET_ESP32S3
config EXAMPLE_PIN_D3
int "D3 GPIO number"
default 34 if IDF_TARGET_ESP32S3
endif # EXAMPLE_SDMMC_BUS_WIDTH_4
endif # SOC_SDMMC_USE_GPIO_MATRIX
endmenu
@@ -6,63 +6,24 @@
CONDITIONS OF ANY KIND, either express or implied. CONDITIONS OF ANY KIND, either express or implied.
*/ */
#include <stdio.h> // This example uses SDMMC peripheral to communicate with SD card.
#include <string.h> #include <string.h>
#include <sys/unistd.h> #include <sys/unistd.h>
#include <sys/stat.h> #include <sys/stat.h>
#include "esp_err.h"
#include "esp_log.h"
#include "esp_vfs_fat.h" #include "esp_vfs_fat.h"
#include "driver/sdspi_host.h"
#include "driver/spi_common.h"
#include "sdmmc_cmd.h" #include "sdmmc_cmd.h"
#include "sdkconfig.h"
#ifdef CONFIG_IDF_TARGET_ESP32
#include "driver/sdmmc_host.h" #include "driver/sdmmc_host.h"
#endif
static const char *TAG = "example"; static const char *TAG = "example";
#define MOUNT_POINT "/sdcard" #define MOUNT_POINT "/sdcard"
// This example can use SDMMC and SPI peripherals to communicate with SD card.
// By default, SDMMC peripheral is used.
// To enable SPI mode, uncomment the following line:
// #define USE_SPI_MODE
// ESP32-S2 doesn't have an SD Host peripheral, always use SPI:
#ifdef CONFIG_IDF_TARGET_ESP32S2
#ifndef USE_SPI_MODE
#define USE_SPI_MODE
#endif // USE_SPI_MODE
// on ESP32-S2, DMA channel must be the same as host id
#define SPI_DMA_CHAN host.slot
#endif //CONFIG_IDF_TARGET_ESP32S2
// DMA channel to be used by the SPI peripheral
#ifndef SPI_DMA_CHAN
#define SPI_DMA_CHAN 1
#endif //SPI_DMA_CHAN
// When testing SD and SPI modes, keep in mind that once the card has been
// initialized in SPI mode, it can not be reinitialized in SD mode without
// toggling power to the card.
#ifdef USE_SPI_MODE
// Pin mapping when using SPI mode.
// With this mapping, SD card can be used both in SPI and 1-line SD mode.
// Note that a pull-up on CS line is required in SD mode.
#define PIN_NUM_MISO 2
#define PIN_NUM_MOSI 15
#define PIN_NUM_CLK 14
#define PIN_NUM_CS 13
#endif //USE_SPI_MODE
void app_main(void) void app_main(void)
{ {
esp_err_t ret; esp_err_t ret;
// Options for mounting the filesystem. // Options for mounting the filesystem.
// If format_if_mount_failed is set to true, SD card will be partitioned and // If format_if_mount_failed is set to true, SD card will be partitioned and
// formatted in case when mounting fails. // formatted in case when mounting fails.
@@ -75,7 +36,7 @@ void app_main(void)
.max_files = 5, .max_files = 5,
.allocation_unit_size = 16 * 1024 .allocation_unit_size = 16 * 1024
}; };
sdmmc_card_t* card; sdmmc_card_t *card;
const char mount_point[] = MOUNT_POINT; const char mount_point[] = MOUNT_POINT;
ESP_LOGI(TAG, "Initializing SD card"); ESP_LOGI(TAG, "Initializing SD card");
@@ -83,7 +44,7 @@ void app_main(void)
// Note: esp_vfs_fat_sdmmc/sdspi_mount is all-in-one convenience functions. // Note: esp_vfs_fat_sdmmc/sdspi_mount is all-in-one convenience functions.
// Please check its source code and implement error recovery when developing // Please check its source code and implement error recovery when developing
// production applications. // production applications.
#ifndef USE_SPI_MODE
ESP_LOGI(TAG, "Using SDMMC peripheral"); ESP_LOGI(TAG, "Using SDMMC peripheral");
sdmmc_host_t host = SDMMC_HOST_DEFAULT(); sdmmc_host_t host = SDMMC_HOST_DEFAULT();
@@ -91,64 +52,56 @@ void app_main(void)
// Modify slot_config.gpio_cd and slot_config.gpio_wp if your board has these signals. // Modify slot_config.gpio_cd and slot_config.gpio_wp if your board has these signals.
sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT(); sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT();
// To use 1-line SD mode, uncomment the following line: // Set bus width to use:
// slot_config.width = 1; #ifdef CONFIG_EXAMPLE_SDMMC_BUS_WIDTH_4
slot_config.width = 4;
// GPIOs 15, 2, 4, 12, 13 should have external 10k pull-ups.
// Internal pull-ups are not sufficient. However, enabling internal pull-ups
// does make a difference some boards, so we do that here.
gpio_set_pull_mode(15, GPIO_PULLUP_ONLY); // CMD, needed in 4- and 1- line modes
gpio_set_pull_mode(2, GPIO_PULLUP_ONLY); // D0, needed in 4- and 1-line modes
gpio_set_pull_mode(4, GPIO_PULLUP_ONLY); // D1, needed in 4-line mode only
gpio_set_pull_mode(12, GPIO_PULLUP_ONLY); // D2, needed in 4-line mode only
gpio_set_pull_mode(13, GPIO_PULLUP_ONLY); // D3, needed in 4- and 1-line modes
ret = esp_vfs_fat_sdmmc_mount(mount_point, &host, &slot_config, &mount_config, &card);
#else #else
ESP_LOGI(TAG, "Using SPI peripheral"); slot_config.width = 1;
#endif
sdmmc_host_t host = SDSPI_HOST_DEFAULT(); // On chips where the GPIOs used for SD card can be configured, set them in
spi_bus_config_t bus_cfg = { // the slot_config structure:
.mosi_io_num = PIN_NUM_MOSI, #ifdef CONFIG_SOC_SDMMC_USE_GPIO_MATRIX
.miso_io_num = PIN_NUM_MISO, slot_config.clk = CONFIG_EXAMPLE_PIN_CLK;
.sclk_io_num = PIN_NUM_CLK, slot_config.cmd = CONFIG_EXAMPLE_PIN_CMD;
.quadwp_io_num = -1, slot_config.d0 = CONFIG_EXAMPLE_PIN_D0;
.quadhd_io_num = -1, #ifdef CONFIG_EXAMPLE_SDMMC_BUS_WIDTH_4
.max_transfer_sz = 4000, slot_config.d1 = CONFIG_EXAMPLE_PIN_D1;
}; slot_config.d2 = CONFIG_EXAMPLE_PIN_D2;
ret = spi_bus_initialize(host.slot, &bus_cfg, SPI_DMA_CHAN); slot_config.d3 = CONFIG_EXAMPLE_PIN_D3;
if (ret != ESP_OK) { #endif // CONFIG_EXAMPLE_SDMMC_BUS_WIDTH_4
ESP_LOGE(TAG, "Failed to initialize bus."); #endif // CONFIG_SOC_SDMMC_USE_GPIO_MATRIX
return;
}
// This initializes the slot without card detect (CD) and write protect (WP) signals. // Enable internal pullups on enabled pins. The internal pullups
// Modify slot_config.gpio_cd and slot_config.gpio_wp if your board has these signals. // are insufficient however, please make sure 10k external pullups are
sdspi_device_config_t slot_config = SDSPI_DEVICE_CONFIG_DEFAULT(); // connected on the bus. This is for debug / example purpose only.
slot_config.gpio_cs = PIN_NUM_CS; slot_config.flags |= SDMMC_SLOT_FLAG_INTERNAL_PULLUP;
slot_config.host_id = host.slot;
ret = esp_vfs_fat_sdspi_mount(mount_point, &host, &slot_config, &mount_config, &card); ESP_LOGI(TAG, "Mounting filesystem");
#endif //USE_SPI_MODE ret = esp_vfs_fat_sdmmc_mount(mount_point, &host, &slot_config, &mount_config, &card);
if (ret != ESP_OK) { if (ret != ESP_OK) {
if (ret == ESP_FAIL) { if (ret == ESP_FAIL) {
ESP_LOGE(TAG, "Failed to mount filesystem. " ESP_LOGE(TAG, "Failed to mount filesystem. "
"If you want the card to be formatted, set the EXAMPLE_FORMAT_IF_MOUNT_FAILED menuconfig option."); "If you want the card to be formatted, set the EXAMPLE_FORMAT_IF_MOUNT_FAILED menuconfig option.");
} else { } else {
ESP_LOGE(TAG, "Failed to initialize the card (%s). " ESP_LOGE(TAG, "Failed to initialize the card (%s). "
"Make sure SD card lines have pull-up resistors in place.", esp_err_to_name(ret)); "Make sure SD card lines have pull-up resistors in place.", esp_err_to_name(ret));
} }
return; return;
} }
ESP_LOGI(TAG, "Filesystem mounted");
// Card has been initialized, print its properties // Card has been initialized, print its properties
sdmmc_card_print_info(stdout, card); sdmmc_card_print_info(stdout, card);
// Use POSIX and C standard library functions to work with files. // Use POSIX and C standard library functions to work with files:
// First create a file. // First create a file.
ESP_LOGI(TAG, "Opening file"); const char *file_hello = MOUNT_POINT"/hello.txt";
FILE* f = fopen(MOUNT_POINT"/hello.txt", "w");
ESP_LOGI(TAG, "Opening file %s", file_hello);
FILE *f = fopen(file_hello, "w");
if (f == NULL) { if (f == NULL) {
ESP_LOGE(TAG, "Failed to open file for writing"); ESP_LOGE(TAG, "Failed to open file for writing");
return; return;
@@ -157,42 +110,43 @@ void app_main(void)
fclose(f); fclose(f);
ESP_LOGI(TAG, "File written"); ESP_LOGI(TAG, "File written");
const char *file_foo = MOUNT_POINT"/foo.txt";
// Check if destination file exists before renaming // Check if destination file exists before renaming
struct stat st; struct stat st;
if (stat(MOUNT_POINT"/foo.txt", &st) == 0) { if (stat(file_foo, &st) == 0) {
// Delete it if it exists // Delete it if it exists
unlink(MOUNT_POINT"/foo.txt"); unlink(file_foo);
} }
// Rename original file // Rename original file
ESP_LOGI(TAG, "Renaming file"); ESP_LOGI(TAG, "Renaming file %s to %s", file_hello, file_foo);
if (rename(MOUNT_POINT"/hello.txt", MOUNT_POINT"/foo.txt") != 0) { if (rename(file_hello, file_foo) != 0) {
ESP_LOGE(TAG, "Rename failed"); ESP_LOGE(TAG, "Rename failed");
return; return;
} }
// Open renamed file for reading // Open renamed file for reading
ESP_LOGI(TAG, "Reading file"); ESP_LOGI(TAG, "Reading file %s", file_foo);
f = fopen(MOUNT_POINT"/foo.txt", "r"); f = fopen(file_foo, "r");
if (f == NULL) { if (f == NULL) {
ESP_LOGE(TAG, "Failed to open file for reading"); ESP_LOGE(TAG, "Failed to open file for reading");
return; return;
} }
// Read a line from file
char line[64]; char line[64];
fgets(line, sizeof(line), f); fgets(line, sizeof(line), f);
fclose(f); fclose(f);
// strip newline
char* pos = strchr(line, '\n'); // Strip newline
char *pos = strchr(line, '\n');
if (pos) { if (pos) {
*pos = '\0'; *pos = '\0';
} }
ESP_LOGI(TAG, "Read from file: '%s'", line); ESP_LOGI(TAG, "Read from file: '%s'", line);
// All done, unmount partition and disable SDMMC or SPI peripheral // All done, unmount partition and disable SDMMC peripheral
esp_vfs_fat_sdcard_unmount(mount_point, card); esp_vfs_fat_sdcard_unmount(mount_point, card);
ESP_LOGI(TAG, "Card unmounted"); ESP_LOGI(TAG, "Card unmounted");
#ifdef USE_SPI_MODE
//deinitialize the bus after all devices are removed
spi_bus_free(host.slot);
#endif
} }
@@ -1,2 +1,2 @@
idf_component_register(SRCS "spiffs_example_main.c" idf_component_register(SRCS "spiffs_example_main.c"
INCLUDE_DIRS ".") INCLUDE_DIRS ".")
@@ -0,0 +1,9 @@
menu "SPIFFS Example menu"
config EXAMPLE_SPIFFS_CHECK_ON_START
bool "Run SPIFFS_check on every start-up"
default y
help
If this config item is set, esp_spiffs_check() will be run on every start-up.
Slow on large flash sizes.
endmenu
@@ -19,14 +19,14 @@ static const char *TAG = "example";
void app_main(void) void app_main(void)
{ {
ESP_LOGI(TAG, "Initializing SPIFFS"); ESP_LOGI(TAG, "Initializing SPIFFS");
esp_vfs_spiffs_conf_t conf = { esp_vfs_spiffs_conf_t conf = {
.base_path = "/spiffs", .base_path = "/spiffs",
.partition_label = NULL, .partition_label = NULL,
.max_files = 5, .max_files = 5,
.format_if_mount_failed = true .format_if_mount_failed = true
}; };
// Use settings defined above to initialize and mount SPIFFS filesystem. // Use settings defined above to initialize and mount SPIFFS filesystem.
// Note: esp_vfs_spiffs_register is an all-in-one convenience function. // Note: esp_vfs_spiffs_register is an all-in-one convenience function.
esp_err_t ret = esp_vfs_spiffs_register(&conf); esp_err_t ret = esp_vfs_spiffs_register(&conf);
@@ -41,20 +41,74 @@ void app_main(void)
} }
return; return;
} }
#ifdef CONFIG_EXAMPLE_SPIFFS_CHECK_ON_START
ESP_LOGI(TAG, "Performing SPIFFS_check().");
ret = esp_spiffs_check(conf.partition_label);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "SPIFFS_check() failed (%s)", esp_err_to_name(ret));
return;
} else {
ESP_LOGI(TAG, "SPIFFS_check() successful");
}
#endif
size_t total = 0, used = 0; size_t total = 0, used = 0;
ret = esp_spiffs_info(conf.partition_label, &total, &used); ret = esp_spiffs_info(conf.partition_label, &total, &used);
if (ret != ESP_OK) { if (ret != ESP_OK) {
ESP_LOGE(TAG, "Failed to get SPIFFS partition information (%s)", esp_err_to_name(ret)); ESP_LOGE(TAG, "Failed to get SPIFFS partition information (%s). Formatting...", esp_err_to_name(ret));
esp_spiffs_format(conf.partition_label);
return;
} else { } else {
ESP_LOGI(TAG, "Partition size: total: %d, used: %d", total, used); ESP_LOGI(TAG, "Partition size: total: %d, used: %d", total, used);
} }
#
// Check consistency of reported partiton size info.
if (used > total) {
ESP_LOGW(TAG, "Number of used bytes cannot be larger than total. Performing SPIFFS_check().");
ret = esp_spiffs_check(conf.partition_label);
// Could be also used to mend broken files, to clean unreferenced pages, etc.
// More info at https://github.com/pellepl/spiffs/wiki/FAQ#powerlosses-contd-when-should-i-run-spiffs_check
if (ret != ESP_OK) {
ESP_LOGE(TAG, "SPIFFS_check() failed (%s)", esp_err_to_name(ret));
return;
} else {
ESP_LOGI(TAG, "SPIFFS_check() successful");
}
}
// Use POSIX and C standard library functions to work with files.
// First create a file.
ESP_LOGI(TAG, "Opening file");
FILE* f = fopen("/spiffs/hello.txt", "w");
if (f == NULL) {
ESP_LOGE(TAG, "Failed to open file for writing");
return;
}
fprintf(f, "Hello World!\n");
fclose(f);
ESP_LOGI(TAG, "File written");
// Check if destination file exists before renaming
struct stat st;
if (stat("/spiffs/foo.txt", &st) == 0) {
// Delete it if it exists
unlink("/spiffs/foo.txt");
}
// Rename original file
ESP_LOGI(TAG, "Renaming file");
if (rename("/spiffs/hello.txt", "/spiffs/foo.txt") != 0) {
ESP_LOGE(TAG, "Rename failed");
return;
}
// Open renamed file for reading // Open renamed file for reading
ESP_LOGI(TAG, "Reading file"); ESP_LOGI(TAG, "Reading file");
FILE* f = fopen("/spiffs/hello.txt", "r"); f = fopen("/spiffs/foo.txt", "r");
if (f == NULL) { if (f == NULL) {
ESP_LOGI(TAG, "Failed to open file for reading"); ESP_LOGE(TAG, "Failed to open file for reading");
return; return;
} }
char line[64]; char line[64];
+4 -2
View File
@@ -1,6 +1,6 @@
idf_component_register(SRCS "ulp_adc_example_main.c" idf_component_register(SRCS "ulp_adc_example_main.c"
INCLUDE_DIRS "" INCLUDE_DIRS ""
REQUIRES soc nvs_flash ulp driver) REQUIRES soc nvs_flash ulp driver esp_adc)
# #
# ULP support additions to component CMakeLists.txt. # ULP support additions to component CMakeLists.txt.
# #
@@ -18,4 +18,6 @@ set(ulp_exp_dep_srcs "ulp_adc_example_main.c")
# #
# 4. Call function to build ULP binary and embed in project using the argument # 4. Call function to build ULP binary and embed in project using the argument
# values above. # values above.
ulp_embed_binary(${ulp_app_name} ${ulp_s_sources} ${ulp_exp_dep_srcs}) ulp_embed_binary(${ulp_app_name} "${ulp_s_sources}" "${ulp_exp_dep_srcs}")
target_compile_options(${COMPONENT_LIB} PRIVATE "-Wno-format")
@@ -16,10 +16,10 @@
#include "soc/sens_reg.h" #include "soc/sens_reg.h"
#include "driver/gpio.h" #include "driver/gpio.h"
#include "driver/rtc_io.h" #include "driver/rtc_io.h"
#include "driver/adc.h"
#include "driver/dac.h" #include "driver/dac.h"
#include "esp32/ulp.h" #include "esp32/ulp.h"
#include "ulp_main.h" #include "ulp_main.h"
#include "esp_adc/adc_oneshot.h"
extern const uint8_t ulp_main_bin_start[] asm("_binary_ulp_main_bin_start"); extern const uint8_t ulp_main_bin_start[] asm("_binary_ulp_main_bin_start");
extern const uint8_t ulp_main_bin_end[] asm("_binary_ulp_main_bin_end"); extern const uint8_t ulp_main_bin_end[] asm("_binary_ulp_main_bin_end");
@@ -60,16 +60,21 @@ static void init_ulp_program(void)
(ulp_main_bin_end - ulp_main_bin_start) / sizeof(uint32_t)); (ulp_main_bin_end - ulp_main_bin_start) / sizeof(uint32_t));
ESP_ERROR_CHECK(err); ESP_ERROR_CHECK(err);
/* Configure ADC channel */ //-------------ADC1 Init---------------//
/* Note: when changing channel here, also change 'adc_channel' constant adc_oneshot_unit_handle_t adc1_handle;
in adc.S */ adc_oneshot_unit_init_cfg_t init_config1 = {
adc1_config_channel_atten(ADC1_CHANNEL_6, ADC_ATTEN_DB_11); .unit_id = ADC_UNIT_1,
#if CONFIG_IDF_TARGET_ESP32 .ulp_mode = ADC_ULP_MODE_FSM,
adc1_config_width(ADC_WIDTH_BIT_12); };
#elif CONFIG_IDF_TARGET_ESP32S2 ESP_ERROR_CHECK(adc_oneshot_new_unit(&init_config1, &adc1_handle));
adc1_config_width(ADC_WIDTH_BIT_13);
#endif //-------------ADC1 Channel Config---------------//
adc1_ulp_enable(); // Note: when changing channel here, also change 'adc_channel' constant in adc.S
adc_oneshot_chan_cfg_t config = {
.bitwidth = ADC_BITWIDTH_DEFAULT,
.atten = ADC_ATTEN_DB_11,
};
ESP_ERROR_CHECK(adc_oneshot_config_channel(adc1_handle, ADC_CHANNEL_6, &config));
/* Set low and high thresholds, approx. 1.35V - 1.75V*/ /* Set low and high thresholds, approx. 1.35V - 1.75V*/
ulp_low_thr = 1500; ulp_low_thr = 1500;
@@ -84,9 +89,7 @@ static void init_ulp_program(void)
*/ */
rtc_gpio_isolate(GPIO_NUM_12); rtc_gpio_isolate(GPIO_NUM_12);
rtc_gpio_isolate(GPIO_NUM_15); rtc_gpio_isolate(GPIO_NUM_15);
#if CONFIG_IDF_TARGET_ESP32
esp_deep_sleep_disable_rom_logging(); // suppress boot messages esp_deep_sleep_disable_rom_logging(); // suppress boot messages
#endif
} }
static void start_ulp_program(void) static void start_ulp_program(void)
+1 -1
View File
@@ -18,7 +18,7 @@
*/ */
/* ULP assembly files are passed through C preprocessor first, so include directives /* ULP assembly files are passed through C preprocessor first, so include directives
and C macros may be used in these files and C macros may be used in these files
*/ */
#include "soc/rtc_cntl_reg.h" #include "soc/rtc_cntl_reg.h"
#include "soc/soc_ulp.h" #include "soc/soc_ulp.h"
+3 -2
View File
@@ -1,6 +1,7 @@
# Enable ULP # Enable ULP
CONFIG_ESP32_ULP_COPROC_ENABLED=y CONFIG_ULP_COPROC_ENABLED=y
CONFIG_ESP32_ULP_COPROC_RESERVE_MEM=1024 CONFIG_ULP_COPROC_TYPE_FSM=y
CONFIG_ULP_COPROC_RESERVE_MEM=1024
# Set log level to Warning to produce clean output # Set log level to Warning to produce clean output
CONFIG_BOOTLOADER_LOG_LEVEL_WARN=y CONFIG_BOOTLOADER_LOG_LEVEL_WARN=y
CONFIG_BOOTLOADER_LOG_LEVEL=2 CONFIG_BOOTLOADER_LOG_LEVEL=2
+3 -1
View File
@@ -1,6 +1,6 @@
idf_component_register(SRCS "ulp_example_main.c" idf_component_register(SRCS "ulp_example_main.c"
INCLUDE_DIRS "" INCLUDE_DIRS ""
REQUIRES soc nvs_flash ulp) REQUIRES driver soc nvs_flash ulp)
# #
# ULP support additions to component CMakeLists.txt. # ULP support additions to component CMakeLists.txt.
# #
@@ -19,3 +19,5 @@ set(ulp_exp_dep_srcs "ulp_example_main.c")
# 4. Call function to build ULP binary and embed in project using the argument # 4. Call function to build ULP binary and embed in project using the argument
# values above. # values above.
ulp_embed_binary(${ulp_app_name} "${ulp_s_sources}" "${ulp_exp_dep_srcs}") ulp_embed_binary(${ulp_app_name} "${ulp_s_sources}" "${ulp_exp_dep_srcs}")
target_compile_options(${COMPONENT_LIB} PRIVATE "-Wno-format")
@@ -16,7 +16,7 @@
#include "soc/rtc_periph.h" #include "soc/rtc_periph.h"
#include "driver/gpio.h" #include "driver/gpio.h"
#include "driver/rtc_io.h" #include "driver/rtc_io.h"
#include "esp32/ulp.h" #include "ulp.h"
#include "ulp_main.h" #include "ulp_main.h"
extern const uint8_t ulp_main_bin_start[] asm("_binary_ulp_main_bin_start"); extern const uint8_t ulp_main_bin_start[] asm("_binary_ulp_main_bin_start");
@@ -74,12 +74,15 @@ static void init_ulp_program(void)
rtc_gpio_pullup_dis(gpio_num); rtc_gpio_pullup_dis(gpio_num);
rtc_gpio_hold_en(gpio_num); rtc_gpio_hold_en(gpio_num);
#if CONFIG_IDF_TARGET_ESP32
/* Disconnect GPIO12 and GPIO15 to remove current drain through /* Disconnect GPIO12 and GPIO15 to remove current drain through
* pullup/pulldown resistors. * pullup/pulldown resistors on modules which have these (e.g. ESP32-WROVER)
* GPIO12 may be pulled high to select flash voltage. * GPIO12 may be pulled high to select flash voltage.
*/ */
rtc_gpio_isolate(GPIO_NUM_12); rtc_gpio_isolate(GPIO_NUM_12);
rtc_gpio_isolate(GPIO_NUM_15); rtc_gpio_isolate(GPIO_NUM_15);
#endif // CONFIG_IDF_TARGET_ESP32
esp_deep_sleep_disable_rom_logging(); // suppress boot messages esp_deep_sleep_disable_rom_logging(); // suppress boot messages
/* Set ULP wake up period to T = 20ms. /* Set ULP wake up period to T = 20ms.
+16 -1
View File
@@ -1,3 +1,8 @@
/*
* SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
/* ULP Example: pulse counting /* ULP Example: pulse counting
This example code is in the Public Domain (or CC0 licensed, at your option.) This example code is in the Public Domain (or CC0 licensed, at your option.)
@@ -20,11 +25,13 @@
*/ */
/* ULP assembly files are passed through C preprocessor first, so include directives /* ULP assembly files are passed through C preprocessor first, so include directives
and C macros may be used in these files and C macros may be used in these files
*/ */
#include "sdkconfig.h"
#include "soc/rtc_cntl_reg.h" #include "soc/rtc_cntl_reg.h"
#include "soc/rtc_io_reg.h" #include "soc/rtc_io_reg.h"
#include "soc/soc_ulp.h" #include "soc/soc_ulp.h"
#include "soc/sens_reg.h"
/* Define variables, which go into .bss section (zero-initialized data) */ /* Define variables, which go into .bss section (zero-initialized data) */
.bss .bss
@@ -70,6 +77,14 @@ entry:
move r3, io_number move r3, io_number
ld r3, r3, 0 ld r3, r3, 0
#if CONFIG_IDF_TARGET_ESP32S2
/* ESP32S2 powers down RTC periph when entering deep sleep and thus by association SENS_SAR_IO_MUX_CONF_REG */
WRITE_RTC_FIELD(SENS_SAR_IO_MUX_CONF_REG, SENS_IOMUX_CLK_GATE_EN, 1)
#elif CONFIG_IDF_TARGET_ESP32S3
/* ESP32S3 powers down RTC periph when entering deep sleep and thus by association SENS_SAR_PERI_CLK_GATE_CONF_REG */
WRITE_RTC_FIELD(SENS_SAR_PERI_CLK_GATE_CONF_REG, SENS_IOMUX_CLK_EN, 1);
#endif
/* Lower 16 IOs and higher need to be handled separately, /* Lower 16 IOs and higher need to be handled separately,
* because r0-r3 registers are 16 bit wide. * because r0-r3 registers are 16 bit wide.
* Check which IO this is. * Check which IO this is.
+1 -1
View File
@@ -1,5 +1,5 @@
/* ULP assembly files are passed through C preprocessor first, so include directives /* ULP assembly files are passed through C preprocessor first, so include directives
and C macros may be used in these files and C macros may be used in these files
*/ */
#include "soc/rtc_cntl_reg.h" #include "soc/rtc_cntl_reg.h"
#include "soc/soc_ulp.h" #include "soc/soc_ulp.h"
+10 -5
View File
@@ -36,25 +36,29 @@
"toolchain-xtensa-esp32": { "toolchain-xtensa-esp32": {
"type": "toolchain", "type": "toolchain",
"owner": "espressif", "owner": "espressif",
"version": "8.4.0+2021r2-patch5" "version": "8.4.0+2021r2-patch5",
"optionalVersions": ["11.2.0+2022r1"]
}, },
"toolchain-xtensa-esp32s2": { "toolchain-xtensa-esp32s2": {
"type": "toolchain", "type": "toolchain",
"optional": true, "optional": true,
"owner": "espressif", "owner": "espressif",
"version": "8.4.0+2021r2-patch5" "version": "8.4.0+2021r2-patch5",
"optionalVersions": ["11.2.0+2022r1"]
}, },
"toolchain-xtensa-esp32s3": { "toolchain-xtensa-esp32s3": {
"type": "toolchain", "type": "toolchain",
"optional": true, "optional": true,
"owner": "espressif", "owner": "espressif",
"version": "8.4.0+2021r2-patch5" "version": "8.4.0+2021r2-patch5",
"optionalVersions": ["11.2.0+2022r1"]
}, },
"toolchain-riscv32-esp": { "toolchain-riscv32-esp": {
"type": "toolchain", "type": "toolchain",
"optional": true, "optional": true,
"owner": "espressif", "owner": "espressif",
"version": "8.4.0+2021r2-patch5" "version": "8.4.0+2021r2-patch5",
"optionalVersions": ["11.2.0+2022r1"]
}, },
"toolchain-esp32ulp": { "toolchain-esp32ulp": {
"type": "toolchain", "type": "toolchain",
@@ -78,7 +82,8 @@
"type": "framework", "type": "framework",
"optional": true, "optional": true,
"owner": "platformio", "owner": "platformio",
"version": "~3.40403.0" "version": "~3.50000.0",
"optionalVersions": ["~3.40402.0"]
}, },
"tool-esptoolpy": { "tool-esptoolpy": {
"type": "uploader", "type": "uploader",
+13
View File
@@ -95,6 +95,19 @@ class Espressif32Platform(PlatformBase):
elif p in ("tool-mconf", "tool-idf") and IS_WINDOWS: elif p in ("tool-mconf", "tool-idf") and IS_WINDOWS:
self.packages[p]["optional"] = False self.packages[p]["optional"] = False
if "arduino" in frameworks:
# Downgrade the IDF version for mixed Arduino+IDF projects
self.packages["framework-espidf"]["version"] = "~3.40403.0"
else:
# Use the latest toolchains available for IDF v5.0
for target in (
"xtensa-esp32",
"xtensa-esp32s2",
"xtensa-esp32s3",
"riscv32-esp"
):
self.packages["toolchain-%s" % target]["version"] = "11.2.0+2022r1"
for available_mcu in ("esp32", "esp32s2", "esp32s3"): for available_mcu in ("esp32", "esp32s2", "esp32s3"):
if available_mcu == mcu: if available_mcu == mcu:
self.packages["toolchain-xtensa-%s" % mcu]["optional"] = False self.packages["toolchain-xtensa-%s" % mcu]["optional"] = False