├── README.md ├── .gitattributes ├── ESP-IDF codes ( .C ) ├── ADC │ └── PIR-sensor-test1-MOTION │ │ ├── .gitignore │ │ ├── main │ │ ├── CMakeLists.txt │ │ └── main.c │ │ ├── .vscode │ │ ├── launch.json │ │ ├── c_cpp_properties.json │ │ ├── settings.json │ │ └── tasks.json │ │ ├── CMakeLists.txt │ │ ├── .devcontainer │ │ ├── devcontainer.json │ │ └── Dockerfile │ │ └── README.md ├── Inputs │ └── ISR_ONE_pin_only_TOUCH │ │ ├── .gitignore │ │ ├── main │ │ ├── CMakeLists.txt │ │ └── main.c │ │ ├── .vscode │ │ ├── launch.json │ │ ├── c_cpp_properties.json │ │ ├── settings.json │ │ └── tasks.json │ │ ├── CMakeLists.txt │ │ ├── .devcontainer │ │ ├── devcontainer.json │ │ └── Dockerfile │ │ └── README.md └── BT │ └── Nimble_server │ └── BLE_test1newLED_ON_OFF │ ├── .gitignore │ ├── main │ ├── CMakeLists.txt │ └── main.c │ ├── .vscode │ ├── launch.json │ ├── c_cpp_properties.json │ ├── settings.json │ └── tasks.json │ ├── CMakeLists.txt │ ├── .devcontainer │ ├── devcontainer.json │ └── Dockerfile │ └── README.md └── ESP32 - arduino IDE codes ( .cpp ) ├── WIFI └── WIFI_MP3_playing_via_I2s │ └── WIFI_MP3_playing_via_I2s │ ├── External libs │ ├── WIFI libs used │ │ ├── WiFiUdp.h │ │ ├── WiFiClient.h │ │ ├── WiFiServer.h │ │ ├── WiFiType.h │ │ ├── WiFi.h │ │ ├── WiFiScan.h │ │ ├── WiFiMulti.h │ │ ├── WiFi.cpp │ │ ├── WiFiAP.h │ │ ├── WiFiGeneric.h │ │ ├── WiFiAP.cpp │ │ ├── WiFiSTA.h │ │ ├── WiFiScan.cpp │ │ ├── WiFiMulti.cpp │ │ ├── AP.cpp │ │ └── WiFiSTA.cpp │ └── AUDIO libs used │ │ ├── aac_decoder │ │ ├── aac_decoder.h │ │ └── aac_decoder.cpp │ │ ├── opus_decoder │ │ └── opus_decoder.h │ │ └── flac_decoder │ │ └── flac_decoder.h │ └── WIFI_MP3_playing_via_I2s.ino ├── PWM ├── PWM_led_c_library │ └── PWM_led_c_library.ino ├── PWM_mcpwm_header │ └── PWM_mcpwm_header.ino ├── PWM_usingTImer_bit │ └── PWM_usingTImer_bit.ino └── PWM_rmt_driver │ └── PWM_rmt_driver.ino ├── I2C MASTER-SLAVE ├── SLAVE │ └── Slave │ │ ├── Air_Quality_Sensor.h │ │ ├── Slave.ino │ │ └── Air_Quality_Sensor.cpp ├── readme.md └── master │ └── master.ino └── Capacitive_touch_Pin └── Capacitive_touch_for_single-double-triple_TAP └── Capacitive_touch_for_single-double-triple_TAP.ino /README.md: -------------------------------------------------------------------------------- 1 | # ESP32-Codes 2 | ESP32 codes in .c and .cpp for various IOT tasks 3 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /ESP-IDF codes ( .C )/ADC/PIR-sensor-test1-MOTION/.gitignore: -------------------------------------------------------------------------------- 1 | build/ 2 | sdkconfig 3 | sdkconfig.old -------------------------------------------------------------------------------- /ESP-IDF codes ( .C )/Inputs/ISR_ONE_pin_only_TOUCH/.gitignore: -------------------------------------------------------------------------------- 1 | build/ 2 | sdkconfig 3 | sdkconfig.old -------------------------------------------------------------------------------- /ESP-IDF codes ( .C )/BT/Nimble_server/BLE_test1newLED_ON_OFF/.gitignore: -------------------------------------------------------------------------------- 1 | build/ 2 | sdkconfig 3 | sdkconfig.old -------------------------------------------------------------------------------- /ESP-IDF codes ( .C )/ADC/PIR-sensor-test1-MOTION/main/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | idf_component_register(SRCS "main.c" 2 | INCLUDE_DIRS ".") -------------------------------------------------------------------------------- /ESP-IDF codes ( .C )/Inputs/ISR_ONE_pin_only_TOUCH/main/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | idf_component_register(SRCS "main.c" 2 | INCLUDE_DIRS ".") -------------------------------------------------------------------------------- /ESP-IDF codes ( .C )/BT/Nimble_server/BLE_test1newLED_ON_OFF/main/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | idf_component_register(SRCS "main.c" 2 | INCLUDE_DIRS ".") -------------------------------------------------------------------------------- /ESP32 - arduino IDE codes ( .cpp )/WIFI/WIFI_MP3_playing_via_I2s/WIFI_MP3_playing_via_I2s/External libs/WIFI libs used/WiFiUdp.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "NetworkUdp.h" 3 | typedef NetworkUDP WiFiUDP; 4 | -------------------------------------------------------------------------------- /ESP32 - arduino IDE codes ( .cpp )/WIFI/WIFI_MP3_playing_via_I2s/WIFI_MP3_playing_via_I2s/External libs/WIFI libs used/WiFiClient.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "NetworkClient.h" 3 | typedef NetworkClient WiFiClient; 4 | -------------------------------------------------------------------------------- /ESP32 - arduino IDE codes ( .cpp )/WIFI/WIFI_MP3_playing_via_I2s/WIFI_MP3_playing_via_I2s/External libs/WIFI libs used/WiFiServer.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "NetworkServer.h" 3 | typedef NetworkServer WiFiServer; 4 | -------------------------------------------------------------------------------- /ESP-IDF codes ( .C )/ADC/PIR-sensor-test1-MOTION/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "type": "gdbtarget", 6 | "request": "attach", 7 | "name": "Eclipse CDT GDB Adapter" 8 | }, 9 | { 10 | "type": "espidf", 11 | "name": "Launch", 12 | "request": "launch" 13 | } 14 | ] 15 | } -------------------------------------------------------------------------------- /ESP-IDF codes ( .C )/Inputs/ISR_ONE_pin_only_TOUCH/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "type": "gdbtarget", 6 | "request": "attach", 7 | "name": "Eclipse CDT GDB Adapter" 8 | }, 9 | { 10 | "type": "espidf", 11 | "name": "Launch", 12 | "request": "launch" 13 | } 14 | ] 15 | } -------------------------------------------------------------------------------- /ESP-IDF codes ( .C )/BT/Nimble_server/BLE_test1newLED_ON_OFF/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "type": "gdbtarget", 6 | "request": "attach", 7 | "name": "Eclipse CDT GDB Adapter" 8 | }, 9 | { 10 | "type": "espidf", 11 | "name": "Launch", 12 | "request": "launch" 13 | } 14 | ] 15 | } -------------------------------------------------------------------------------- /ESP-IDF codes ( .C )/ADC/PIR-sensor-test1-MOTION/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # For more information about build system see 2 | # https://docs.espressif.com/projects/esp-idf/en/latest/api-guides/build-system.html 3 | # The following five lines of boilerplate have to be in your project's 4 | # CMakeLists in this exact order for cmake to work correctly 5 | cmake_minimum_required(VERSION 3.5) 6 | 7 | include($ENV{IDF_PATH}/tools/cmake/project.cmake) 8 | project(PIR-sensor-test1) -------------------------------------------------------------------------------- /ESP-IDF codes ( .C )/BT/Nimble_server/BLE_test1newLED_ON_OFF/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # For more information about build system see 2 | # https://docs.espressif.com/projects/esp-idf/en/latest/api-guides/build-system.html 3 | # The following five lines of boilerplate have to be in your project's 4 | # CMakeLists in this exact order for cmake to work correctly 5 | cmake_minimum_required(VERSION 3.5) 6 | 7 | include($ENV{IDF_PATH}/tools/cmake/project.cmake) 8 | project(BLE_test1new) -------------------------------------------------------------------------------- /ESP-IDF codes ( .C )/Inputs/ISR_ONE_pin_only_TOUCH/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # For more information about build system see 2 | # https://docs.espressif.com/projects/esp-idf/en/latest/api-guides/build-system.html 3 | # The following five lines of boilerplate have to be in your project's 4 | # CMakeLists in this exact order for cmake to work correctly 5 | cmake_minimum_required(VERSION 3.5) 6 | 7 | include($ENV{IDF_PATH}/tools/cmake/project.cmake) 8 | project(ISR_ONE_pin_only_TOUCH) -------------------------------------------------------------------------------- /ESP-IDF codes ( .C )/ADC/PIR-sensor-test1-MOTION/.vscode/c_cpp_properties.json: -------------------------------------------------------------------------------- 1 | { 2 | "configurations": [ 3 | { 4 | "name": "ESP-IDF", 5 | "compilerPath": "${config:idf.toolsPathWin}\\tools\\xtensa-esp-elf\\esp-13.2.0_20240530\\xtensa-esp-elf\\bin\\xtensa-esp32-elf-gcc.exe", 6 | "compileCommands": "${config:idf.buildPath}/compile_commands.json", 7 | "includePath": [ 8 | "${config:idf.espIdfPath}/components/**", 9 | "${config:idf.espIdfPathWin}/components/**", 10 | "${workspaceFolder}/**" 11 | ], 12 | "browse": { 13 | "path": [ 14 | "${config:idf.espIdfPath}/components", 15 | "${config:idf.espIdfPathWin}/components", 16 | "${workspaceFolder}" 17 | ], 18 | "limitSymbolsToIncludedHeaders": true 19 | } 20 | } 21 | ], 22 | "version": 4 23 | } 24 | -------------------------------------------------------------------------------- /ESP-IDF codes ( .C )/Inputs/ISR_ONE_pin_only_TOUCH/.vscode/c_cpp_properties.json: -------------------------------------------------------------------------------- 1 | { 2 | "configurations": [ 3 | { 4 | "name": "ESP-IDF", 5 | "compilerPath": "${config:idf.toolsPathWin}\\tools\\xtensa-esp-elf\\esp-13.2.0_20240530\\xtensa-esp-elf\\bin\\xtensa-esp32-elf-gcc.exe", 6 | "compileCommands": "${config:idf.buildPath}/compile_commands.json", 7 | "includePath": [ 8 | "${config:idf.espIdfPath}/components/**", 9 | "${config:idf.espIdfPathWin}/components/**", 10 | "${workspaceFolder}/**" 11 | ], 12 | "browse": { 13 | "path": [ 14 | "${config:idf.espIdfPath}/components", 15 | "${config:idf.espIdfPathWin}/components", 16 | "${workspaceFolder}" 17 | ], 18 | "limitSymbolsToIncludedHeaders": true 19 | } 20 | } 21 | ], 22 | "version": 4 23 | } 24 | -------------------------------------------------------------------------------- /ESP-IDF codes ( .C )/BT/Nimble_server/BLE_test1newLED_ON_OFF/.vscode/c_cpp_properties.json: -------------------------------------------------------------------------------- 1 | { 2 | "configurations": [ 3 | { 4 | "name": "ESP-IDF", 5 | "compilerPath": "${config:idf.toolsPathWin}\\tools\\xtensa-esp-elf\\esp-13.2.0_20240530\\xtensa-esp-elf\\bin\\xtensa-esp32-elf-gcc.exe", 6 | "compileCommands": "${config:idf.buildPath}/compile_commands.json", 7 | "includePath": [ 8 | "${config:idf.espIdfPath}/components/**", 9 | "${config:idf.espIdfPathWin}/components/**", 10 | "${workspaceFolder}/**" 11 | ], 12 | "browse": { 13 | "path": [ 14 | "${config:idf.espIdfPath}/components", 15 | "${config:idf.espIdfPathWin}/components", 16 | "${workspaceFolder}" 17 | ], 18 | "limitSymbolsToIncludedHeaders": true 19 | } 20 | } 21 | ], 22 | "version": 4 23 | } 24 | -------------------------------------------------------------------------------- /ESP-IDF codes ( .C )/ADC/PIR-sensor-test1-MOTION/.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ESP-IDF QEMU", 3 | "build": { 4 | "dockerfile": "Dockerfile" 5 | }, 6 | "customizations": { 7 | "vscode": { 8 | "settings": { 9 | "terminal.integrated.defaultProfile.linux": "bash", 10 | "idf.espIdfPath": "/opt/esp/idf", 11 | "idf.customExtraPaths": "", 12 | "idf.pythonBinPath": "/opt/esp/python_env/idf5.4_py3.12_env/bin/python", 13 | "idf.toolsPath": "/opt/esp", 14 | "idf.gitPath": "/usr/bin/git" 15 | }, 16 | "extensions": [ 17 | "espressif.esp-idf-extension" 18 | ] 19 | }, 20 | "codespaces": { 21 | "settings": { 22 | "terminal.integrated.defaultProfile.linux": "bash", 23 | "idf.espIdfPath": "/opt/esp/idf", 24 | "idf.customExtraPaths": "", 25 | "idf.pythonBinPath": "/opt/esp/python_env/idf5.4_py3.12_env/bin/python", 26 | "idf.toolsPath": "/opt/esp", 27 | "idf.gitPath": "/usr/bin/git" 28 | }, 29 | "extensions": [ 30 | "espressif.esp-idf-extension", 31 | "espressif.esp-idf-web" 32 | ] 33 | } 34 | }, 35 | "runArgs": ["--privileged"] 36 | } -------------------------------------------------------------------------------- /ESP-IDF codes ( .C )/Inputs/ISR_ONE_pin_only_TOUCH/.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ESP-IDF QEMU", 3 | "build": { 4 | "dockerfile": "Dockerfile" 5 | }, 6 | "customizations": { 7 | "vscode": { 8 | "settings": { 9 | "terminal.integrated.defaultProfile.linux": "bash", 10 | "idf.espIdfPath": "/opt/esp/idf", 11 | "idf.customExtraPaths": "", 12 | "idf.pythonBinPath": "/opt/esp/python_env/idf5.4_py3.12_env/bin/python", 13 | "idf.toolsPath": "/opt/esp", 14 | "idf.gitPath": "/usr/bin/git" 15 | }, 16 | "extensions": [ 17 | "espressif.esp-idf-extension" 18 | ] 19 | }, 20 | "codespaces": { 21 | "settings": { 22 | "terminal.integrated.defaultProfile.linux": "bash", 23 | "idf.espIdfPath": "/opt/esp/idf", 24 | "idf.customExtraPaths": "", 25 | "idf.pythonBinPath": "/opt/esp/python_env/idf5.4_py3.12_env/bin/python", 26 | "idf.toolsPath": "/opt/esp", 27 | "idf.gitPath": "/usr/bin/git" 28 | }, 29 | "extensions": [ 30 | "espressif.esp-idf-extension", 31 | "espressif.esp-idf-web" 32 | ] 33 | } 34 | }, 35 | "runArgs": ["--privileged"] 36 | } -------------------------------------------------------------------------------- /ESP-IDF codes ( .C )/BT/Nimble_server/BLE_test1newLED_ON_OFF/.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ESP-IDF QEMU", 3 | "build": { 4 | "dockerfile": "Dockerfile" 5 | }, 6 | "customizations": { 7 | "vscode": { 8 | "settings": { 9 | "terminal.integrated.defaultProfile.linux": "bash", 10 | "idf.espIdfPath": "/opt/esp/idf", 11 | "idf.customExtraPaths": "", 12 | "idf.pythonBinPath": "/opt/esp/python_env/idf5.4_py3.12_env/bin/python", 13 | "idf.toolsPath": "/opt/esp", 14 | "idf.gitPath": "/usr/bin/git" 15 | }, 16 | "extensions": [ 17 | "espressif.esp-idf-extension" 18 | ] 19 | }, 20 | "codespaces": { 21 | "settings": { 22 | "terminal.integrated.defaultProfile.linux": "bash", 23 | "idf.espIdfPath": "/opt/esp/idf", 24 | "idf.customExtraPaths": "", 25 | "idf.pythonBinPath": "/opt/esp/python_env/idf5.4_py3.12_env/bin/python", 26 | "idf.toolsPath": "/opt/esp", 27 | "idf.gitPath": "/usr/bin/git" 28 | }, 29 | "extensions": [ 30 | "espressif.esp-idf-extension", 31 | "espressif.esp-idf-web" 32 | ] 33 | } 34 | }, 35 | "runArgs": ["--privileged"] 36 | } -------------------------------------------------------------------------------- /ESP32 - arduino IDE codes ( .cpp )/WIFI/WIFI_MP3_playing_via_I2s/WIFI_MP3_playing_via_I2s/External libs/AUDIO libs used/aac_decoder/aac_decoder.h: -------------------------------------------------------------------------------- 1 | /* 2 | * aac_decoder.h 3 | * faad2 - ESP32 adaptation 4 | * Created on: 12.09.2023 5 | * Updated on: 13.08.2024 6 | */ 7 | 8 | 9 | #pragma once 10 | 11 | #include 12 | #pragma GCC diagnostic warning "-Wunused-function" 13 | 14 | struct AudioSpecificConfig { 15 | uint8_t audioObjectType; 16 | uint8_t samplingFrequencyIndex; 17 | uint8_t channelConfiguration; 18 | }; 19 | 20 | bool AACDecoder_IsInit(); 21 | bool AACDecoder_AllocateBuffers(); 22 | void AACDecoder_FreeBuffers(); 23 | uint8_t AACGetFormat(); 24 | uint8_t AACGetParametricStereo(); 25 | uint8_t AACGetSBR(); 26 | int AACFindSyncWord(uint8_t *buf, int nBytes); 27 | int AACSetRawBlockParams(int nChans, int sampRateCore, int profile); 28 | int16_t AACGetOutputSamps(); 29 | int AACGetBitrate(); 30 | int AACGetChannels(); 31 | int AACGetSampRate(); 32 | int AACGetBitsPerSample(); 33 | int AACDecode(uint8_t *inbuf, int32_t *bytesLeft, short *outbuf); 34 | const char* AACGetErrorMessage(int8_t err); 35 | -------------------------------------------------------------------------------- /ESP-IDF codes ( .C )/ADC/PIR-sensor-test1-MOTION/.devcontainer/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM espressif/idf 2 | 3 | ARG DEBIAN_FRONTEND=nointeractive 4 | ARG CONTAINER_USER=esp 5 | ARG USER_UID=1050 6 | ARG USER_GID=$USER_UID 7 | 8 | RUN apt-get update \ 9 | && apt install -y -q \ 10 | cmake \ 11 | git \ 12 | libglib2.0-0 \ 13 | libnuma1 \ 14 | libpixman-1-0 \ 15 | && rm -rf /var/lib/apt/lists/* 16 | 17 | # QEMU 18 | ENV QEMU_REL=esp_develop_8.2.0_20240122 19 | ENV QEMU_SHA256=e7c72ef5705ad1444d391711088c8717fc89f42e9bf6d1487f9c2a326b8cfa83 20 | ENV QEMU_DIST=qemu-xtensa-softmmu-${QEMU_REL}-x86_64-linux-gnu.tar.xz 21 | ENV QEMU_URL=https://github.com/espressif/qemu/releases/download/esp-develop-8.2.0-20240122/${QEMU_DIST} 22 | 23 | ENV LC_ALL=C.UTF-8 24 | ENV LANG=C.UTF-8 25 | 26 | RUN wget --no-verbose ${QEMU_URL} \ 27 | && echo "${QEMU_SHA256} *${QEMU_DIST}" | sha256sum --check --strict - \ 28 | && tar -xf $QEMU_DIST -C /opt \ 29 | && rm ${QEMU_DIST} 30 | 31 | ENV PATH=/opt/qemu/bin:${PATH} 32 | 33 | RUN groupadd --gid $USER_GID $CONTAINER_USER \ 34 | && adduser --uid $USER_UID --gid $USER_GID --disabled-password --gecos "" ${CONTAINER_USER} \ 35 | && usermod -a -G root $CONTAINER_USER && usermod -a -G dialout $CONTAINER_USER 36 | 37 | RUN chmod -R 775 /opt/esp/python_env/ 38 | 39 | USER ${CONTAINER_USER} 40 | ENV USER=${CONTAINER_USER} 41 | WORKDIR /home/${CONTAINER_USER} 42 | 43 | RUN echo "source /opt/esp/idf/export.sh > /dev/null 2>&1" >> ~/.bashrc 44 | 45 | ENTRYPOINT [ "/opt/esp/entrypoint.sh" ] 46 | 47 | CMD ["/bin/bash", "-c"] -------------------------------------------------------------------------------- /ESP-IDF codes ( .C )/Inputs/ISR_ONE_pin_only_TOUCH/.devcontainer/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM espressif/idf 2 | 3 | ARG DEBIAN_FRONTEND=nointeractive 4 | ARG CONTAINER_USER=esp 5 | ARG USER_UID=1050 6 | ARG USER_GID=$USER_UID 7 | 8 | RUN apt-get update \ 9 | && apt install -y -q \ 10 | cmake \ 11 | git \ 12 | libglib2.0-0 \ 13 | libnuma1 \ 14 | libpixman-1-0 \ 15 | && rm -rf /var/lib/apt/lists/* 16 | 17 | # QEMU 18 | ENV QEMU_REL=esp_develop_8.2.0_20240122 19 | ENV QEMU_SHA256=e7c72ef5705ad1444d391711088c8717fc89f42e9bf6d1487f9c2a326b8cfa83 20 | ENV QEMU_DIST=qemu-xtensa-softmmu-${QEMU_REL}-x86_64-linux-gnu.tar.xz 21 | ENV QEMU_URL=https://github.com/espressif/qemu/releases/download/esp-develop-8.2.0-20240122/${QEMU_DIST} 22 | 23 | ENV LC_ALL=C.UTF-8 24 | ENV LANG=C.UTF-8 25 | 26 | RUN wget --no-verbose ${QEMU_URL} \ 27 | && echo "${QEMU_SHA256} *${QEMU_DIST}" | sha256sum --check --strict - \ 28 | && tar -xf $QEMU_DIST -C /opt \ 29 | && rm ${QEMU_DIST} 30 | 31 | ENV PATH=/opt/qemu/bin:${PATH} 32 | 33 | RUN groupadd --gid $USER_GID $CONTAINER_USER \ 34 | && adduser --uid $USER_UID --gid $USER_GID --disabled-password --gecos "" ${CONTAINER_USER} \ 35 | && usermod -a -G root $CONTAINER_USER && usermod -a -G dialout $CONTAINER_USER 36 | 37 | RUN chmod -R 775 /opt/esp/python_env/ 38 | 39 | USER ${CONTAINER_USER} 40 | ENV USER=${CONTAINER_USER} 41 | WORKDIR /home/${CONTAINER_USER} 42 | 43 | RUN echo "source /opt/esp/idf/export.sh > /dev/null 2>&1" >> ~/.bashrc 44 | 45 | ENTRYPOINT [ "/opt/esp/entrypoint.sh" ] 46 | 47 | CMD ["/bin/bash", "-c"] -------------------------------------------------------------------------------- /ESP32 - arduino IDE codes ( .cpp )/PWM/PWM_led_c_library/PWM_led_c_library.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include "driver/ledc.h" 3 | #include "freertos/FreeRTOS.h" 4 | #include "freertos/task.h" 5 | 6 | #define LEDC_CHANNEL LEDC_CHANNEL_0 7 | #define LEDC_TIMER LEDC_TIMER_0 8 | #define LEDC_MODE LEDC_HIGH_SPEED_MODE 9 | #define LEDC_OUTPUT_IO 21 //18 // Use GPIO 18 (adjust as needed) 10 | #define LEDC_DUTY_RES LEDC_TIMER_8_BIT 11 | #define LEDC_FREQUENCY 2400000 //113000//5000 // PWM frequency in Hertz (5 kHz) 12 | 13 | void setup() { 14 | // Configure the LEDC timer 15 | ledc_timer_config_t ledc_timer = { 16 | .speed_mode = LEDC_MODE, 17 | .duty_resolution = LEDC_DUTY_RES, 18 | .timer_num = LEDC_TIMER, 19 | .freq_hz = LEDC_FREQUENCY, 20 | .clk_cfg = LEDC_AUTO_CLK 21 | }; 22 | ledc_timer_config(&ledc_timer); 23 | 24 | // Configure the LEDC channel for PWM output 25 | ledc_channel_config_t ledc_channel = { 26 | .gpio_num = LEDC_OUTPUT_IO, 27 | .speed_mode = LEDC_MODE, 28 | .channel = LEDC_CHANNEL, 29 | .intr_type = LEDC_INTR_DISABLE, 30 | .timer_sel = LEDC_TIMER, 31 | .duty = 128, // 50% duty cycle (range 0–255 for 8-bit resolution) 32 | .hpoint = 0 33 | }; 34 | ledc_channel_config(&ledc_channel); 35 | } 36 | 37 | void loop() { 38 | // Nothing needed here; PWM is handled by hardware. 39 | delay(1000); 40 | } 41 | -------------------------------------------------------------------------------- /ESP-IDF codes ( .C )/BT/Nimble_server/BLE_test1newLED_ON_OFF/.devcontainer/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM espressif/idf 2 | 3 | ARG DEBIAN_FRONTEND=nointeractive 4 | ARG CONTAINER_USER=esp 5 | ARG USER_UID=1050 6 | ARG USER_GID=$USER_UID 7 | 8 | RUN apt-get update \ 9 | && apt install -y -q \ 10 | cmake \ 11 | git \ 12 | libglib2.0-0 \ 13 | libnuma1 \ 14 | libpixman-1-0 \ 15 | && rm -rf /var/lib/apt/lists/* 16 | 17 | # QEMU 18 | ENV QEMU_REL=esp_develop_8.2.0_20240122 19 | ENV QEMU_SHA256=e7c72ef5705ad1444d391711088c8717fc89f42e9bf6d1487f9c2a326b8cfa83 20 | ENV QEMU_DIST=qemu-xtensa-softmmu-${QEMU_REL}-x86_64-linux-gnu.tar.xz 21 | ENV QEMU_URL=https://github.com/espressif/qemu/releases/download/esp-develop-8.2.0-20240122/${QEMU_DIST} 22 | 23 | ENV LC_ALL=C.UTF-8 24 | ENV LANG=C.UTF-8 25 | 26 | RUN wget --no-verbose ${QEMU_URL} \ 27 | && echo "${QEMU_SHA256} *${QEMU_DIST}" | sha256sum --check --strict - \ 28 | && tar -xf $QEMU_DIST -C /opt \ 29 | && rm ${QEMU_DIST} 30 | 31 | ENV PATH=/opt/qemu/bin:${PATH} 32 | 33 | RUN groupadd --gid $USER_GID $CONTAINER_USER \ 34 | && adduser --uid $USER_UID --gid $USER_GID --disabled-password --gecos "" ${CONTAINER_USER} \ 35 | && usermod -a -G root $CONTAINER_USER && usermod -a -G dialout $CONTAINER_USER 36 | 37 | RUN chmod -R 775 /opt/esp/python_env/ 38 | 39 | USER ${CONTAINER_USER} 40 | ENV USER=${CONTAINER_USER} 41 | WORKDIR /home/${CONTAINER_USER} 42 | 43 | RUN echo "source /opt/esp/idf/export.sh > /dev/null 2>&1" >> ~/.bashrc 44 | 45 | ENTRYPOINT [ "/opt/esp/entrypoint.sh" ] 46 | 47 | CMD ["/bin/bash", "-c"] -------------------------------------------------------------------------------- /ESP-IDF codes ( .C )/ADC/PIR-sensor-test1-MOTION/README.md: -------------------------------------------------------------------------------- 1 | # _Sample project_ 2 | 3 | (See the README.md file in the upper level 'examples' directory for more information about examples.) 4 | 5 | This is the simplest buildable example. The example is used by command `idf.py create-project` 6 | that copies the project to user specified path and set it's name. For more information follow the [docs page](https://docs.espressif.com/projects/esp-idf/en/latest/api-guides/build-system.html#start-a-new-project) 7 | 8 | 9 | 10 | ## How to use example 11 | We encourage the users to use the example as a template for the new projects. 12 | A recommended way is to follow the instructions on a [docs page](https://docs.espressif.com/projects/esp-idf/en/latest/api-guides/build-system.html#start-a-new-project). 13 | 14 | ## Example folder contents 15 | 16 | The project **sample_project** contains one source file in C language [main.c](main/main.c). The file is located in folder [main](main). 17 | 18 | ESP-IDF projects are built using CMake. The project build configuration is contained in `CMakeLists.txt` 19 | files that provide set of directives and instructions describing the project's source files and targets 20 | (executable, library, or both). 21 | 22 | Below is short explanation of remaining files in the project folder. 23 | 24 | ``` 25 | ├── CMakeLists.txt 26 | ├── main 27 | │   ├── CMakeLists.txt 28 | │   └── main.c 29 | └── README.md This is the file you are currently reading 30 | ``` 31 | Additionally, the sample project contains Makefile and component.mk files, used for the legacy Make based build system. 32 | They are not used or needed when building with CMake and idf.py. 33 | -------------------------------------------------------------------------------- /ESP-IDF codes ( .C )/Inputs/ISR_ONE_pin_only_TOUCH/README.md: -------------------------------------------------------------------------------- 1 | # _Sample project_ 2 | 3 | (See the README.md file in the upper level 'examples' directory for more information about examples.) 4 | 5 | This is the simplest buildable example. The example is used by command `idf.py create-project` 6 | that copies the project to user specified path and set it's name. For more information follow the [docs page](https://docs.espressif.com/projects/esp-idf/en/latest/api-guides/build-system.html#start-a-new-project) 7 | 8 | 9 | 10 | ## How to use example 11 | We encourage the users to use the example as a template for the new projects. 12 | A recommended way is to follow the instructions on a [docs page](https://docs.espressif.com/projects/esp-idf/en/latest/api-guides/build-system.html#start-a-new-project). 13 | 14 | ## Example folder contents 15 | 16 | The project **sample_project** contains one source file in C language [main.c](main/main.c). The file is located in folder [main](main). 17 | 18 | ESP-IDF projects are built using CMake. The project build configuration is contained in `CMakeLists.txt` 19 | files that provide set of directives and instructions describing the project's source files and targets 20 | (executable, library, or both). 21 | 22 | Below is short explanation of remaining files in the project folder. 23 | 24 | ``` 25 | ├── CMakeLists.txt 26 | ├── main 27 | │   ├── CMakeLists.txt 28 | │   └── main.c 29 | └── README.md This is the file you are currently reading 30 | ``` 31 | Additionally, the sample project contains Makefile and component.mk files, used for the legacy Make based build system. 32 | They are not used or needed when building with CMake and idf.py. 33 | -------------------------------------------------------------------------------- /ESP-IDF codes ( .C )/BT/Nimble_server/BLE_test1newLED_ON_OFF/README.md: -------------------------------------------------------------------------------- 1 | # _Sample project_ 2 | 3 | (See the README.md file in the upper level 'examples' directory for more information about examples.) 4 | 5 | This is the simplest buildable example. The example is used by command `idf.py create-project` 6 | that copies the project to user specified path and set it's name. For more information follow the [docs page](https://docs.espressif.com/projects/esp-idf/en/latest/api-guides/build-system.html#start-a-new-project) 7 | 8 | 9 | 10 | ## How to use example 11 | We encourage the users to use the example as a template for the new projects. 12 | A recommended way is to follow the instructions on a [docs page](https://docs.espressif.com/projects/esp-idf/en/latest/api-guides/build-system.html#start-a-new-project). 13 | 14 | ## Example folder contents 15 | 16 | The project **sample_project** contains one source file in C language [main.c](main/main.c). The file is located in folder [main](main). 17 | 18 | ESP-IDF projects are built using CMake. The project build configuration is contained in `CMakeLists.txt` 19 | files that provide set of directives and instructions describing the project's source files and targets 20 | (executable, library, or both). 21 | 22 | Below is short explanation of remaining files in the project folder. 23 | 24 | ``` 25 | ├── CMakeLists.txt 26 | ├── main 27 | │   ├── CMakeLists.txt 28 | │   └── main.c 29 | └── README.md This is the file you are currently reading 30 | ``` 31 | Additionally, the sample project contains Makefile and component.mk files, used for the legacy Make based build system. 32 | They are not used or needed when building with CMake and idf.py. 33 | -------------------------------------------------------------------------------- /ESP-IDF codes ( .C )/ADC/PIR-sensor-test1-MOTION/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "C_Cpp.intelliSenseEngine": "default", 3 | "idf.adapterTargetName": "esp32", 4 | "idf.customExtraPaths": "C:\\Users\\Vignesh\\.espressif\\tools\\xtensa-esp-elf-gdb\\14.2_20240403\\xtensa-esp-elf-gdb\\bin;C:\\Users\\Vignesh\\.espressif\\tools\\riscv32-esp-elf-gdb\\14.2_20240403\\riscv32-esp-elf-gdb\\bin;C:\\Users\\Vignesh\\.espressif\\tools\\xtensa-esp-elf\\esp-13.2.0_20240530\\xtensa-esp-elf\\bin;C:\\Users\\Vignesh\\.espressif\\tools\\riscv32-esp-elf\\esp-13.2.0_20240530\\riscv32-esp-elf\\bin;C:\\Users\\Vignesh\\.espressif\\tools\\esp32ulp-elf\\2.38_20240113\\esp32ulp-elf\\bin;C:\\Users\\Vignesh\\.espressif\\tools\\cmake\\3.24.0\\bin;C:\\Users\\Vignesh\\.espressif\\tools\\openocd-esp32\\v0.12.0-esp32-20240318\\openocd-esp32\\bin;C:\\Users\\Vignesh\\.espressif\\tools\\ninja\\1.11.1;C:\\Users\\Vignesh\\.espressif\\tools\\idf-exe\\1.0.3;C:\\Users\\Vignesh\\.espressif\\tools\\ccache\\4.8\\ccache-4.8-windows-x86_64;C:\\Users\\Vignesh\\.espressif\\tools\\dfu-util\\0.11\\dfu-util-0.11-win64;C:\\Users\\Vignesh\\.espressif\\tools\\esp-rom-elfs\\20240305", 5 | "idf.customExtraVars": { 6 | "OPENOCD_SCRIPTS": "C:\\Users\\Vignesh\\.espressif\\tools\\openocd-esp32\\v0.12.0-esp32-20240318/openocd-esp32/share/openocd/scripts", 7 | "IDF_CCACHE_ENABLE": "1", 8 | "ESP_ROM_ELF_DIR": "C:\\Users\\Vignesh\\.espressif\\tools\\esp-rom-elfs\\20240305/" 9 | }, 10 | "idf.espIdfPathWin": "C:\\Users\\Vignesh\\esp\\v5.3.1\\esp-idf", 11 | "idf.openOcdConfigs": [ 12 | "board/esp32-wrover-kit-3.3v.cfg" 13 | ], 14 | "idf.portWin": "COM5", 15 | "idf.pythonBinPathWin": "C:\\Users\\Vignesh\\.espressif\\python_env\\idf5.3_py3.11_env\\Scripts\\python.exe", 16 | "idf.toolsPathWin": "C:\\Users\\Vignesh\\.espressif", 17 | "idf.flashType": "UART" 18 | } 19 | -------------------------------------------------------------------------------- /ESP-IDF codes ( .C )/Inputs/ISR_ONE_pin_only_TOUCH/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "C_Cpp.intelliSenseEngine": "default", 3 | "idf.adapterTargetName": "esp32", 4 | "idf.customExtraPaths": "C:\\Users\\Vignesh\\.espressif\\tools\\xtensa-esp-elf-gdb\\14.2_20240403\\xtensa-esp-elf-gdb\\bin;C:\\Users\\Vignesh\\.espressif\\tools\\riscv32-esp-elf-gdb\\14.2_20240403\\riscv32-esp-elf-gdb\\bin;C:\\Users\\Vignesh\\.espressif\\tools\\xtensa-esp-elf\\esp-13.2.0_20240530\\xtensa-esp-elf\\bin;C:\\Users\\Vignesh\\.espressif\\tools\\riscv32-esp-elf\\esp-13.2.0_20240530\\riscv32-esp-elf\\bin;C:\\Users\\Vignesh\\.espressif\\tools\\esp32ulp-elf\\2.38_20240113\\esp32ulp-elf\\bin;C:\\Users\\Vignesh\\.espressif\\tools\\cmake\\3.24.0\\bin;C:\\Users\\Vignesh\\.espressif\\tools\\openocd-esp32\\v0.12.0-esp32-20240318\\openocd-esp32\\bin;C:\\Users\\Vignesh\\.espressif\\tools\\ninja\\1.11.1;C:\\Users\\Vignesh\\.espressif\\tools\\idf-exe\\1.0.3;C:\\Users\\Vignesh\\.espressif\\tools\\ccache\\4.8\\ccache-4.8-windows-x86_64;C:\\Users\\Vignesh\\.espressif\\tools\\dfu-util\\0.11\\dfu-util-0.11-win64;C:\\Users\\Vignesh\\.espressif\\tools\\esp-rom-elfs\\20240305", 5 | "idf.customExtraVars": { 6 | "OPENOCD_SCRIPTS": "C:\\Users\\Vignesh\\.espressif\\tools\\openocd-esp32\\v0.12.0-esp32-20240318/openocd-esp32/share/openocd/scripts", 7 | "IDF_CCACHE_ENABLE": "1", 8 | "ESP_ROM_ELF_DIR": "C:\\Users\\Vignesh\\.espressif\\tools\\esp-rom-elfs\\20240305/" 9 | }, 10 | "idf.espIdfPathWin": "C:\\Users\\Vignesh\\esp\\v5.3.1\\esp-idf", 11 | "idf.openOcdConfigs": [ 12 | "board/esp32-wrover-kit-3.3v.cfg" 13 | ], 14 | "idf.portWin": "COM5", 15 | "idf.pythonBinPathWin": "C:\\Users\\Vignesh\\.espressif\\python_env\\idf5.3_py3.11_env\\Scripts\\python.exe", 16 | "idf.toolsPathWin": "C:\\Users\\Vignesh\\.espressif", 17 | "idf.flashType": "UART" 18 | } 19 | -------------------------------------------------------------------------------- /ESP-IDF codes ( .C )/BT/Nimble_server/BLE_test1newLED_ON_OFF/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "C_Cpp.intelliSenseEngine": "default", 3 | "idf.adapterTargetName": "esp32", 4 | "idf.customExtraPaths": "C:\\Users\\Vignesh\\.espressif\\tools\\xtensa-esp-elf-gdb\\14.2_20240403\\xtensa-esp-elf-gdb\\bin;C:\\Users\\Vignesh\\.espressif\\tools\\riscv32-esp-elf-gdb\\14.2_20240403\\riscv32-esp-elf-gdb\\bin;C:\\Users\\Vignesh\\.espressif\\tools\\xtensa-esp-elf\\esp-13.2.0_20240530\\xtensa-esp-elf\\bin;C:\\Users\\Vignesh\\.espressif\\tools\\riscv32-esp-elf\\esp-13.2.0_20240530\\riscv32-esp-elf\\bin;C:\\Users\\Vignesh\\.espressif\\tools\\esp32ulp-elf\\2.38_20240113\\esp32ulp-elf\\bin;C:\\Users\\Vignesh\\.espressif\\tools\\cmake\\3.24.0\\bin;C:\\Users\\Vignesh\\.espressif\\tools\\openocd-esp32\\v0.12.0-esp32-20240318\\openocd-esp32\\bin;C:\\Users\\Vignesh\\.espressif\\tools\\ninja\\1.11.1;C:\\Users\\Vignesh\\.espressif\\tools\\idf-exe\\1.0.3;C:\\Users\\Vignesh\\.espressif\\tools\\ccache\\4.8\\ccache-4.8-windows-x86_64;C:\\Users\\Vignesh\\.espressif\\tools\\dfu-util\\0.11\\dfu-util-0.11-win64;C:\\Users\\Vignesh\\.espressif\\tools\\esp-rom-elfs\\20240305", 5 | "idf.customExtraVars": { 6 | "OPENOCD_SCRIPTS": "C:\\Users\\Vignesh\\.espressif\\tools\\openocd-esp32\\v0.12.0-esp32-20240318/openocd-esp32/share/openocd/scripts", 7 | "IDF_CCACHE_ENABLE": "1", 8 | "ESP_ROM_ELF_DIR": "C:\\Users\\Vignesh\\.espressif\\tools\\esp-rom-elfs\\20240305/" 9 | }, 10 | "idf.espIdfPathWin": "C:\\Users\\Vignesh\\esp\\v5.3.1\\esp-idf", 11 | "idf.openOcdConfigs": [ 12 | "board/esp32-wrover-kit-3.3v.cfg" 13 | ], 14 | "idf.portWin": "COM5", 15 | "idf.pythonBinPathWin": "C:\\Users\\Vignesh\\.espressif\\python_env\\idf5.3_py3.11_env\\Scripts\\python.exe", 16 | "idf.toolsPathWin": "C:\\Users\\Vignesh\\.espressif", 17 | "idf.flashType": "UART" 18 | } 19 | -------------------------------------------------------------------------------- /ESP32 - arduino IDE codes ( .cpp )/WIFI/WIFI_MP3_playing_via_I2s/WIFI_MP3_playing_via_I2s/External libs/WIFI libs used/WiFiType.h: -------------------------------------------------------------------------------- 1 | /* 2 | ESP8266WiFiType.h - esp8266 Wifi support. 3 | Copyright (c) 2011-2014 Arduino. All right reserved. 4 | Modified by Ivan Grokhotkov, December 2014 5 | Reworked by Markus Sattler, December 2015 6 | 7 | This library is free software; you can redistribute it and/or 8 | modify it under the terms of the GNU Lesser General Public 9 | License as published by the Free Software Foundation; either 10 | version 2.1 of the License, or (at your option) any later version. 11 | 12 | This library is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 | Lesser General Public License for more details. 16 | 17 | You should have received a copy of the GNU Lesser General Public 18 | License along with this library; if not, write to the Free Software 19 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 20 | */ 21 | 22 | #pragma once 23 | 24 | #include "soc/soc_caps.h" 25 | #include "sdkconfig.h" 26 | #if SOC_WIFI_SUPPORTED || CONFIG_ESP_WIFI_REMOTE_ENABLED 27 | 28 | #include "esp_wifi_types.h" 29 | 30 | #define WIFI_SCAN_RUNNING (-1) 31 | #define WIFI_SCAN_FAILED (-2) 32 | 33 | #define WiFiMode_t wifi_mode_t 34 | #define WIFI_OFF WIFI_MODE_NULL 35 | #define WIFI_STA WIFI_MODE_STA 36 | #define WIFI_AP WIFI_MODE_AP 37 | #define WIFI_AP_STA WIFI_MODE_APSTA 38 | 39 | #define WiFiEvent_t arduino_event_id_t 40 | #define WiFiEventInfo_t arduino_event_info_t 41 | #define WiFiEventId_t wifi_event_id_t 42 | 43 | typedef enum { 44 | WL_NO_SHIELD = 255, // for compatibility with WiFi Shield library 45 | WL_STOPPED = 254, 46 | WL_IDLE_STATUS = 0, 47 | WL_NO_SSID_AVAIL = 1, 48 | WL_SCAN_COMPLETED = 2, 49 | WL_CONNECTED = 3, 50 | WL_CONNECT_FAILED = 4, 51 | WL_CONNECTION_LOST = 5, 52 | WL_DISCONNECTED = 6 53 | } wl_status_t; 54 | 55 | #endif /* SOC_WIFI_SUPPORTED */ 56 | -------------------------------------------------------------------------------- /ESP32 - arduino IDE codes ( .cpp )/PWM/PWM_mcpwm_header/PWM_mcpwm_header.ino: -------------------------------------------------------------------------------- 1 | #include "driver/mcpwm.h" 2 | 3 | // Use only one pin: GPIO 21 for MCPWM0A 4 | #define PWM_PIN_A 21 5 | // #define PWM_PIN_B 19 // Complementary output (not used) 6 | 7 | void setup() { 8 | Serial.begin(115200); 9 | 10 | // Initialize the MCPWM GPIO pin for channel A on MCPWM_UNIT_0 11 | mcpwm_gpio_init(MCPWM_UNIT_0, MCPWM0A, PWM_PIN_A); 12 | // The complementary channel is commented out: 13 | // mcpwm_gpio_init(MCPWM_UNIT_0, MCPWM0B, PWM_PIN_B); 14 | 15 | // Configure PWM parameters 16 | mcpwm_config_t pwm_config; 17 | pwm_config.frequency = 2400000; //113000;// 2000; // PWM frequency: 2 kHz 18 | pwm_config.cmpr_a = 50; //30; // Initial duty cycle: 30% on channel A // Constant duty cycle: 50% on channel A 19 | pwm_config.cmpr_b = 50; //30; // Duty cycle for channel B (not used) 20 | pwm_config.counter_mode = MCPWM_UP_COUNTER; 21 | pwm_config.duty_mode = MCPWM_DUTY_MODE_0; 22 | 23 | // Initialize MCPWM Timer 0 on MCPWM_UNIT_0 with the configuration 24 | mcpwm_init(MCPWM_UNIT_0, MCPWM_TIMER_0, &pwm_config); 25 | 26 | // Dead time configuration is omitted since we are not using the complementary channel 27 | // mcpwm_deadtime_enable(MCPWM_UNIT_0, MCPWM_TIMER_0, MCPWM_ACTIVE_HIGH_COMPLIMENT_MODE, 10, 10); 28 | 29 | // Start PWM output 30 | mcpwm_start(MCPWM_UNIT_0, MCPWM_TIMER_0); 31 | } 32 | 33 | void loop() { 34 | 35 | 36 | // No changes here: PWM output remains constant at 50% duty cycle. 37 | delay(1000); 38 | 39 | 40 | 41 | /* for dim in and out looping 42 | // Sweep the duty cycle on channel A from 10% to 90% and back 43 | for (int duty = 10; duty <= 90; duty += 2) { 44 | mcpwm_set_duty(MCPWM_UNIT_0, MCPWM_TIMER_0, MCPWM_OPR_A, duty); 45 | // mcpwm_set_duty(MCPWM_UNIT_0, MCPWM_TIMER_0, MCPWM_OPR_B, duty); // Not used 46 | delay(50); 47 | } 48 | for (int duty = 90; duty >= 10; duty -= 2) { 49 | mcpwm_set_duty(MCPWM_UNIT_0, MCPWM_TIMER_0, MCPWM_OPR_A, duty); 50 | // mcpwm_set_duty(MCPWM_UNIT_0, MCPWM_TIMER_0, MCPWM_OPR_B, duty); // Not used 51 | delay(50); 52 | } 53 | 54 | */ 55 | } 56 | -------------------------------------------------------------------------------- /ESP32 - arduino IDE codes ( .cpp )/I2C MASTER-SLAVE/SLAVE/Slave/Air_Quality_Sensor.h: -------------------------------------------------------------------------------- 1 | /* 2 | Air_Quality_Sensor.h 3 | Header file for Grove - Air Quality Sensor. 4 | 5 | Copyright (c) 2019 seeed technology inc. 6 | Author : Lets Blu 7 | Created Time : Jan 2019 8 | Modified Time: 9 | 10 | The MIT License (MIT) 11 | 12 | Permission is hereby granted, free of charge, to any person obtaining a copy 13 | of this software and associated documentation files (the "Software"), to deal 14 | in the Software without restriction, including without limitation the rights 15 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 16 | copies of the Software, and to permit persons to whom the Software is 17 | furnished to do so, subject to the following conditions: 18 | 19 | The above copyright notice and this permission notice shall be included in 20 | all copies or substantial portions of the Software. 21 | 22 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 23 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 24 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 25 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 26 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 27 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 28 | THE SOFTWARE. 29 | */ 30 | #ifndef __AIR_QUALITY_SENSOR_H__ 31 | #define __AIR_QUALITY_SENSOR_H__ 32 | 33 | #include "Arduino.h" 34 | 35 | class AirQualitySensor { 36 | public: 37 | AirQualitySensor(int pin); 38 | 39 | bool init(void); 40 | int slope(void); 41 | int getValue(void); 42 | 43 | static const int FORCE_SIGNAL; 44 | static const int HIGH_POLLUTION; 45 | static const int LOW_POLLUTION; 46 | static const int FRESH_AIR; 47 | 48 | protected: 49 | int _pin; 50 | 51 | int _lastVoltage; 52 | int _currentVoltage; 53 | int _standardVoltage; 54 | 55 | long _voltageSum; 56 | int _volSumCount; 57 | long _lastStdVolUpdated; 58 | 59 | void updateStandardVoltage(void); 60 | }; 61 | 62 | #endif // __AIR_QUALITY_SENSOR_H__ 63 | -------------------------------------------------------------------------------- /ESP32 - arduino IDE codes ( .cpp )/Capacitive_touch_Pin/Capacitive_touch_for_single-double-triple_TAP/Capacitive_touch_for_single-double-triple_TAP.ino: -------------------------------------------------------------------------------- 1 | #define TAP_PIN1 4 // GPIO4 2 | int threshold = 30; // Adjust based on calibration 3 | 4 | // Timing thresholds in milliseconds 5 | const unsigned long singleTapMaxDuration = 500; // Max duration for a single tap 6 | const unsigned long doubleTapMaxInterval = 500; // Max interval between two taps for a double tap 7 | const unsigned long tripleTapMaxInterval = 500; // Max interval between three taps for a triple tap 8 | 9 | enum TapType { 10 | NO_TAP, 11 | SINGLE_TAP, 12 | DOUBLE_TAP, 13 | TRIPLE_TAP 14 | }; 15 | 16 | unsigned long lastTapTime = 0; 17 | int tapCount = 0; 18 | 19 | void setup() { 20 | Serial.begin(115200); // Initialize serial communication at 115200 baud 21 | } 22 | 23 | void loop() { 24 | static bool touchRegistered = false; 25 | unsigned long currentTime = millis(); 26 | uint16_t capacitiveValueLevel1 = touchRead(TAP_PIN1); 27 | 28 | if (capacitiveValueLevel1 < threshold) { 29 | if (!touchRegistered) { 30 | touchRegistered = true; 31 | tapCount++; 32 | lastTapTime = currentTime; 33 | } 34 | } else { 35 | touchRegistered = false; 36 | } 37 | 38 | if (tapCount > 0 && (currentTime - lastTapTime > doubleTapMaxInterval)) { 39 | TapType tapType = identifyTapType(tapCount); 40 | executeTapAction(tapType); 41 | tapCount = 0; 42 | } 43 | 44 | delay(10); // Short delay to debounce touch readings 45 | } 46 | 47 | TapType identifyTapType(int count) { 48 | switch (count) { 49 | case 1: 50 | return SINGLE_TAP; 51 | case 2: 52 | return DOUBLE_TAP; 53 | case 3: 54 | return TRIPLE_TAP; 55 | default: 56 | return NO_TAP; 57 | } 58 | } 59 | 60 | void executeTapAction(TapType tapType) { 61 | switch (tapType) { 62 | case SINGLE_TAP: 63 | Serial.println("Single Tap Detected"); 64 | // Add action for single tap here 65 | break; 66 | case DOUBLE_TAP: 67 | Serial.println("Double Tap Detected"); 68 | // Add action for double tap here 69 | break; 70 | case TRIPLE_TAP: 71 | Serial.println("Triple Tap Detected"); 72 | // Add action for triple tap here 73 | break; 74 | default: 75 | break; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /ESP32 - arduino IDE codes ( .cpp )/PWM/PWM_usingTImer_bit/PWM_usingTImer_bit.ino: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Global settings: set the PWM output pin and initial frequency (in Hz) 4 | const int pwmPin = 21; //18; // PWM output pin (change as needed) 5 | volatile uint32_t pwmFrequency = 2400000;//113000; // Initial PWM frequency (113 kHz) 6 | 7 | // esp_timer handle for our periodic callback 8 | esp_timer_handle_t periodic_timer = NULL; 9 | 10 | // Variable to hold the current state of the pin (HIGH or LOW) 11 | volatile bool pinState = false; 12 | 13 | // Timer callback that toggles the PWM output 14 | void IRAM_ATTR onTimer(void* arg) { 15 | // Toggle the pin state 16 | pinState = !pinState; 17 | digitalWrite(pwmPin, pinState); 18 | } 19 | 20 | // Function to update the timer period according to the current pwmFrequency. 21 | // The timer is configured so that each callback toggles the pin, which is half the PWM period. 22 | // Hence, half_period (in microseconds) = 1e6 / (2 * pwmFrequency) 23 | void updateTimerPeriod() { 24 | uint64_t half_period_us = 1000000ULL / (2 * pwmFrequency); 25 | // Ensure we have at least 1 µs period (esp_timer resolution) 26 | if (half_period_us < 1) { 27 | half_period_us = 1; 28 | } 29 | 30 | // Stop the timer before updating its period 31 | esp_timer_stop(periodic_timer); 32 | // Restart the timer with the new period (in microseconds) 33 | esp_timer_start_periodic(periodic_timer, half_period_us); 34 | } 35 | 36 | void setup() { 37 | Serial.begin(115200); 38 | // Initialize the PWM pin as an output 39 | pinMode(pwmPin, OUTPUT); 40 | 41 | // Create the esp_timer that will call onTimer periodically 42 | const esp_timer_create_args_t timer_args = { 43 | .callback = &onTimer, 44 | .arg = NULL, 45 | .name = "PWM_Timer" 46 | }; 47 | esp_timer_create(&timer_args, &periodic_timer); 48 | 49 | // Set the initial timer period based on pwmFrequency 50 | updateTimerPeriod(); 51 | 52 | Serial.print("PWM running on pin "); 53 | Serial.print(pwmPin); 54 | Serial.print(" at "); 55 | Serial.print(pwmFrequency); 56 | Serial.println(" Hz"); 57 | } 58 | 59 | void loop() { 60 | // In this example, we do nothing in loop. 61 | // If you want to change the frequency at runtime, 62 | // update 'pwmFrequency' and then call updateTimerPeriod(). 63 | delay(1000); 64 | } 65 | -------------------------------------------------------------------------------- /ESP32 - arduino IDE codes ( .cpp )/WIFI/WIFI_MP3_playing_via_I2s/WIFI_MP3_playing_via_I2s/External libs/WIFI libs used/WiFi.h: -------------------------------------------------------------------------------- 1 | /* 2 | WiFi.h - esp32 Wifi support. 3 | Based on WiFi.h from Arduino WiFi shield library. 4 | Copyright (c) 2011-2014 Arduino. All right reserved. 5 | Modified by Ivan Grokhotkov, December 2014 6 | 7 | This library is free software; you can redistribute it and/or 8 | modify it under the terms of the GNU Lesser General Public 9 | License as published by the Free Software Foundation; either 10 | version 2.1 of the License, or (at your option) any later version. 11 | 12 | This library is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 | Lesser General Public License for more details. 16 | 17 | You should have received a copy of the GNU Lesser General Public 18 | License along with this library; if not, write to the Free Software 19 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 20 | */ 21 | 22 | #pragma once 23 | 24 | #include "soc/soc_caps.h" 25 | #include "sdkconfig.h" 26 | #if SOC_WIFI_SUPPORTED || CONFIG_ESP_WIFI_REMOTE_ENABLED 27 | 28 | #include 29 | 30 | #include "Print.h" 31 | #include "IPAddress.h" 32 | 33 | #include "WiFiType.h" 34 | #include "WiFiSTA.h" 35 | #include "WiFiAP.h" 36 | #include "WiFiScan.h" 37 | #include "WiFiGeneric.h" 38 | 39 | #include "WiFiClient.h" 40 | #include "WiFiServer.h" 41 | #include "WiFiUdp.h" 42 | 43 | class WiFiClass : public WiFiGenericClass, public WiFiSTAClass, public WiFiScanClass, public WiFiAPClass { 44 | private: 45 | bool prov_enable; 46 | 47 | public: 48 | WiFiClass() { 49 | prov_enable = false; 50 | } 51 | 52 | using WiFiGenericClass::channel; 53 | 54 | using WiFiSTAClass::BSSID; 55 | using WiFiSTAClass::BSSIDstr; 56 | using WiFiSTAClass::RSSI; 57 | using WiFiSTAClass::SSID; 58 | 59 | using WiFiScanClass::BSSID; 60 | using WiFiScanClass::BSSIDstr; 61 | using WiFiScanClass::channel; 62 | using WiFiScanClass::encryptionType; 63 | using WiFiScanClass::RSSI; 64 | using WiFiScanClass::SSID; 65 | 66 | public: 67 | void printDiag(Print &dest); 68 | friend class NetworkClient; 69 | friend class NetworkServer; 70 | friend class NetworkUDP; 71 | void enableProv(bool status); 72 | bool isProvEnabled(); 73 | }; 74 | 75 | extern WiFiClass WiFi; 76 | 77 | #endif /* SOC_WIFI_SUPPORTED */ 78 | -------------------------------------------------------------------------------- /ESP32 - arduino IDE codes ( .cpp )/PWM/PWM_rmt_driver/PWM_rmt_driver.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include "driver/rmt.h" 3 | 4 | // ---------- USER SETTINGS ---------- 5 | static const rmt_channel_t RMT_CHANNEL = RMT_CHANNEL_0; // Use channel 0 (range: 0–7) 6 | static const gpio_num_t RMT_PIN = GPIO_NUM_21; // GPIO pin for output 7 | static const uint32_t DESIRED_FREQ = 2400000;// 113000; // Target frequency (113 kHz) 8 | // ----------------------------------- 9 | 10 | // We use the 80 MHz APB clock with divider=1 => 12.5 ns per RMT tick. 11 | // For a 113 kHz square wave, the period is ~8.85 µs; half-period ~4.425 µs. 12 | // Half-period in ticks = 4.425e-6 / 12.5e-9 = ~354 ticks. 13 | void setup() { 14 | Serial.begin(115200); 15 | delay(100); 16 | 17 | // Calculate the half-period in RMT clock ticks. 18 | // We toggle the pin once per half-period => one RMT item can represent one full period 19 | // by encoding “high for halfPeriodTicks, then low for halfPeriodTicks”. 20 | uint32_t halfPeriodTicks = (uint32_t)(40000000ULL / DESIRED_FREQ); 21 | // Explanation: We have an 80 MHz clock, but each full cycle is 2 toggles => 80e6/2 = 40e6. 22 | 23 | // 1) Configure the RMT peripheral 24 | rmt_config_t config = { 25 | .rmt_mode = RMT_MODE_TX, // Transmit mode 26 | .channel = RMT_CHANNEL, 27 | .gpio_num = RMT_PIN, 28 | .clk_div = 1, // Divide 80 MHz by 1 => 80 MHz RMT clock 29 | .mem_block_num = 1, // One memory block is enough for a small pattern 30 | .flags = 0 31 | }; 32 | rmt_config(&config); 33 | rmt_driver_install(RMT_CHANNEL, 0, 0); 34 | 35 | // 2) Prepare one RMT “item” that represents one full cycle: 36 | // - HIGH for halfPeriodTicks 37 | // - LOW for halfPeriodTicks 38 | rmt_item32_t waveItem; 39 | waveItem.level0 = 1; // First level is HIGH 40 | waveItem.duration0 = halfPeriodTicks; // for halfPeriodTicks 41 | waveItem.level1 = 0; // Then LOW 42 | waveItem.duration1 = halfPeriodTicks; // for halfPeriodTicks 43 | 44 | // 3) Write the item and enable “loop” mode to repeat forever 45 | rmt_write_items(RMT_CHANNEL, &waveItem, 1, true); 46 | rmt_set_tx_loop_mode(RMT_CHANNEL, true); 47 | 48 | Serial.print("RMT-based square wave started on GPIO "); 49 | Serial.print((int)RMT_PIN); 50 | Serial.print(" at ~"); 51 | Serial.print(DESIRED_FREQ); 52 | Serial.println(" Hz"); 53 | } 54 | 55 | void loop() { 56 | // Nothing else needed; the RMT hardware handles the waveform generation. 57 | delay(1000); 58 | } 59 | -------------------------------------------------------------------------------- /ESP32 - arduino IDE codes ( .cpp )/I2C MASTER-SLAVE/SLAVE/Slave/Slave.ino: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define I2C_DEV_ADDR 0x55 4 | 5 | 6 | #define PIR_PIN 15 7 | 8 | 9 | #define MOSFET_AMBIENCE_RED_LED 19 //GPIO_NUM_13 //rgb pins // change to ORANGE ** 10 | #define MOSFET_AMBIENCE_BLUE_LED 11 | #define MOSFET_AMBIENCE_GREEN_LED 12 | #define MOSFET_AMBIENCE_WARM_LED //GPIO_NUM_2 // warm light pin 13 | 14 | 15 | 16 | // Global variable to store the command received from the master 17 | String commandReceived = ""; 18 | 19 | void onReceive(int len) { 20 | commandReceived = ""; 21 | while (Wire.available()) { 22 | char c = Wire.read(); 23 | if (c != '\0') { 24 | commandReceived += c; 25 | } 26 | } 27 | Serial.print("I2C command received: "); 28 | Serial.println(commandReceived); 29 | } 30 | 31 | void onRequest() { 32 | String response = ""; 33 | if (commandReceived.equalsIgnoreCase("red")) { 34 | response = "colour1"; 35 | } else if (commandReceived.equalsIgnoreCase("blue")) { 36 | response = "colour2"; 37 | } else if (commandReceived.equalsIgnoreCase("green")) { 38 | response = "colour3"; 39 | } else if (commandReceived.equalsIgnoreCase("pir")) { 40 | int pirValue = digitalRead(PIR_PIN); // Read the PIR sensor value 41 | 42 | // Convert the sensor reading into a string 43 | if (pirValue == HIGH) { 44 | response = "yes"; 45 | } else { 46 | response = "no"; 47 | } 48 | } else if (commandReceived.equalsIgnoreCase("EM1_ON")) { 49 | digitalWrite(MOSFET_AMBIENCE_RED_LED, HIGH); 50 | response = "EM1_ON_STATE"; 51 | 52 | 53 | 54 | } else if (commandReceived.equalsIgnoreCase("EM1_OFF")) { 55 | digitalWrite(MOSFET_AMBIENCE_RED_LED, LOW); 56 | response = "EM1_OFF_STATE"; 57 | 58 | 59 | 60 | } else { 61 | response = "unknown"; 62 | } 63 | 64 | Serial.print("I2C sending response: "); 65 | Serial.println(response); 66 | 67 | // Send the response string to the master 68 | Wire.write((const uint8_t*)response.c_str(), response.length()); 69 | 70 | // Clear the command so that response is only sent once per request 71 | commandReceived = ""; 72 | } 73 | 74 | 75 | 76 | 77 | 78 | void setup() { 79 | Serial.begin(115200); 80 | Wire.begin((uint8_t)I2C_DEV_ADDR); 81 | Wire.onReceive(onReceive); 82 | Wire.onRequest(onRequest); 83 | 84 | pinMode(PIR_PIN, INPUT); // Set PIR_PIN as input 85 | 86 | pinMode(MOSFET_AMBIENCE_RED_LED, OUTPUT); 87 | //pinMode(MOSFET_AMBIENCE_WARM_LED, OUTPUT); 88 | 89 | digitalWrite(MOSFET_AMBIENCE_RED_LED, LOW); 90 | 91 | } 92 | 93 | void loop() { 94 | // No additional processing required in loop 95 | delay(100); 96 | } 97 | -------------------------------------------------------------------------------- /ESP32 - arduino IDE codes ( .cpp )/WIFI/WIFI_MP3_playing_via_I2s/WIFI_MP3_playing_via_I2s/External libs/WIFI libs used/WiFiScan.h: -------------------------------------------------------------------------------- 1 | /* 2 | ESP8266WiFiScan.h - esp8266 Wifi support. 3 | Based on WiFi.h from Ardiono WiFi shield library. 4 | Copyright (c) 2011-2014 Arduino. All right reserved. 5 | Modified by Ivan Grokhotkov, December 2014 6 | Reworked by Markus Sattler, December 2015 7 | 8 | This library is free software; you can redistribute it and/or 9 | modify it under the terms of the GNU Lesser General Public 10 | License as published by the Free Software Foundation; either 11 | version 2.1 of the License, or (at your option) any later version. 12 | 13 | This library is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 16 | Lesser General Public License for more details. 17 | 18 | You should have received a copy of the GNU Lesser General Public 19 | License along with this library; if not, write to the Free Software 20 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 21 | */ 22 | 23 | #pragma once 24 | 25 | #include "soc/soc_caps.h" 26 | #include "sdkconfig.h" 27 | #if SOC_WIFI_SUPPORTED || CONFIG_ESP_WIFI_REMOTE_ENABLED 28 | 29 | #include "WiFiType.h" 30 | #include "WiFiGeneric.h" 31 | 32 | class WiFiScanClass { 33 | 34 | public: 35 | void setScanTimeout(uint32_t ms); 36 | void setScanActiveMinTime(uint32_t ms); 37 | 38 | int16_t scanNetworks( 39 | bool async = false, bool show_hidden = false, bool passive = false, uint32_t max_ms_per_chan = 300, uint8_t channel = 0, const char *ssid = nullptr, 40 | const uint8_t *bssid = nullptr 41 | ); 42 | 43 | int16_t scanComplete(); 44 | void scanDelete(); 45 | 46 | // scan result 47 | bool getNetworkInfo(uint8_t networkItem, String &ssid, uint8_t &encryptionType, int32_t &RSSI, uint8_t *&BSSID, int32_t &channel); 48 | 49 | String SSID(uint8_t networkItem); 50 | wifi_auth_mode_t encryptionType(uint8_t networkItem); 51 | int32_t RSSI(uint8_t networkItem); 52 | uint8_t *BSSID(uint8_t networkItem, uint8_t *bssid = NULL); 53 | String BSSIDstr(uint8_t networkItem); 54 | int32_t channel(uint8_t networkItem); 55 | static void *getScanInfoByIndex(int i) { 56 | return _getScanInfoByIndex(i); 57 | }; 58 | 59 | static void _scanDone(); 60 | 61 | protected: 62 | static bool _scanAsync; 63 | 64 | static uint32_t _scanStarted; 65 | static uint32_t _scanTimeout; 66 | static uint16_t _scanCount; 67 | static uint32_t _scanActiveMinTime; 68 | 69 | static void *_scanResult; 70 | 71 | static void *_getScanInfoByIndex(int i); 72 | }; 73 | 74 | #endif /* SOC_WIFI_SUPPORTED */ 75 | -------------------------------------------------------------------------------- /ESP-IDF codes ( .C )/ADC/PIR-sensor-test1-MOTION/main/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "freertos/FreeRTOS.h" 3 | #include "freertos/task.h" 4 | #include "driver/gpio.h" 5 | #include "esp_log.h" 6 | 7 | #define PIR_PIN GPIO_NUM_36 // Change this to your connected GPIO pin 8 | 9 | //static const char *TAG = "PIR_Sensor"; 10 | 11 | 12 | 13 | /*// ISR to handle the PIT motion detection 14 | void IRAM_ATTR PIR_ISR_handler(void* arg) { 15 | if (Buck5VPIR == 1 && buck12to5 ==1){ 16 | 17 | 18 | static uint32_t last_PIR_ISR_time = 0; 19 | uint32_t PIR_ISR_time = xTaskGetTickCountFromISR(); 20 | 21 | 22 | if (PIR_ISR_time - last_PIR_ISR_time > pdMS_TO_TICKS(200)) { 23 | printf("motion Detected not going to deep sleep"); 24 | } 25 | last_PIR_ISR_time = PIR_ISR_time; 26 | } 27 | } 28 | 29 | 30 | 31 | 32 | 33 | // Function to initialize GPIO for the button 34 | void button_init() { 35 | 36 | // (PIR_PIN) 37 | io_conf.intr_type = GPIO_INTR_POSEDGE; // Interrupt on rising edge when motion is deteced HIGH/1 38 | io_conf.pin_bit_mask = (1ULL << PIR_PIN); // Set pin of PIR 39 | io_conf.mode = GPIO_MODE_INPUT; // Set as input 40 | io_conf.pull_up_en = 0; // Enable pull-down resistor 41 | io_conf.pull_down_en = 0; 42 | gpio_config(&io_conf); 43 | 44 | 45 | 46 | 47 | // Install ISR service and add ISR handler 48 | gpio_install_isr_service(0); 49 | 50 | gpio_isr_handler_add(PIR_PIN, PIR_ISR_handler, NULL); // Second button ISR 51 | 52 | 53 | 54 | 55 | 56 | }*/ 57 | 58 | 59 | void app_main(void) { 60 | // Configure the PIR sensor pin as input 61 | esp_rom_gpio_pad_select_gpio(PIR_PIN); 62 | gpio_set_direction(PIR_PIN, GPIO_MODE_INPUT); 63 | int sec=0; 64 | while (1) { 65 | // Read the digital value from the PIR sensor 66 | int pir_value = gpio_get_level(PIR_PIN); 67 | printf("VALUE= %d ,," , pir_value); 68 | // Check if motion is detected 69 | if (pir_value == 1) { 70 | // ESP_LOGI(TAG, "Motion detected!"); 71 | printf("Motion detected! ,, "); 72 | } else { 73 | // ESP_LOGI(TAG, "No motion."); 74 | printf("No motion. ,,"); 75 | } 76 | 77 | 78 | sec++; 79 | printf("secs = %d \n", sec); 80 | vTaskDelay(100 ); // Adjust the delay as needed 81 | 82 | 83 | 84 | int pir_value = gpio_get_level(PIR_PIN); 85 | printf("VALUE= %d ,," , pir_value); 86 | if (pir_value == 1) { 87 | 88 | printf("Motion detected! ,, "); 89 | } else { 90 | 91 | printf("No motion. ,,"); 92 | } 93 | 94 | 95 | } 96 | 97 | } 98 | 99 | -------------------------------------------------------------------------------- /ESP32 - arduino IDE codes ( .cpp )/I2C MASTER-SLAVE/readme.md: -------------------------------------------------------------------------------- 1 | # ESP32 I2C & BLE Master-Slave Communication 2 | 3 | This project demonstrates communication between two ESP32 devices using I2C and BLE. The master device hosts a BLE server that listens for string commands ("red", "blue", "green") from a BLE client (e.g., a smartphone). Based on the received BLE command, the master sends an I2C request to the slave device, which then responds with a corresponding message (e.g., "colour1", "colour2", "colour3"). This response can later be replaced with real sensor data or actuation commands. 4 | 5 | ## Overview 6 | 7 | - **I2C Communication:** The master and slave devices communicate using the I2C protocol. The master sends a command string via I2C to the slave and then requests a response. 8 | - **BLE Integration:** The master initializes a BLE server with an input and output characteristic. When a command is received via BLE, it triggers the I2C request. 9 | - **Dynamic Data Handling:** The slave processes the received I2C command and returns a corresponding response. In this example, the responses are hard-coded strings, but they could be sensor data or control signals in a real application. 10 | - **Buffer Management:** The master performs a dummy I2C read to flush any stale data from the I2C buffer before reading the valid response from the slave. 11 | 12 | ## How It Works 13 | 14 | 1. **BLE on the Master:** 15 | - The master initializes a BLE server with a writeable input characteristic and a readable/notify output characteristic. 16 | - A BLE client sends a command (e.g., "red") to the master. 17 | - The BLE callback triggers the `requestSlaveData()` function. 18 | 19 | 2. **I2C Communication:** 20 | - The master sends the received command string over I2C to the slave. 21 | - To ensure that stale data is cleared, the master performs a dummy I2C read before making the actual data request. 22 | - The slave listens for the I2C command in its `onReceive()` callback and stores the command. 23 | - When the master requests data (triggering `onRequest()` on the slave), the slave checks the stored command and sends back the appropriate response: 24 | - `"red"` → `"colour1"` 25 | - `"blue"` → `"colour2"` 26 | - `"green"` → `"colour3"` 27 | - Otherwise, it sends `"unknown"`. 28 | 29 | 3. **BLE Data Update:** 30 | - The master receives the I2C response and updates its BLE output characteristic, notifying the connected BLE client of the new data. 31 | 32 | ## Requirements 33 | 34 | - Two ESP32 boards. 35 | - Arduino IDE with ESP32 board support. 36 | - Basic I2C wiring (connect SDA, SCL, and GND between master and slave). 37 | - A BLE-capable device (e.g., a smartphone with a BLE scanner app like nRF Connect). 38 | 39 | ## Setup and Installation 40 | 41 | 1. **Clone the Repository:** 42 | 43 | ```bash 44 | git clone https://github.com/yourusername/esp32-i2c-ble-master-slave.git 45 | cd esp32-i2c-ble-master-slave 46 | -------------------------------------------------------------------------------- /ESP32 - arduino IDE codes ( .cpp )/WIFI/WIFI_MP3_playing_via_I2s/WIFI_MP3_playing_via_I2s/External libs/WIFI libs used/WiFiMulti.h: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @file ESP8266WiFiMulti.h 4 | * @date 16.05.2015 5 | * @author Markus Sattler 6 | * 7 | * Copyright (c) 2015 Markus Sattler. All rights reserved. 8 | * This file is part of the esp8266 core for Arduino environment. 9 | * 10 | * This library is free software; you can redistribute it and/or 11 | * modify it under the terms of the GNU Lesser General Public 12 | * License as published by the Free Software Foundation; either 13 | * version 2.1 of the License, or (at your option) any later version. 14 | * 15 | * This library is distributed in the hope that it will be useful, 16 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 18 | * Lesser General Public License for more details. 19 | * 20 | * You should have received a copy of the GNU Lesser General Public 21 | * License along with this library; if not, write to the Free Software 22 | * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 23 | * 24 | */ 25 | 26 | #pragma once 27 | 28 | #include "soc/soc_caps.h" 29 | #include "sdkconfig.h" 30 | #if SOC_WIFI_SUPPORTED || CONFIG_ESP_WIFI_REMOTE_ENABLED 31 | 32 | #include "WiFi.h" 33 | #include 34 | 35 | typedef struct { 36 | char *ssid; 37 | char *passphrase; 38 | bool hasFailed; 39 | } WifiAPlist_t; 40 | 41 | typedef std::function ConnectionTestCB_t; 42 | 43 | class WiFiMulti { 44 | public: 45 | WiFiMulti(); 46 | ~WiFiMulti(); 47 | 48 | bool addAP(const char *ssid, const char *passphrase = NULL); 49 | uint8_t run(uint32_t connectTimeout = 5000, bool scanHidden = false); 50 | #if CONFIG_LWIP_IPV6 51 | void enableIPv6(bool state); 52 | #endif 53 | 54 | // Force (default: true) to only keep connected or to connect to an AP from the provided WiFiMulti list. 55 | // When bStrict is false, it will keep the last/current connected AP even if not in the WiFiMulti List. 56 | void setStrictMode(bool bStrict = true); 57 | 58 | // allows (true) to connect to ANY open AP, even if not in the user list 59 | // default false (do not connect to an open AP that has not been explicitaly added by the user to list) 60 | void setAllowOpenAP(bool bAllowOpenAP = false); 61 | 62 | // clears the current list of Multi APs and frees the memory 63 | void APlistClean(void); 64 | 65 | // allow the user to define a callback function that will validate the connection to the Internet. 66 | // if the callback returns true, the connection is considered valid and the AP will added to the validated AP list. 67 | // set the callback to NULL to disable the feature and validate any SSID that is in the list. 68 | void setConnectionTestCallbackFunc(ConnectionTestCB_t cbFunc); 69 | 70 | private: 71 | std::vector APlist; 72 | bool ipv6_support; 73 | 74 | bool _bStrict = true; 75 | bool _bAllowOpenAP = false; 76 | ConnectionTestCB_t _connectionTestCBFunc = NULL; 77 | bool _bWFMInit = false; 78 | 79 | void markAsFailed(int32_t i); 80 | void resetFails(); 81 | }; 82 | 83 | #endif /* SOC_WIFI_SUPPORTED */ 84 | -------------------------------------------------------------------------------- /ESP32 - arduino IDE codes ( .cpp )/WIFI/WIFI_MP3_playing_via_I2s/WIFI_MP3_playing_via_I2s/External libs/WIFI libs used/WiFi.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | ESP8266WiFi.cpp - WiFi library for esp8266 3 | 4 | Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. 5 | This file is part of the esp8266 core for Arduino environment. 6 | 7 | This library is free software; you can redistribute it and/or 8 | modify it under the terms of the GNU Lesser General Public 9 | License as published by the Free Software Foundation; either 10 | version 2.1 of the License, or (at your option) any later version. 11 | 12 | This library is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 | Lesser General Public License for more details. 16 | 17 | You should have received a copy of the GNU Lesser General Public 18 | License along with this library; if not, write to the Free Software 19 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 20 | 21 | Reworked on 28 Dec 2015 by Markus Sattler 22 | 23 | */ 24 | #include "WiFi.h" 25 | #if SOC_WIFI_SUPPORTED || CONFIG_ESP_WIFI_REMOTE_ENABLED 26 | 27 | extern "C" { 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | } 38 | 39 | // ----------------------------------------------------------------------------------------------------------------------- 40 | // ---------------------------------------------------------- Debug ------------------------------------------------------ 41 | // ----------------------------------------------------------------------------------------------------------------------- 42 | 43 | /** 44 | * Output WiFi settings to an object derived from Print interface (like Serial). 45 | * @param p Print interface 46 | */ 47 | void WiFiClass::printDiag(Print &p) { 48 | const char *modes[] = {"NULL", "STA", "AP", "STA+AP"}; 49 | 50 | wifi_mode_t mode; 51 | esp_wifi_get_mode(&mode); 52 | 53 | uint8_t primaryChan; 54 | wifi_second_chan_t secondChan; 55 | esp_wifi_get_channel(&primaryChan, &secondChan); 56 | 57 | p.print("Mode: "); 58 | p.println(modes[mode]); 59 | 60 | p.print("Channel: "); 61 | p.println(primaryChan); 62 | /* 63 | p.print("AP id: "); 64 | p.println(wifi_station_get_current_ap_id()); 65 | 66 | p.print("Status: "); 67 | p.println(wifi_station_get_connect_status()); 68 | */ 69 | 70 | wifi_config_t conf; 71 | esp_wifi_get_config((wifi_interface_t)WIFI_IF_STA, &conf); 72 | 73 | const char *ssid = reinterpret_cast(conf.sta.ssid); 74 | p.print("SSID ("); 75 | p.print(strlen(ssid)); 76 | p.print("): "); 77 | p.println(ssid); 78 | 79 | const char *passphrase = reinterpret_cast(conf.sta.password); 80 | p.print("Passphrase ("); 81 | p.print(strlen(passphrase)); 82 | p.print("): "); 83 | p.println(passphrase); 84 | 85 | p.print("BSSID set: "); 86 | p.println(conf.sta.bssid_set); 87 | } 88 | 89 | void WiFiClass::enableProv(bool status) { 90 | prov_enable = status; 91 | } 92 | 93 | bool WiFiClass::isProvEnabled() { 94 | return prov_enable; 95 | } 96 | 97 | WiFiClass WiFi; 98 | 99 | #endif /* SOC_WIFI_SUPPORTED */ 100 | -------------------------------------------------------------------------------- /ESP32 - arduino IDE codes ( .cpp )/I2C MASTER-SLAVE/SLAVE/Slave/Air_Quality_Sensor.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Air_Quality_Sensor.cpp 3 | Source file for Grove - Air Quality Sensor. 4 | 5 | Copyright (c) 2019 seeed technology inc. 6 | Author : Lets Blu 7 | Created Time : Jan 2019 8 | Modified Time: 9 | 10 | The MIT License (MIT) 11 | 12 | Permission is hereby granted, free of charge, to any person obtaining a copy 13 | of this software and associated documentation files (the "Software"), to deal 14 | in the Software without restriction, including without limitation the rights 15 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 16 | copies of the Software, and to permit persons to whom the Software is 17 | furnished to do so, subject to the following conditions: 18 | 19 | The above copyright notice and this permission notice shall be included in 20 | all copies or substantial portions of the Software. 21 | 22 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 23 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 24 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 25 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 26 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 27 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 28 | THE SOFTWARE. 29 | */ 30 | #include "Air_Quality_Sensor.h" 31 | 32 | const int AirQualitySensor::FORCE_SIGNAL = 0; 33 | const int AirQualitySensor::HIGH_POLLUTION = 1; 34 | const int AirQualitySensor::LOW_POLLUTION = 2; 35 | const int AirQualitySensor::FRESH_AIR = 3; 36 | 37 | AirQualitySensor::AirQualitySensor(int pin) 38 | : _pin(pin), _voltageSum(0), _volSumCount(0) { 39 | // do nothing 40 | } 41 | 42 | bool AirQualitySensor::init(void) { 43 | int initVoltage = analogRead(_pin); 44 | 45 | if (10 < initVoltage && initVoltage < 798) { 46 | _currentVoltage = initVoltage; 47 | _lastVoltage = _currentVoltage; 48 | 49 | _standardVoltage = initVoltage; 50 | _lastStdVolUpdated = millis(); 51 | 52 | return true; 53 | } else { 54 | return false; 55 | } 56 | } 57 | 58 | int AirQualitySensor::slope(void) { 59 | _lastVoltage = _currentVoltage; 60 | _currentVoltage = analogRead(_pin); 61 | 62 | _voltageSum += _currentVoltage; 63 | _volSumCount += 1; 64 | 65 | updateStandardVoltage(); 66 | if (_currentVoltage - _lastVoltage > 400 || _currentVoltage > 700) { 67 | return AirQualitySensor::FORCE_SIGNAL; 68 | } else if ((_currentVoltage - _lastVoltage > 400 && _currentVoltage < 700) 69 | || _currentVoltage - _standardVoltage > 150) { 70 | return AirQualitySensor::HIGH_POLLUTION; 71 | } else if ((_currentVoltage - _lastVoltage > 200 && _currentVoltage < 700) 72 | || _currentVoltage - _standardVoltage > 50) { 73 | return AirQualitySensor::LOW_POLLUTION; 74 | } else { 75 | return AirQualitySensor::FRESH_AIR; 76 | } 77 | 78 | return -1; 79 | } 80 | 81 | int AirQualitySensor::getValue(void) { 82 | return _currentVoltage; 83 | } 84 | 85 | void AirQualitySensor::updateStandardVoltage(void) { 86 | if (millis() - _lastStdVolUpdated > 500000) { 87 | _standardVoltage = _voltageSum / _volSumCount; 88 | _lastStdVolUpdated = millis(); 89 | 90 | _voltageSum = 0; 91 | _volSumCount = 0; 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /ESP32 - arduino IDE codes ( .cpp )/WIFI/WIFI_MP3_playing_via_I2s/WIFI_MP3_playing_via_I2s/External libs/AUDIO libs used/opus_decoder/opus_decoder.h: -------------------------------------------------------------------------------- 1 | // based on Xiph.Org Foundation celt decoder 2 | #pragma once 3 | //#pragma GCC optimize ("O3") 4 | //#pragma GCC diagnostic ignored "-Wnarrowing" 5 | 6 | #include 7 | #include 8 | #include 9 | using namespace std; 10 | 11 | enum : int8_t {OPUS_END = 120, 12 | OPUS_CONTINUE = 110, 13 | OPUS_PARSE_OGG_DONE = 100, 14 | ERR_OPUS_NONE = 0, 15 | ERR_OPUS_CHANNELS_OUT_OF_RANGE = -1, 16 | ERR_OPUS_INVALID_SAMPLERATE = -2, 17 | ERR_OPUS_EXTRA_CHANNELS_UNSUPPORTED = -3, 18 | ERR_OPUS_DECODER_ASYNC = -4, 19 | ERR_OPUS_SILK_MODE_UNSUPPORTED = -5, 20 | ERR_OPUS_HYBRID_MODE_UNSUPPORTED = -6, 21 | ERR_OPUS_NARROW_BAND_UNSUPPORTED = -7, 22 | ERR_OPUS_WIDE_BAND_UNSUPPORTED = -8, 23 | ERR_OPUS_SUPER_WIDE_BAND_UNSUPPORTED = -9, 24 | ERR_OPUS_OGG_SYNC_NOT_FOUND = - 10, 25 | ERR_OPUS_BUFFER_TOO_SMALL = -11, 26 | ERR_OPUS_CELT_BAD_ARG = -18, 27 | ERR_OPUS_CELT_INTERNAL_ERROR = -19, 28 | ERR_OPUS_CELT_UNIMPLEMENTED = -20, 29 | ERR_OPUS_CELT_ALLOC_FAIL = -21, 30 | ERR_OPUS_CELT_UNKNOWN_REQUEST = -22, 31 | ERR_OPUS_CELT_GET_MODE_REQUEST = - 23, 32 | ERR_OPUS_CELT_CLEAR_REQUEST = -24, 33 | ERR_OPUS_CELT_SET_CHANNELS = -25, 34 | ERR_OPUS_CELT_END_BAND = -26, 35 | ERR_OPUS_CELT_START_BAND = -27, 36 | ERR_CELT_OPUS_INTERNAL_ERROR = -28}; 37 | 38 | bool OPUSDecoder_AllocateBuffers(); 39 | void OPUSDecoder_FreeBuffers(); 40 | void OPUSDecoder_ClearBuffers(); 41 | void OPUSsetDefaults(); 42 | int32_t OPUSDecode(uint8_t* inbuf, int32_t* bytesLeft, int16_t* outbuf); 43 | int32_t opusDecodePage0(uint8_t* inbuf, int32_t* bytesLeft, uint32_t segmentLength); 44 | int32_t opusDecodePage3(uint8_t* inbuf, int32_t* bytesLeft, uint32_t segmentLength, int16_t *outbuf); 45 | int8_t opus_FramePacking_Code0(uint8_t *inbuf, int32_t *bytesLeft, int16_t *outbuf, int32_t packetLen, uint16_t samplesPerFrame); 46 | int8_t opus_FramePacking_Code1(uint8_t *inbuf, int32_t *bytesLeft, int16_t *outbuf, int32_t packetLen, uint16_t samplesPerFrame, uint8_t* frameCount); 47 | int8_t opus_FramePacking_Code2(uint8_t *inbuf, int32_t *bytesLeft, int16_t *outbuf, int32_t packetLen, uint16_t samplesPerFrame, uint8_t* frameCount); 48 | int8_t opus_FramePacking_Code3(uint8_t *inbuf, int32_t *bytesLeft, int16_t *outbuf, int32_t packetLen, uint16_t samplesPerFrame, uint8_t* frameCount); 49 | uint8_t OPUSGetChannels(); 50 | uint32_t OPUSGetSampRate(); 51 | uint8_t OPUSGetBitsPerSample(); 52 | uint32_t OPUSGetBitRate(); 53 | uint16_t OPUSGetOutputSamps(); 54 | uint32_t OPUSGetAudioDataStart(); 55 | char* OPUSgetStreamTitle(); 56 | vector OPUSgetMetadataBlockPicture(); 57 | int32_t OPUSFindSyncWord(unsigned char* buf, int32_t nBytes); 58 | int32_t OPUSparseOGG(uint8_t* inbuf, int32_t* bytesLeft); 59 | int32_t parseOpusHead(uint8_t* inbuf, int32_t nBytes); 60 | int32_t parseOpusComment(uint8_t* inbuf, int32_t nBytes); 61 | int8_t parseOpusTOC(uint8_t TOC_Byte); 62 | int32_t opus_packet_get_samples_per_frame(const uint8_t* data, int32_t Fs); 63 | 64 | // some helper functions 65 | int32_t OPUS_specialIndexOf(uint8_t* base, const char* str, int32_t baselen, bool exact = false); 66 | -------------------------------------------------------------------------------- /ESP32 - arduino IDE codes ( .cpp )/WIFI/WIFI_MP3_playing_via_I2s/WIFI_MP3_playing_via_I2s/External libs/WIFI libs used/WiFiAP.h: -------------------------------------------------------------------------------- 1 | /* 2 | ESP8266WiFiAP.h - esp8266 Wifi support. 3 | Based on WiFi.h from Arduino WiFi shield library. 4 | Copyright (c) 2011-2014 Arduino. All right reserved. 5 | Modified by Ivan Grokhotkov, December 2014 6 | Reworked by Markus Sattler, December 2015 7 | 8 | This library is free software; you can redistribute it and/or 9 | modify it under the terms of the GNU Lesser General Public 10 | License as published by the Free Software Foundation; either 11 | version 2.1 of the License, or (at your option) any later version. 12 | 13 | This library is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 16 | Lesser General Public License for more details. 17 | 18 | You should have received a copy of the GNU Lesser General Public 19 | License along with this library; if not, write to the Free Software 20 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 21 | */ 22 | 23 | #pragma once 24 | 25 | #include "soc/soc_caps.h" 26 | #include "sdkconfig.h" 27 | #if SOC_WIFI_SUPPORTED || CONFIG_ESP_WIFI_REMOTE_ENABLED 28 | 29 | #include "esp_wifi_types.h" 30 | #include "WiFiType.h" 31 | #include "WiFiGeneric.h" 32 | 33 | #define WIFI_AP_DEFAULT_AUTH_MODE WIFI_AUTH_WPA2_PSK 34 | #define WIFI_AP_DEFAULT_CIPHER WIFI_CIPHER_TYPE_CCMP // Disable by default enabled insecure TKIP and use just CCMP. 35 | 36 | // ---------------------------------------------------------------------------------------------- 37 | // ------------------------------------ NEW AP Implementation ---------------------------------- 38 | // ---------------------------------------------------------------------------------------------- 39 | 40 | class APClass : public NetworkInterface { 41 | public: 42 | APClass(); 43 | ~APClass(); 44 | 45 | bool begin(); 46 | bool end(); 47 | 48 | bool create( 49 | const char *ssid, const char *passphrase = NULL, int channel = 1, int ssid_hidden = 0, int max_connection = 4, bool ftm_responder = false, 50 | wifi_auth_mode_t auth_mode = WIFI_AP_DEFAULT_AUTH_MODE, wifi_cipher_type_t cipher = WIFI_AP_DEFAULT_CIPHER 51 | ); 52 | bool clear(); 53 | 54 | bool bandwidth(wifi_bandwidth_t bandwidth); 55 | bool enableNAPT(bool enable = true); 56 | 57 | String SSID(void) const; 58 | uint8_t stationCount(); 59 | 60 | void _onApEvent(int32_t event_id, void *event_data); 61 | 62 | protected: 63 | network_event_handle_t _wifi_ap_event_handle; 64 | 65 | size_t printDriverInfo(Print &out) const; 66 | 67 | friend class WiFiGenericClass; 68 | bool onEnable(); 69 | bool onDisable(); 70 | }; 71 | 72 | // ---------------------------------------------------------------------------------------------- 73 | // ------------------------------- OLD AP API (compatibility) ---------------------------------- 74 | // ---------------------------------------------------------------------------------------------- 75 | 76 | class WiFiAPClass { 77 | 78 | public: 79 | APClass AP; 80 | 81 | bool softAP( 82 | const char *ssid, const char *passphrase = NULL, int channel = 1, int ssid_hidden = 0, int max_connection = 4, bool ftm_responder = false, 83 | wifi_auth_mode_t auth_mode = WIFI_AP_DEFAULT_AUTH_MODE, wifi_cipher_type_t cipher = WIFI_AP_DEFAULT_CIPHER 84 | ); 85 | bool softAP( 86 | const String &ssid, const String &passphrase = emptyString, int channel = 1, int ssid_hidden = 0, int max_connection = 4, bool ftm_responder = false, 87 | wifi_auth_mode_t auth_mode = WIFI_AP_DEFAULT_AUTH_MODE, wifi_cipher_type_t cipher = WIFI_AP_DEFAULT_CIPHER 88 | ) { 89 | return softAP(ssid.c_str(), passphrase.c_str(), channel, ssid_hidden, max_connection, ftm_responder, auth_mode, cipher); 90 | } 91 | 92 | bool softAPConfig(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dhcp_lease_start = (uint32_t)0, IPAddress dns = (uint32_t)0); 93 | bool softAPdisconnect(bool wifioff = false); 94 | 95 | bool softAPbandwidth(wifi_bandwidth_t bandwidth); 96 | 97 | uint8_t softAPgetStationNum(); 98 | String softAPSSID(void) const; 99 | 100 | IPAddress softAPIP(); 101 | IPAddress softAPBroadcastIP(); 102 | IPAddress softAPNetworkID(); 103 | IPAddress softAPSubnetMask(); 104 | uint8_t softAPSubnetCIDR(); 105 | 106 | #if CONFIG_LWIP_IPV6 107 | bool softAPenableIPv6(bool enable = true); 108 | IPAddress softAPlinkLocalIPv6(); 109 | #endif 110 | 111 | const char *softAPgetHostname(); 112 | bool softAPsetHostname(const char *hostname); 113 | 114 | uint8_t *softAPmacAddress(uint8_t *mac); 115 | String softAPmacAddress(void); 116 | 117 | protected: 118 | }; 119 | 120 | #endif /* SOC_WIFI_SUPPORTED*/ 121 | -------------------------------------------------------------------------------- /ESP32 - arduino IDE codes ( .cpp )/WIFI/WIFI_MP3_playing_via_I2s/WIFI_MP3_playing_via_I2s/External libs/WIFI libs used/WiFiGeneric.h: -------------------------------------------------------------------------------- 1 | /* 2 | ESP8266WiFiGeneric.h - esp8266 Wifi support. 3 | Based on WiFi.h from Ardiono WiFi shield library. 4 | Copyright (c) 2011-2014 Arduino. All right reserved. 5 | Modified by Ivan Grokhotkov, December 2014 6 | Reworked by Markus Sattler, December 2015 7 | 8 | This library is free software; you can redistribute it and/or 9 | modify it under the terms of the GNU Lesser General Public 10 | License as published by the Free Software Foundation; either 11 | version 2.1 of the License, or (at your option) any later version. 12 | 13 | This library is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 16 | Lesser General Public License for more details. 17 | 18 | You should have received a copy of the GNU Lesser General Public 19 | License along with this library; if not, write to the Free Software 20 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 21 | */ 22 | 23 | #pragma once 24 | 25 | #include "soc/soc_caps.h" 26 | #include "sdkconfig.h" 27 | #if SOC_WIFI_SUPPORTED || CONFIG_ESP_WIFI_REMOTE_ENABLED 28 | 29 | #include "esp_err.h" 30 | #include "esp_event.h" 31 | #include 32 | #include "WiFiType.h" 33 | #include "IPAddress.h" 34 | #include "esp_smartconfig.h" 35 | #include "esp_netif_types.h" 36 | #if CONFIG_ETH_ENABLED 37 | #include "esp_eth_driver.h" 38 | #endif 39 | #if CONFIG_NETWORK_PROV_NETWORK_TYPE_WIFI 40 | #include "network_provisioning/manager.h" 41 | #endif 42 | #include "lwip/ip_addr.h" 43 | 44 | #include "Network.h" 45 | 46 | #define WiFiEventCb NetworkEventCb 47 | #define WiFiEventFuncCb NetworkEventFuncCb 48 | #define WiFiEventSysCb NetworkEventSysCb 49 | #define wifi_event_id_t network_event_handle_t 50 | 51 | typedef enum { 52 | WIFI_POWER_21dBm = 84, // 21dBm 53 | WIFI_POWER_20_5dBm = 82, // 20.5dBm 54 | WIFI_POWER_20dBm = 80, // 20dBm 55 | WIFI_POWER_19_5dBm = 78, // 19.5dBm 56 | WIFI_POWER_19dBm = 76, // 19dBm 57 | WIFI_POWER_18_5dBm = 74, // 18.5dBm 58 | WIFI_POWER_17dBm = 68, // 17dBm 59 | WIFI_POWER_15dBm = 60, // 15dBm 60 | WIFI_POWER_13dBm = 52, // 13dBm 61 | WIFI_POWER_11dBm = 44, // 11dBm 62 | WIFI_POWER_8_5dBm = 34, // 8.5dBm 63 | WIFI_POWER_7dBm = 28, // 7dBm 64 | WIFI_POWER_5dBm = 20, // 5dBm 65 | WIFI_POWER_2dBm = 8, // 2dBm 66 | WIFI_POWER_MINUS_1dBm = -4 // -1dBm 67 | } wifi_power_t; 68 | 69 | typedef enum { 70 | WIFI_RX_ANT0 = 0, 71 | WIFI_RX_ANT1, 72 | WIFI_RX_ANT_AUTO 73 | } wifi_rx_ant_t; 74 | 75 | typedef enum { 76 | WIFI_TX_ANT0 = 0, 77 | WIFI_TX_ANT1, 78 | WIFI_TX_ANT_AUTO 79 | } wifi_tx_ant_t; 80 | 81 | class WiFiGenericClass { 82 | public: 83 | WiFiGenericClass(); 84 | 85 | wifi_event_id_t onEvent(WiFiEventCb cbEvent, arduino_event_id_t event = ARDUINO_EVENT_MAX); 86 | wifi_event_id_t onEvent(WiFiEventFuncCb cbEvent, arduino_event_id_t event = ARDUINO_EVENT_MAX); 87 | wifi_event_id_t onEvent(WiFiEventSysCb cbEvent, arduino_event_id_t event = ARDUINO_EVENT_MAX); 88 | void removeEvent(WiFiEventCb cbEvent, arduino_event_id_t event = ARDUINO_EVENT_MAX); 89 | void removeEvent(WiFiEventSysCb cbEvent, arduino_event_id_t event = ARDUINO_EVENT_MAX); 90 | void removeEvent(wifi_event_id_t id); 91 | 92 | static int getStatusBits(); 93 | static int waitStatusBits(int bits, uint32_t timeout_ms); 94 | 95 | int32_t channel(void); 96 | int setChannel(uint8_t primary, wifi_second_chan_t secondary = WIFI_SECOND_CHAN_NONE); 97 | 98 | void persistent(bool persistent); 99 | void enableLongRange(bool enable); 100 | 101 | static bool mode(wifi_mode_t); 102 | static wifi_mode_t getMode(); 103 | 104 | bool enableSTA(bool enable); 105 | bool enableAP(bool enable); 106 | 107 | bool setSleep(bool enabled); 108 | bool setSleep(wifi_ps_type_t sleepType); 109 | wifi_ps_type_t getSleep(); 110 | 111 | bool setTxPower(wifi_power_t power); 112 | wifi_power_t getTxPower(); 113 | 114 | bool initiateFTM(uint8_t frm_count = 16, uint16_t burst_period = 2, uint8_t channel = 1, const uint8_t *mac = NULL); 115 | 116 | static bool setDualAntennaConfig(uint8_t gpio_ant1, uint8_t gpio_ant2, wifi_rx_ant_t rx_mode, wifi_tx_ant_t tx_mode); 117 | 118 | static const char *getHostname(); 119 | static bool setHostname(const char *hostname); 120 | static bool hostname(const String &aHostname) { 121 | return setHostname(aHostname.c_str()); 122 | } 123 | 124 | static void useStaticBuffers(bool bufferMode); 125 | static bool useStaticBuffers(); 126 | 127 | static int hostByName(const char *aHostname, IPAddress &aResult); 128 | 129 | static IPAddress calculateNetworkID(IPAddress ip, IPAddress subnet); 130 | static IPAddress calculateBroadcast(IPAddress ip, IPAddress subnet); 131 | static uint8_t calculateSubnetCIDR(IPAddress subnetMask); 132 | 133 | const char *disconnectReasonName(wifi_err_reason_t reason); 134 | const char *eventName(arduino_event_id_t id); 135 | 136 | static void _eventCallback(arduino_event_t *event); 137 | 138 | protected: 139 | static bool _persistent; 140 | static bool _long_range; 141 | static wifi_mode_t _forceSleepLastMode; 142 | static wifi_ps_type_t _sleepEnabled; 143 | static bool _wifiUseStaticBuffers; 144 | 145 | static int setStatusBits(int bits); 146 | static int clearStatusBits(int bits); 147 | 148 | friend class WiFiSTAClass; 149 | friend class WiFiScanClass; 150 | friend class WiFiAPClass; 151 | friend class ETHClass; 152 | }; 153 | 154 | #endif /* SOC_WIFI_SUPPORTED */ 155 | -------------------------------------------------------------------------------- /ESP32 - arduino IDE codes ( .cpp )/WIFI/WIFI_MP3_playing_via_I2s/WIFI_MP3_playing_via_I2s/External libs/WIFI libs used/WiFiAP.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | ESP8266WiFiSTA.cpp - WiFi library for esp8266 3 | 4 | Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. 5 | This file is part of the esp8266 core for Arduino environment. 6 | 7 | This library is free software; you can redistribute it and/or 8 | modify it under the terms of the GNU Lesser General Public 9 | License as published by the Free Software Foundation; either 10 | version 2.1 of the License, or (at your option) any later version. 11 | 12 | This library is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 | Lesser General Public License for more details. 16 | 17 | You should have received a copy of the GNU Lesser General Public 18 | License along with this library; if not, write to the Free Software 19 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 20 | 21 | Reworked on 28 Dec 2015 by Markus Sattler 22 | 23 | */ 24 | 25 | #include "WiFi.h" 26 | #include "WiFiGeneric.h" 27 | #include "WiFiAP.h" 28 | #if SOC_WIFI_SUPPORTED || CONFIG_ESP_WIFI_REMOTE_ENABLED 29 | 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include 39 | #include 40 | #include "dhcpserver/dhcpserver_options.h" 41 | 42 | /** 43 | * Set up an access point 44 | * @param ssid Pointer to the SSID (max 63 char). 45 | * @param passphrase (for WPA2 min 8 char, for open use NULL) 46 | * @param channel WiFi channel number, 1 - 13. 47 | * @param ssid_hidden Network cloaking (0 = broadcast SSID, 1 = hide SSID) 48 | * @param max_connection Max simultaneous connected clients, 1 - 4. 49 | */ 50 | bool WiFiAPClass::softAP( 51 | const char *ssid, const char *passphrase, int channel, int ssid_hidden, int max_connection, bool ftm_responder, wifi_auth_mode_t auth_mode, 52 | wifi_cipher_type_t cipher 53 | ) { 54 | return AP.begin() && AP.create(ssid, passphrase, channel, ssid_hidden, max_connection, ftm_responder, auth_mode, cipher); 55 | } 56 | 57 | /** 58 | * Return the current SSID associated with the network 59 | * @return SSID 60 | */ 61 | String WiFiAPClass::softAPSSID() const { 62 | return AP.SSID(); 63 | } 64 | 65 | /** 66 | * Configure access point 67 | * @param local_ip access point IP 68 | * @param gateway gateway IP 69 | * @param subnet subnet mask 70 | */ 71 | bool WiFiAPClass::softAPConfig(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dhcp_lease_start, IPAddress dns) { 72 | return AP.begin() && AP.config(local_ip, gateway, subnet, dhcp_lease_start, dns); 73 | } 74 | 75 | /** 76 | * Disconnect from the network (close AP) 77 | * @param wifioff disable mode? 78 | * @return one value of wl_status_t enum 79 | */ 80 | bool WiFiAPClass::softAPdisconnect(bool wifioff) { 81 | if (!AP.clear()) { 82 | return false; 83 | } 84 | if (wifioff) { 85 | return AP.end(); 86 | } 87 | return true; 88 | } 89 | 90 | /** 91 | * Sets the working bandwidth of the AP mode 92 | * @param m wifi_bandwidth_t 93 | */ 94 | bool WiFiAPClass::softAPbandwidth(wifi_bandwidth_t bandwidth) { 95 | return AP.bandwidth(bandwidth); 96 | } 97 | 98 | /** 99 | * Get the count of the Station / client that are connected to the softAP interface 100 | * @return Stations count 101 | */ 102 | uint8_t WiFiAPClass::softAPgetStationNum() { 103 | return AP.stationCount(); 104 | } 105 | 106 | /** 107 | * Get the softAP interface IP address. 108 | * @return IPAddress softAP IP 109 | */ 110 | IPAddress WiFiAPClass::softAPIP() { 111 | return AP.localIP(); 112 | } 113 | 114 | /** 115 | * Get the softAP broadcast IP address. 116 | * @return IPAddress softAP broadcastIP 117 | */ 118 | IPAddress WiFiAPClass::softAPBroadcastIP() { 119 | return AP.broadcastIP(); 120 | } 121 | 122 | /** 123 | * Get the softAP network ID. 124 | * @return IPAddress softAP networkID 125 | */ 126 | IPAddress WiFiAPClass::softAPNetworkID() { 127 | return AP.networkID(); 128 | } 129 | 130 | /** 131 | * Get the softAP subnet mask. 132 | * @return IPAddress subnetMask 133 | */ 134 | IPAddress WiFiAPClass::softAPSubnetMask() { 135 | return AP.subnetMask(); 136 | } 137 | 138 | /** 139 | * Get the softAP subnet CIDR. 140 | * @return uint8_t softAP subnetCIDR 141 | */ 142 | uint8_t WiFiAPClass::softAPSubnetCIDR() { 143 | return AP.subnetCIDR(); 144 | } 145 | 146 | /** 147 | * Get the softAP interface MAC address. 148 | * @param mac pointer to uint8_t array with length WL_MAC_ADDR_LENGTH 149 | * @return pointer to uint8_t* 150 | */ 151 | uint8_t *WiFiAPClass::softAPmacAddress(uint8_t *mac) { 152 | return AP.macAddress(mac); 153 | } 154 | 155 | /** 156 | * Get the softAP interface MAC address. 157 | * @return String mac 158 | */ 159 | String WiFiAPClass::softAPmacAddress(void) { 160 | return AP.macAddress(); 161 | } 162 | 163 | /** 164 | * Get the softAP interface Host name. 165 | * @return char array hostname 166 | */ 167 | const char *WiFiAPClass::softAPgetHostname() { 168 | return AP.getHostname(); 169 | } 170 | 171 | /** 172 | * Set the softAP interface Host name. 173 | * @param hostname pointer to const string 174 | * @return true on success 175 | */ 176 | bool WiFiAPClass::softAPsetHostname(const char *hostname) { 177 | return AP.setHostname(hostname); 178 | } 179 | 180 | #if CONFIG_LWIP_IPV6 181 | /** 182 | * Enable IPv6 on the softAP interface. 183 | * @return true on success 184 | */ 185 | bool WiFiAPClass::softAPenableIPv6(bool enable) { 186 | return AP.enableIPv6(enable); 187 | } 188 | 189 | /** 190 | * Get the softAP interface IPv6 address. 191 | * @return IPAddress softAP IPv6 192 | */ 193 | 194 | IPAddress WiFiAPClass::softAPlinkLocalIPv6() { 195 | return AP.linkLocalIPv6(); 196 | } 197 | #endif 198 | #endif /* SOC_WIFI_SUPPORTED */ 199 | -------------------------------------------------------------------------------- /ESP-IDF codes ( .C )/BT/Nimble_server/BLE_test1newLED_ON_OFF/main/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "freertos/FreeRTOS.h" 3 | #include "freertos/task.h" 4 | #include "freertos/event_groups.h" 5 | #include "esp_event.h" 6 | #include "nvs_flash.h" 7 | #include "esp_log.h" 8 | #include "esp_nimble_hci.h" 9 | #include "nimble/nimble_port.h" 10 | #include "nimble/nimble_port_freertos.h" 11 | #include "host/ble_hs.h" 12 | #include "services/gap/ble_svc_gap.h" 13 | #include "services/gatt/ble_svc_gatt.h" 14 | #include "sdkconfig.h" 15 | 16 | # include "driver/gpio.h" 17 | 18 | #define LED_PIN 2 // Define the LED GPIO pin (for example, GPIO2 on ESP32) 19 | 20 | // Buffer to store incoming data from BLE client 21 | char received_data[50]; 22 | 23 | 24 | 25 | char *TAG = "BLE-Server"; 26 | uint8_t ble_addr_type; 27 | void ble_app_advertise(void); 28 | 29 | 30 | 31 | // Initialize LED GPIO pin as output 32 | void init_led() { 33 | gpio_set_direction(LED_PIN, GPIO_MODE_OUTPUT); 34 | } 35 | 36 | 37 | // Write data to ESP32 defined as server 38 | static int device_write(uint16_t conn_handle, uint16_t attr_handle, struct ble_gatt_access_ctxt *ctxt, void *arg) { 39 | // Ensure received data does not exceed buffer size 40 | int len = ctxt->om->om_len; 41 | len = len < sizeof(received_data) ? len : sizeof(received_data) - 1; 42 | memcpy(received_data, ctxt->om->om_data, len); 43 | received_data[len] = '\0'; // Null-terminate the received data 44 | 45 | printf("Data from the client: %s\n", received_data); 46 | 47 | // Compare received data to control LED 48 | if (strcmp(received_data, "led_on") == 0) { 49 | gpio_set_level(LED_PIN, 1); // Turn on LED 50 | printf("LED turned ON\n"); 51 | } else if (strcmp(received_data, "led_off") == 0) { 52 | gpio_set_level(LED_PIN, 0); // Turn off LED 53 | printf("LED turned OFF\n"); 54 | } else { 55 | printf("Unknown command: %s\n", received_data); 56 | } 57 | return 0; 58 | } 59 | 60 | // Read data from ESP32 defined as server 61 | static int device_read(uint16_t con_handle, uint16_t attr_handle, struct ble_gatt_access_ctxt *ctxt, void *arg) 62 | { 63 | os_mbuf_append(ctxt->om, "Data from the server", strlen("Data from the server")); 64 | return 0; 65 | } 66 | 67 | // Array of pointers to other service definitions 68 | // UUID - Universal Unique Identifier 69 | static const struct ble_gatt_svc_def gatt_svcs[] = { 70 | {.type = BLE_GATT_SVC_TYPE_PRIMARY, 71 | .uuid = BLE_UUID16_DECLARE(0x180), // Define UUID for device type 72 | .characteristics = (struct ble_gatt_chr_def[]){ 73 | {.uuid = BLE_UUID16_DECLARE(0xFEF4), // Define UUID for reading 74 | .flags = BLE_GATT_CHR_F_READ, 75 | .access_cb = device_read}, 76 | {.uuid = BLE_UUID16_DECLARE(0xDEAD), // Define UUID for writing 77 | .flags = BLE_GATT_CHR_F_WRITE, 78 | .access_cb = device_write}, 79 | {0}}}, 80 | {0}}; 81 | 82 | // BLE event handling 83 | static int ble_gap_event(struct ble_gap_event *event, void *arg) 84 | { 85 | switch (event->type) 86 | { 87 | // Advertise if connected 88 | case BLE_GAP_EVENT_CONNECT: 89 | ESP_LOGI("GAP", "BLE GAP EVENT CONNECT %s", event->connect.status == 0 ? "OK!" : "FAILED!"); 90 | if (event->connect.status != 0) 91 | { 92 | ble_app_advertise(); 93 | } 94 | break; 95 | // Advertise again after completion of the event 96 | case BLE_GAP_EVENT_ADV_COMPLETE: 97 | ESP_LOGI("GAP", "BLE GAP EVENT"); 98 | ble_app_advertise(); 99 | break; 100 | default: 101 | break; 102 | } 103 | return 0; 104 | } 105 | 106 | // Define the BLE connection 107 | void ble_app_advertise(void) 108 | { 109 | // GAP - device name definition 110 | struct ble_hs_adv_fields fields; 111 | const char *device_name; 112 | memset(&fields, 0, sizeof(fields)); 113 | device_name = ble_svc_gap_device_name(); // Read the BLE device name 114 | fields.name = (uint8_t *)device_name; 115 | fields.name_len = strlen(device_name); 116 | fields.name_is_complete = 1; 117 | ble_gap_adv_set_fields(&fields); 118 | 119 | // GAP - device connectivity definition 120 | struct ble_gap_adv_params adv_params; 121 | memset(&adv_params, 0, sizeof(adv_params)); 122 | adv_params.conn_mode = BLE_GAP_CONN_MODE_UND; // connectable or non-connectable 123 | adv_params.disc_mode = BLE_GAP_DISC_MODE_GEN; // discoverable or non-discoverable 124 | ble_gap_adv_start(ble_addr_type, NULL, BLE_HS_FOREVER, &adv_params, ble_gap_event, NULL); 125 | } 126 | 127 | // The application 128 | void ble_app_on_sync(void) 129 | { 130 | ble_hs_id_infer_auto(0, &ble_addr_type); // Determines the best address type automatically 131 | ble_app_advertise(); // Define the BLE connection 132 | } 133 | 134 | // The infinite task 135 | void host_task(void *param) 136 | { 137 | nimble_port_run(); // This function will return only when nimble_port_stop() is executed 138 | } 139 | 140 | void app_main() 141 | { 142 | 143 | // Initialize NVS, BLE, and other components as usual 144 | 145 | init_led(); // Initialize the LED GPIO 146 | 147 | 148 | nvs_flash_init(); // 1 - Initialize NVS flash using 149 | nimble_port_init(); //esp_nimble_hci_and_controller_init(); // 2 - Initialize ESP controller 150 | nimble_port_init(); // 3 - Initialize the host stack 151 | ble_svc_gap_device_name_set("BLE-Server"); // 4 - Initialize NimBLE configuration - server name 152 | ble_svc_gap_init(); // 4 - Initialize NimBLE configuration - gap service 153 | ble_svc_gatt_init(); // 4 - Initialize NimBLE configuration - gatt service 154 | ble_gatts_count_cfg(gatt_svcs); // 4 - Initialize NimBLE configuration - config gatt services 155 | ble_gatts_add_svcs(gatt_svcs); // 4 - Initialize NimBLE configuration - queues gatt services. 156 | ble_hs_cfg.sync_cb = ble_app_on_sync; // 5 - Initialize application 157 | nimble_port_freertos_init(host_task); // 6 - Run the thread 158 | } -------------------------------------------------------------------------------- /ESP32 - arduino IDE codes ( .cpp )/I2C MASTER-SLAVE/master/master.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #define PERIPHERAL_NAME "Smart-Mat_esp32" 8 | #define SERVICE_UUID "fd34f551-28ea-4db1-b83d-d4dc4719c508" 9 | #define CHARACTERISTIC_INPUT_UUID "fad2648e-5eba-4cf8-9275-68df18d432e0" 10 | #define CHARACTERISTIC_OUTPUT_UUID "142F29DD-B1F0-4FA8-8E55-5A2D5F3E2471" 11 | 12 | #define I2C_DEV_ADDR 0x55 13 | 14 | // Global pointer for the BLE output characteristic 15 | BLECharacteristic *pOutputChar; 16 | 17 | // Function to request data from the slave based on a command 18 | String requestSlaveData(String command) { 19 | // Send the command to the slave via I2C. 20 | Wire.beginTransmission(I2C_DEV_ADDR); 21 | Wire.write((const uint8_t*)command.c_str(), command.length()); 22 | uint8_t error = Wire.endTransmission(); 23 | if (error != 0) { 24 | Serial.printf("I2C Transmission error: %u\n", error); 25 | return ""; 26 | } 27 | 28 | // Allow the slave time to process the command. 29 | delay(100); 30 | 31 | int expectedLength = 8; // adjust this if your responses change in length 32 | 33 | // === Dummy Read: Flush the first (stale) response === 34 | int dummyBytes = Wire.requestFrom(I2C_DEV_ADDR, expectedLength); 35 | Serial.printf("Dummy read bytes: %d\n", dummyBytes); 36 | while (Wire.available()) { 37 | Wire.read(); // discard all bytes from the dummy read 38 | } 39 | 40 | // Short delay between the dummy read and the actual request. 41 | delay(100); 42 | 43 | // === Actual Read: Get the valid response === 44 | int bytesReceived = Wire.requestFrom(I2C_DEV_ADDR, expectedLength); 45 | Serial.printf("I2C bytes received (requested): %d\n", bytesReceived); 46 | 47 | int availableBytes = Wire.available(); 48 | Serial.printf("I2C bytes available: %d\n", availableBytes); 49 | 50 | String response = ""; 51 | while (Wire.available()) { 52 | char c = Wire.read(); 53 | if (c != '\0') { // ignore null terminators 54 | response += c; 55 | } 56 | } 57 | Serial.printf("Received from slave: %s\n", response.c_str()); 58 | return response; 59 | } 60 | 61 | 62 | 63 | // Define the PIR sensor pin and initialize the motion count 64 | 65 | int Motion_count = 0; 66 | 67 | // Function to check the PIR sensor for 10 seconds 68 | void checkMotionFor10Seconds() { 69 | unsigned long startTime = millis(); // record the start time 70 | 71 | // Loop for 10,000 milliseconds (10 seconds) 72 | while (millis() - startTime < 10000) { 73 | //int pir_value = digitalRead(PIR_PIN); // Read the PIR sensor value 74 | String slaveData2 = ""; 75 | slaveData2 = requestSlaveData("pir"); 76 | Serial.print("Motion = "); 77 | Serial.println(slaveData2); 78 | 79 | // If motion is detected (HIGH), print a message and increment the count 80 | // if (pir_value == HIGH) { 81 | // Serial.println("Motion detected!"); 82 | // Motion_count++; 83 | // } 84 | 85 | delay(1000); // Wait 1 second before checking again 86 | } 87 | } 88 | 89 | // BLE callback for when the input characteristic is written 90 | class InputReceivedCallbacks: public BLECharacteristicCallbacks { 91 | void onWrite(BLECharacteristic *pCharacteristic) { 92 | // Use Arduino String type for convenience. 93 | String value = pCharacteristic->getValue(); 94 | Serial.printf("BLE Received: %s\n", value.c_str()); 95 | 96 | value.trim(); 97 | String slaveData = ""; 98 | 99 | if (value.equalsIgnoreCase("red")) { 100 | slaveData = requestSlaveData("red"); 101 | } else if (value.equalsIgnoreCase("blue")) { 102 | slaveData = requestSlaveData("blue"); 103 | } else if (value.equalsIgnoreCase("green")) { 104 | slaveData = requestSlaveData("green"); 105 | } else if (value.equalsIgnoreCase("motion")) { 106 | checkMotionFor10Seconds(); 107 | 108 | } else if (value.equalsIgnoreCase("EM1_ON")) { 109 | slaveData = requestSlaveData("EM1_ON"); 110 | } else if (value.equalsIgnoreCase("EM1_OFF")) { 111 | slaveData = requestSlaveData("EM1_OFF"); 112 | } else { 113 | Serial.println("Invalid command received via BLE"); 114 | return; 115 | } 116 | 117 | // Update the BLE output characteristic and notify the client. 118 | pOutputChar->setValue(slaveData.c_str()); 119 | pOutputChar->notify(); 120 | } 121 | }; 122 | 123 | // BLE server callbacks 124 | class ServerCallbacks: public BLEServerCallbacks { 125 | void onConnect(BLEServer* pServer) { 126 | Serial.println("BLE Client Connected"); 127 | } 128 | void onDisconnect(BLEServer* pServer) { 129 | Serial.println("BLE Client Disconnected"); 130 | BLEDevice::startAdvertising(); 131 | } 132 | }; 133 | 134 | void initBLE() { 135 | BLEDevice::init(PERIPHERAL_NAME); 136 | BLEServer *pServer = BLEDevice::createServer(); 137 | pServer->setCallbacks(new ServerCallbacks()); 138 | 139 | BLEService *pService = pServer->createService(SERVICE_UUID); 140 | 141 | // Create input characteristic for BLE writes. 142 | BLECharacteristic *pInputChar = pService->createCharacteristic( 143 | CHARACTERISTIC_INPUT_UUID, 144 | BLECharacteristic::PROPERTY_WRITE 145 | ); 146 | pInputChar->setCallbacks(new InputReceivedCallbacks()); 147 | 148 | // Create output characteristic for BLE reads/notifications. 149 | pOutputChar = pService->createCharacteristic( 150 | CHARACTERISTIC_OUTPUT_UUID, 151 | BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY 152 | ); 153 | pOutputChar->addDescriptor(new BLE2902()); 154 | 155 | pService->start(); 156 | 157 | BLEAdvertising *pAdvertising = BLEDevice::getAdvertising(); 158 | pAdvertising->addServiceUUID(SERVICE_UUID); 159 | pAdvertising->setScanResponse(true); 160 | BLEDevice::startAdvertising(); 161 | 162 | Serial.println("BLE Initialized and Advertising"); 163 | } 164 | 165 | 166 | 167 | 168 | void setup() { 169 | Serial.begin(115200); 170 | // Initialize I2C as master. 171 | Wire.begin(); 172 | // Initialize BLE. 173 | initBLE(); 174 | 175 | 176 | 177 | } 178 | 179 | void loop() { 180 | // The main loop does nothing; BLE callback triggers I2C requests when data is written. 181 | 182 | 183 | 184 | delay(1000); 185 | } 186 | -------------------------------------------------------------------------------- /ESP32 - arduino IDE codes ( .cpp )/WIFI/WIFI_MP3_playing_via_I2s/WIFI_MP3_playing_via_I2s/WIFI_MP3_playing_via_I2s.ino: -------------------------------------------------------------------------------- 1 | #include "Arduino.h" 2 | #include "WiFi.h" 3 | #include "Audio.h" 4 | 5 | // I2S audio output pins 6 | #define I2S_DOUT 13 // Data 7 | #define I2S_BCLK 25 // Bit Clock 8 | #define I2S_LRC 26 // Left/Right Clock or WS pin 9 | 10 | #define LED_PIN 2 // Built-in LED for status indication 11 | 12 | // WiFi credentials 13 | const String ssid = "Vigneshhh"; 14 | const String password = "Vigneshhh"; 15 | 16 | Audio audio; 17 | 18 | // Memory monitoring variables 19 | unsigned long lastMemoryCheck = 0; 20 | unsigned long lastReconnect = 0; 21 | const unsigned long MEMORY_CHECK_INTERVAL = 5000; // Check every 5 seconds 22 | const unsigned long RECONNECT_INTERVAL = 1800000; // Reconnect every 30 minutes 23 | const int MIN_FREE_HEAP = 15000; // Minimum free heap in bytes 24 | 25 | #define WIFI_MAX_TRIES 5 26 | 27 | void setupAudio() { 28 | Serial.println("Setting I2S output pins with memory-safe settings."); 29 | 30 | audio.setPinout(I2S_BCLK, I2S_LRC, I2S_DOUT); 31 | 32 | // Conservative settings to prevent memory issues 33 | audio.setVolume(18); // Lower volume to reduce processing 34 | audio.setConnectionTimeout(5000, 1500); // Shorter timeouts to prevent buffer overflow 35 | 36 | Serial.println("Audio configured with memory-safe settings"); 37 | } 38 | 39 | void connectWiFi() { 40 | Serial.println("Connecting to WiFi..."); 41 | 42 | WiFi.disconnect(true); // Full disconnect and clear settings 43 | delay(100); 44 | 45 | WiFi.mode(WIFI_STA); 46 | WiFi.setSleep(false); 47 | 48 | // Set specific WiFi configuration for stability 49 | WiFi.setAutoReconnect(true); 50 | WiFi.persistent(false); // Don't save WiFi config to flash 51 | 52 | WiFi.begin(ssid.c_str(), password.c_str()); 53 | 54 | int tries = 0; 55 | while (WiFi.status() != WL_CONNECTED && tries < WIFI_MAX_TRIES) { 56 | tries++; 57 | Serial.printf("WiFi attempt #%d\n", tries); 58 | digitalWrite(LED_PIN, HIGH); 59 | delay(300); 60 | digitalWrite(LED_PIN, LOW); 61 | delay(300); 62 | } 63 | 64 | if (WiFi.status() == WL_CONNECTED) { 65 | Serial.printf("WiFi connected! RSSI: %d dBm\n", WiFi.RSSI()); 66 | Serial.printf("Free heap after WiFi: %d bytes\n", ESP.getFreeHeap()); 67 | digitalWrite(LED_PIN, LOW); 68 | } else { 69 | Serial.println("WiFi FAILED!"); 70 | ESP.restart(); // Restart if WiFi fails 71 | } 72 | } 73 | 74 | void connectStream() { 75 | Serial.println("Connecting to audio stream..."); 76 | 77 | // Disconnect any existing stream first 78 | audio.stopSong(); 79 | delay(100); 80 | 81 | //https://res.cloudinary.com/dlx1rzgjq/video/upload/v1748697172/birds-ambiance-204513_cpdig1.mp3 82 | //https://res.cloudinary.com/dsmvqzs8n/video/upload/v1748699612/birds-chirping-ambiance-26052_nghkuf.mp3 83 | bool connected = audio.connecttohost("https://res.cloudinary.com/dsmvqzs8n/video/upload/v1748699612/birds-chirping-ambiance-26052_nghkuf.mp3"); 84 | 85 | if (connected) { 86 | Serial.println("Audio stream connected."); 87 | } else { 88 | Serial.println("Stream connection failed!"); 89 | delay(5000); 90 | ESP.restart(); 91 | } 92 | } 93 | 94 | void checkMemoryAndReconnect() { 95 | unsigned long currentTime = millis(); 96 | 97 | // Regular memory monitoring 98 | if (currentTime - lastMemoryCheck >= MEMORY_CHECK_INTERVAL) { 99 | int freeHeap = ESP.getFreeHeap(); 100 | Serial.printf("Free Heap: %d bytes\n", freeHeap); 101 | 102 | // If memory is critically low, restart 103 | if (freeHeap < MIN_FREE_HEAP) { 104 | Serial.println("CRITICAL: Low memory detected! Restarting..."); 105 | delay(1000); 106 | ESP.restart(); 107 | } 108 | 109 | lastMemoryCheck = currentTime; 110 | } 111 | 112 | // Preventive reconnection every 30 minutes to clear buffers 113 | if (currentTime - lastReconnect >= RECONNECT_INTERVAL) { 114 | Serial.println("Preventive reconnection to clear buffers..."); 115 | 116 | audio.stopSong(); 117 | delay(500); 118 | 119 | if (WiFi.status() == WL_CONNECTED) { 120 | connectStream(); 121 | } else { 122 | connectWiFi(); 123 | connectStream(); 124 | } 125 | 126 | lastReconnect = currentTime; 127 | Serial.printf("Reconnected. Free heap: %d bytes\n", ESP.getFreeHeap()); 128 | } 129 | } 130 | 131 | void blinkSOS(int repeats) { 132 | for (int t = 0; t < repeats; t++) { 133 | // S 134 | for (int i = 0; i < 3; i++) { 135 | digitalWrite(LED_PIN, HIGH); delay(200); 136 | digitalWrite(LED_PIN, LOW); delay(200); 137 | } 138 | // O 139 | for (int i = 0; i < 3; i++) { 140 | digitalWrite(LED_PIN, HIGH); delay(800); 141 | digitalWrite(LED_PIN, LOW); delay(200); 142 | } 143 | // S 144 | for (int i = 0; i < 3; i++) { 145 | digitalWrite(LED_PIN, HIGH); delay(200); 146 | digitalWrite(LED_PIN, LOW); delay(200); 147 | } 148 | delay(1000); 149 | } 150 | } 151 | 152 | void setup() { 153 | Serial.begin(115200); 154 | delay(1000); 155 | Serial.println("=== ESP32 Audio Player (Memory-Safe) ==="); 156 | 157 | pinMode(LED_PIN, OUTPUT); 158 | digitalWrite(LED_PIN, HIGH); // LED on during setup 159 | 160 | // Set CPU to 240MHz but with memory optimization 161 | setCpuFrequencyMhz(240); 162 | Serial.printf("CPU: %d MHz, Initial Heap: %d bytes\n", 163 | getCpuFrequencyMhz(), ESP.getFreeHeap()); 164 | 165 | connectWiFi(); 166 | setupAudio(); 167 | connectStream(); 168 | 169 | digitalWrite(LED_PIN, LOW); // LED off when ready 170 | 171 | lastMemoryCheck = millis(); 172 | lastReconnect = millis(); 173 | 174 | Serial.println("Setup complete - monitoring memory..."); 175 | } 176 | 177 | void loop() { 178 | // Main audio loop 179 | audio.loop(); 180 | 181 | // Memory and connection monitoring 182 | checkMemoryAndReconnect(); 183 | 184 | // Check WiFi status periodically 185 | static unsigned long lastWiFiCheck = 0; 186 | if (millis() - lastWiFiCheck > 10000) { // Every 10 seconds 187 | if (WiFi.status() != WL_CONNECTED) { 188 | Serial.println("WiFi disconnected! Restarting..."); 189 | ESP.restart(); 190 | } 191 | lastWiFiCheck = millis(); 192 | } 193 | 194 | // Small delay to prevent watchdog issues 195 | delay(1); 196 | } -------------------------------------------------------------------------------- /ESP-IDF codes ( .C )/Inputs/ISR_ONE_pin_only_TOUCH/main/main.c: -------------------------------------------------------------------------------- 1 | /* 2 | * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD 3 | * 4 | * SPDX-License-Identifier: CC0-1.0 5 | */ 6 | 7 | #include 8 | #include 9 | #include "freertos/FreeRTOS.h" 10 | #include "freertos/task.h" 11 | #include "freertos/queue.h" 12 | #include "esp_log.h" 13 | 14 | #include "driver/touch_pad.h" 15 | #include "soc/rtc_periph.h" 16 | 17 | static const char *TAG = "Touch pad"; 18 | 19 | #define TOUCH_THRESH_NO_USE (0) 20 | #define TOUCH_THRESH_PERCENT (80) 21 | #define TOUCHPAD_FILTER_TOUCH_PERIOD (10) 22 | 23 | static bool s_pad_activated; 24 | static uint32_t s_pad_init_val; 25 | 26 | /* 27 | Read values sensed at all available touch pads. 28 | Use 2 / 3 of read value as the threshold 29 | to trigger interrupt when the pad is touched. 30 | Note: this routine demonstrates a simple way 31 | to configure activation threshold for the touch pads. 32 | Do not touch any pads when this routine 33 | is running (on application start). 34 | */ 35 | static void tp_example_set_thresholds(void) 36 | { 37 | uint16_t touch_value; 38 | int i = 8; 39 | //read filtered value 40 | touch_pad_read_filtered(i, &touch_value); 41 | s_pad_init_val = touch_value; 42 | ESP_LOGI(TAG, "test init: touch pad [%d] val is %d", i, touch_value); 43 | //set interrupt threshold. 44 | ESP_ERROR_CHECK(touch_pad_set_thresh(i, touch_value * 2 / 3)); 45 | 46 | 47 | } 48 | 49 | /* 50 | Check if any of touch pads has been activated 51 | by reading a table updated by rtc_intr() 52 | If so, then print it out on a serial monitor. 53 | Clear related entry in the table afterwards 54 | 55 | In interrupt mode, the table is updated in touch ISR. 56 | 57 | In filter mode, we will compare the current filtered value with the initial one. 58 | If the current filtered value is less than 80% of the initial value, we can 59 | regard it as a 'touched' event. 60 | When calling touch_pad_init, a timer will be started to run the filter. 61 | This mode is designed for the situation that the pad is covered 62 | by a 2-or-3-mm-thick medium, usually glass or plastic. 63 | The difference caused by a 'touch' action could be very small, but we can still use 64 | filter mode to detect a 'touch' event. 65 | */ 66 | static void tp_example_read_task(void *pvParameter) 67 | { 68 | static int show_message; 69 | //int change_mode = 0; 70 | int filter_mode = 0; 71 | while (1) { 72 | if (filter_mode == 0) { 73 | //interrupt mode, enable touch interrupt 74 | touch_pad_intr_enable(); 75 | int i = 8; 76 | if (s_pad_activated == true) { 77 | ESP_LOGI(TAG, "T%d activated!", i); 78 | // Wait a while for the pad being released 79 | vTaskDelay(200 / portTICK_PERIOD_MS); 80 | // Clear information on pad activation 81 | s_pad_activated = false; 82 | // Reset the counter triggering a message 83 | // that application is running 84 | show_message = 1; 85 | } 86 | 87 | } /*else { 88 | //filter mode, disable touch interrupt 89 | touch_pad_intr_disable(); 90 | touch_pad_clear_status(); 91 | for (int i = 0; i < TOUCH_PAD_MAX; i++) { 92 | uint16_t value = 0; 93 | touch_pad_read_filtered(i, &value); 94 | if (value < s_pad_init_val[i] * TOUCH_THRESH_PERCENT / 100) { 95 | ESP_LOGI(TAG, "T%d activated!", i); 96 | ESP_LOGI(TAG, "value: %"PRIu16"; init val: %"PRIu32, value, s_pad_init_val[i]); 97 | vTaskDelay(200 / portTICK_PERIOD_MS); 98 | // Reset the counter to stop changing mode. 99 | change_mode = 1; 100 | show_message = 1; 101 | } 102 | } 103 | } 104 | */ 105 | vTaskDelay(10 / portTICK_PERIOD_MS); 106 | 107 | // If no pad is touched, every couple of seconds, show a message 108 | // that application is running 109 | if (show_message++ % 500 == 0) { 110 | ESP_LOGI(TAG, "Waiting for any pad being touched..."); 111 | } 112 | // Change mode if no pad is touched for a long time. 113 | // We can compare the two different mode. 114 | /* if (change_mode++ % 2000 == 0) { 115 | filter_mode = !filter_mode; 116 | ESP_LOGW(TAG, "Change mode...%s", filter_mode == 0 ? "interrupt mode" : "filter mode"); 117 | } 118 | }*/ 119 | } 120 | } 121 | 122 | /* 123 | Handle an interrupt triggered when a pad is touched. 124 | Recognize what pad has been touched and save it in a table. 125 | */ 126 | static void tp_example_rtc_intr(void *arg) 127 | { 128 | uint32_t pad_intr = touch_pad_get_status(); 129 | //clear interrupt 130 | touch_pad_clear_status(); 131 | int i = 8; 132 | if ((pad_intr >> i) & 0x01) { 133 | s_pad_activated = true; 134 | } 135 | 136 | } 137 | 138 | /* 139 | * Before reading touch pad, we need to initialize the RTC IO. 140 | */ 141 | static void tp_example_touch_pad_init(void) 142 | { 143 | int i = 8; 144 | //init RTC IO and mode for touch pad. 145 | touch_pad_config(i, TOUCH_THRESH_NO_USE); 146 | 147 | } 148 | 149 | void app_main(void) 150 | { 151 | // Initialize touch pad peripheral, it will start a timer to run a filter 152 | ESP_LOGI(TAG, "Initializing touch pad"); 153 | ESP_ERROR_CHECK(touch_pad_init()); 154 | // If use interrupt trigger mode, should set touch sensor FSM mode at 'TOUCH_FSM_MODE_TIMER'. 155 | touch_pad_set_fsm_mode(TOUCH_FSM_MODE_TIMER); 156 | // Set reference voltage for charging/discharging 157 | // For most usage scenarios, we recommend using the following combination: 158 | // the high reference valtage will be 2.7V - 1V = 1.7V, The low reference voltage will be 0.5V. 159 | touch_pad_set_voltage(TOUCH_HVOLT_2V7, TOUCH_LVOLT_0V5, TOUCH_HVOLT_ATTEN_1V); 160 | // Init touch pad IO 161 | tp_example_touch_pad_init(); 162 | // Initialize and start a software filter to detect slight change of capacitance. 163 | touch_pad_filter_start(TOUCHPAD_FILTER_TOUCH_PERIOD); 164 | // Set thresh hold 165 | tp_example_set_thresholds(); 166 | // Register touch interrupt ISR 167 | touch_pad_isr_register(tp_example_rtc_intr, NULL); 168 | // Start a task to show what pads have been touched 169 | xTaskCreate(&tp_example_read_task, "touch_pad_read_task", 4096, NULL, 5, NULL); 170 | } 171 | -------------------------------------------------------------------------------- /ESP-IDF codes ( .C )/ADC/PIR-sensor-test1-MOTION/.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "Build - Build project", 6 | "type": "shell", 7 | "command": "${config:idf.pythonBinPath} ${config:idf.espIdfPath}/tools/idf.py build", 8 | "windows": { 9 | "command": "${config:idf.pythonBinPathWin} ${config:idf.espIdfPathWin}\\tools\\idf.py build", 10 | "options": { 11 | "env": { 12 | "PATH": "${env:PATH};${config:idf.customExtraPaths}" 13 | } 14 | } 15 | }, 16 | "options": { 17 | "env": { 18 | "PATH": "${env:PATH}:${config:idf.customExtraPaths}" 19 | } 20 | }, 21 | "problemMatcher": [ 22 | { 23 | "owner": "cpp", 24 | "fileLocation": [ 25 | "autoDetect", 26 | "${workspaceFolder}" 27 | ], 28 | "pattern": { 29 | "regexp": "^(.*?):(\\d+):(\\d*):?\\s+(?:fatal\\s+)?(warning|error):\\s+(.*)$", 30 | "file": 1, 31 | "line": 2, 32 | "column": 3, 33 | "severity": 4, 34 | "message": 5 35 | } 36 | } 37 | ], 38 | "group": { 39 | "kind": "build", 40 | "isDefault": true 41 | } 42 | }, 43 | { 44 | "label": "Set ESP-IDF Target", 45 | "type": "shell", 46 | "command": "${command:espIdf.setTarget}", 47 | "problemMatcher": { 48 | "owner": "cpp", 49 | "fileLocation": [ 50 | "autoDetect", 51 | "${workspaceFolder}" 52 | ], 53 | "pattern": { 54 | "regexp": "^(.*?):(\\d+):(\\d*):?\\s+(?:fatal\\s+)?(warning|error):\\s+(.*)$", 55 | "file": 1, 56 | "line": 2, 57 | "column": 3, 58 | "severity": 4, 59 | "message": 5 60 | } 61 | } 62 | }, 63 | { 64 | "label": "Clean - Clean the project", 65 | "type": "shell", 66 | "command": "${config:idf.pythonBinPath} ${config:idf.espIdfPath}/tools/idf.py fullclean", 67 | "windows": { 68 | "command": "${config:idf.pythonBinPathWin} ${config:idf.espIdfPathWin}\\tools\\idf.py fullclean", 69 | "options": { 70 | "env": { 71 | "PATH": "${env:PATH};${config:idf.customExtraPaths}" 72 | } 73 | } 74 | }, 75 | "options": { 76 | "env": { 77 | "PATH": "${env:PATH}:${config:idf.customExtraPaths}" 78 | } 79 | }, 80 | "problemMatcher": [ 81 | { 82 | "owner": "cpp", 83 | "fileLocation": [ 84 | "autoDetect", 85 | "${workspaceFolder}" 86 | ], 87 | "pattern": { 88 | "regexp": "^(.*?):(\\d+):(\\d*):?\\s+(?:fatal\\s+)?(warning|error):\\s+(.*)$", 89 | "file": 1, 90 | "line": 2, 91 | "column": 3, 92 | "severity": 4, 93 | "message": 5 94 | } 95 | } 96 | ] 97 | }, 98 | { 99 | "label": "Flash - Flash the device", 100 | "type": "shell", 101 | "command": "${config:idf.pythonBinPath} ${config:idf.espIdfPath}/tools/idf.py -p ${config:idf.port} -b ${config:idf.flashBaudRate} flash", 102 | "windows": { 103 | "command": "${config:idf.pythonBinPathWin} ${config:idf.espIdfPathWin}\\tools\\idf.py flash -p ${config:idf.portWin} -b ${config:idf.flashBaudRate}", 104 | "options": { 105 | "env": { 106 | "PATH": "${env:PATH};${config:idf.customExtraPaths}" 107 | } 108 | } 109 | }, 110 | "options": { 111 | "env": { 112 | "PATH": "${env:PATH}:${config:idf.customExtraPaths}" 113 | } 114 | }, 115 | "problemMatcher": [ 116 | { 117 | "owner": "cpp", 118 | "fileLocation": [ 119 | "autoDetect", 120 | "${workspaceFolder}" 121 | ], 122 | "pattern": { 123 | "regexp": "^(.*?):(\\d+):(\\d*):?\\s+(?:fatal\\s+)?(warning|error):\\s+(.*)$", 124 | "file": 1, 125 | "line": 2, 126 | "column": 3, 127 | "severity": 4, 128 | "message": 5 129 | } 130 | } 131 | ] 132 | }, 133 | { 134 | "label": "Monitor: Start the monitor", 135 | "type": "shell", 136 | "command": "${config:idf.pythonBinPath} ${config:idf.espIdfPath}/tools/idf.py -p ${config:idf.port} monitor", 137 | "windows": { 138 | "command": "${config:idf.pythonBinPathWin} ${config:idf.espIdfPathWin}\\tools\\idf.py -p ${config:idf.portWin} monitor", 139 | "options": { 140 | "env": { 141 | "PATH": "${env:PATH};${config:idf.customExtraPaths}" 142 | } 143 | } 144 | }, 145 | "options": { 146 | "env": { 147 | "PATH": "${env:PATH}:${config:idf.customExtraPaths}" 148 | } 149 | }, 150 | "problemMatcher": [ 151 | { 152 | "owner": "cpp", 153 | "fileLocation": [ 154 | "autoDetect", 155 | "${workspaceFolder}" 156 | ], 157 | "pattern": { 158 | "regexp": "^(.*?):(\\d+):(\\d*):?\\s+(?:fatal\\s+)?(warning|error):\\s+(.*)$", 159 | "file": 1, 160 | "line": 2, 161 | "column": 3, 162 | "severity": 4, 163 | "message": 5 164 | } 165 | } 166 | ], 167 | "dependsOn": "Flash - Flash the device" 168 | }, 169 | { 170 | "label": "OpenOCD: Start openOCD", 171 | "type": "shell", 172 | "presentation": { 173 | "echo": true, 174 | "reveal": "never", 175 | "focus": false, 176 | "panel": "new" 177 | }, 178 | "command": "openocd -s ${command:espIdf.getOpenOcdScriptValue} ${command:espIdf.getOpenOcdConfigs}", 179 | "windows": { 180 | "command": "openocd.exe -s ${command:espIdf.getOpenOcdScriptValue} ${command:espIdf.getOpenOcdConfigs}", 181 | "options": { 182 | "env": { 183 | "PATH": "${env:PATH};${config:idf.customExtraPaths}" 184 | } 185 | } 186 | }, 187 | "options": { 188 | "env": { 189 | "PATH": "${env:PATH}:${config:idf.customExtraPaths}" 190 | } 191 | }, 192 | "problemMatcher": { 193 | "owner": "cpp", 194 | "fileLocation": [ 195 | "autoDetect", 196 | "${workspaceFolder}" 197 | ], 198 | "pattern": { 199 | "regexp": "^(.*?):(\\d+):(\\d*):?\\s+(?:fatal\\s+)?(warning|error):\\s+(.*)$", 200 | "file": 1, 201 | "line": 2, 202 | "column": 3, 203 | "severity": 4, 204 | "message": 5 205 | } 206 | } 207 | }, 208 | { 209 | "label": "adapter", 210 | "type": "shell", 211 | "command": "${config:idf.pythonBinPath}", 212 | "isBackground": true, 213 | "options": { 214 | "env": { 215 | "PATH": "${env:PATH}:${config:idf.customExtraPaths}", 216 | "PYTHONPATH": "${command:espIdf.getExtensionPath}/esp_debug_adapter/debug_adapter" 217 | } 218 | }, 219 | "problemMatcher": { 220 | "background": { 221 | "beginsPattern": "\bDEBUG_ADAPTER_STARTED\b", 222 | "endsPattern": "DEBUG_ADAPTER_READY2CONNECT", 223 | "activeOnStart": true 224 | }, 225 | "pattern": { 226 | "regexp": "(\\d+)-(\\d+)-(\\d+)\\s(\\d+):(\\d+):(\\d+),(\\d+)\\s-(.+)\\s(ERROR)", 227 | "file": 8, 228 | "line": 2, 229 | "column": 3, 230 | "severity": 4, 231 | "message": 9 232 | } 233 | }, 234 | "args": [ 235 | "${command:espIdf.getExtensionPath}/esp_debug_adapter/debug_adapter_main.py", 236 | "-e", 237 | "${workspaceFolder}/build/${command:espIdf.getProjectName}.elf", 238 | "-s", 239 | "$OPENOCD_SCRIPTS", 240 | "-dn", 241 | "esp32", 242 | "-om", 243 | "connect_to_instance", 244 | "-t", 245 | "xtensa-esp32-elf-" 246 | 247 | ], 248 | "windows": { 249 | "command": "${config:idf.pythonBinPathWin}", 250 | "options": { 251 | "env": { 252 | "PATH": "${env:PATH};${config:idf.customExtraPaths}", 253 | "PYTHONPATH": "${command:espIdf.getExtensionPath}/esp_debug_adapter/debug_adapter" 254 | } 255 | } 256 | } 257 | } 258 | ] 259 | } -------------------------------------------------------------------------------- /ESP-IDF codes ( .C )/Inputs/ISR_ONE_pin_only_TOUCH/.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "Build - Build project", 6 | "type": "shell", 7 | "command": "${config:idf.pythonBinPath} ${config:idf.espIdfPath}/tools/idf.py build", 8 | "windows": { 9 | "command": "${config:idf.pythonBinPathWin} ${config:idf.espIdfPathWin}\\tools\\idf.py build", 10 | "options": { 11 | "env": { 12 | "PATH": "${env:PATH};${config:idf.customExtraPaths}" 13 | } 14 | } 15 | }, 16 | "options": { 17 | "env": { 18 | "PATH": "${env:PATH}:${config:idf.customExtraPaths}" 19 | } 20 | }, 21 | "problemMatcher": [ 22 | { 23 | "owner": "cpp", 24 | "fileLocation": [ 25 | "autoDetect", 26 | "${workspaceFolder}" 27 | ], 28 | "pattern": { 29 | "regexp": "^(.*?):(\\d+):(\\d*):?\\s+(?:fatal\\s+)?(warning|error):\\s+(.*)$", 30 | "file": 1, 31 | "line": 2, 32 | "column": 3, 33 | "severity": 4, 34 | "message": 5 35 | } 36 | } 37 | ], 38 | "group": { 39 | "kind": "build", 40 | "isDefault": true 41 | } 42 | }, 43 | { 44 | "label": "Set ESP-IDF Target", 45 | "type": "shell", 46 | "command": "${command:espIdf.setTarget}", 47 | "problemMatcher": { 48 | "owner": "cpp", 49 | "fileLocation": [ 50 | "autoDetect", 51 | "${workspaceFolder}" 52 | ], 53 | "pattern": { 54 | "regexp": "^(.*?):(\\d+):(\\d*):?\\s+(?:fatal\\s+)?(warning|error):\\s+(.*)$", 55 | "file": 1, 56 | "line": 2, 57 | "column": 3, 58 | "severity": 4, 59 | "message": 5 60 | } 61 | } 62 | }, 63 | { 64 | "label": "Clean - Clean the project", 65 | "type": "shell", 66 | "command": "${config:idf.pythonBinPath} ${config:idf.espIdfPath}/tools/idf.py fullclean", 67 | "windows": { 68 | "command": "${config:idf.pythonBinPathWin} ${config:idf.espIdfPathWin}\\tools\\idf.py fullclean", 69 | "options": { 70 | "env": { 71 | "PATH": "${env:PATH};${config:idf.customExtraPaths}" 72 | } 73 | } 74 | }, 75 | "options": { 76 | "env": { 77 | "PATH": "${env:PATH}:${config:idf.customExtraPaths}" 78 | } 79 | }, 80 | "problemMatcher": [ 81 | { 82 | "owner": "cpp", 83 | "fileLocation": [ 84 | "autoDetect", 85 | "${workspaceFolder}" 86 | ], 87 | "pattern": { 88 | "regexp": "^(.*?):(\\d+):(\\d*):?\\s+(?:fatal\\s+)?(warning|error):\\s+(.*)$", 89 | "file": 1, 90 | "line": 2, 91 | "column": 3, 92 | "severity": 4, 93 | "message": 5 94 | } 95 | } 96 | ] 97 | }, 98 | { 99 | "label": "Flash - Flash the device", 100 | "type": "shell", 101 | "command": "${config:idf.pythonBinPath} ${config:idf.espIdfPath}/tools/idf.py -p ${config:idf.port} -b ${config:idf.flashBaudRate} flash", 102 | "windows": { 103 | "command": "${config:idf.pythonBinPathWin} ${config:idf.espIdfPathWin}\\tools\\idf.py flash -p ${config:idf.portWin} -b ${config:idf.flashBaudRate}", 104 | "options": { 105 | "env": { 106 | "PATH": "${env:PATH};${config:idf.customExtraPaths}" 107 | } 108 | } 109 | }, 110 | "options": { 111 | "env": { 112 | "PATH": "${env:PATH}:${config:idf.customExtraPaths}" 113 | } 114 | }, 115 | "problemMatcher": [ 116 | { 117 | "owner": "cpp", 118 | "fileLocation": [ 119 | "autoDetect", 120 | "${workspaceFolder}" 121 | ], 122 | "pattern": { 123 | "regexp": "^(.*?):(\\d+):(\\d*):?\\s+(?:fatal\\s+)?(warning|error):\\s+(.*)$", 124 | "file": 1, 125 | "line": 2, 126 | "column": 3, 127 | "severity": 4, 128 | "message": 5 129 | } 130 | } 131 | ] 132 | }, 133 | { 134 | "label": "Monitor: Start the monitor", 135 | "type": "shell", 136 | "command": "${config:idf.pythonBinPath} ${config:idf.espIdfPath}/tools/idf.py -p ${config:idf.port} monitor", 137 | "windows": { 138 | "command": "${config:idf.pythonBinPathWin} ${config:idf.espIdfPathWin}\\tools\\idf.py -p ${config:idf.portWin} monitor", 139 | "options": { 140 | "env": { 141 | "PATH": "${env:PATH};${config:idf.customExtraPaths}" 142 | } 143 | } 144 | }, 145 | "options": { 146 | "env": { 147 | "PATH": "${env:PATH}:${config:idf.customExtraPaths}" 148 | } 149 | }, 150 | "problemMatcher": [ 151 | { 152 | "owner": "cpp", 153 | "fileLocation": [ 154 | "autoDetect", 155 | "${workspaceFolder}" 156 | ], 157 | "pattern": { 158 | "regexp": "^(.*?):(\\d+):(\\d*):?\\s+(?:fatal\\s+)?(warning|error):\\s+(.*)$", 159 | "file": 1, 160 | "line": 2, 161 | "column": 3, 162 | "severity": 4, 163 | "message": 5 164 | } 165 | } 166 | ], 167 | "dependsOn": "Flash - Flash the device" 168 | }, 169 | { 170 | "label": "OpenOCD: Start openOCD", 171 | "type": "shell", 172 | "presentation": { 173 | "echo": true, 174 | "reveal": "never", 175 | "focus": false, 176 | "panel": "new" 177 | }, 178 | "command": "openocd -s ${command:espIdf.getOpenOcdScriptValue} ${command:espIdf.getOpenOcdConfigs}", 179 | "windows": { 180 | "command": "openocd.exe -s ${command:espIdf.getOpenOcdScriptValue} ${command:espIdf.getOpenOcdConfigs}", 181 | "options": { 182 | "env": { 183 | "PATH": "${env:PATH};${config:idf.customExtraPaths}" 184 | } 185 | } 186 | }, 187 | "options": { 188 | "env": { 189 | "PATH": "${env:PATH}:${config:idf.customExtraPaths}" 190 | } 191 | }, 192 | "problemMatcher": { 193 | "owner": "cpp", 194 | "fileLocation": [ 195 | "autoDetect", 196 | "${workspaceFolder}" 197 | ], 198 | "pattern": { 199 | "regexp": "^(.*?):(\\d+):(\\d*):?\\s+(?:fatal\\s+)?(warning|error):\\s+(.*)$", 200 | "file": 1, 201 | "line": 2, 202 | "column": 3, 203 | "severity": 4, 204 | "message": 5 205 | } 206 | } 207 | }, 208 | { 209 | "label": "adapter", 210 | "type": "shell", 211 | "command": "${config:idf.pythonBinPath}", 212 | "isBackground": true, 213 | "options": { 214 | "env": { 215 | "PATH": "${env:PATH}:${config:idf.customExtraPaths}", 216 | "PYTHONPATH": "${command:espIdf.getExtensionPath}/esp_debug_adapter/debug_adapter" 217 | } 218 | }, 219 | "problemMatcher": { 220 | "background": { 221 | "beginsPattern": "\bDEBUG_ADAPTER_STARTED\b", 222 | "endsPattern": "DEBUG_ADAPTER_READY2CONNECT", 223 | "activeOnStart": true 224 | }, 225 | "pattern": { 226 | "regexp": "(\\d+)-(\\d+)-(\\d+)\\s(\\d+):(\\d+):(\\d+),(\\d+)\\s-(.+)\\s(ERROR)", 227 | "file": 8, 228 | "line": 2, 229 | "column": 3, 230 | "severity": 4, 231 | "message": 9 232 | } 233 | }, 234 | "args": [ 235 | "${command:espIdf.getExtensionPath}/esp_debug_adapter/debug_adapter_main.py", 236 | "-e", 237 | "${workspaceFolder}/build/${command:espIdf.getProjectName}.elf", 238 | "-s", 239 | "$OPENOCD_SCRIPTS", 240 | "-dn", 241 | "esp32", 242 | "-om", 243 | "connect_to_instance", 244 | "-t", 245 | "xtensa-esp32-elf-" 246 | 247 | ], 248 | "windows": { 249 | "command": "${config:idf.pythonBinPathWin}", 250 | "options": { 251 | "env": { 252 | "PATH": "${env:PATH};${config:idf.customExtraPaths}", 253 | "PYTHONPATH": "${command:espIdf.getExtensionPath}/esp_debug_adapter/debug_adapter" 254 | } 255 | } 256 | } 257 | } 258 | ] 259 | } -------------------------------------------------------------------------------- /ESP-IDF codes ( .C )/BT/Nimble_server/BLE_test1newLED_ON_OFF/.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "Build - Build project", 6 | "type": "shell", 7 | "command": "${config:idf.pythonBinPath} ${config:idf.espIdfPath}/tools/idf.py build", 8 | "windows": { 9 | "command": "${config:idf.pythonBinPathWin} ${config:idf.espIdfPathWin}\\tools\\idf.py build", 10 | "options": { 11 | "env": { 12 | "PATH": "${env:PATH};${config:idf.customExtraPaths}" 13 | } 14 | } 15 | }, 16 | "options": { 17 | "env": { 18 | "PATH": "${env:PATH}:${config:idf.customExtraPaths}" 19 | } 20 | }, 21 | "problemMatcher": [ 22 | { 23 | "owner": "cpp", 24 | "fileLocation": [ 25 | "autoDetect", 26 | "${workspaceFolder}" 27 | ], 28 | "pattern": { 29 | "regexp": "^(.*?):(\\d+):(\\d*):?\\s+(?:fatal\\s+)?(warning|error):\\s+(.*)$", 30 | "file": 1, 31 | "line": 2, 32 | "column": 3, 33 | "severity": 4, 34 | "message": 5 35 | } 36 | } 37 | ], 38 | "group": { 39 | "kind": "build", 40 | "isDefault": true 41 | } 42 | }, 43 | { 44 | "label": "Set ESP-IDF Target", 45 | "type": "shell", 46 | "command": "${command:espIdf.setTarget}", 47 | "problemMatcher": { 48 | "owner": "cpp", 49 | "fileLocation": [ 50 | "autoDetect", 51 | "${workspaceFolder}" 52 | ], 53 | "pattern": { 54 | "regexp": "^(.*?):(\\d+):(\\d*):?\\s+(?:fatal\\s+)?(warning|error):\\s+(.*)$", 55 | "file": 1, 56 | "line": 2, 57 | "column": 3, 58 | "severity": 4, 59 | "message": 5 60 | } 61 | } 62 | }, 63 | { 64 | "label": "Clean - Clean the project", 65 | "type": "shell", 66 | "command": "${config:idf.pythonBinPath} ${config:idf.espIdfPath}/tools/idf.py fullclean", 67 | "windows": { 68 | "command": "${config:idf.pythonBinPathWin} ${config:idf.espIdfPathWin}\\tools\\idf.py fullclean", 69 | "options": { 70 | "env": { 71 | "PATH": "${env:PATH};${config:idf.customExtraPaths}" 72 | } 73 | } 74 | }, 75 | "options": { 76 | "env": { 77 | "PATH": "${env:PATH}:${config:idf.customExtraPaths}" 78 | } 79 | }, 80 | "problemMatcher": [ 81 | { 82 | "owner": "cpp", 83 | "fileLocation": [ 84 | "autoDetect", 85 | "${workspaceFolder}" 86 | ], 87 | "pattern": { 88 | "regexp": "^(.*?):(\\d+):(\\d*):?\\s+(?:fatal\\s+)?(warning|error):\\s+(.*)$", 89 | "file": 1, 90 | "line": 2, 91 | "column": 3, 92 | "severity": 4, 93 | "message": 5 94 | } 95 | } 96 | ] 97 | }, 98 | { 99 | "label": "Flash - Flash the device", 100 | "type": "shell", 101 | "command": "${config:idf.pythonBinPath} ${config:idf.espIdfPath}/tools/idf.py -p ${config:idf.port} -b ${config:idf.flashBaudRate} flash", 102 | "windows": { 103 | "command": "${config:idf.pythonBinPathWin} ${config:idf.espIdfPathWin}\\tools\\idf.py flash -p ${config:idf.portWin} -b ${config:idf.flashBaudRate}", 104 | "options": { 105 | "env": { 106 | "PATH": "${env:PATH};${config:idf.customExtraPaths}" 107 | } 108 | } 109 | }, 110 | "options": { 111 | "env": { 112 | "PATH": "${env:PATH}:${config:idf.customExtraPaths}" 113 | } 114 | }, 115 | "problemMatcher": [ 116 | { 117 | "owner": "cpp", 118 | "fileLocation": [ 119 | "autoDetect", 120 | "${workspaceFolder}" 121 | ], 122 | "pattern": { 123 | "regexp": "^(.*?):(\\d+):(\\d*):?\\s+(?:fatal\\s+)?(warning|error):\\s+(.*)$", 124 | "file": 1, 125 | "line": 2, 126 | "column": 3, 127 | "severity": 4, 128 | "message": 5 129 | } 130 | } 131 | ] 132 | }, 133 | { 134 | "label": "Monitor: Start the monitor", 135 | "type": "shell", 136 | "command": "${config:idf.pythonBinPath} ${config:idf.espIdfPath}/tools/idf.py -p ${config:idf.port} monitor", 137 | "windows": { 138 | "command": "${config:idf.pythonBinPathWin} ${config:idf.espIdfPathWin}\\tools\\idf.py -p ${config:idf.portWin} monitor", 139 | "options": { 140 | "env": { 141 | "PATH": "${env:PATH};${config:idf.customExtraPaths}" 142 | } 143 | } 144 | }, 145 | "options": { 146 | "env": { 147 | "PATH": "${env:PATH}:${config:idf.customExtraPaths}" 148 | } 149 | }, 150 | "problemMatcher": [ 151 | { 152 | "owner": "cpp", 153 | "fileLocation": [ 154 | "autoDetect", 155 | "${workspaceFolder}" 156 | ], 157 | "pattern": { 158 | "regexp": "^(.*?):(\\d+):(\\d*):?\\s+(?:fatal\\s+)?(warning|error):\\s+(.*)$", 159 | "file": 1, 160 | "line": 2, 161 | "column": 3, 162 | "severity": 4, 163 | "message": 5 164 | } 165 | } 166 | ], 167 | "dependsOn": "Flash - Flash the device" 168 | }, 169 | { 170 | "label": "OpenOCD: Start openOCD", 171 | "type": "shell", 172 | "presentation": { 173 | "echo": true, 174 | "reveal": "never", 175 | "focus": false, 176 | "panel": "new" 177 | }, 178 | "command": "openocd -s ${command:espIdf.getOpenOcdScriptValue} ${command:espIdf.getOpenOcdConfigs}", 179 | "windows": { 180 | "command": "openocd.exe -s ${command:espIdf.getOpenOcdScriptValue} ${command:espIdf.getOpenOcdConfigs}", 181 | "options": { 182 | "env": { 183 | "PATH": "${env:PATH};${config:idf.customExtraPaths}" 184 | } 185 | } 186 | }, 187 | "options": { 188 | "env": { 189 | "PATH": "${env:PATH}:${config:idf.customExtraPaths}" 190 | } 191 | }, 192 | "problemMatcher": { 193 | "owner": "cpp", 194 | "fileLocation": [ 195 | "autoDetect", 196 | "${workspaceFolder}" 197 | ], 198 | "pattern": { 199 | "regexp": "^(.*?):(\\d+):(\\d*):?\\s+(?:fatal\\s+)?(warning|error):\\s+(.*)$", 200 | "file": 1, 201 | "line": 2, 202 | "column": 3, 203 | "severity": 4, 204 | "message": 5 205 | } 206 | } 207 | }, 208 | { 209 | "label": "adapter", 210 | "type": "shell", 211 | "command": "${config:idf.pythonBinPath}", 212 | "isBackground": true, 213 | "options": { 214 | "env": { 215 | "PATH": "${env:PATH}:${config:idf.customExtraPaths}", 216 | "PYTHONPATH": "${command:espIdf.getExtensionPath}/esp_debug_adapter/debug_adapter" 217 | } 218 | }, 219 | "problemMatcher": { 220 | "background": { 221 | "beginsPattern": "\bDEBUG_ADAPTER_STARTED\b", 222 | "endsPattern": "DEBUG_ADAPTER_READY2CONNECT", 223 | "activeOnStart": true 224 | }, 225 | "pattern": { 226 | "regexp": "(\\d+)-(\\d+)-(\\d+)\\s(\\d+):(\\d+):(\\d+),(\\d+)\\s-(.+)\\s(ERROR)", 227 | "file": 8, 228 | "line": 2, 229 | "column": 3, 230 | "severity": 4, 231 | "message": 9 232 | } 233 | }, 234 | "args": [ 235 | "${command:espIdf.getExtensionPath}/esp_debug_adapter/debug_adapter_main.py", 236 | "-e", 237 | "${workspaceFolder}/build/${command:espIdf.getProjectName}.elf", 238 | "-s", 239 | "$OPENOCD_SCRIPTS", 240 | "-dn", 241 | "esp32", 242 | "-om", 243 | "connect_to_instance", 244 | "-t", 245 | "xtensa-esp32-elf-" 246 | 247 | ], 248 | "windows": { 249 | "command": "${config:idf.pythonBinPathWin}", 250 | "options": { 251 | "env": { 252 | "PATH": "${env:PATH};${config:idf.customExtraPaths}", 253 | "PYTHONPATH": "${command:espIdf.getExtensionPath}/esp_debug_adapter/debug_adapter" 254 | } 255 | } 256 | } 257 | } 258 | ] 259 | } -------------------------------------------------------------------------------- /ESP32 - arduino IDE codes ( .cpp )/WIFI/WIFI_MP3_playing_via_I2s/WIFI_MP3_playing_via_I2s/External libs/WIFI libs used/WiFiSTA.h: -------------------------------------------------------------------------------- 1 | /* 2 | ESP8266WiFiSTA.h - esp8266 Wifi support. 3 | Based on WiFi.h from Ardiono WiFi shield library. 4 | Copyright (c) 2011-2014 Arduino. All right reserved. 5 | Modified by Ivan Grokhotkov, December 2014 6 | Reworked by Markus Sattler, December 2015 7 | 8 | This library is free software; you can redistribute it and/or 9 | modify it under the terms of the GNU Lesser General Public 10 | License as published by the Free Software Foundation; either 11 | version 2.1 of the License, or (at your option) any later version. 12 | 13 | This library is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 16 | Lesser General Public License for more details. 17 | 18 | You should have received a copy of the GNU Lesser General Public 19 | License along with this library; if not, write to the Free Software 20 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 21 | */ 22 | 23 | #pragma once 24 | 25 | #include "soc/soc_caps.h" 26 | #include "sdkconfig.h" 27 | #if SOC_WIFI_SUPPORTED || CONFIG_ESP_WIFI_REMOTE_ENABLED 28 | 29 | #include "WiFiType.h" 30 | #include "WiFiGeneric.h" 31 | #ifdef ESP_IDF_VERSION_MAJOR 32 | #include "esp_event.h" 33 | #endif 34 | 35 | typedef enum { 36 | WPA2_AUTH_TLS = 0, 37 | WPA2_AUTH_PEAP = 1, 38 | WPA2_AUTH_TTLS = 2 39 | } wpa2_auth_method_t; 40 | 41 | // ---------------------------------------------------------------------------------------------- 42 | // ------------------------------------ NEW STA Implementation ---------------------------------- 43 | // ---------------------------------------------------------------------------------------------- 44 | 45 | class STAClass : public NetworkInterface { 46 | public: 47 | STAClass(); 48 | ~STAClass(); 49 | 50 | bool begin(bool tryConnect = false); 51 | bool end(); 52 | 53 | bool bandwidth(wifi_bandwidth_t bandwidth); 54 | 55 | bool connect(); 56 | bool connect(const char *ssid, const char *passphrase = NULL, int32_t channel = 0, const uint8_t *bssid = NULL, bool connect = true); 57 | #if CONFIG_ESP_WIFI_ENTERPRISE_SUPPORT 58 | bool connect( 59 | const char *wpa2_ssid, wpa2_auth_method_t method, const char *wpa2_identity = NULL, const char *wpa2_username = NULL, const char *wpa2_password = NULL, 60 | const char *ca_pem = NULL, const char *client_crt = NULL, const char *client_key = NULL, int ttls_phase2_type = -1, int32_t channel = 0, 61 | const uint8_t *bssid = 0, bool connect = true 62 | ); 63 | #endif /* CONFIG_ESP_WIFI_ENTERPRISE_SUPPORT */ 64 | bool disconnect(bool eraseap = false, unsigned long timeout = 0); 65 | bool reconnect(); 66 | bool erase(); 67 | 68 | uint8_t waitForConnectResult(unsigned long timeoutLength = 60000); 69 | 70 | bool setAutoReconnect(bool autoReconnect); 71 | bool getAutoReconnect(); 72 | 73 | // Next group functions must be called before WiFi.begin() 74 | void setMinSecurity(wifi_auth_mode_t minSecurity); // Default is WIFI_AUTH_WPA2_PSK 75 | void setScanMethod(wifi_scan_method_t scanMethod); // Default is WIFI_FAST_SCAN 76 | void setSortMethod(wifi_sort_method_t sortMethod); // Default is WIFI_CONNECT_AP_BY_SIGNAL 77 | 78 | wl_status_t status(); 79 | 80 | String SSID() const; 81 | String psk() const; 82 | uint8_t *BSSID(uint8_t *bssid = NULL); 83 | String BSSIDstr(); 84 | int8_t RSSI(); 85 | 86 | const char *disconnectReasonName(wifi_err_reason_t reason); 87 | 88 | // Private Use 89 | void _setStatus(wl_status_t status); 90 | void _onStaEvent(int32_t event_id, void *event_data); 91 | 92 | protected: 93 | wifi_auth_mode_t _minSecurity; 94 | wifi_scan_method_t _scanMethod; 95 | wifi_sort_method_t _sortMethod; 96 | bool _autoReconnect; 97 | wl_status_t _status; 98 | network_event_handle_t _wifi_sta_event_handle; 99 | 100 | size_t printDriverInfo(Print &out) const; 101 | 102 | friend class WiFiGenericClass; 103 | bool onEnable(); 104 | bool onDisable(); 105 | }; 106 | 107 | // ---------------------------------------------------------------------------------------------- 108 | // ------------------------------- OLD STA API (compatibility) ---------------------------------- 109 | // ---------------------------------------------------------------------------------------------- 110 | 111 | class WiFiSTAClass { 112 | public: 113 | STAClass STA; 114 | 115 | #if CONFIG_ESP_WIFI_ENTERPRISE_SUPPORT 116 | wl_status_t begin( 117 | const char *wpa2_ssid, wpa2_auth_method_t method, const char *wpa2_identity = NULL, const char *wpa2_username = NULL, const char *wpa2_password = NULL, 118 | const char *ca_pem = NULL, const char *client_crt = NULL, const char *client_key = NULL, int ttls_phase2_type = -1, int32_t channel = 0, 119 | const uint8_t *bssid = 0, bool connect = true 120 | ); 121 | wl_status_t begin( 122 | const String &wpa2_ssid, wpa2_auth_method_t method, const String &wpa2_identity = (const char *)NULL, const String &wpa2_username = (const char *)NULL, 123 | const String &wpa2_password = (const char *)NULL, const String &ca_pem = (const char *)NULL, const String &client_crt = (const char *)NULL, 124 | const String &client_key = (const char *)NULL, int ttls_phase2_type = -1, int32_t channel = 0, const uint8_t *bssid = 0, bool connect = true 125 | ) { 126 | return begin( 127 | wpa2_ssid.c_str(), method, wpa2_identity.c_str(), wpa2_username.c_str(), wpa2_password.c_str(), ca_pem.c_str(), client_crt.c_str(), client_key.c_str(), 128 | ttls_phase2_type, channel, bssid, connect 129 | ); 130 | } 131 | #endif /* CONFIG_ESP_WIFI_ENTERPRISE_SUPPORT */ 132 | 133 | wl_status_t begin(const char *ssid, const char *passphrase = NULL, int32_t channel = 0, const uint8_t *bssid = NULL, bool connect = true); 134 | wl_status_t begin(const String &ssid, const String &passphrase = (const char *)NULL, int32_t channel = 0, const uint8_t *bssid = NULL, bool connect = true) { 135 | return begin(ssid.c_str(), passphrase.c_str(), channel, bssid, connect); 136 | } 137 | wl_status_t begin(); 138 | 139 | // also accepts Arduino ordering of parameters: ip, dns, gw, mask 140 | bool config(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dns1 = (uint32_t)0x00000000, IPAddress dns2 = (uint32_t)0x00000000); 141 | 142 | // two and one parameter version. 2nd parameter is DNS like in Arduino 143 | bool config(IPAddress local_ip, IPAddress dns = (uint32_t)0x00000000); 144 | 145 | bool setDNS(IPAddress dns1, IPAddress dns2 = (uint32_t)0x00000000); // sets DNS IP for all network interfaces 146 | 147 | bool bandwidth(wifi_bandwidth_t bandwidth); 148 | 149 | bool reconnect(); 150 | bool disconnectAsync(bool wifioff = false, bool eraseap = false); 151 | bool disconnect(bool wifioff = false, bool eraseap = false, unsigned long timeoutLength = 100); 152 | bool eraseAP(void); 153 | 154 | bool isConnected(); 155 | 156 | bool setAutoReconnect(bool autoReconnect); 157 | bool getAutoReconnect(); 158 | 159 | uint8_t waitForConnectResult(unsigned long timeoutLength = 60000); 160 | 161 | // Next group functions must be called before WiFi.begin() 162 | void setMinSecurity(wifi_auth_mode_t minSecurity); // Default is WIFI_AUTH_WPA2_PSK 163 | void setScanMethod(wifi_scan_method_t scanMethod); // Default is WIFI_FAST_SCAN 164 | void setSortMethod(wifi_sort_method_t sortMethod); // Default is WIFI_CONNECT_AP_BY_SIGNAL 165 | 166 | // STA WiFi info 167 | wl_status_t status(); 168 | String SSID() const; 169 | String psk() const; 170 | 171 | uint8_t *BSSID(uint8_t *bssid = NULL); 172 | String BSSIDstr(); 173 | 174 | int8_t RSSI(); 175 | 176 | IPAddress localIP(); 177 | 178 | uint8_t *macAddress(uint8_t *mac); 179 | String macAddress(); 180 | 181 | IPAddress subnetMask(); 182 | IPAddress gatewayIP(); 183 | IPAddress dnsIP(uint8_t dns_no = 0); 184 | 185 | IPAddress broadcastIP(); 186 | IPAddress networkID(); 187 | uint8_t subnetCIDR(); 188 | 189 | #if CONFIG_LWIP_IPV6 190 | bool enableIPv6(bool en = true); 191 | IPAddress linkLocalIPv6(); 192 | IPAddress globalIPv6(); 193 | #endif 194 | 195 | // ---------------------------------------------------------------------------------------------- 196 | // ---------------------------------------- Smart Config ---------------------------------------- 197 | // ---------------------------------------------------------------------------------------------- 198 | protected: 199 | static bool _smartConfigStarted; 200 | 201 | public: 202 | bool beginSmartConfig(smartconfig_type_t type = SC_TYPE_ESPTOUCH, char *crypt_key = NULL); 203 | bool stopSmartConfig(); 204 | bool smartConfigDone(); 205 | 206 | static bool _smartConfigDone; 207 | }; 208 | 209 | #endif /* SOC_WIFI_SUPPORTED */ 210 | -------------------------------------------------------------------------------- /ESP32 - arduino IDE codes ( .cpp )/WIFI/WIFI_MP3_playing_via_I2s/WIFI_MP3_playing_via_I2s/External libs/AUDIO libs used/aac_decoder/aac_decoder.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * aac_decoder.cpp 3 | * faad2 - ESP32 adaptation 4 | * Created on: 12.09.2023 5 | * Updated on: 14.01.2025 6 | */ 7 | 8 | #include "Arduino.h" 9 | #include "aac_decoder.h" 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include "libfaad/neaacdec.h" 16 | 17 | 18 | // Declaration of the required global variables 19 | 20 | NeAACDecHandle hAac; 21 | NeAACDecFrameInfo frameInfo; 22 | NeAACDecConfigurationPtr conf; 23 | const uint8_t SYNCWORDH = 0xff; /* 12-bit syncword */ 24 | const uint8_t SYNCWORDL = 0xf0; 25 | bool f_decoderIsInit = false; 26 | bool f_firstCall = false; 27 | bool f_setRaWBlockParams = false; 28 | uint32_t aacSamplerate = 0; 29 | uint8_t aacChannels = 0; 30 | uint8_t aacProfile = 0; 31 | static uint16_t validSamples = 0; 32 | clock_t before; 33 | float compressionRatio = 1; 34 | mp4AudioSpecificConfig* mp4ASC; 35 | 36 | //---------------------------------------------------------------------------------------------------------------------- 37 | bool AACDecoder_IsInit(){ 38 | return f_decoderIsInit; 39 | } 40 | //---------------------------------------------------------------------------------------------------------------------- 41 | bool AACDecoder_AllocateBuffers(){ 42 | before = clock(); 43 | hAac = NeAACDecOpen(); 44 | conf = NeAACDecGetCurrentConfiguration(hAac); 45 | 46 | if(hAac) f_decoderIsInit = true; 47 | f_firstCall = false; 48 | f_setRaWBlockParams = false; 49 | return f_decoderIsInit; 50 | } 51 | //---------------------------------------------------------------------------------------------------------------------- 52 | void AACDecoder_FreeBuffers(){ 53 | NeAACDecClose(hAac); 54 | hAac = NULL; 55 | f_decoderIsInit = false; 56 | f_firstCall = false; 57 | clock_t difference = clock() - before; 58 | int msec = difference / CLOCKS_PER_SEC; (void)msec; 59 | // printf("ms %li\n", difference); 60 | } 61 | //---------------------------------------------------------------------------------------------------------------------- 62 | uint8_t AACGetFormat(){ 63 | return frameInfo.header_type; // RAW 0 /* No header */ 64 | // ADIF 1 /* single ADIF header at the beginning of the file */ 65 | // ADTS 2 /* ADTS header at the beginning of each frame */ 66 | } 67 | //---------------------------------------------------------------------------------------------------------------------- 68 | uint8_t AACGetSBR(){ 69 | return frameInfo.sbr; // NO_SBR 0 /* no SBR used in this file */ 70 | // SBR_UPSAMPLED 1 /* upsampled SBR used */ 71 | // SBR_DOWNSAMPLED 2 /* downsampled SBR used */ 72 | // NO_SBR_UPSAMPLED 3 /* no SBR used, but file is upsampled by a factor 2 anyway */ 73 | } 74 | //---------------------------------------------------------------------------------------------------------------------- 75 | uint8_t AACGetParametricStereo(){ // not used (0) or used (1) 76 | // log_w("frameInfo.ps %i", frameInfo.isPS); 77 | return frameInfo.isPS; 78 | } 79 | //---------------------------------------------------------------------------------------------------------------------- 80 | int AACFindSyncWord(uint8_t *buf, int nBytes){ 81 | const int MIN_ADTS_HEADER_SIZE = 7; 82 | auto validate = [](const uint8_t *buf) -> bool { // check the ADTS header for validity 83 | // Layer (bits 14-15) must be 00 84 | if ((buf[1] & 0x06) != 0x00) { 85 | return false; 86 | } 87 | 88 | // Sampling Frequency Index (Bits 18-21) cannot be invalid 89 | uint8_t sampling_frequency_index = (buf[2] & 0x3C) >> 2; 90 | if (sampling_frequency_index > 12) { 91 | return false; 92 | } 93 | 94 | // Frame length (bits 30-42) must be at least the header size 95 | int frame_length = ((buf[3] & 0x03) << 11) | (buf[4] << 3) | ((buf[5] & 0xE0) >> 5); 96 | if (frame_length < MIN_ADTS_HEADER_SIZE) { 97 | return false; 98 | } 99 | 100 | return true; 101 | }; 102 | 103 | /* find byte-aligned syncword (12 bits = 0xFFF) */ 104 | for (int i = 0; i < nBytes - 1; i++) { 105 | if ( (buf[i+0] & SYNCWORDH) == SYNCWORDH && (buf[i+1] & SYNCWORDL) == SYNCWORDL ){ 106 | int frame_length = ((buf[i + 3] & 0x03) << 11) | (buf[i + 4] << 3) | ((buf[i + 5] & 0xE0) >> 5); 107 | if (i + frame_length + MIN_ADTS_HEADER_SIZE > nBytes) { 108 | return -1; // Puffergrenze überschritten, kein gültiger Header 109 | } 110 | /* find a second byte-aligned syncword (12 bits = 0xFFF) */ 111 | if ( (buf[i + frame_length + 0] & SYNCWORDH) == SYNCWORDH && (buf[i + frame_length + 1] & SYNCWORDL) == SYNCWORDL ){ 112 | return validate(&buf[i]) ? i : -1; 113 | } 114 | } 115 | } 116 | 117 | return -1; 118 | } 119 | //---------------------------------------------------------------------------------------------------------------------- 120 | int AACSetRawBlockParams(int nChans, int sampRateCore, int profile){ 121 | f_setRaWBlockParams = true; 122 | aacChannels = nChans; // 1: Mono, 2: Stereo 123 | aacSamplerate = (uint32_t)sampRateCore; // 8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000 124 | aacProfile = profile; //1: AAC Main, 2: AAC LC (Low Complexity), 3: AAC SSR (Scalable Sample Rate), 4: AAC LTP (Long Term Prediction) 125 | return 0; 126 | } 127 | //---------------------------------------------------------------------------------------------------------------------- 128 | int16_t AACGetOutputSamps(){ 129 | return validSamples; 130 | } 131 | //---------------------------------------------------------------------------------------------------------------------- 132 | int AACGetBitrate(){ 133 | uint32_t br = AACGetBitsPerSample() * AACGetChannels() * AACGetSampRate(); 134 | return (br / compressionRatio);; 135 | } 136 | //---------------------------------------------------------------------------------------------------------------------- 137 | int AACGetChannels(){ 138 | return aacChannels; 139 | } 140 | //---------------------------------------------------------------------------------------------------------------------- 141 | int AACGetSampRate(){ 142 | return aacSamplerate; 143 | } 144 | //---------------------------------------------------------------------------------------------------------------------- 145 | int AACGetBitsPerSample(){ 146 | return 16; 147 | } 148 | //---------------------------------------------------------------------------------------------------------------------- 149 | void createAudioSpecificConfig(uint8_t* config, uint8_t audioObjectType, uint8_t samplingFrequencyIndex, uint8_t channelConfiguration) { 150 | config[0] = (audioObjectType << 3) | (samplingFrequencyIndex >> 1); 151 | config[1] = (samplingFrequencyIndex << 7) | (channelConfiguration << 3); 152 | } 153 | //---------------------------------------------------------------------------------------------------------------------- 154 | extern uint8_t get_sr_index(const uint32_t samplerate); 155 | 156 | int AACDecode(uint8_t *inbuf, int32_t *bytesLeft, short *outbuf){ 157 | uint8_t* ob = (uint8_t*)outbuf; 158 | if (f_firstCall == false){ 159 | if(f_setRaWBlockParams){ // set raw AAC values, e.g. for M4A config. 160 | f_setRaWBlockParams = false; 161 | conf->defSampleRate = aacSamplerate; 162 | conf->outputFormat = FAAD_FMT_16BIT; 163 | conf->useOldADTSFormat = 1; 164 | conf->defObjectType = 2; 165 | int8_t ret = NeAACDecSetConfiguration(hAac, conf); (void)ret; 166 | 167 | uint8_t specificInfo[2]; 168 | createAudioSpecificConfig(specificInfo, aacProfile, get_sr_index(aacSamplerate), aacChannels); 169 | int8_t err = NeAACDecInit2(hAac, specificInfo, 2, &aacSamplerate, &aacChannels);(void)err; 170 | } 171 | else{ 172 | NeAACDecSetConfiguration(hAac, conf); 173 | int8_t err = NeAACDecInit(hAac, inbuf, *bytesLeft, &aacSamplerate, &aacChannels); (void)err; 174 | } 175 | f_firstCall = true; 176 | } 177 | 178 | NeAACDecDecode2(hAac, &frameInfo, inbuf, *bytesLeft, (void**)&ob, 2048 * 2 * sizeof(int16_t)); 179 | *bytesLeft -= frameInfo.bytesconsumed; 180 | validSamples = frameInfo.samples; 181 | int8_t err = 0 - frameInfo.error; 182 | compressionRatio = (float)frameInfo.samples * 2 / frameInfo.bytesconsumed; 183 | return err; 184 | } 185 | //---------------------------------------------------------------------------------------------------------------------- 186 | const char* AACGetErrorMessage(int8_t err){ 187 | return NeAACDecGetErrorMessage(abs(err)); 188 | } 189 | //---------------------------------------------------------------------------------------------------------------------- 190 | -------------------------------------------------------------------------------- /ESP32 - arduino IDE codes ( .cpp )/WIFI/WIFI_MP3_playing_via_I2s/WIFI_MP3_playing_via_I2s/External libs/WIFI libs used/WiFiScan.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | ESP8266WiFiScan.cpp - WiFi library for esp8266 3 | 4 | Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. 5 | This file is part of the esp8266 core for Arduino environment. 6 | 7 | This library is free software; you can redistribute it and/or 8 | modify it under the terms of the GNU Lesser General Public 9 | License as published by the Free Software Foundation; either 10 | version 2.1 of the License, or (at your option) any later version. 11 | 12 | This library is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 | Lesser General Public License for more details. 16 | 17 | You should have received a copy of the GNU Lesser General Public 18 | License along with this library; if not, write to the Free Software 19 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 20 | 21 | Reworked on 28 Dec 2015 by Markus Sattler 22 | 23 | */ 24 | 25 | #include "WiFi.h" 26 | #include "WiFiGeneric.h" 27 | #include "WiFiScan.h" 28 | #if SOC_WIFI_SUPPORTED || CONFIG_ESP_WIFI_REMOTE_ENABLED 29 | 30 | extern "C" { 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include 39 | #include 40 | #include 41 | #include 42 | #include "lwip/err.h" 43 | } 44 | 45 | bool WiFiScanClass::_scanAsync = false; 46 | uint32_t WiFiScanClass::_scanStarted = 0; 47 | uint32_t WiFiScanClass::_scanTimeout = 60000; 48 | uint16_t WiFiScanClass::_scanCount = 0; 49 | uint32_t WiFiScanClass::_scanActiveMinTime = 100; 50 | 51 | void *WiFiScanClass::_scanResult = nullptr; 52 | 53 | void WiFiScanClass::setScanTimeout(uint32_t ms) { 54 | WiFiScanClass::_scanTimeout = ms; 55 | } 56 | 57 | void WiFiScanClass::setScanActiveMinTime(uint32_t ms) { 58 | WiFiScanClass::_scanActiveMinTime = ms; 59 | } 60 | 61 | /** 62 | * Start scan WiFi networks available 63 | * @param async run in async mode 64 | * @param show_hidden show hidden networks 65 | * @return Number of discovered networks 66 | */ 67 | int16_t 68 | WiFiScanClass::scanNetworks(bool async, bool show_hidden, bool passive, uint32_t max_ms_per_chan, uint8_t channel, const char *ssid, const uint8_t *bssid) { 69 | if (WiFiGenericClass::getStatusBits() & WIFI_SCANNING_BIT) { 70 | return WIFI_SCAN_RUNNING; 71 | } 72 | 73 | WiFiScanClass::_scanAsync = async; 74 | 75 | WiFi.enableSTA(true); 76 | 77 | scanDelete(); 78 | 79 | wifi_scan_config_t config; 80 | memset(&config, 0, sizeof(wifi_scan_config_t)); 81 | config.ssid = (uint8_t *)ssid; 82 | config.bssid = (uint8_t *)bssid; 83 | config.channel = channel; 84 | config.show_hidden = show_hidden; 85 | if (passive) { 86 | config.scan_type = WIFI_SCAN_TYPE_PASSIVE; 87 | config.scan_time.passive = max_ms_per_chan; 88 | } else { 89 | config.scan_type = WIFI_SCAN_TYPE_ACTIVE; 90 | config.scan_time.active.min = _scanActiveMinTime; 91 | config.scan_time.active.max = max_ms_per_chan; 92 | } 93 | if (esp_wifi_scan_start(&config, false) == ESP_OK) { 94 | _scanStarted = millis(); 95 | 96 | WiFiGenericClass::clearStatusBits(WIFI_SCAN_DONE_BIT); 97 | WiFiGenericClass::setStatusBits(WIFI_SCANNING_BIT); 98 | 99 | if (WiFiScanClass::_scanAsync) { 100 | return WIFI_SCAN_RUNNING; 101 | } 102 | if (WiFiGenericClass::waitStatusBits(WIFI_SCAN_DONE_BIT, _scanTimeout)) { 103 | return (int16_t)WiFiScanClass::_scanCount; 104 | } 105 | } 106 | return WIFI_SCAN_FAILED; 107 | } 108 | 109 | /** 110 | * private 111 | * scan callback 112 | * @param result void *arg 113 | * @param status STATUS 114 | */ 115 | void WiFiScanClass::_scanDone() { 116 | esp_wifi_scan_get_ap_num(&(WiFiScanClass::_scanCount)); 117 | if (WiFiScanClass::_scanResult) { 118 | free(WiFiScanClass::_scanResult); 119 | WiFiScanClass::_scanResult = NULL; 120 | } 121 | 122 | if (WiFiScanClass::_scanCount) { 123 | WiFiScanClass::_scanResult = calloc(WiFiScanClass::_scanCount, sizeof(wifi_ap_record_t)); 124 | if (!WiFiScanClass::_scanResult) { 125 | WiFiScanClass::_scanCount = 0; 126 | } else if (esp_wifi_scan_get_ap_records(&(WiFiScanClass::_scanCount), (wifi_ap_record_t *)_scanResult) != ESP_OK) { 127 | free(WiFiScanClass::_scanResult); 128 | WiFiScanClass::_scanResult = NULL; 129 | WiFiScanClass::_scanCount = 0; 130 | } 131 | } 132 | WiFiGenericClass::setStatusBits(WIFI_SCAN_DONE_BIT); 133 | WiFiGenericClass::clearStatusBits(WIFI_SCANNING_BIT); 134 | } 135 | 136 | /** 137 | * 138 | * @param i specify from which network item want to get the information 139 | * @return bss_info * 140 | */ 141 | void *WiFiScanClass::_getScanInfoByIndex(int i) { 142 | if (!WiFiScanClass::_scanResult || (size_t)i >= WiFiScanClass::_scanCount) { 143 | return 0; 144 | } 145 | return reinterpret_cast(WiFiScanClass::_scanResult) + i; 146 | } 147 | 148 | /** 149 | * called to get the scan state in Async mode 150 | * @return scan result or status 151 | * -1 if scan not fin 152 | * -2 if scan not triggered 153 | */ 154 | int16_t WiFiScanClass::scanComplete() { 155 | if (WiFiGenericClass::getStatusBits() & WIFI_SCAN_DONE_BIT) { 156 | return WiFiScanClass::_scanCount; 157 | } 158 | 159 | if (WiFiGenericClass::getStatusBits() & WIFI_SCANNING_BIT) { 160 | // Check if the delay expired, return WIFI_SCAN_FAILED in this case 161 | if ((millis() - WiFiScanClass::_scanStarted) > WiFiScanClass::_scanTimeout) { 162 | WiFiGenericClass::clearStatusBits(WIFI_SCANNING_BIT); 163 | return WIFI_SCAN_FAILED; 164 | } 165 | return WIFI_SCAN_RUNNING; 166 | } 167 | 168 | return WIFI_SCAN_FAILED; 169 | } 170 | 171 | /** 172 | * delete last scan result from RAM 173 | */ 174 | void WiFiScanClass::scanDelete() { 175 | WiFiGenericClass::clearStatusBits(WIFI_SCAN_DONE_BIT); 176 | WiFiGenericClass::clearStatusBits(WIFI_SCANNING_BIT); 177 | if (WiFiScanClass::_scanResult) { 178 | free(WiFiScanClass::_scanResult); 179 | WiFiScanClass::_scanResult = NULL; 180 | } 181 | WiFiScanClass::_scanCount = 0; 182 | } 183 | 184 | /** 185 | * loads all infos from a scanned wifi in to the ptr parameters 186 | * @param networkItem uint8_t 187 | * @param ssid const char** 188 | * @param encryptionType uint8_t * 189 | * @param RSSI int32_t * 190 | * @param BSSID uint8_t ** 191 | * @param channel int32_t * 192 | * @return (true if ok) 193 | */ 194 | bool WiFiScanClass::getNetworkInfo(uint8_t i, String &ssid, uint8_t &encType, int32_t &rssi, uint8_t *&bssid, int32_t &channel) { 195 | wifi_ap_record_t *it = reinterpret_cast(_getScanInfoByIndex(i)); 196 | if (!it) { 197 | return false; 198 | } 199 | ssid = (const char *)it->ssid; 200 | encType = it->authmode; 201 | rssi = it->rssi; 202 | bssid = it->bssid; 203 | channel = it->primary; 204 | return true; 205 | } 206 | 207 | /** 208 | * Return the SSID discovered during the network scan. 209 | * @param i specify from which network item want to get the information 210 | * @return ssid string of the specified item on the networks scanned list 211 | */ 212 | String WiFiScanClass::SSID(uint8_t i) { 213 | wifi_ap_record_t *it = reinterpret_cast(_getScanInfoByIndex(i)); 214 | if (!it) { 215 | return String(); 216 | } 217 | return String(reinterpret_cast(it->ssid)); 218 | } 219 | 220 | /** 221 | * Return the encryption type of the networks discovered during the scanNetworks 222 | * @param i specify from which network item want to get the information 223 | * @return encryption type (enum wl_enc_type) of the specified item on the networks scanned list 224 | */ 225 | wifi_auth_mode_t WiFiScanClass::encryptionType(uint8_t i) { 226 | wifi_ap_record_t *it = reinterpret_cast(_getScanInfoByIndex(i)); 227 | if (!it) { 228 | return WIFI_AUTH_OPEN; 229 | } 230 | return it->authmode; 231 | } 232 | 233 | /** 234 | * Return the RSSI of the networks discovered during the scanNetworks 235 | * @param i specify from which network item want to get the information 236 | * @return signed value of RSSI of the specified item on the networks scanned list 237 | */ 238 | int32_t WiFiScanClass::RSSI(uint8_t i) { 239 | wifi_ap_record_t *it = reinterpret_cast(_getScanInfoByIndex(i)); 240 | if (!it) { 241 | return 0; 242 | } 243 | return it->rssi; 244 | } 245 | 246 | /** 247 | * return MAC / BSSID of scanned wifi 248 | * @param i specify from which network item want to get the information 249 | * @param buff optional buffer for the result uint8_t array with length 6 250 | * @return uint8_t * MAC / BSSID of scanned wifi 251 | */ 252 | uint8_t *WiFiScanClass::BSSID(uint8_t i, uint8_t *buff) { 253 | wifi_ap_record_t *it = reinterpret_cast(_getScanInfoByIndex(i)); 254 | if (buff != NULL) { 255 | if (!it) { 256 | memset(buff, 0, 6); 257 | } else { 258 | memcpy(buff, it->bssid, 6); 259 | } 260 | return buff; 261 | } 262 | if (!it) { 263 | return 0; 264 | } 265 | return it->bssid; 266 | } 267 | 268 | /** 269 | * return MAC / BSSID of scanned wifi 270 | * @param i specify from which network item want to get the information 271 | * @return String MAC / BSSID of scanned wifi 272 | */ 273 | String WiFiScanClass::BSSIDstr(uint8_t i) { 274 | char mac[18] = {0}; 275 | wifi_ap_record_t *it = reinterpret_cast(_getScanInfoByIndex(i)); 276 | if (!it) { 277 | return String(); 278 | } 279 | sprintf(mac, "%02X:%02X:%02X:%02X:%02X:%02X", it->bssid[0], it->bssid[1], it->bssid[2], it->bssid[3], it->bssid[4], it->bssid[5]); 280 | return String(mac); 281 | } 282 | 283 | int32_t WiFiScanClass::channel(uint8_t i) { 284 | wifi_ap_record_t *it = reinterpret_cast(_getScanInfoByIndex(i)); 285 | if (!it) { 286 | return 0; 287 | } 288 | return it->primary; 289 | } 290 | 291 | #endif /* SOC_WIFI_SUPPORTED */ 292 | -------------------------------------------------------------------------------- /ESP32 - arduino IDE codes ( .cpp )/WIFI/WIFI_MP3_playing_via_I2s/WIFI_MP3_playing_via_I2s/External libs/AUDIO libs used/flac_decoder/flac_decoder.h: -------------------------------------------------------------------------------- 1 | /* 2 | * flac_decoder.h 3 | * 4 | * Created on: Jul 03,2020 5 | * Updated on: Mar 29,2025 6 | * 7 | * Author: wolle 8 | * 9 | * Restrictions: 10 | * blocksize must not exceed 24576 bytes 11 | * bits per sample must be 8 or 16 12 | * num Channels must be 1 or 2 13 | * 14 | * 15 | */ 16 | #pragma once 17 | #pragma GCC optimize ("Ofast") 18 | 19 | #include "Arduino.h" 20 | #include 21 | using namespace std; 22 | 23 | #define MAX_CHANNELS 2 24 | #define MAX_BLOCKSIZE 24576 // 24 * 1024 25 | #define MAX_OUTBUFFSIZE 4096 * 2 26 | 27 | enum : uint8_t {FLACDECODER_INIT, FLACDECODER_READ_IN, FLACDECODER_WRITE_OUT}; 28 | enum : uint8_t {DECODE_FRAME, DECODE_SUBFRAMES, OUT_SAMPLES}; 29 | enum : int8_t {FLAC_PARSE_OGG_DONE = 100, 30 | FLAC_DECODE_FRAMES_LOOP = 100, 31 | OGG_SYNC_FOUND = +2, 32 | GIVE_NEXT_LOOP = +1, 33 | ERR_FLAC_NONE = 0, 34 | ERR_FLAC_BLOCKSIZE_TOO_BIG = -1, 35 | ERR_FLAC_RESERVED_BLOCKSIZE_UNSUPPORTED = -2, 36 | ERR_FLAC_SYNC_CODE_NOT_FOUND = -3, 37 | ERR_FLAC_UNKNOWN_CHANNEL_ASSIGNMENT = -4, 38 | ERR_FLAC_RESERVED_CHANNEL_ASSIGNMENT = -5, 39 | ERR_FLAC_RESERVED_SUB_TYPE = -6, 40 | ERR_FLAC_PREORDER_TOO_BIG = -7, 41 | ERR_FLAC_RESERVED_RESIDUAL_CODING = -8, 42 | ERR_FLAC_WRONG_RICE_PARTITION_NR = -9, 43 | ERR_FLAC_BITS_PER_SAMPLE_TOO_BIG = -10, 44 | ERR_FLAC_BITS_PER_SAMPLE_UNKNOWN = -11, 45 | ERR_FLAC_DECODER_ASYNC = -12, 46 | ERR_FLAC_UNIMPLEMENTED = -13, 47 | ERR_FLAC_BITREADER_UNDERFLOW = -14, 48 | ERR_FLAC_OUTBUFFER_TOO_SMALL = -15}; 49 | 50 | typedef struct FLACMetadataBlock_t{ 51 | // METADATA_BLOCK_STREAMINFO 52 | uint16_t minblocksize; // The minimum block size (in samples) used in the stream. 53 | //---------------------------------------------------------------------------------------- 54 | // The maximum block size (in samples) used in the stream. 55 | uint16_t maxblocksize; // (Minimum blocksize == maximum blocksize) implies a fixed-blocksize stream. 56 | //---------------------------------------------------------------------------------------- 57 | // The minimum frame size (in bytes) used in the stream. 58 | uint32_t minframesize; // May be 0 to imply the value is not known. 59 | //---------------------------------------------------------------------------------------- 60 | // The maximum frame size (in bytes) used in the stream. 61 | uint32_t maxframesize; // May be 0 to imply the value is not known. 62 | //---------------------------------------------------------------------------------------- 63 | // Sample rate in Hz. Though 20 bits are available, 64 | // the maximum sample rate is limited by the structure of frame headers to 655350Hz. 65 | uint32_t sampleRate; // Also, a value of 0 is invalid. 66 | //---------------------------------------------------------------------------------------- 67 | // Number of channels FLAC supports from 1 to 8 channels 68 | uint8_t numChannels; // 000 : 1 channel .... 111 : 8 channels 69 | //---------------------------------------------------------------------------------------- 70 | // Sample size in bits: 71 | // 000 : get from STREAMINFO metadata block 72 | // 001 : 8 bits per sample 73 | // 010 : 12 bits per sample 74 | // 011 : reserved 75 | // 100 : 16 bits per sample 76 | // 101 : 20 bits per sample 77 | // 110 : 24 bits per sample 78 | uint8_t bitsPerSample; // 111 : reserved 79 | //---------------------------------------------------------------------------------------- 80 | // Total samples in stream. 'Samples' means inter-channel sample, 81 | // i.e. one second of 44.1Khz audio will have 44100 samples regardless of the number 82 | uint64_t totalSamples; // of channels. A value of zero here means the number of total samples is unknown. 83 | //---------------------------------------------------------------------------------------- 84 | uint32_t audioDataLength;// is not the filelength, is only the length of the audio datablock in bytes 85 | 86 | 87 | 88 | }FLACMetadataBlock_t; 89 | 90 | 91 | typedef struct FLACFrameHeader_t { 92 | // 0 : fixed-blocksize stream; frame header encodes the frame number 93 | uint8_t blockingStrategy; // 1 : variable-blocksize stream; frame header encodes the sample number 94 | //---------------------------------------------------------------------------------------- 95 | // Block size in inter-channel samples: 96 | // 0000 : reserved 97 | // 0001 : 192 samples 98 | // 0010-0101 : 576 * (2^(n-2)) samples, i.e. 576/1152/2304/4608 99 | // 0110 : get 8 bit (blocksize-1) from end of header 100 | // 0111 : get 16 bit (blocksize-1) from end of header 101 | uint8_t blockSizeCode; // 1000-1111 : 256 * (2^(n-8)) samples, i.e. 256/512/1024/2048/4096/8192/16384/32768 102 | //---------------------------------------------------------------------------------------- 103 | // 0000 : get from STREAMINFO metadata block 104 | // 0001 : 88.2kHz 105 | // 0010 : 176.4kHz 106 | // 0011 : 192kHz 107 | // 0100 : 8kHz 108 | // 0101 : 16kHz 109 | // 0110 : 22.05kHz 110 | // 0111 : 24kHz 111 | // 1000 : 32kHz 112 | // 1001 : 44.1kHz 113 | // 1010 : 48kHz 114 | // 1011 : 96kHz 115 | // 1100 : get 8 bit sample rate (in kHz) from end of header 116 | // 1101 : get 16 bit sample rate (in Hz) from end of header 117 | // 1110 : get 16 bit sample rate (in tens of Hz) from end of header 118 | uint8_t sampleRateCode; // 1111 : invalid, to prevent sync-fooling string of 1s 119 | //---------------------------------------------------------------------------------------- 120 | // Channel assignment 121 | // 0000 1 channel: mono 122 | // 0001 2 channels: left, right 123 | // 0010 3 channels 124 | // 0011 4 channels 125 | // 0100 5 channels 126 | // 0101 6 channels 127 | // 0110 7 channels 128 | // 0111 8 channels 129 | // 1000 : left/side stereo: channel 0 is the left channel, channel 1 is the side(difference) channel 130 | // 1001 : right/side stereo: channel 0 is the side(difference) channel, channel 1 is the right channel 131 | // 1010 : mid/side stereo: channel 0 is the mid(average) channel, channel 1 is the side(difference) channel 132 | uint8_t chanAsgn; // 1011-1111 : reserved 133 | //---------------------------------------------------------------------------------------- 134 | // Sample size in bits: 135 | // 000 : get from STREAMINFO metadata block 136 | // 001 : 8 bits per sample 137 | // 010 : 12 bits per sample 138 | // 011 : reserved 139 | // 100 : 16 bits per sample 140 | // 101 : 20 bits per sample 141 | // 110 : 24 bits per sample 142 | uint8_t sampleSizeCode; // 111 : reserved 143 | //---------------------------------------------------------------------------------------- 144 | uint32_t totalSamples; // totalSamplesInStream 145 | //---------------------------------------------------------------------------------------- 146 | uint32_t bitrate; // bitrate 147 | 148 | 149 | }FLACFrameHeader_t; 150 | 151 | int32_t FLACFindSyncWord(unsigned char* buf, int32_t nBytes); 152 | boolean FLACFindMagicWord(unsigned char* buf, int32_t nBytes); 153 | char* FLACgetStreamTitle(); 154 | int32_t FLACparseOGG(uint8_t* inbuf, int32_t* bytesLeft); 155 | vector FLACgetMetadataBlockPicture(); 156 | int32_t parseFlacFirstPacket(uint8_t* inbuf, int16_t nBytes); 157 | int32_t parseMetaDataBlockHeader(uint8_t* inbuf, int16_t nBytes); 158 | bool FLACDecoder_AllocateBuffers(void); 159 | void FLACDecoder_setDefaults(); 160 | void FLACDecoder_ClearBuffer(); 161 | void FLACDecoder_FreeBuffers(); 162 | void FLACSetRawBlockParams(uint8_t Chans, uint32_t SampRate, uint8_t BPS, uint32_t tsis, uint32_t AuDaLength); 163 | void FLACDecoderReset(); 164 | int8_t FLACDecode(uint8_t* inbuf, int32_t* bytesLeft, int16_t* outbuf); 165 | int8_t FLACDecodeNative(uint8_t* inbuf, int32_t* bytesLeft, int16_t* outbuf); 166 | int8_t flacDecodeFrame(uint8_t* inbuf, int32_t* bytesLeft); 167 | uint32_t FLACGetOutputSamps(); 168 | uint64_t FLACGetTotoalSamplesInStream(); 169 | uint8_t FLACGetBitsPerSample(); 170 | uint8_t FLACGetChannels(); 171 | uint32_t FLACGetSampRate(); 172 | uint32_t FLACGetBitRate(); 173 | uint32_t FLACGetAudioDataStart(); 174 | uint32_t FLACGetAudioFileDuration(); 175 | uint32_t readUint(uint8_t nBits, int32_t* bytesLeft); 176 | int32_t readSignedInt(int32_t nBits, int32_t* bytesLeft); 177 | int64_t readRiceSignedInt(uint8_t param, int32_t* bytesLeft); 178 | void alignToByte(); 179 | int8_t decodeSubframes(int32_t* bytesLeft); 180 | int8_t decodeSubframe(uint8_t sampleDepth, uint8_t ch, int32_t* bytesLeft); 181 | int8_t decodeFixedPredictionSubframe(uint8_t predOrder, uint8_t sampleDepth, uint8_t ch, int32_t* bytesLeft); 182 | int8_t decodeLinearPredictiveCodingSubframe(int32_t lpcOrder, int32_t sampleDepth, uint8_t ch, int32_t* bytesLeft); 183 | int8_t decodeResiduals(uint8_t warmup, uint8_t ch, int32_t* bytesLeft); 184 | void restoreLinearPrediction(uint8_t ch, uint8_t shift); 185 | int32_t FLAC_specialIndexOf(uint8_t* base, const char* str, int32_t baselen, bool exact = false); 186 | char* flac_x_ps_malloc(uint16_t len); 187 | char* flac_x_ps_calloc(uint16_t len, uint8_t size); 188 | char* flac_x_ps_strdup(const char* str); 189 | char* flac_x_ps_strndup(const char* str, uint16_t n); 190 | -------------------------------------------------------------------------------- /ESP32 - arduino IDE codes ( .cpp )/WIFI/WIFI_MP3_playing_via_I2s/WIFI_MP3_playing_via_I2s/External libs/WIFI libs used/WiFiMulti.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @file WiFiMulti.cpp 4 | * @date 16.05.2015 5 | * @author Markus Sattler 6 | * 7 | * Copyright (c) 2015 Markus Sattler. All rights reserved. 8 | * This file is part of the esp8266 core for Arduino environment. 9 | * 10 | * This library is free software; you can redistribute it and/or 11 | * modify it under the terms of the GNU Lesser General Public 12 | * License as published by the Free Software Foundation; either 13 | * version 2.1 of the License, or (at your option) any later version. 14 | * 15 | * This library is distributed in the hope that it will be useful, 16 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 18 | * Lesser General Public License for more details. 19 | * 20 | * You should have received a copy of the GNU Lesser General Public 21 | * License along with this library; if not, write to the Free Software 22 | * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 23 | * 24 | */ 25 | 26 | #include "WiFiMulti.h" 27 | #if SOC_WIFI_SUPPORTED || CONFIG_ESP_WIFI_REMOTE_ENABLED 28 | #include 29 | #include 30 | #include 31 | 32 | WiFiMulti::WiFiMulti() { 33 | ipv6_support = false; 34 | } 35 | 36 | void WiFiMulti::APlistClean(void) { 37 | for (auto entry : APlist) { 38 | if (entry.ssid) { 39 | free(entry.ssid); 40 | } 41 | if (entry.passphrase) { 42 | free(entry.passphrase); 43 | } 44 | } 45 | APlist.clear(); 46 | } 47 | 48 | WiFiMulti::~WiFiMulti() { 49 | APlistClean(); 50 | } 51 | 52 | bool WiFiMulti::addAP(const char *ssid, const char *passphrase) { 53 | WifiAPlist_t newAP; 54 | 55 | if (!ssid || *ssid == '\0' || strlen(ssid) > 31) { 56 | // fail SSID too long or missing! 57 | log_e("[WIFI][APlistAdd] no ssid or ssid too long"); 58 | return false; 59 | } 60 | 61 | if (passphrase && strlen(passphrase) > 63) { 62 | // fail passphrase too long! 63 | log_e("[WIFI][APlistAdd] passphrase too long"); 64 | return false; 65 | } 66 | 67 | newAP.ssid = strdup(ssid); 68 | 69 | if (!newAP.ssid) { 70 | log_e("[WIFI][APlistAdd] fail newAP.ssid == 0"); 71 | return false; 72 | } 73 | 74 | if (passphrase && *passphrase != '\0') { 75 | newAP.passphrase = strdup(passphrase); 76 | if (!newAP.passphrase) { 77 | log_e("[WIFI][APlistAdd] fail newAP.passphrase == 0"); 78 | free(newAP.ssid); 79 | return false; 80 | } 81 | } else { 82 | newAP.passphrase = NULL; 83 | } 84 | newAP.hasFailed = false; 85 | APlist.push_back(newAP); 86 | log_i("[WIFI][APlistAdd] add SSID: %s", newAP.ssid); 87 | return true; 88 | } 89 | 90 | uint8_t WiFiMulti::run(uint32_t connectTimeout, bool scanHidden) { 91 | int8_t scanResult; 92 | unsigned long startTime; 93 | uint8_t status = WiFi.status(); 94 | if (status == WL_CONNECTED) { 95 | if (!_bWFMInit && _connectionTestCBFunc != NULL) { 96 | if (_connectionTestCBFunc() == true) { 97 | _bWFMInit = true; 98 | return status; 99 | } 100 | } else { 101 | if (!_bStrict) { 102 | return status; 103 | } else { 104 | for (auto ap : APlist) { 105 | if (WiFi.SSID() == ap.ssid) { 106 | return status; 107 | } 108 | } 109 | } 110 | } 111 | WiFi.disconnect(false, false); 112 | delay(10); 113 | status = WiFi.status(); 114 | } 115 | 116 | scanResult = WiFi.scanNetworks(false, scanHidden); 117 | if (scanResult == WIFI_SCAN_RUNNING) { 118 | // scan is running 119 | return WL_NO_SSID_AVAIL; 120 | } else if (scanResult >= 0) { 121 | // scan done analyze 122 | int32_t bestIndex = -1; 123 | WifiAPlist_t bestNetwork{NULL, NULL, false}; 124 | int bestNetworkDb = INT_MIN; 125 | int bestNetworkSec = WIFI_AUTH_MAX; 126 | uint8_t bestBSSID[6]; 127 | int32_t bestChannel = 0; 128 | 129 | log_i("[WIFI] scan done"); 130 | 131 | if (scanResult == 0) { 132 | log_e("[WIFI] no networks found"); 133 | } else { 134 | log_i("[WIFI] %d networks found", scanResult); 135 | 136 | int8_t failCount = 0; 137 | int8_t foundCount = 0; 138 | for (int8_t i = 0; i < scanResult; ++i) { 139 | 140 | String ssid_scan; 141 | int32_t rssi_scan; 142 | uint8_t sec_scan; 143 | uint8_t *BSSID_scan; 144 | int32_t chan_scan; 145 | bool hidden_scan; 146 | 147 | WiFi.getNetworkInfo(i, ssid_scan, sec_scan, rssi_scan, BSSID_scan, chan_scan); 148 | hidden_scan = (ssid_scan.length() == 0) && scanHidden; 149 | // add any Open WiFi AP to the list, if allowed with setAllowOpenAP(true) 150 | if (_bAllowOpenAP && sec_scan == WIFI_AUTH_OPEN) { 151 | bool found = false; 152 | for (auto check : APlist) { 153 | if (ssid_scan == check.ssid) { 154 | found = true; 155 | break; 156 | } 157 | } 158 | // If we didn't find it, add this Open WiFi AP to the list 159 | if (!found) { 160 | log_i("[WIFI][APlistAdd] adding Open WiFi SSID: %s", ssid_scan.c_str()); 161 | addAP(ssid_scan.c_str()); 162 | } 163 | } 164 | 165 | if (hidden_scan) { 166 | log_v("hidden ssid on channel %d found, trying to connect with known credentials...", chan_scan); 167 | } 168 | 169 | bool known = false; 170 | for (uint32_t x = 0; x < APlist.size(); x++) { 171 | WifiAPlist_t entry = APlist[x]; 172 | 173 | if (ssid_scan == entry.ssid || hidden_scan) { // SSID match or hidden network found 174 | if (!hidden_scan) { 175 | log_v("known ssid: %s, has failed: %s", entry.ssid, entry.hasFailed ? "yes" : "no"); 176 | foundCount++; 177 | } 178 | if (!entry.hasFailed) { 179 | if (hidden_scan) { 180 | WiFi.begin(entry.ssid, entry.passphrase, chan_scan, BSSID_scan); 181 | 182 | // If the ssid returned from the scan is empty, it is a hidden SSID 183 | // it appears that the WiFi.begin() function is asynchronous and takes 184 | // additional time to connect to a hidden SSID. Therefore a delay of 1000ms 185 | // is added for hidden SSIDs before calling WiFi.status() 186 | delay(1000); 187 | 188 | status = WiFi.status(); 189 | startTime = millis(); 190 | 191 | while (status != WL_CONNECTED && (millis() - startTime) <= connectTimeout) { 192 | delay(10); 193 | status = WiFi.status(); 194 | } 195 | 196 | WiFi.disconnect(); 197 | delay(10); 198 | 199 | if (status == WL_CONNECTED) { 200 | log_v("hidden ssid %s found", entry.ssid); 201 | ssid_scan = entry.ssid; 202 | foundCount++; 203 | } else { 204 | continue; 205 | } 206 | } 207 | known = true; 208 | log_v("rssi_scan: %d, bestNetworkDb: %d", rssi_scan, bestNetworkDb); 209 | if (rssi_scan > bestNetworkDb) { // best network 210 | if (_bAllowOpenAP || (sec_scan == WIFI_AUTH_OPEN || entry.passphrase)) { // check for passphrase if not open wlan 211 | log_v("best network is now: %s", ssid_scan); 212 | bestIndex = x; 213 | bestNetworkSec = sec_scan; 214 | bestNetworkDb = rssi_scan; 215 | bestChannel = chan_scan; 216 | memcpy((void *)&bestNetwork, (void *)&entry, sizeof(bestNetwork)); 217 | memcpy((void *)&bestBSSID, (void *)BSSID_scan, sizeof(bestBSSID)); 218 | } 219 | } 220 | break; 221 | } else { 222 | failCount++; 223 | } 224 | } 225 | } 226 | 227 | if (known) { 228 | log_d( 229 | " ---> %d: [%d][%02X:%02X:%02X:%02X:%02X:%02X] %s (%d) (%c) (%s)", i, chan_scan, BSSID_scan[0], BSSID_scan[1], BSSID_scan[2], BSSID_scan[3], 230 | BSSID_scan[4], BSSID_scan[5], ssid_scan.c_str(), rssi_scan, (sec_scan == WIFI_AUTH_OPEN) ? ' ' : '*', (hidden_scan) ? "hidden" : "visible" 231 | ); 232 | } else { 233 | log_d( 234 | " %d: [%d][%02X:%02X:%02X:%02X:%02X:%02X] %s (%d) (%c) (%s)", i, chan_scan, BSSID_scan[0], BSSID_scan[1], BSSID_scan[2], BSSID_scan[3], 235 | BSSID_scan[4], BSSID_scan[5], ssid_scan.c_str(), rssi_scan, (sec_scan == WIFI_AUTH_OPEN) ? ' ' : '*', (hidden_scan) ? "hidden" : "visible" 236 | ); 237 | } 238 | } 239 | log_v("foundCount = %d, failCount = %d", foundCount, failCount); 240 | // if all the APs in the list have failed, reset the failure flags 241 | if (foundCount == failCount) { 242 | resetFails(); // keeps trying the APs in the list 243 | } 244 | } 245 | // clean up ram 246 | WiFi.scanDelete(); 247 | 248 | if (bestIndex >= 0) { 249 | log_i( 250 | "[WIFI] Connecting BSSID: %02X:%02X:%02X:%02X:%02X:%02X SSID: %s Channel: %d (%d)", bestBSSID[0], bestBSSID[1], bestBSSID[2], bestBSSID[3], 251 | bestBSSID[4], bestBSSID[5], bestNetwork.ssid, bestChannel, bestNetworkDb 252 | ); 253 | 254 | #if CONFIG_LWIP_IPV6 255 | if (ipv6_support == true) { 256 | WiFi.enableIPv6(); 257 | } 258 | #endif 259 | WiFi.disconnect(); 260 | delay(10); 261 | WiFi.begin(bestNetwork.ssid, (_bAllowOpenAP && bestNetworkSec == WIFI_AUTH_OPEN) ? NULL : bestNetwork.passphrase, bestChannel, bestBSSID); 262 | status = WiFi.status(); 263 | _bWFMInit = true; 264 | 265 | startTime = millis(); 266 | // wait for connection, fail, or timeout 267 | while (status != WL_CONNECTED && (millis() - startTime) <= connectTimeout) { // && status != WL_NO_SSID_AVAIL && status != WL_CONNECT_FAILED 268 | delay(10); 269 | status = WiFi.status(); 270 | } 271 | 272 | switch (status) { 273 | case WL_CONNECTED: 274 | log_i("[WIFI] Connecting done."); 275 | log_d("[WIFI] SSID: %s", WiFi.SSID().c_str()); 276 | log_d("[WIFI] IP: %s", WiFi.localIP().toString().c_str()); 277 | log_d("[WIFI] MAC: %s", WiFi.BSSIDstr().c_str()); 278 | log_d("[WIFI] Channel: %d", WiFi.channel()); 279 | 280 | if (_connectionTestCBFunc != NULL) { 281 | // We connected to an AP but if it's a captive portal we're not going anywhere. Test it. 282 | if (_connectionTestCBFunc()) { 283 | resetFails(); 284 | } else { 285 | markAsFailed(bestIndex); 286 | WiFi.disconnect(); 287 | delay(10); 288 | status = WiFi.status(); 289 | } 290 | } else { 291 | resetFails(); 292 | } 293 | break; 294 | case WL_NO_SSID_AVAIL: 295 | log_e("[WIFI] Connecting Failed AP not found."); 296 | markAsFailed(bestIndex); 297 | break; 298 | case WL_CONNECT_FAILED: 299 | log_e("[WIFI] Connecting Failed."); 300 | markAsFailed(bestIndex); 301 | break; 302 | default: 303 | log_e("[WIFI] Connecting Failed (%d).", status); 304 | markAsFailed(bestIndex); 305 | break; 306 | } 307 | } else { 308 | log_e("[WIFI] no matching wifi found!"); 309 | } 310 | } else { 311 | // start scan 312 | log_d("[WIFI] delete old wifi config..."); 313 | WiFi.disconnect(); 314 | 315 | log_d("[WIFI] start scan"); 316 | // scan wifi async mode 317 | WiFi.scanNetworks(true); 318 | } 319 | 320 | return status; 321 | } 322 | 323 | #if CONFIG_LWIP_IPV6 324 | void WiFiMulti::enableIPv6(bool state) { 325 | ipv6_support = state; 326 | } 327 | #endif 328 | 329 | void WiFiMulti::markAsFailed(int32_t i) { 330 | APlist[i].hasFailed = true; 331 | log_d("[WIFI] Marked SSID %s as failed", APlist[i].ssid); 332 | } 333 | 334 | void WiFiMulti::resetFails() { 335 | for (uint32_t i = 0; i < APlist.size(); i++) { 336 | APlist[i].hasFailed = false; 337 | } 338 | log_d("[WIFI] Resetting failure flags"); 339 | } 340 | 341 | void WiFiMulti::setStrictMode(bool bStrict) { 342 | _bStrict = bStrict; 343 | } 344 | 345 | void WiFiMulti::setAllowOpenAP(bool bAllowOpenAP) { 346 | _bAllowOpenAP = bAllowOpenAP; 347 | } 348 | 349 | void WiFiMulti::setConnectionTestCallbackFunc(ConnectionTestCB_t cbFunc) { 350 | _connectionTestCBFunc = cbFunc; 351 | } 352 | 353 | #endif /* SOC_WIFI_SUPPORTED */ 354 | -------------------------------------------------------------------------------- /ESP32 - arduino IDE codes ( .cpp )/WIFI/WIFI_MP3_playing_via_I2s/WIFI_MP3_playing_via_I2s/External libs/WIFI libs used/AP.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * SPDX-FileCopyrightText: 2023 Espressif Systems (Shanghai) CO LTD 3 | * 4 | * SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | #include "WiFi.h" 8 | #include "WiFiGeneric.h" 9 | #include "WiFiAP.h" 10 | #if SOC_WIFI_SUPPORTED || CONFIG_ESP_WIFI_REMOTE_ENABLED 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include "dhcpserver/dhcpserver_options.h" 23 | #include "esp_netif.h" 24 | 25 | esp_netif_t *get_esp_interface_netif(esp_interface_t interface); 26 | 27 | static size_t _wifi_strncpy(char *dst, const char *src, size_t dst_len) { 28 | if (!dst || !src || !dst_len) { 29 | return 0; 30 | } 31 | size_t src_len = strlen(src); 32 | if (src_len >= dst_len) { 33 | src_len = dst_len; 34 | } else { 35 | src_len += 1; 36 | } 37 | memcpy(dst, src, src_len); 38 | return src_len; 39 | } 40 | 41 | /** 42 | * compare two AP configurations 43 | * @param lhs softap_config 44 | * @param rhs softap_config 45 | * @return equal 46 | */ 47 | static bool softap_config_equal(const wifi_config_t &lhs, const wifi_config_t &rhs) { 48 | if (strncmp(reinterpret_cast(lhs.ap.ssid), reinterpret_cast(rhs.ap.ssid), 32) != 0) { 49 | return false; 50 | } 51 | if (strncmp(reinterpret_cast(lhs.ap.password), reinterpret_cast(rhs.ap.password), 64) != 0) { 52 | return false; 53 | } 54 | if (lhs.ap.channel != rhs.ap.channel) { 55 | return false; 56 | } 57 | if (lhs.ap.authmode != rhs.ap.authmode) { 58 | return false; 59 | } 60 | if (lhs.ap.ssid_hidden != rhs.ap.ssid_hidden) { 61 | return false; 62 | } 63 | if (lhs.ap.max_connection != rhs.ap.max_connection) { 64 | return false; 65 | } 66 | if (lhs.ap.pairwise_cipher != rhs.ap.pairwise_cipher) { 67 | return false; 68 | } 69 | if (lhs.ap.ftm_responder != rhs.ap.ftm_responder) { 70 | return false; 71 | } 72 | return true; 73 | } 74 | 75 | static APClass *_ap_network_if = NULL; 76 | 77 | static esp_event_handler_instance_t _ap_ev_instance = NULL; 78 | static void _ap_event_cb(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data) { 79 | if (event_base == WIFI_EVENT) { 80 | ((APClass *)arg)->_onApEvent(event_id, event_data); 81 | } 82 | } 83 | 84 | static void _onApArduinoEvent(arduino_event_t *ev) { 85 | if (_ap_network_if == NULL || ev->event_id < ARDUINO_EVENT_WIFI_AP_START || ev->event_id > ARDUINO_EVENT_WIFI_AP_GOT_IP6) { 86 | return; 87 | } 88 | log_v("Arduino AP Event: %d - %s", ev->event_id, Network.eventName(ev->event_id)); 89 | if (ev->event_id == ARDUINO_EVENT_WIFI_AP_START) { 90 | #if CONFIG_LWIP_IPV6 91 | if (_ap_network_if->getStatusBits() & ESP_NETIF_WANT_IP6_BIT) { 92 | esp_err_t err = esp_netif_create_ip6_linklocal(_ap_network_if->netif()); 93 | if (err != ESP_OK) { 94 | log_e("Failed to enable IPv6 Link Local on AP: 0x%x: %s", err, esp_err_to_name(err)); 95 | } else { 96 | log_v("Enabled IPv6 Link Local on %s", _ap_network_if->desc()); 97 | } 98 | } 99 | #endif 100 | } 101 | } 102 | 103 | void APClass::_onApEvent(int32_t event_id, void *event_data) { 104 | arduino_event_t arduino_event; 105 | arduino_event.event_id = ARDUINO_EVENT_MAX; 106 | 107 | if (event_id == WIFI_EVENT_AP_START) { 108 | log_v("AP Started"); 109 | arduino_event.event_id = ARDUINO_EVENT_WIFI_AP_START; 110 | setStatusBits(ESP_NETIF_STARTED_BIT); 111 | } else if (event_id == WIFI_EVENT_AP_STOP) { 112 | log_v("AP Stopped"); 113 | arduino_event.event_id = ARDUINO_EVENT_WIFI_AP_STOP; 114 | clearStatusBits(ESP_NETIF_STARTED_BIT | ESP_NETIF_CONNECTED_BIT | ESP_NETIF_HAS_IP_BIT | ESP_NETIF_HAS_LOCAL_IP6_BIT | ESP_NETIF_HAS_GLOBAL_IP6_BIT); 115 | } else if (event_id == WIFI_EVENT_AP_PROBEREQRECVED) { 116 | #if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_VERBOSE 117 | wifi_event_ap_probe_req_rx_t *event = (wifi_event_ap_probe_req_rx_t *)event_data; 118 | log_v("AP Probe Request: RSSI: %d, MAC: " MACSTR, event->rssi, MAC2STR(event->mac)); 119 | #endif 120 | arduino_event.event_id = ARDUINO_EVENT_WIFI_AP_PROBEREQRECVED; 121 | memcpy(&arduino_event.event_info.wifi_ap_probereqrecved, event_data, sizeof(wifi_event_ap_probe_req_rx_t)); 122 | } else if (event_id == WIFI_EVENT_AP_STACONNECTED) { 123 | #if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_VERBOSE 124 | wifi_event_ap_staconnected_t *event = (wifi_event_ap_staconnected_t *)event_data; 125 | log_v("AP Station Connected: MAC: " MACSTR ", AID: %d", MAC2STR(event->mac), event->aid); 126 | #endif 127 | arduino_event.event_id = ARDUINO_EVENT_WIFI_AP_STACONNECTED; 128 | memcpy(&arduino_event.event_info.wifi_ap_staconnected, event_data, sizeof(wifi_event_ap_staconnected_t)); 129 | setStatusBits(ESP_NETIF_CONNECTED_BIT); 130 | } else if (event_id == WIFI_EVENT_AP_STADISCONNECTED) { 131 | #if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_VERBOSE 132 | wifi_event_ap_stadisconnected_t *event = (wifi_event_ap_stadisconnected_t *)event_data; 133 | log_v("AP Station Disconnected: MAC: " MACSTR ", AID: %d", MAC2STR(event->mac), event->aid); 134 | #endif 135 | arduino_event.event_id = ARDUINO_EVENT_WIFI_AP_STADISCONNECTED; 136 | memcpy(&arduino_event.event_info.wifi_ap_stadisconnected, event_data, sizeof(wifi_event_ap_stadisconnected_t)); 137 | // If no more clients are left 138 | wifi_sta_list_t clients; 139 | if (esp_wifi_ap_get_sta_list(&clients) != ESP_OK || clients.num == 0) { 140 | clearStatusBits(ESP_NETIF_CONNECTED_BIT); 141 | } 142 | } else { 143 | return; 144 | } 145 | 146 | if (arduino_event.event_id < ARDUINO_EVENT_MAX) { 147 | Network.postEvent(&arduino_event); 148 | } 149 | } 150 | 151 | APClass::APClass() : _wifi_ap_event_handle(0) { 152 | _ap_network_if = this; 153 | } 154 | 155 | APClass::~APClass() { 156 | end(); 157 | _ap_network_if = NULL; 158 | } 159 | 160 | bool APClass::onEnable() { 161 | if (_ap_ev_instance == NULL && esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &_ap_event_cb, this, &_ap_ev_instance)) { 162 | log_e("event_handler_instance_register for WIFI_EVENT Failed!"); 163 | return false; 164 | } 165 | if (_esp_netif == NULL) { 166 | _wifi_ap_event_handle = Network.onSysEvent(_onApArduinoEvent); 167 | _esp_netif = get_esp_interface_netif(ESP_IF_WIFI_AP); 168 | /* attach to receive events */ 169 | initNetif(ESP_NETIF_ID_AP); 170 | } 171 | return true; 172 | } 173 | 174 | bool APClass::onDisable() { 175 | Network.removeEvent(_wifi_ap_event_handle); 176 | _wifi_ap_event_handle = 0; 177 | // we just set _esp_netif to NULL here, so destroyNetif() does not try to destroy it. 178 | // That would be done by WiFi.enableAP(false) if STA is not enabled, or when it gets disabled 179 | _esp_netif = NULL; 180 | destroyNetif(); 181 | if (_ap_ev_instance != NULL) { 182 | esp_event_handler_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID, &_ap_event_cb); 183 | _ap_ev_instance = NULL; 184 | } 185 | return true; 186 | } 187 | 188 | bool APClass::begin() { 189 | if (!WiFi.enableAP(true)) { 190 | log_e("AP enable failed!"); 191 | return false; 192 | } 193 | if (!waitStatusBits(ESP_NETIF_STARTED_BIT, 1000)) { 194 | log_e("Failed to start AP!"); 195 | return false; 196 | } 197 | return true; 198 | } 199 | 200 | bool APClass::end() { 201 | if (!WiFi.enableAP(false)) { 202 | log_e("AP disable failed!"); 203 | return false; 204 | } 205 | return true; 206 | } 207 | 208 | bool APClass::create( 209 | const char *ssid, const char *passphrase, int channel, int ssid_hidden, int max_connection, bool ftm_responder, wifi_auth_mode_t auth_mode, 210 | wifi_cipher_type_t cipher 211 | ) { 212 | if (!ssid || *ssid == 0) { 213 | log_e("SSID missing!"); 214 | return false; 215 | } 216 | 217 | if (passphrase && (strlen(passphrase) > 0 && strlen(passphrase) < 8)) { 218 | log_e("passphrase too short!"); 219 | return false; 220 | } 221 | 222 | if (!begin()) { 223 | return false; 224 | } 225 | 226 | wifi_config_t conf; 227 | memset(&conf, 0, sizeof(wifi_config_t)); 228 | conf.ap.channel = channel; 229 | conf.ap.max_connection = max_connection; 230 | conf.ap.beacon_interval = 100; 231 | conf.ap.ssid_hidden = ssid_hidden; 232 | conf.ap.ftm_responder = ftm_responder; 233 | if (ssid != NULL && ssid[0] != 0) { 234 | _wifi_strncpy((char *)conf.ap.ssid, ssid, 32); 235 | conf.ap.ssid_len = strlen(ssid); 236 | if (passphrase != NULL && passphrase[0] != 0) { 237 | conf.ap.authmode = auth_mode; 238 | conf.ap.pairwise_cipher = cipher; 239 | _wifi_strncpy((char *)conf.ap.password, passphrase, 64); 240 | } 241 | } 242 | 243 | wifi_config_t conf_current; 244 | esp_err_t err = esp_wifi_get_config(WIFI_IF_AP, &conf_current); 245 | if (err) { 246 | log_e("Get AP config failed! 0x%x: %s", err, esp_err_to_name(err)); 247 | return false; 248 | } 249 | if (!softap_config_equal(conf, conf_current)) { 250 | err = esp_wifi_set_config(WIFI_IF_AP, &conf); 251 | if (err) { 252 | log_e("Set AP config failed! 0x%x: %s", err, esp_err_to_name(err)); 253 | return false; 254 | } 255 | } 256 | 257 | return true; 258 | } 259 | 260 | bool APClass::clear() { 261 | if (!begin()) { 262 | return false; 263 | } 264 | wifi_config_t conf; 265 | memset(&conf, 0, sizeof(wifi_config_t)); 266 | conf.ap.channel = 1; 267 | conf.ap.max_connection = 4; 268 | conf.ap.beacon_interval = 100; 269 | esp_err_t err = esp_wifi_set_config(WIFI_IF_AP, &conf); 270 | if (err) { 271 | log_e("Set AP config failed! 0x%x: %s", err, esp_err_to_name(err)); 272 | return false; 273 | } 274 | return true; 275 | } 276 | 277 | bool APClass::bandwidth(wifi_bandwidth_t bandwidth) { 278 | if (!begin()) { 279 | return false; 280 | } 281 | esp_err_t err = esp_wifi_set_bandwidth(WIFI_IF_AP, bandwidth); 282 | if (err) { 283 | log_e("Could not set AP bandwidth! 0x%x: %s", err, esp_err_to_name(err)); 284 | return false; 285 | } 286 | 287 | return true; 288 | } 289 | 290 | bool APClass::enableNAPT(bool enable) { 291 | if (!started()) { 292 | log_e("AP must be first started to enable/disable NAPT"); 293 | return false; 294 | } 295 | esp_err_t err = ESP_OK; 296 | if (enable) { 297 | err = esp_netif_napt_enable(_esp_netif); 298 | } else { 299 | err = esp_netif_napt_disable(_esp_netif); 300 | } 301 | if (err) { 302 | log_e("Could not set enable/disable NAPT! 0x%x: %s", err, esp_err_to_name(err)); 303 | return false; 304 | } 305 | return true; 306 | } 307 | 308 | String APClass::SSID(void) const { 309 | if (!started()) { 310 | return String(); 311 | } 312 | wifi_config_t info; 313 | if (!esp_wifi_get_config(WIFI_IF_AP, &info)) { 314 | return String(reinterpret_cast(info.ap.ssid)); 315 | } 316 | return String(); 317 | } 318 | 319 | uint8_t APClass::stationCount() { 320 | wifi_sta_list_t clients; 321 | if (!started()) { 322 | return 0; 323 | } 324 | if (esp_wifi_ap_get_sta_list(&clients) == ESP_OK) { 325 | return clients.num; 326 | } 327 | return 0; 328 | } 329 | 330 | size_t APClass::printDriverInfo(Print &out) const { 331 | size_t bytes = 0; 332 | wifi_config_t info; 333 | wifi_sta_list_t clients; 334 | if (!started()) { 335 | return bytes; 336 | } 337 | if (esp_wifi_get_config(WIFI_IF_AP, &info) != ESP_OK) { 338 | return bytes; 339 | } 340 | bytes += out.print(","); 341 | bytes += out.print((const char *)info.ap.ssid); 342 | bytes += out.print(",CH:"); 343 | bytes += out.print(info.ap.channel); 344 | 345 | if (info.ap.authmode == WIFI_AUTH_OPEN) { 346 | bytes += out.print(",OPEN"); 347 | } else if (info.ap.authmode == WIFI_AUTH_WEP) { 348 | bytes += out.print(",WEP"); 349 | } else if (info.ap.authmode == WIFI_AUTH_WPA_PSK) { 350 | bytes += out.print(",WPA_PSK"); 351 | } else if (info.ap.authmode == WIFI_AUTH_WPA2_PSK) { 352 | bytes += out.print(",WPA2_PSK"); 353 | } else if (info.ap.authmode == WIFI_AUTH_WPA_WPA2_PSK) { 354 | bytes += out.print(",WPA_WPA2_PSK"); 355 | } else if (info.ap.authmode == WIFI_AUTH_ENTERPRISE) { 356 | bytes += out.print(",WEAP"); 357 | } else if (info.ap.authmode == WIFI_AUTH_WPA3_PSK) { 358 | bytes += out.print(",WPA3_PSK"); 359 | } else if (info.ap.authmode == WIFI_AUTH_WPA2_WPA3_PSK) { 360 | bytes += out.print(",WPA2_WPA3_PSK"); 361 | } else if (info.ap.authmode == WIFI_AUTH_WAPI_PSK) { 362 | bytes += out.print(",WAPI_PSK"); 363 | } else if (info.ap.authmode == WIFI_AUTH_OWE) { 364 | bytes += out.print(",OWE"); 365 | } else if (info.ap.authmode == WIFI_AUTH_WPA3_ENT_192) { 366 | bytes += out.print(",WPA3_ENT_SUITE_B_192_BIT"); 367 | } 368 | 369 | if (esp_wifi_ap_get_sta_list(&clients) == ESP_OK) { 370 | bytes += out.print(",STA:"); 371 | bytes += out.print(clients.num); 372 | } 373 | return bytes; 374 | } 375 | 376 | #endif /* SOC_WIFI_SUPPORTED */ 377 | -------------------------------------------------------------------------------- /ESP32 - arduino IDE codes ( .cpp )/WIFI/WIFI_MP3_playing_via_I2s/WIFI_MP3_playing_via_I2s/External libs/WIFI libs used/WiFiSTA.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | WiFiSTA.cpp - WiFi library for esp32 3 | 4 | Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. 5 | This file is part of the esp8266 core for Arduino environment. 6 | 7 | This library is free software; you can redistribute it and/or 8 | modify it under the terms of the GNU Lesser General Public 9 | License as published by the Free Software Foundation; either 10 | version 2.1 of the License, or (at your option) any later version. 11 | 12 | This library is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 | Lesser General Public License for more details. 16 | 17 | You should have received a copy of the GNU Lesser General Public 18 | License along with this library; if not, write to the Free Software 19 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 20 | 21 | Reworked on 28 Dec 2015 by Markus Sattler 22 | 23 | */ 24 | 25 | #include "WiFi.h" 26 | #include "WiFiGeneric.h" 27 | #include "WiFiSTA.h" 28 | #if SOC_WIFI_SUPPORTED || CONFIG_ESP_WIFI_REMOTE_ENABLED 29 | 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include 39 | #include 40 | #include 41 | #include "lwip/err.h" 42 | #include "lwip/dns.h" 43 | #include 44 | #include 45 | #include "esp_mac.h" 46 | 47 | #if __has_include("esp_eap_client.h") 48 | #include "esp_eap_client.h" 49 | #else 50 | #include "esp_wpa2.h" 51 | #endif 52 | 53 | // ----------------------------------------------------------------------------------------------------------------------- 54 | // ---------------------------------------------------- STA function ----------------------------------------------------- 55 | // ----------------------------------------------------------------------------------------------------------------------- 56 | 57 | /** 58 | * Return Connection status. 59 | * @return one of the value defined in wl_status_t 60 | * 61 | */ 62 | wl_status_t WiFiSTAClass::status() { 63 | return STA.status(); 64 | } 65 | 66 | #if CONFIG_ESP_WIFI_ENTERPRISE_SUPPORT 67 | wl_status_t WiFiSTAClass::begin( 68 | const char *wpa2_ssid, wpa2_auth_method_t method, const char *wpa2_identity, const char *wpa2_username, const char *wpa2_password, const char *ca_pem, 69 | const char *client_crt, const char *client_key, int ttls_phase2_type, int32_t channel, const uint8_t *bssid, bool connect 70 | ) { 71 | if (!STA.begin()) { 72 | return WL_CONNECT_FAILED; 73 | } 74 | 75 | if (!STA.connect(wpa2_ssid, method, wpa2_identity, wpa2_username, wpa2_password, ca_pem, client_crt, client_key, ttls_phase2_type, channel, bssid, connect)) { 76 | return WL_CONNECT_FAILED; 77 | } 78 | 79 | return STA.status(); 80 | } 81 | #endif /* CONFIG_ESP_WIFI_ENTERPRISE_SUPPORT */ 82 | 83 | wl_status_t WiFiSTAClass::begin(const char *ssid, const char *passphrase, int32_t channel, const uint8_t *bssid, bool connect) { 84 | if (!STA.begin()) { 85 | return WL_CONNECT_FAILED; 86 | } 87 | 88 | if (!STA.connect(ssid, passphrase, channel, bssid, connect)) { 89 | return WL_CONNECT_FAILED; 90 | } 91 | 92 | return STA.status(); 93 | } 94 | 95 | /** 96 | * Use to connect to SDK config. 97 | * @return wl_status_t 98 | */ 99 | wl_status_t WiFiSTAClass::begin() { 100 | if (!STA.begin(true)) { 101 | return WL_CONNECT_FAILED; 102 | } 103 | 104 | return STA.status(); 105 | } 106 | 107 | /** 108 | * will force a disconnect and then start reconnecting to AP 109 | * @return true when successful 110 | */ 111 | bool WiFiSTAClass::reconnect() { 112 | return STA.reconnect(); 113 | } 114 | 115 | /** 116 | * Disconnect from the network. 117 | * @param wifioff `true` to turn the Wi-Fi radio off. 118 | * @param eraseap `true` to erase the AP configuration from the NVS memory. 119 | * @return `true` when successful. 120 | */ 121 | bool WiFiSTAClass::disconnectAsync(bool wifioff, bool eraseap) { 122 | return disconnect(wifioff, eraseap, 0); 123 | } 124 | 125 | /** 126 | * Disconnect from the network. 127 | * @param wifioff `true` to turn the Wi-Fi radio off. 128 | * @param eraseap `true` to erase the AP configuration from the NVS memory. 129 | * @param timeoutLength timeout to wait for status change 130 | * @return `true` when successful. 131 | */ 132 | bool WiFiSTAClass::disconnect(bool wifioff, bool eraseap, unsigned long timeoutLength) { 133 | if (!STA.disconnect(eraseap, timeoutLength)) { 134 | return false; 135 | } 136 | if (wifioff) { 137 | return STA.end(); 138 | } 139 | return true; 140 | } 141 | 142 | /** 143 | * @brief Reset WiFi settings in NVS to default values. 144 | * 145 | * This function will reset settings made using the following APIs: 146 | * - esp_wifi_set_bandwidth, 147 | * - esp_wifi_set_protocol, 148 | * - esp_wifi_set_config related 149 | * - esp_wifi_set_mode 150 | * 151 | * @return true if erase succeeded 152 | * @note: Resets SSID, password, protocol, mode, etc. 153 | * These settings are maintained by WiFi driver in IDF. 154 | * WiFi driver must be initialized. 155 | */ 156 | bool WiFiSTAClass::eraseAP(void) { 157 | return STA.erase(); 158 | } 159 | 160 | /** 161 | * Change IP configuration settings disabling the dhcp client 162 | * @param local_ip Static ip configuration 163 | * @param gateway Static gateway configuration 164 | * @param subnet Static Subnet mask 165 | * @param dns1 Static DNS server 1 166 | * @param dns2 Static DNS server 2 167 | */ 168 | bool WiFiSTAClass::config(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dns1, IPAddress dns2) { 169 | // handle Arduino ordering of parameters: ip, dns, gw, subnet 170 | if (local_ip.type() == IPv4 && local_ip != INADDR_NONE && subnet[0] != 255) { 171 | IPAddress tmp = dns1; 172 | dns1 = gateway; 173 | gateway = subnet; 174 | subnet = (tmp != INADDR_NONE) ? tmp : IPAddress(255, 255, 255, 0); 175 | } 176 | 177 | return STA.begin() && STA.config(local_ip, gateway, subnet, dns1, dns2); 178 | } 179 | 180 | bool WiFiSTAClass::config(IPAddress local_ip, IPAddress dns) { 181 | 182 | if (local_ip == INADDR_NONE) { 183 | return config(INADDR_NONE, INADDR_NONE, INADDR_NONE); 184 | } 185 | 186 | if (local_ip.type() != IPv4) { 187 | return false; 188 | } 189 | 190 | IPAddress gw(local_ip); 191 | gw[3] = 1; 192 | if (dns == INADDR_NONE) { 193 | dns = gw; 194 | } 195 | return config(local_ip, gw, IPAddress(255, 255, 255, 0), dns); 196 | } 197 | 198 | /** 199 | * Change DNS server for static IP configuration 200 | * @param dns1 Static DNS server 1 201 | * @param dns2 Static DNS server 2 (optional) 202 | */ 203 | bool WiFiSTAClass::setDNS(IPAddress dns1, IPAddress dns2) { 204 | return STA.begin() && STA.dnsIP(0, dns1) && STA.dnsIP(1, dns2); 205 | } 206 | 207 | /** 208 | * Sets the working bandwidth of the STA mode 209 | * @param m wifi_bandwidth_t 210 | */ 211 | bool WiFiSTAClass::bandwidth(wifi_bandwidth_t bandwidth) { 212 | return STA.bandwidth(bandwidth); 213 | } 214 | 215 | /** 216 | * is STA interface connected? 217 | * @return true if STA is connected to an AP 218 | */ 219 | bool WiFiSTAClass::isConnected() { 220 | return STA.connected() && STA.hasIP(); 221 | } 222 | 223 | /** 224 | * Set the minimum security for AP to be considered connectable. 225 | * Must be called before WiFi.begin(). 226 | * @param minSecurity wifi_auth_mode_t 227 | */ 228 | void WiFiSTAClass::setMinSecurity(wifi_auth_mode_t minSecurity) { 229 | return STA.setMinSecurity(minSecurity); 230 | } 231 | 232 | /** 233 | * Set the way that AP is chosen. 234 | * First SSID match[WIFI_FAST_SCAN] or Sorted[WIFI_ALL_CHANNEL_SCAN] (RSSI or Security) 235 | * Must be called before WiFi.begin() 236 | * @param scanMethod wifi_scan_method_t 237 | */ 238 | void WiFiSTAClass::setScanMethod(wifi_scan_method_t scanMethod) { 239 | return STA.setScanMethod(scanMethod); 240 | } 241 | 242 | /** 243 | * Set the way that AP is sorted. (requires scanMethod WIFI_ALL_CHANNEL_SCAN) 244 | * By SSID[WIFI_CONNECT_AP_BY_SIGNAL] or Security[WIFI_CONNECT_AP_BY_SECURITY] 245 | * Must be called before WiFi.begin() 246 | * @param sortMethod wifi_sort_method_t 247 | */ 248 | void WiFiSTAClass::setSortMethod(wifi_sort_method_t sortMethod) { 249 | return STA.setSortMethod(sortMethod); 250 | } 251 | 252 | /** 253 | * Function used to set the automatic reconnection if the connection is lost. 254 | * @param autoReconnect `true` to enable this option. 255 | * @return true 256 | */ 257 | bool WiFiSTAClass::setAutoReconnect(bool autoReconnect) { 258 | return STA.setAutoReconnect(autoReconnect); 259 | } 260 | /** 261 | * Function used to get the automatic reconnection if the connection is lost. 262 | * @return The function will return `true` if this setting is enabled. 263 | */ 264 | bool WiFiSTAClass::getAutoReconnect() { 265 | return STA.getAutoReconnect(); 266 | } 267 | 268 | /** 269 | * Wait for WiFi connection to reach a result 270 | * returns the status reached or disconnect if STA is off 271 | * @return wl_status_t 272 | */ 273 | uint8_t WiFiSTAClass::waitForConnectResult(unsigned long timeoutLength) { 274 | return STA.waitForConnectResult(timeoutLength); 275 | } 276 | 277 | /** 278 | * Get the station interface IP address. 279 | * @return IPAddress station IP 280 | */ 281 | IPAddress WiFiSTAClass::localIP() { 282 | return STA.localIP(); 283 | } 284 | 285 | /** 286 | * Get the station interface MAC address. 287 | * @param mac pointer to uint8_t array with length WL_MAC_ADDR_LENGTH 288 | * @return pointer to uint8_t * 289 | */ 290 | uint8_t *WiFiSTAClass::macAddress(uint8_t *mac) { 291 | return STA.macAddress(mac); 292 | } 293 | 294 | /** 295 | * Get the station interface MAC address. 296 | * @return String mac 297 | */ 298 | String WiFiSTAClass::macAddress(void) { 299 | return STA.macAddress(); 300 | } 301 | 302 | /** 303 | * Get the interface subnet mask address. 304 | * @return IPAddress subnetMask 305 | */ 306 | IPAddress WiFiSTAClass::subnetMask() { 307 | return STA.subnetMask(); 308 | } 309 | 310 | /** 311 | * Get the gateway ip address. 312 | * @return IPAddress gatewayIP 313 | */ 314 | IPAddress WiFiSTAClass::gatewayIP() { 315 | return STA.gatewayIP(); 316 | } 317 | 318 | /** 319 | * Get the DNS ip address. 320 | * @param dns_no 321 | * @return IPAddress DNS Server IP 322 | */ 323 | IPAddress WiFiSTAClass::dnsIP(uint8_t dns_no) { 324 | return STA.dnsIP(dns_no); 325 | } 326 | 327 | /** 328 | * Get the broadcast ip address. 329 | * @return IPAddress broadcastIP 330 | */ 331 | IPAddress WiFiSTAClass::broadcastIP() { 332 | return STA.broadcastIP(); 333 | } 334 | 335 | /** 336 | * Get the network id. 337 | * @return IPAddress networkID 338 | */ 339 | IPAddress WiFiSTAClass::networkID() { 340 | return STA.networkID(); 341 | } 342 | 343 | /** 344 | * Get the subnet CIDR. 345 | * @return uint8_t subnetCIDR 346 | */ 347 | uint8_t WiFiSTAClass::subnetCIDR() { 348 | return STA.subnetCIDR(); 349 | } 350 | 351 | /** 352 | * Return the current SSID associated with the network 353 | * @return SSID 354 | */ 355 | String WiFiSTAClass::SSID() const { 356 | return STA.SSID(); 357 | } 358 | 359 | /** 360 | * Return the current pre shared key associated with the network 361 | * @return psk string 362 | */ 363 | String WiFiSTAClass::psk() const { 364 | return STA.psk(); 365 | } 366 | 367 | /** 368 | * Return the current bssid / mac associated with the network if configured 369 | * @return bssid uint8_t * 370 | */ 371 | uint8_t *WiFiSTAClass::BSSID(uint8_t *buff) { 372 | return STA.BSSID(buff); 373 | } 374 | 375 | /** 376 | * Return the current bssid / mac associated with the network if configured 377 | * @return String bssid mac 378 | */ 379 | String WiFiSTAClass::BSSIDstr(void) { 380 | return STA.BSSIDstr(); 381 | } 382 | 383 | /** 384 | * Return the current network RSSI. 385 | * @return RSSI value 386 | */ 387 | int8_t WiFiSTAClass::RSSI(void) { 388 | return STA.RSSI(); 389 | } 390 | 391 | #if CONFIG_LWIP_IPV6 392 | /** 393 | * Enable IPv6 on the station interface. 394 | * Should be called before WiFi.begin() 395 | * 396 | * @return true on success 397 | */ 398 | bool WiFiSTAClass::enableIPv6(bool en) { 399 | return STA.enableIPv6(en); 400 | } 401 | 402 | /** 403 | * Get the station interface link-local IPv6 address. 404 | * @return IPAddress 405 | */ 406 | IPAddress WiFiSTAClass::linkLocalIPv6() { 407 | return STA.linkLocalIPv6(); 408 | } 409 | 410 | /** 411 | * Get the station interface global IPv6 address. 412 | * @return IPAddress 413 | */ 414 | IPAddress WiFiSTAClass::globalIPv6() { 415 | return STA.globalIPv6(); 416 | } 417 | #endif 418 | 419 | bool WiFiSTAClass::_smartConfigStarted = false; 420 | bool WiFiSTAClass::_smartConfigDone = false; 421 | 422 | /** 423 | * @brief 424 | * 425 | * @param type Select type of SmartConfig. Default type is SC_TYPE_ESPTOUCH 426 | * @param crypt_key When using type SC_TYPE_ESPTOUTCH_V2 crypt key needed, else ignored. Length should be 16 chars. 427 | * @return true if configuration is successful. 428 | * @return false if configuration fails. 429 | */ 430 | bool WiFiSTAClass::beginSmartConfig(smartconfig_type_t type, char *crypt_key) { 431 | esp_err_t err; 432 | if (_smartConfigStarted) { 433 | return false; 434 | } 435 | 436 | if (!WiFi.mode(WIFI_STA)) { 437 | return false; 438 | } 439 | esp_wifi_disconnect(); 440 | 441 | smartconfig_start_config_t conf = SMARTCONFIG_START_CONFIG_DEFAULT(); 442 | 443 | if (type == SC_TYPE_ESPTOUCH_V2) { 444 | conf.esp_touch_v2_enable_crypt = true; 445 | conf.esp_touch_v2_key = crypt_key; 446 | } 447 | 448 | err = esp_smartconfig_set_type(type); 449 | if (err != ESP_OK) { 450 | log_e("SmartConfig Set Type Failed!"); 451 | return false; 452 | } 453 | err = esp_smartconfig_start(&conf); 454 | if (err != ESP_OK) { 455 | log_e("SmartConfig Start Failed!"); 456 | return false; 457 | } 458 | _smartConfigStarted = true; 459 | _smartConfigDone = false; 460 | return true; 461 | } 462 | 463 | bool WiFiSTAClass::stopSmartConfig() { 464 | if (!_smartConfigStarted) { 465 | return true; 466 | } 467 | 468 | if (esp_smartconfig_stop() == ESP_OK) { 469 | _smartConfigStarted = false; 470 | return true; 471 | } 472 | 473 | return false; 474 | } 475 | 476 | bool WiFiSTAClass::smartConfigDone() { 477 | if (!_smartConfigStarted) { 478 | return false; 479 | } 480 | 481 | return _smartConfigDone; 482 | } 483 | 484 | #endif /* SOC_WIFI_SUPPORTED */ 485 | --------------------------------------------------------------------------------