Compare commits

...

459 Commits

Author SHA1 Message Date
4ada3f5804 Fix Windows USB issues
- Device will not reset if previous baudrate was not 9600
- CDC Device is not recognized if WebUSB is enabled
2021-07-20 13:36:27 +03:00
268595c743 Various USB fixes (#5422)
* Fix compile archive arguments for the new toolchain

* Add menu to S2 for picking through which port to upload

Internal USB CDC requires to reset and wait for the new port (because persistence is not yet stable)

* USB CDC should also be started in main

* Fix URL and USB version for WebUSB

* Update vendor callback API

* Update CDC::write to use TX_DONE semaphore

* Update USB_Serial example
2021-07-20 11:59:13 +03:00
4a0305a05e Fixes SD begin() end() memory leak #2897 (#5419) 2021-07-19 19:08:51 +03:00
6393dbc91b Fix gh-pages update script 2021-07-19 18:56:00 +03:00
49df8778f9 Merge pull request #5417 from pedrominatel/docs/readme_docs_update
Links to the new docs updated and new docs build badge added
2021-07-19 17:31:48 +02:00
f79411f3d3 Links to the new docs updated and new docs build badge added 2021-07-19 15:01:39 +01:00
db4e7667af add callback to HTTPUpdate (#5408)
- add callback function to HTTPUpdate
- update example to print httpupdate progress
- fix ArduinoIDE syntax coloring

Signed-off-by: Jayantajit Gogoi <jayanta.gogoi525@gmail.com>
2021-07-19 14:28:17 +03:00
f64ca2e084 Fixed typo in comments. (#5407)
A typographical error is corrected in the 2nd line of the comment. 
From = " This is un example howto use Touch Intrrerupts "
To = " This is an example of how to use Touch Intrrerupts "
2021-07-19 13:38:40 +03:00
1effae46ea Docs: Initial documentation structure using Sphinx (#5355)
This PR is the initial documentation structure including the basic information about the project and Sphinx configuration.

####CONTENTS:
- Getting Started
- Installing
- Boards
- Libraries
- Library Builder
- Tutorials
- ESP-IDF as Component
- OTA Web Update
- makeEspArduino
- Troubleshooting
- Contributing

This PR also changes the README.md.
2021-07-19 13:37:26 +03:00
d9833f9b6d Remove mkfatfs tool from package json
Fixes: https://github.com/espressif/arduino-esp32/issues/5376
2021-07-18 22:48:03 +03:00
0aafa05e8f Added function to retrieve the amount of data received from an BLECharacteristic (#5339) 2021-07-17 02:03:44 +03:00
16f4b0f5ba IDF master d93887f9f (#5336)
* Update toolchain

* Update package_esp32_index.template.json

* add optional component dependencies after Kconfig options are known (#5404)

Until this commit, Kconfig options (e.g. CONFIG_TINYUSB_ENABLED) were
used in conditions preceding idf_component_register to determine which
components need to be added to `arduino` component requirements.
However the Kconfig options aren't known at the early expansion stage,
when the component CMakeLists.txt files are expanded the first time
and requirements are evaluated. So all the conditions evaluated as if
the options were not set.
This commit changes the logic to only add these components as
dependencies when the Kconfig options are known. Dependencies become
"weak", which means that if one of the components isn't included into
the build for some reason, it is not added as a dependency.
This may happen, for example, if the component is not present in the
`components` directory or is excluded by setting `COMPONENTS` variable
in the project CMakeLists.txt file.
This also ensures that if the component is not present, it will not be
added as a dependency, and this will allow the build to proceed.

Follow-up to https://github.com/espressif/arduino-esp32/pull/5391.
Closes https://github.com/espressif/arduino-esp32/issues/5319.

* IDF master d93887f9f

* PlatformIO updates for CI (#5387)

* Update PlatformIO CI build script

- Switch to the latest toolchains 8.4.0 for ESP32, ESP32S2, ESP32C3
- Use PlatformIO from master branch for better robustness

* Update package.json for PlatformIO

Co-authored-by: Ivan Grokhotkov <ivan@espressif.com>
Co-authored-by: Valerii Koval <valeros@users.noreply.github.com>
2021-07-17 01:57:49 +03:00
780588dce3 Remove undocumented and uncontrollable WiFI RSSI filter. (#5393)
Commit d15e1b0e [1] in the 2.0.0 pull request #4996 introduced a filter
to connect only to WiFi networks with a RSSI of -75 or better. This
results in strage behaviour, as a scan still shows networks, that can't
be connected to, even though with older versions, connecting to those
networks was possible and the connection (albeit slow) was stable.

Remove the RSSI filter for now by setting the threshold to -127, i.e.
the lowest possible value. Maybe in the future the filter threshold
could be exposed to users, to allow filtering out nearly unreachable
networks.

[1] github.com/espressif/arduino-esp32/pull/4996/commits/d15e1b0
2021-07-16 23:43:25 +03:00
eac8b2def3 fix port{Input,Output,Mode}Register macros for chips with <=32 pins (#5402)
Closes https://github.com/espressif/arduino-esp32/issues/5378
2021-07-16 23:42:08 +03:00
a9bd39de66 Fix pin attenuation being overwritten (#5399)
Fixes: #5041
2021-07-16 17:34:25 +03:00
5eda278177 Update camera example (#5397)
Fixes: https://github.com/espressif/arduino-esp32/issues/5128
Fixes: https://github.com/espressif/arduino-esp32/issues/5324
2021-07-16 16:55:59 +03:00
c8a4010fa6 Rename LITTLEFS to LittleFS to match ESP8266 (#5396)
Fixes: https://github.com/espressif/arduino-esp32/issues/5103
2021-07-16 15:46:38 +03:00
dd25e2b9d6 Fix some WiFi issues (#5395)
* Add back ARDUINO_EVENT_WIFI_READY

Fixes: https://github.com/espressif/arduino-esp32/issues/5315

* use strncpy and strncmp for WiFi SSID and Password in AP and STA

Fixes: https://github.com/espressif/arduino-esp32/issues/5367

* Implement timeout for waitForConnectResult

Fixes: https://github.com/espressif/arduino-esp32/issues/5330

* Remove old definition of "reverse" from stdlib_noniso

Fixes: https://github.com/espressif/arduino-esp32/issues/5045

* Make "reverse" noniso conditional on ESP_DSP
2021-07-16 14:48:57 +03:00
cf6ab9c8a3 component: Remove circular dependency around 'main' (#5391)
arduino-esp32 has to depend on main in autostart mode, for setup() and loop(),
but this can be done with undefined symbol entries to avoid a large dependency
cycle and other linker errors.

Closes https://github.com/espressif/esp-idf/issues/6968
2021-07-16 12:25:53 +03:00
676f5cfe30 fix UART FIFO test for being full (#5390)
Fixes #5362
2021-07-16 03:21:49 +03:00
f4f1c8956b pinMatrixInDetach() has wrong parameter (#5385)
Fixes #5112
Call to pinMatrixInDetach() was changed from version 1.0.6 in version 2.0.0 injecting a bug as seen in cores/esp32/esp32-hal-uart.c
80418fadcf

Co-authored-by: Me No Dev <me-no-dev@users.noreply.github.com>
2021-07-15 02:07:43 +03:00
cbcba53dff Improve error message when ADC2 can not be used because WiFi is On
reference: https://github.com/espressif/arduino-esp32/issues/102
2021-07-08 13:58:17 +03:00
c37557c711 Update .gitignore (#5323)
In current master, after get.exe, there's tools/mkfatfs.exe that must be ignored.
Also cleaning up a simple duplicate line in .gitignore.
This is for Windows only, any hints on what can be done for Linux, Mac, is appreciated.
2021-06-29 11:45:08 +03:00
8f46bade7a Fix hardware timers
Fixes: https://github.com/espressif/arduino-esp32/issues/5337
Fixes: https://github.com/espressif/arduino-esp32/issues/4743

Thanks to @maxgerhardt
2021-06-28 15:44:30 +03:00
21947ebe76 Make String::concat() faster for some types. (#5307)
* Make String::concat() faster for some types.

This patch removes the unneeded call to `strlen()` when concatenating some types to a `String`. Additionally it fixes some whitespace for consistency.

* Update WString.cpp
2021-06-18 13:10:40 +03:00
c7bdb234bf Update stale.yml (#5299)
Stale bot labels fix.
2021-06-17 20:01:29 +03:00
cf43d174b7 Add FTM support and examples (#5272)
Rework of #5266 by @pedrominatel
2021-06-16 21:24:48 +03:00
b1bcec08f8 Update boards_manager.md (#5296) 2021-06-16 20:58:31 +03:00
46d888eb68 Fix #5293 by adding missing dependency to nghttp (#5294)
Fixes #5293

/components/arduino/libraries/WebServer/src/HTTP_Method.h:4:10: fatal error: http_parser.h: No such file or directory #include "http_parser.h"
2021-06-16 20:56:25 +03:00
1f4f2b6e97 Enable clock output for Ethernet RMII on ESP32 (#5274)
fixes #5239

* Add back clock mode argument
2021-06-16 20:45:20 +03:00
ea236e28e5 Fix incorrect Flash Size in Esp32c3 (#5279)
original PR #5278 from @s-hadinger, which is not accepted because of failure of CLAassistant

`ESP.getFlashChipSize()` always returns `0` on Esp32c3 due to a change in the Flash layout. It looks like to Espressif documentation was not updated accordingly.

https://docs.espressif.com/projects/esp-idf/en/latest/esp32c3/api-reference/storage/spi_flash.html#spi-flash-size

- Esp32 and Esp32s3 have the flash information update by esptool.py
and decribed here
- https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/storage/spi_flash.html
Esp32c3 has no image information at 0x0000 and contrary to the docu
this information is at offset 0x0000
2021-06-11 13:46:14 +03:00
5ae3e836f9 Fix wrong password same SSID (#5124)
When iterating through APlist from first to the last element, a corrected password for already known SSID is not used. Therefore, I propose to iterate from the back of the list. With iterating from the back through the vector, an already known SSID with a corrected password is used instead.
2021-06-10 13:19:58 +03:00
eca328e576 Add support for build_opt.h in the sketch folder to use additional global build options (#5237)
Additional compile arguments can be given by a file named "build_opt.h".
This enables users to easily extend their arguments on a central place.
The script has been taken from stm32duino's Arduino_Core_STM32 package

Co-authored-by: Me No Dev <me-no-dev@users.noreply.github.com>
2021-06-10 13:18:03 +03:00
5b5cbb4926 Fix softap_config_equal compare auth_mode/cipher #5115 (#5121)
fixes #5115
2021-06-10 13:16:38 +03:00
aec2635b07 WifiAP disable insecure TKIP (#5122)
fixes #4805
2021-06-10 13:16:12 +03:00
e7e94ea247 Enable I2C_BUFFER_LENGTH definition for Wire lib (#5172) 2021-06-10 13:15:35 +03:00
b5ee7ddeed Convert hall read to use hal/idf (#5268)
Fixes #4866
2021-06-10 11:58:08 +03:00
10602939cc Added support for Trueverit ESP32 Universal IoT Driver MK II (#5269)
Add support for the Trueverit Universal IoT Driver MK II (https://www.trueverit.com)

The board will be released on market using electronic distributors soon, as the other one board added via #5219

This new board (referred as MK II) has onboard Texas Instruments DP83848 Eth PHY chip.
2021-06-10 11:57:10 +03:00
23820874ec Added the README template for examples and libraries (#5228)
Typos fixed and added more details and instructions
Added README file to WiFiScan example
Review on the README template
Added link to DevKits
2021-06-09 21:12:29 +03:00
4f9e583b29 IDF master 1d7068e4b (#5257)
esp-dsp: master 7cc5073
esp-face: master 420fc7e
esp-rainmaker: f1b82c7
esp32-camera: master 7a06a7e
esp_littlefs: master b58f00c
2021-06-09 13:12:47 +03:00
7f87d0fc3a Fix compilation for use as IDF component (#5265) 2021-06-09 12:56:12 +03:00
90fc68d83f doitESPduino32 - Add definitions for SPI pins names (#5248)
The doitESPduino32/pins_Arduino.h lacks definitions for the common SPI pins names: SS, MOSI, MISO, SCK
This breaks compatibility with Arduino libs, including SPI.h/.cpp

This PR solves the issue while maintaining compatibility with previous pin naming (IO5/23/19/18), and ensures consistency with other boards variants.
2021-06-09 12:55:13 +03:00
4f8e5b54b7 Add new board (Deneyap Kart) (#5236)
New board addition request for an ESP32 Wrover based Developer Board
2021-06-09 12:51:45 +03:00
483a424d0a restore apache-2.0 licence to to BLE library (#5261)
The code in the BLE library originates from https://github.com/nkolban/esp32-snippets/tree/master/cpp_utils as well as https://github.com/nkolban/ESP32_BLE_Arduino

The original code in the esp32-snippets library is apache-2.0 licence'ed.
In addition when Neil Kolban stopped maintaining this library he made it available with the express requirement that the licence stays as apache-2.0
(Please see: https://github.com/nkolban/esp32-snippets/issues/813)
"... I do require that it continue to be Apache Licensed and free of charge for any and all uses (private or commercial)."

This change is to clarify the licence of this library.
2021-06-09 12:41:19 +03:00
e7d0ad2efd Update BLEScan.cpp (#5241)
Proposed fix to #4627 as a remediation to PR #3995
#3995 introduced that a device detected on BLE would not be entered in vector if a callback has been defined. 
By doing so, it was not possible anymore to have a counter in a call back (AND device in vector) to limit the number of detected device in a single scan, which could crash ESP32 as a result.
2021-06-09 12:40:59 +03:00
77f504453f WMath.cpp doesn't include Arduino.h, where makeWord(h, l) is declared, common denominator type therefore is uint8_t, which is in use already in Arduino.h, too. (#5230)
Fixes #5229
2021-06-09 12:40:08 +03:00
67de199bac add onMtuChanged to BLEServerCallbacks (#5222)
* add onMtuChanged to BLEServerCallbacks

Add method onMtuChanged to the BLEServerCallbacks so the application can be notified if the MTU size changes.

* Correct missing semicolon and misspelled method.

Correct missing semicolon and misspelled method.
2021-06-09 12:37:46 +03:00
39155e70a6 ssl_client.cpp: Fix parameter name in _handle_error. (#5217) 2021-06-09 12:33:52 +03:00
f385ee4219 Fixed labels on the boards pinouts images (#5213) 2021-06-09 12:33:12 +03:00
e30b821be1 Add missing Wifi Provisioning dependency (#5203) 2021-06-09 12:32:40 +03:00
cb7aef1e88 Fix crash in WiFiClient when read() called after stop() (#5197)
Thi may happen if read() gets called repeatedly (such as in HttpClient to parse response headers) and the connection is closed unexpectedly or the remote peer may have unexpected behavior that causes the underlying socket to report an error. In that case read() itself calls stop(), which invalidates the receive buffer object. Then when read() is called again without checking, such as inside readStringUntil(), the _rxBuffer is null and ESP32 crashes.
2021-06-09 12:30:14 +03:00
fb513c79fa Add uPesy ESP32 DevKit boards support (#5144)
* Add uPesy ESP32 DevKit boards support
2021-06-09 12:29:23 +03:00
90d3ae25af Added support for Trueverit Universal IoT Driver (#5219)
Add support for the Trueverit Universal IoT Driver (https://www.trueverit.com)

The board will be released on market using electronic distributors soon
2021-06-09 12:27:32 +03:00
a618fc1361 IDF master c13afea63 (#5214)
esp-dsp: master 7cc5073
esp-face: master 420fc7e
esp-rainmaker: f1b82c7
esp32-camera: master 6f8489e
esp_littlefs: master b58f00c
2021-05-31 16:32:51 +03:00
0db9e2f45b Update esptool 2021-05-28 10:05:19 +03:00
a1d8b959b0 Fix length typo (#5189) 2021-05-18 14:01:20 +03:00
de66c39f04 Bump library versions to 2.0.0 (#5182)
* Bump library versions to 2.0.0

* Fixed name on SD library (see #5181)
2021-05-18 14:00:49 +03:00
1b5696a534 Bug fix for Heltec boards defintion (#5180) 2021-05-18 14:00:22 +03:00
955675e712 Adding build.mcu to save name killed export. reverting. fixes #5174 (#5177) 2021-05-18 13:59:36 +03:00
2082945d36 Make LOOP_STACK_SIZE user configurable at compile-time. (#5173)
This PR lets the user override the LOOP STACK SIZE set in sdkconfig (for example with -DARDUINO_LOOP_STACK_SIZE=12288).
2021-05-18 13:58:56 +03:00
0d6b142228 Update BLE_client.ino (#5156)
Pull request #4999 added setMTU function to BLEClient.cpp/.h, this line provides implementation of this added functionality to the BLE client example to resolve cases in which data from notifyCallback exceeds 20 characters (3 bytes for command type and attribute ID, 20 bytes for attribute data (char*)pData).
2021-05-18 13:57:56 +03:00
7c3a82a525 Fix (en|dis)able typo on BLEAdvertising start() (#5142) 2021-05-18 13:54:48 +03:00
dadc101506 Add files via upload - CONTRIBUTING.rst (#5138)
* Add files via upload

Adding of Contributing.rst file.

* Update CONTRIBUTING.rst
2021-05-18 13:54:25 +03:00
1b2f34b0d6 MDNSResponder: Add method to get TXT key values. (#5135) 2021-05-18 13:51:43 +03:00
76f0a80fe7 Removed second NTP server from configTime. SNTP only uses one (#5127) 2021-05-18 13:50:40 +03:00
5bfbcfc91c Added condition to only use tinyusb as needed (#5123)
* Added condition to only use tinyusb as needed

* Removed esp32c3 from targets supporting tinyusb
2021-05-18 13:49:32 +03:00
7a53c2d371 softAP should only start modern WPA2 (#5114)
* AP with old WPA should not be used due security flaws.
* restore behavior from 1.0.6, see 46d5afb17f/libraries/WiFi/src/WiFiAP.cpp (L127)
2021-05-18 13:34:52 +03:00
cb2fbe445d Added new boads pinout images for ESP32, ESP32-S2 and ESP32-C3 (#5133)
Board images updated and added warning on Flash/PSRAM pins
2021-05-18 13:33:57 +03:00
48becf8966 Update boards.txt (#5113)
add board KB32-FT
2021-05-18 13:32:30 +03:00
15f8853819 RMaker_readme: Minor corrections (#5175) 2021-05-18 13:31:29 +03:00
7856de7a57 BLE5 features to use with C3/S3 (#5085)
Added new BLE5 features to use on C3/S3 family:

extended scan,
extended/multi advertising
New code is not fancy (no feedback from events), but i think it is functional. To get feedback from events i am suggesting to use custom GAP callback, which is already implemented in BLEDevice.
2021-04-22 13:01:20 +03:00
e62ff6dc37 RainMaker library: Minor changes (#5092)
- Use Serial.print instead of log_i for QR code helper information,
  so that it is always printed by default.
- Expose the RainMaker factory reset and wifi reset APIs.
- Simplify example to have only a Switch device. Create another example for custom device.
- Enable push button based Factory reset and Wi-Fi reset.
- Added support for the TimeZone service.
- Moved API doc to RainMaker library's top level README.
- Other minor doc changes.
2021-04-22 12:59:27 +03:00
182499071a Still finding missing bits for the tinys2 board definition :( (#5098) 2021-04-22 12:57:41 +03:00
cdd48e4ee4 Re-add TinyS2 to boards.txt (#5093)
* Removed ProS2 and added TinyS2 to boards.txt

* Fixed incorrect NUM_OUTPUT_PINS - should be 47 not 45
This is why my APA doesn't work on my FeatherS2 as it usess IO45 and the check is for < not <=

* TinyS2 from boards.txt got stomped with old proS2 stuff (no idea why), so adding it back in.
2021-04-21 18:57:10 +03:00
0c3597f8d7 readme: minor fixes around chip names (#5097) 2021-04-21 18:55:58 +03:00
82161bebe3 Use cpu_hal_get_cycle_count for all chips 2021-04-19 14:25:09 +03:00
55b8f67d80 In esp32-hal-log, direct calls to ESP_LOG_x macros is more efficient than using intermediate function log_to_esp (#5081)
As indicated in https://github.com/espressif/arduino-esp32/issues/4845#issuecomment-820540642_ it is more efficient to call directly the ESP LOG macros. This spares a function call, a 512b buffer and a call to vsnprintf. No change in functionality.
2021-04-19 12:30:01 +03:00
9c20f1bdd0 added denky boards (#5079)
Added new boards including one with brand new ESP32-PICO-V3-02
2021-04-19 12:28:58 +03:00
b45cf11ff1 Fixed ESP::getCycleCount for S2/C3 (#5075)
Fixes #5071
2021-04-19 12:28:06 +03:00
fb0d63b576 Update README.md 2021-04-17 15:48:13 +03:00
5d9b98c9b0 IDF master cf457d412 (#5073)
esp-dsp: master 7cc5073
esp-face: master 420fc7e
esp-rainmaker: f1b82c7
esp32-camera: master 2dded7c
esp_littlefs: master d268e18
2021-04-17 15:28:16 +03:00
11f89cddf6 WiFiClientSecure fix flipped cert/key in comment (#5065) 2021-04-17 02:07:41 +03:00
01c8cae0dc Added method to change the ledc PWM frequency programmatically (#5003)
Added method to change the ledc PWM frequence programmatically
Returning frequency from ledcChangeFrequency
2021-04-17 02:06:58 +03:00
57cf2fb9f5 Fix possible string overflow in BTAdvertisedDeviceSet::toString() 2021-04-16 18:51:01 +03:00
41c372c143 [2.0.0] BtClassic Discovery with info without connect (#4811)
Hey guys,
so I wanted to do a BtClassic Discovery without the need to call connect
and to list all found devices on a display and continue work with that list.

I wasn't capable to test the example code with my file structure, but I did use the discovery already in some different situations.

However when I noted that the Bluedroid stack won't let me enforce an RfComm SPP connection to a GPS Device (Skytraxx 2 plus, I guess its interface is built so simple that it doesn't advertise its SPP over SDP), I will probably have to switch to BtStack (BlueKitchen) and stop on this side meanwhile
2021-04-16 01:37:33 +03:00
223acb3511 C3 toolchain uses github as source 2021-04-16 00:50:27 +03:00
f6c9faf4da [2.0.0] FS::name() returns the item name as in Arduino SD (#4892)
* FS::name() returns the item name as in Arduino SD

Added method FS::path() that returns the full path

* Adjust examples
2021-04-15 17:25:01 +03:00
89e7893b1a [2.0.0] Add BLE characteristic callbacks overloads (#4832)
Add BLE characteristic callbacks overloads with esp_ble_gatts_cb_param_t* param.
Example:

class BleCharactCallback : public BLECharacteristicCallbacks
{
    void onRead(BLECharacteristic *pCharacteristic, esp_ble_gatts_cb_param_t *param)
    {
        auto addr = param->read.bda;
        ESP_LOGV(TAG, "Device " ESP_BD_ADDR_STR " request data", ESP_BD_ADDR_HEX(addr));
    }
    void onWrite(BLECharacteristic *pCharacteristic, esp_ble_gatts_cb_param_t *param)
    {
        auto addr = param->write.bda;
        ESP_LOGV(TAG, "Device " ESP_BD_ADDR_STR " transmit data", ESP_BD_ADDR_HEX(addr));
    }
};
2021-04-15 16:08:22 +03:00
7a4e7066f9 Add setMTU function to BLEClient.cpp/.h (#4999)
The current implementation has a getMTU function which returns the mtu sent in a message.

This function allows you to set the MTU value on the connected device, it first sets the MTU locally by calling esp_ble_gatt_set_local_mtu. It then calls esp_ble_gattc_send_mtu_req to have the connected device also change its MTU size.
2021-04-15 16:07:45 +03:00
f3dca15a6f Fix TTGO Boards missing upload parameters,add Twatch revision (#5063) 2021-04-15 14:32:39 +03:00
9f1330c70c esp32s2 temp sensor (#5044) 2021-04-15 14:32:03 +03:00
ec7aeb4903 Removed ProS2 and added TinyS2 to boards.txt (#5037) 2021-04-15 14:31:41 +03:00
9a518cd3d7 LITTLEFS update - partition label and multiple partitions, idea copied from SPIFFS (#5023)
Note, maxOpenFiles parameter is unused but kept for compatibility.
2021-04-15 14:31:01 +03:00
81b7c47203 Serial::end hang (#5047)
workaround for #5043. There is a timing issue with HardwareSerial::end. I'm not sure what is hung, but it should be possible to see this in jtag, as it does cause a reboot if you let it. The delay needs to be before you detach the device!?
2021-04-15 12:46:53 +03:00
e6ba8c7ac9 Add KSZ8081 support. (#5061)
This adds support for the KSZ8081 ethernet phy.
Only the IDF 4+ specific code is modified, as the phy support was only
added recently:
espressif/esp-idf@aecfbf96
2021-04-15 12:43:29 +03:00
72eb3f32fe Add Adafruit esp32s2 boards with custom bootloader, partition and upload.extra_flags (#5056)
done on behalf of @ladyada, this PR does:

Add Adafruit FunHouse and upcoming Adafruit Feather Esp32s2
Update Adafruit magtag and metro esp32s2 to have tinyuf2 as factory app
Also modify platform.txt as discussed in adafruit#2 + adafruit#3 + adafruit#4 to add support for
Board/variant partition.csv, bootloader.bin ( priority is user sketch > variant > build.parition/boot )
upload.extra_flags to optionally flash tinyuf2 as factory application
Remove duplicated parameter in running python script in linux and windows
Please review and let me know if you want any changes.

Notes: tinyuf2 is a uf2 bootloader for multiple platforms. For esp32s2, it is an factory app to perform uf2 firmware update.
2021-04-15 12:41:59 +03:00
66b11ff2a4 Update platformio-build-esp32c3.py 2021-04-14 18:18:48 +03:00
404a31f445 Initial Esp32c3 Support (#5060) 2021-04-14 18:10:05 +03:00
371f382db7 Fix Serial RX and add option for FIFO Full Threshold in Serial.begin
Fixes: https://github.com/espressif/arduino-esp32/issues/5005
2021-04-08 15:29:53 +03:00
425619dfea Fix upload over USB CDC (USB serial must be set to 0) 2021-04-05 20:24:46 +03:00
aeb4a13aad ESP32S2 pinmap (#5015) 2021-04-05 16:54:40 +03:00
8645971981 Fix delayMicroseconds() to use 64bit period
fixes: https://github.com/espressif/arduino-esp32/issues/5000
2021-04-05 15:15:09 +03:00
5502879a5b v2.0.0 Add support for ESP32S2 and update ESP-IDF to 4.4 (#4996)
This is very much still work in progress and much more will change before the final 2.0.0

Some APIs have changed. New libraries have been added. LittleFS included.

Co-authored-by: Seon Rozenblum <seonr@3sprockets.com>
Co-authored-by: Me No Dev <me-no-dev@users.noreply.github.com>
Co-authored-by: geeksville <kevinh@geeksville.com>
Co-authored-by: Mike Dunston <m_dunston@comcast.net>
Co-authored-by: Unexpected Maker <seon@unexpectedmaker.com>
Co-authored-by: Seon Rozenblum <seonr@3sprockets.com>
Co-authored-by: microDev <70126934+microDev1@users.noreply.github.com>
Co-authored-by: tobozo <tobozo@users.noreply.github.com>
Co-authored-by: bobobo1618 <bobobo1618@users.noreply.github.com>
Co-authored-by: lorol <lorolouis@gmail.com>
Co-authored-by: geeksville <kevinh@geeksville.com>
Co-authored-by: Limor "Ladyada" Fried <limor@ladyada.net>
Co-authored-by: Sweety <switi.mhaiske@espressif.com>
Co-authored-by: Loick MAHIEUX <loick111@gmail.com>
Co-authored-by: Larry Bernstone <lbernstone@gmail.com>
Co-authored-by: Valerii Koval <valeros@users.noreply.github.com>
Co-authored-by: 快乐的我531 <2302004040@qq.com>
Co-authored-by: chegewara <imperiaonline4@gmail.com>
Co-authored-by: Clemens Kirchgatterer <clemens@1541.org>
Co-authored-by: Aron Rubin <aronrubin@gmail.com>
Co-authored-by: Pete Lewis <601236+lewispg228@users.noreply.github.com>
2021-04-05 14:23:58 +03:00
46d5afb17f Quote {build.source.path} to allow spaces in path (#4868)
Previously sketches or examples that had spaces anywhere in their absolute
path caused a total build failure. By adding quotes around the path in
platform.txt, they now build correctly

Co-authored-by: Me No Dev <me-no-dev@users.noreply.github.com>
2021-03-26 13:24:21 +02:00
66746750a4 IDF release/v3.3.5 85c43024c (#4976)
esp-face: master 420fc7e
esp32-camera: master 488c308
2021-03-26 12:56:06 +02:00
e7a2759b65 Allow STA SSID length of 32
Fixes: https://github.com/espressif/arduino-esp32/issues/3218
2021-03-23 14:30:19 +02:00
2ee66b54f0 IDF release/v3.3 c43efe150 (#4936)
esp-face: master 420fc7e
esp32-camera: master 488c308
FreeRTOS Static
2021-03-20 14:04:35 +02:00
2d3c57635d Fix: WebServer: Digest authentication failed for some clients
Ports: 4d3850e87e
2021-03-19 02:10:16 +02:00
a299ddc99e Change send_ssl_data to use size_t instead of uint16_t
Fixes: https://github.com/espressif/arduino-esp32/issues/4960
2021-03-18 15:02:37 +02:00
93bcf5f250 Allow passing custom HTTPClient to HTTPUpdate (#4959)
This enables customizing HTTP headers which adds some extra flexibility.
This does not break anything of course because this change introduces a new constructor with a new additional HTTPClient argument for HTTPUpdate class.
2021-03-18 13:12:57 +02:00
bd41334265 Fix ETH not enabling DHCP when configured with INADDR_NONE
Fixes: https://github.com/espressif/arduino-esp32/issues/4778
2021-03-18 00:53:53 +02:00
9a0762ad2a [BLE Client] Fix Deadlock when calling writeValue after registerForNotify
Fixes: https://github.com/espressif/arduino-esp32/issues/4952
2021-03-17 18:46:55 +02:00
a451c9ef0d Fix HTTPClient crash on GET() for url with redirects
Fixes: https://github.com/espressif/arduino-esp32/issues/4931
2021-03-16 21:28:19 +02:00
d362e1ee1a [BLE] Allows you to specify which channels are used to advertise. (#4954)
In some use cases getting rssi signal from one channel is more stable (less variance) than rssi from the three advertising channels.

This change allows you to specify which channels are used to advertise.
2021-03-16 11:56:23 +02:00
33d9f4aa19 Update GitHub Pages Builder
Add some debug and allow building from a branch named `pages`
2021-03-16 02:48:17 +02:00
63c51d51fb Update HTTPUpdate.cpp (#4942)
This is a mirror of a change in esp8266 needed to update with a url that redirects.
2021-03-16 02:14:53 +02:00
5b845272ed Fix BluetoothSerial TX Stall
Fixes: https://github.com/espressif/arduino-esp32/issues/4949
2021-03-16 02:11:59 +02:00
5da4a47bdf Update debian_ubuntu.md (#4907)
* Update debian_ubuntu.md

ERROR: This script does not work on Python 2.7 The minimum supported Python version is 3.6. Please use https://bootstrap.pypa.io/2.7/get-pip.py instead.

* Update debian_ubuntu.md

Co-authored-by: Me No Dev <me-no-dev@users.noreply.github.com>
2021-03-15 13:22:34 +02:00
3253de8792 added scan_method = WIFI_ALL_CHANNEL_SCAN into wifi config in WiFi.begin() to let the scan choose the nearest / strongest AP in case that there are multiple APs with the same SSID (#4947)
In case you have multiple APs with the same SSID/password and WiFi.begin(ssid, pwd) is called, ESP32 defaults to connect to THE FIRST AP FOUND matching ssid - according to:
https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/network/esp_wifi.html#_CPPv418wifi_scan_method_t

This can cause situations that ESP32 is trying to connect to AP which is far away from it (weak signal) even there is AP close to it, just as in my house - I have AP on channel 6 which is in the 1st floor (quite far from room where I do the programming) and AP on channel 13 in the same room I do the programming (which is in the 2nd floor) - result: ESP32 is trying to connect to the AP on channel 6 because it finds it first and never try the AP on channel 13 in the same room, result of this is very unreliable WiFi connection.

When scan_method is set to WIFI_ALL_CHANNEL_SCAN, ESP32 scans all channels and choose the nearest / strongest AP (matching the ssid of course) as expected - result is no connection problems at all.

Therefore I propose adding this parameter into WiFi.begin, connection problems as described above are quite confusing (especially for beginners), I can imagine that for example Schools there are usually using mutliple APs and this can cause intermittent connection problems without obvious reason.
2021-03-15 13:21:43 +02:00
a31f30529d fix spiTransferBytesNL() writes past end of data_out
Fixes: https://github.com/espressif/arduino-esp32/issues/4935
2021-03-15 10:40:50 +02:00
35643bdd9b adds esp8266-style hostname setting (#4938)
a little step to make esp8266 code compile without changes under esp32
2021-03-15 10:10:30 +02:00
8dc70e0add Revert "Update licenses"
This reverts commit 4b3f5c8ed4.
2021-03-11 12:11:53 +02:00
b42739dfa4 Update howsmyssl.com root certificate 2021-03-10 17:55:40 +02:00
93d5b8c672 Fix String::replace()
Fixes: https://github.com/espressif/arduino-esp32/issues/4920
2021-03-10 17:13:14 +02:00
f815a7c636 Add WiFi.softAPSSID()
Fixes: https://github.com/espressif/arduino-esp32/issues/4922
2021-03-10 16:36:51 +02:00
23f6e81d52 Fix AsyncUDP reporting bad address and port
Fixes: https://github.com/espressif/arduino-esp32/issues/4923
2021-03-10 16:20:18 +02:00
e8311b00ae IDF release/v3.3 0bfff0b25 (#4895)
esp-face: master 420fc7e
esp32-camera: master 770f26a
2021-03-10 14:48:35 +02:00
4d95e3a7ea Fix BT not starting correctly and SPP Coex not working
Fixes: https://github.com/espressif/arduino-esp32/issues/4912
2021-03-09 01:56:47 +02:00
7dc769d81c Board name change (ETBoard -> ET-Board) (#4858)
Co-authored-by: ketri-kjy <jinyoung@ketri.re.kr>
Co-authored-by: ketri2484 <ketri2484@gamil.com>
Co-authored-by: me-no-dev <hristo@espressif.com>
2021-03-09 00:32:02 +02:00
4204d1e60a Handle PSRAM libs in PlatformIO build script (#4911)
This PR adds PSRAM-specific libraries to the final linker command depending on the `BOARD_HAS_PSRAM` macro.

cc @me-no-dev
2021-03-09 00:21:52 +02:00
d7fda910fb Update stale.yml (#4902)
Labels names updated. Not sure if the spaces in label's names are going to work.
2021-03-06 14:15:46 +02:00
f7fc8ab377 Use HTTP method table from ESP-IDF's nghttp (#4900)
Fixes: #4884

* Use HTTP method table from ESP-IDF's nghttp
* Parse methods using IDF's HTTP method list
* Make example's loops to allow the CPU to switch tasks
2021-03-05 13:40:52 +02:00
dd834b3372 Ensure that String::setLen() is always after any memory operation
Since `String::setLen()` is now modifying the buffer, this change is required to ensure that the proper buffer is changed.
2021-03-05 12:00:39 +02:00
0e55f775d3 Fixing issue in String::remove 2021-03-04 22:41:46 +02:00
22a488cf23 Fix String::clear() not clearing the string properly
Fixes: https://github.com/espressif/arduino-esp32/issues/4893
2021-03-04 21:20:27 +02:00
6e7cc5210d Update pins_arduino.h for FireBettle-ESP32 (#4867)
* Update pins_arduino.h

Fix the bug that the IDE show: "Error compiling for the board FireBettle-ESP32" 
Detial"error : redefinition of const uint8_t D0~D9"

* Update pins_arduino.h

Co-authored-by: Me No Dev <me-no-dev@users.noreply.github.com>
2021-03-04 17:04:18 +02:00
7a6900a1f2 Correct issue 4871 - change space to underscore in boards.txt setting lolin32-lite.build.board (#4885) 2021-03-04 15:31:23 +02:00
0e0a7565e8 Remove tools/sdk/include/nimble from include path (#4891) 2021-03-04 15:30:34 +02:00
bd3addeb8e Fixed use of Bluedroid instead of BT in HAL. (#4879)
Fixed use of CONFIG_BLUEDROID_ENABLED instead of CONFIG_BT_ENABLED in HAL. This prevented compilation with Nimble-only configuration without apparent benefit.
2021-03-01 23:55:04 +02:00
1cf1c8eb79 Fix several SD card issues (#4876)
- File might not eval to false if opened with write/append and SD is gone
- Allow card to be formatted if FAT partition was not found
- Mark card as gone in certain situations
- Fix several logic errors in low level SD API
2021-03-01 23:52:57 +02:00
3fe7c2e8cd Add div by zero check back into WMath::map (#4853)
* Add div by zero check back into WMath::map
* include esp32-hal-log.h

Co-authored-by: Me No Dev <me-no-dev@users.noreply.github.com>
2021-02-24 19:04:36 +02:00
5d00b6eb16 Fix case where EEPROM will try to return longer string than it should
Fixes: https://github.com/espressif/arduino-esp32/issues/4768
2021-02-24 18:47:11 +02:00
419ba32432 etboard pinmap upload (#4748)
Co-authored-by: ketri-kjy <jinyoung@ketri.re.kr>
Co-authored-by: ketri2484 <ketri2484@gamil.com>
2021-02-23 09:49:38 +02:00
a0ddd8a16e IDF release/v3.3 7a85334d8 (#4813)
esp-face: master 420fc7e
esp32-camera: master a5ccbec
2021-02-23 01:06:41 +02:00
b8dab5ed1a Added possibility to use ESP32-IDF log insted of redefined one (#4845)
With this PR user can select to use the original ESP-IDF log instead of the redefined one.

User can also redefine the log function as per [Logging Library](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/log.html#_CPPv419esp_log_set_vprintf14vprintf_like_t) so he can for example redirect logs to a file.

To enable this change just add -DUSE_ESP32_LOG to build flags.
User can also change the default TAG (that now is ES32) to whatever it wants adding '-DTAG="tag_value"' to build flags
2021-02-23 00:18:15 +02:00
2141313148 Fix PSRAM support (#4850) 2021-02-23 00:15:48 +02:00
44aaf13225 Added BLEAddress operator overload methods (#4839)
Allows BLEAddress to be used as key in std::map etc
2021-02-22 19:37:07 +02:00
560c0f45f5 Fix dropped SSL connection when buffer gets full. (#4820)
mbedTLS requires repeated calls to mbedtls_ssl_write() whenever it returns MBEDTLS_ERR_SSL_WANT_READ or MBEDTLS_ERR_SSL_WANT_WRITE. this happens when the client sends data faster then the server or the connection can handle.
2021-02-22 19:34:56 +02:00
4b3f5c8ed4 Update licenses 2021-02-18 12:14:35 +02:00
c282cd8f5f Remove temp buffer in WiFiClientSecure::lastError (#4822)
The temp buffer serves no purpose here. Also mbedtls_strerror can be called with size == 0 safely.
2021-02-18 11:44:44 +02:00
7e59971d2f Add Lolin32 Lite and TTGO T7 boards (#4819)
Add the Wemos Lolin32 Lite (no longer being produced same as Lolin32) and
the TTGO T7 v1.3 and v1.4 boards (status unknown). All three are rather
generic ESP32 boards the main difference being pin layouts.
2021-02-18 11:43:11 +02:00
f4b17b3033 Allow releases from different branches 2021-02-17 14:06:30 +02:00
1ab550f6f2 Changed BLE notify_callback from raw function pointer to std::function (#4737) 2021-02-16 22:10:04 +02:00
9be784f69b Improve cleanup in BLEClient (#4742)
- Remove client from the list of devices in case registration fails
- Filter other events not related to registration during registration phase
- Cleanup if connect fails
- Reset if after disconnect
- Disconnect callback *after* cleanup is done so object can be deleted

This fixes some of the issues I had like:
- `BLEClient::connect` hangs up and never recovered because registration failed
- `BLEClient` could not be deleted after disconnect or deletion creating ghost events https://github.com/espressif/arduino-esp32/issues/4047
- `BLEClient` could not be properly reused after a connection was attempted (successful or not) 

* Cleanup in case of registration and connect failure.
Cleanup before calling disconnect callback for safe delete.
Reject other events during registration.
Adresses #4047, #4055

* Clear if after unregister #4047
2021-02-16 11:21:45 +02:00
7cdfb8bc7c Refactor BLEAdvertisedDevice (#4739)
fixes #4596

* Prevent possible undefined behaviour by get methods not taking an index as parameter
* Add methods to get the count of service data UUIDs and service UUIDs
* Various code improvements
2021-02-16 11:02:58 +02:00
8134a42162 Fix leak of memory and possible crashes in AsyncUDP 2021-02-16 10:26:37 +02:00
f13ff65691 AsyncUDP: Added lastErr helper variable (#4789)
The variable is useful when debugging AsyncUDP send problems.
The upper application can read and analyze the error reason.
2021-02-16 02:21:53 +02:00
e831680a41 Fixed a memory leak in BLE (issue #4753) (#4761)
* Fixed crash on delete after disconnect

* Fixed memory leak when getting characteristics

* Removed guard

Co-authored-by: ushiboy <ushiboy.dev@gmail.com>
2021-02-16 01:50:24 +02:00
d964873840 Added more inclusive CORS policy (#4767) 2021-02-16 01:49:30 +02:00
7e8993fc83 Speed up upload by a factor of 17 (#4787)
* Speed up upload by a factor of 17

Uploads are very slow because of an unnecessary "client.connected()" check in _uploadReadByte().

Here is what happens:
client.connected() is called for every byte read.  WiFiClient::connected() calls recv(fd(), &dummy, 0, MSG_DONTWAIT); which takes a relatively long time, so the optimized path of returning a buffered byte via client.read() is effectively nullified.

Removing the one line changed the upload speed for a 2 MB file (discarding the received data) from 22 KB/sec (before) to 367 KB/sec (after).

The change is safe in the face of disconnects because client.read(), when it no longer has buffered data, calls (WiFiClient)  fillBuffer(), which calls recv(), so the disconnection will be detected in due course.

* Move disconnect check into the timeout loop
2021-02-16 01:47:01 +02:00
15bae92a72 Idf release/v3.3 d8082b7f3
* Update IDF to d8082b7f3
2021-02-16 01:37:37 +02:00
6f23cd5988 Make sure that HTTPClient disconnects from the old server if redirecting to new one
Fixes: https://github.com/espressif/arduino-esp32/issues/4763
2021-02-04 02:42:44 +02:00
ad4cf1461b Rework setHostname for WiFi STA
Fixes: https://github.com/espressif/arduino-esp32/issues/2537
2021-02-03 13:17:49 +02:00
5de03a3918 Fix WiFi STA config IP to INADDR_NONE results in 255.255.255.255
Fixes: https://github.com/espressif/arduino-esp32/issues/4732
2021-02-03 11:47:35 +02:00
4b385690bc Move default Arduino partitions to a separate section (#4747) 2021-01-27 13:52:39 +02:00
dd513df124 Add arm64 support for mkspiffs 2021-01-21 14:42:31 +02:00
cee659563d IDF release/v3.3 7e63061fa (#4726)
Co-authored-by: me-no-dev <me-no-dev@github.com>
2021-01-21 14:33:55 +02:00
55442a05a4 Remove an unused variable 'channel' (#4725) 2021-01-21 14:31:25 +02:00
c9b3e512dd Make BLERemoteCharacteristic::getRemoteService() public #3367 (#4735) 2021-01-21 14:30:33 +02:00
8d0e68db4f Added parameter to Preferences::begin to select non-default NVS partition (#4718) 2021-01-15 19:06:51 +02:00
d2530850a3 Copy platformio-build.py in the release package 2021-01-14 11:17:21 +02:00
7ecbb483da Update toolchain and move files to github 2021-01-12 17:53:49 +02:00
b0e896e9ae IDF release/v3.3 cd59d107b (#4708)
Co-authored-by: me-no-dev <me-no-dev@github.com>
2021-01-12 15:24:34 +02:00
08f4665775 Change fetch depth for release so that history can be fetched 2021-01-12 15:09:28 +02:00
2452c1fb53 IDF release/v3.3 71df1f742
esp-face: master 420fc7e
esp32-camera: master 0107093
2021-01-11 14:20:02 +02:00
5f98370707 Add IP101 support (#4620) 2021-01-11 12:00:35 +02:00
81b9130d8d BluetoothSerial SSP Authentication with callbacks (#4634)
Added authentication callbacks and example, resolves #4622.
2021-01-11 11:58:15 +02:00
434d02c49f BLERemoteCharacteristic::registerForNotify: Permit event registration without updating descriptor. (#4659) 2021-01-11 11:44:38 +02:00
15db297130 availableForWrite (#4664)
added availableForWrite to Print.h to make compatible with Arduino Print.h
2021-01-11 11:43:10 +02:00
fe093a5e35 Sanitize compiler warning in BLERemoteService.cpp (issue #4660) (#4669)
Compiler complains on unused parameter pCharacteristicMap:

framework-arduinoespressif32\libraries\BLE\src\BLERemoteService.cpp: In member function 'void BLERemoteService::getCharacteristics(std::map<short unsigned int, BLERemoteCharacteristic*>*)':
\framework-arduinoespressif32\libraries\BLE\src\BLERemoteService.cpp:246:89: warning: parameter 'pCharacteristicMap' set but not used [-Wunused-but-set-parameter]
 void BLERemoteService::getCharacteristics(std::map<uint16_t, BLERemoteCharacteristic*>* pCharacteristicMap) {
2021-01-11 11:42:32 +02:00
a0ef17a9dd Use non-deprecated DPORT values in SPI HAL (#4682) 2021-01-11 11:40:18 +02:00
be77bd4e27 Resolve crash with timer interrupt functions called from ISR (#4684) 2021-01-11 11:39:39 +02:00
ef99cd7fe7 Add WiFiClientSecure::setInsecure() to equalize API with ESP8266 (#4648) 2020-12-21 01:09:37 +02:00
b05bdf6904 Update esptool for Big Sur 2020-12-07 10:19:55 +02:00
442c63a4c6 IDF release/v3.3 b4c075169 (#4604)
esp-face: master 420fc7e
esp32-camera: master 0107093
2020-12-07 10:03:16 +02:00
d1a4b3b822 Add loop task stack size config to Kconfig
Follow up for https://github.com/espressif/arduino-esp32/pull/4564
2020-12-02 11:56:45 +02:00
7d5bf9e385 [1.0.5] Make looptask stack size configurable (#4564)
Added guarded define to set the stacksize on the main looptask.
Advantage of this is that build_flags can be used to provide a different value for the stack size should it be neccessary
default behaviour is unaffected
2020-12-02 11:52:04 +02:00
aac26a4d1e [1.0.5] Update Heltec ESP32 series boards definition (#4577) 2020-12-02 11:50:12 +02:00
804c221499 Update .gitignore 2020-12-01 22:20:06 +02:00
3236358ded Update WiFiClient.cpp (#4573)
Replace (depricated) bzero, bcopy with memset and memcpy.
2020-12-01 16:35:12 +02:00
82e71f9b50 Update ssl_client.cpp (#4574)
Replace (depricated) bzero with memset.
2020-12-01 16:34:36 +02:00
2e12392721 IDF release/v3.3 c33fc7821
esp-face: master 420fc7e
esp32-camera: master 0107093
2020-12-01 16:22:18 +02:00
6b0114366b Fix logic in SPIClass::setHwCs. (#4559)
Fixes #4558
2020-11-23 14:22:43 +02:00
18832bb418 M5TimerCam: add LED_BUILTIN & SS/MOSI/MISO/SCK (#4560) 2020-11-23 14:21:58 +02:00
97dcea2b99 Update library.properties (#4563)
Set the category to silence this warning in the Arduino IDE:
```
WARNING: Category '' in library WiFiProv is not valid. Setting to 'Uncategorized'
```
2020-11-23 14:21:34 +02:00
dcff2e9774 Separate Provisioning library from WiFi library (#4547) 2020-11-19 00:12:16 +02:00
6d256b6454 IDF release/v3.3 68b237fe5 with Disable IRAM optimisation for WiFi 2020-11-16 13:06:50 +02:00
f6bf0f7aa2 IDF release/v3.3 68b237fe5 2020-11-16 12:44:07 +02:00
a59eb5d51e Merge branch 'master' into idf-release/v3.3 2020-11-16 12:09:23 +02:00
adafd9d7c0 Merge pull request #4538 from loick111/feature/custom_variants_dir
The goal is to allow custom configuration for `variants_dir` to define our own board variant directly in the project.

With this functionnality, we are now allowed to define in our projects a custom board **AND** a custom variant.
https://docs.platformio.org/en/latest/platforms/creating_board.html#custom-embedded-boards

Here is an example of how to define a custom board with custom variant:
```
my_project
├── boards
│   └── custom_esp32dev.json
└── variants
    └── custom-esp32dev
        └── pins_arduino.h
```

custom_esp32dev.json
```json
{
  "build": {
    "arduino":{
      "ldscript": "esp32_out.ld"
    },
    "core": "esp32",
    "extra_flags": "-DARDUINO_ESP32_DEV",
    "f_cpu": "240000000L",
    "f_flash": "40000000L",
    "flash_mode": "dio",
    "mcu": "esp32",
    "variants_dir": "variants",
    "variant": "custom-esp32dev"
  },
  "connectivity": [
    "wifi",
    "bluetooth",
    "ethernet",
    "can"
  ],
  "debug": {
    "openocd_board": "esp-wroom-32.cfg"
  },
  "frameworks": [
    "arduino",
    "espidf"
  ],
  "name": "My Custom Espressif ESP32 Dev Module",
  "upload": {
    "flash_size": "4MB",
    "maximum_ram_size": 327680,
    "maximum_size": 4194304,
    "require_upload_port": true,
    "speed": 460800
  },
  "url": "https://en.wikipedia.org/wiki/ESP32",
  "vendor": "Espressif"
}
```
2020-11-15 20:43:43 +02:00
ac9fdeffe4 Allow custom variants directory 2020-11-15 16:20:02 +01:00
cee7b4237c Merge branch 'master' into idf-release/v3.3 2020-11-15 12:02:51 +02:00
954df2fc3e Disable IRAM optimization for WiFi 2020-11-15 11:56:01 +02:00
e41fb08b2a Update esptool to work on BigSur 2020-11-15 08:53:07 +02:00
d8b1fc81c0 Added usedBytes to match other filesystems (#4534) 2020-11-15 08:48:21 +02:00
378b6ac032 Fix issue in webserver with Chrome based browsers
https://github.com/espressif/arduino-esp32/issues/3652
2020-11-15 08:46:23 +02:00
cecef8e930 IDF release/v3.3 68b237fe5 2020-11-14 00:33:27 +00:00
a8e99baeab Merge branch 'master' into idf-release/v3.3 2020-11-12 21:29:57 +02:00
b6cc108d49 Update WiFiProv.cpp (#4519)
Do not pollute the global namespace with generic names like 'config' by declaring global variables 'static'.
2020-11-10 20:51:10 +02:00
8816bb5505 Added #define LED_BUILTIN to all pins_arduino.h that need it. (#4520) 2020-11-10 20:50:35 +02:00
3274602eb0 Notify the batteryLevel change (#4517) 2020-11-10 13:02:00 +02:00
534f0810a6 fix bitWrite macro (#4507)
Fixes https://github.com/espressif/arduino-esp32/issues/4466
2020-11-09 17:08:13 +02:00
28a8073069 Fix issue 4095 (#4503)
pgmspace.h missing 'pgm_get_far_address'
2020-11-08 04:55:59 +02:00
7494c4e76d IDF release/v3.3 44ec7972b 2020-11-08 00:36:32 +00:00
486a4c66c4 SDCARD: First sector always written twice if multiple sectors are updated 2020-11-06 22:20:20 +02:00
c1951670d1 IDF release/v3.3 66d3783c8 2020-11-06 18:15:23 +00:00
ad07d36932 Update README.md 2020-11-06 17:21:12 +02:00
c6a8da61f7 Allow faster reuse of socket, to be able to restart WifiServer. (#4306)
See #3960 for more details of the problem and the solution. I only implemented what was proposed in this ticket, as it solves my problem, which was the same as in this ticket. Credits for the code going to @etrinh ;-)

This also is a more consistence behaviour compared to esp8266, where it also is possible to restart the wifiserver immediately on the same port.
2020-11-06 14:16:50 +02:00
dd1a15478f add TimerCAM and CoreInk board (#4498) 2020-11-06 13:30:57 +02:00
bcb7012a32 Change variants folder T-Beam (#4496) 2020-11-06 12:42:18 +02:00
3968821834 HttpClient uses Serial.printf() (#4488)
changed to log_d()
2020-11-04 14:49:33 +02:00
90f869e772 Fix BUG: Parsing of first line fails (#4484)
..because a firstLine = false; is missing ;)
2020-11-04 02:24:01 +02:00
be4d3b6cb8 Try to fix issue with GIT 2.29.0 2020-11-03 22:22:35 +02:00
60606e5ad0 Update on-release.sh 2020-11-03 21:53:22 +02:00
22b427df0f IDF release/v3.3 (#3672)
ESP-IDF release/v3.3: 66d3783c8
esp-face: 420fc7e
esp32-camera: 0107093
2020-11-03 21:20:00 +02:00
6e5be78838 Update install-arduino-ide.sh 2020-11-03 21:12:05 +02:00
e2452c0dfc Added isKey method to Preferences (#4441)
Checks to see if a string is a key in the namespace. 

Fixes #4440
2020-11-03 17:03:04 +02:00
56a7ae8712 Trailing spaces (#3738)
* fix typo in WiFiMulti

* clean up trailing spaces

* clean up script file used in cleaning

Co-authored-by: Me No Dev <me-no-dev@users.noreply.github.com>
2020-11-02 22:11:26 +02:00
e4b008e712 Handle stream timeouts properly, for slow HTTP/HTTPS links (#3752)
This patch fixes update timeouts (error #6) on slow HTTP/HTTPS links.
2020-11-02 22:01:27 +02:00
76afaf2d6b Add more options to the AI thinker cam. (#4253)
* Add more options to the AI thinker cam.

The reason is power saving and compatibility of cheap chines clones with crappy flash chips.
2020-11-02 21:21:22 +02:00
dccb4e8608 improve & fix BLEScan when wantDuplicates (#3995)
* improve & fix BLEScan when too many BLE devices
- when wantDuplicates, no need to check duplicate and no more insert into vector
- delete advertisedDevice when not insert into vector, fix memory leak
- add showParse when you just want raw advertised data
2020-11-02 20:41:50 +02:00
c2346c37da Add initial support for arm64 toolchain. (#4117)
Closes #4111.
gcc: I was not able to find an arm64 build on espressif's website so I choosed to put the armhf version, even if this should works this is only ok as temporary, arm64 runs better on arm64 than armhf :)
esptool: being interpreted python its ok
mkspiff: need igrr/mkspiffs#74 to be merged and artifacts added in /package/package_esp32_index.template.json.
2020-11-02 20:39:31 +02:00
3491ca7845 Add virtual beginMulticast(...) stub to UDP class (#4061)
https://github.com/arduino/ArduinoCore-sam/pull/6/files

It is used here:
https://github.com/arduino-libraries/ArduinoMDNS/blob/master/MDNS.cpp#L150
2020-11-02 20:26:50 +02:00
0e341a6192 Add sdkconfig option CONFIG_ARDUINO_UDP_TASK_PRIORITY, which sets the task priority for the UDP vtask." (#4131) 2020-11-02 20:21:59 +02:00
76cd2e2375 Fix BLE connection handling (#4137)
Remove device from Peer list if connection fails.

Only call onConnect callback if connection was successful.

Only call onDisconnect callback if the connection was previously connected (ESP_GATTC_DISCONNECT_EVT is fired on a unsuccessful connection attempt also).

Resolves a number of issues with phantom events and callbacks being fired.
2020-11-02 20:20:40 +02:00
9f7ff009c6 Fix parameter to BLEDevice::updatePeerDevice (#4133)
::addPeerDevice and ::removePeerDevice are called with m_appId, so should ::updatePeerDevice as all use the same parameter for the underlying map's key.
2020-11-02 20:20:16 +02:00
704b71dabe Fix header parsing
fixes #4454

closes #4455
2020-11-02 20:10:22 +02:00
7c0572172c Fix for issue #4158: BLEAdvertising - Crash with stack trace originating in Bluedroid (#4182)
* Fix for issue #4158: Crash with stack trace originating in Bluedroid
Improved configuration of scan response data in 'BLEAdvertising' avoids the crash:
- Added member variable 'm_scanRespData' to configure scan response differently from advertising data
- Initialization of 'm_scanRespData' in BLEAdvertising constructor
- Use of 'm_scanRespData' within BLEAdvertising::start() to configure the scan response
- 'Flags' and 'Appearance' are cleared in the scan response data
- With this fix, device names of up to 29 characters can be used without causing a crash.
2020-11-02 19:39:20 +02:00
f57c36782f Add sendContent overload that takes a const char* and a length (#4276)
The web server currently lacks the ability to send a buffer. Only strings are supported.

This PR adds an overload to sendContent.
2020-11-02 19:17:02 +02:00
3054bdf5a5 HTTPUpdateServer library (#4244) 2020-11-02 19:16:23 +02:00
1014ba40af Update ISSUE_TEMPLATE.md (#4416)
Make options list into a table
2020-11-02 18:59:46 +02:00
d6b91872cb Fix for espressif#3460 issue (#4424)
Fixes: #3460

This code has been run in production for 1 month and it looks stable, no data dropped and it definitely fixes the issue described. I think that this can be merged to avoid using custom package referencing in PlatformIO that has been used in quite a few projects for now.

Co-authored-by: Ivan Golubic <ivan@mvt-solutions.com>
2020-11-02 18:59:03 +02:00
d6b383f84b Merge pull request #4429 from Bmooij/feature/Add_flash_helper_constructor_to_Uri
Add flash helper constructor to Uri
2020-11-02 18:56:08 +02:00
cadbad8850 Add partition label argument to Update and ArduinoOTA classThe UpdateClass in the Updater component has the ability to update data toa SPIFFS partition. It selects the first available partition using theESP-IDF esp_partition_find_first() function.That behaviour is problematic if one has multiple SPIFFS partitions.This change allows a user to pass the label argument (defaults to NULL)to UpdateClass::begin() so a specific SPIFFS partition can be updated.Additionally, ArduinoOTA can set this partition label using thenew method ArduinoOTAClass::setPartitionLabel which is optional.This change does not break compatibility. (#4442)
The UpdateClass in the Updater component has the ability to update data to
a SPIFFS partition. It selects the first available partition using the
ESP-IDF esp_partition_find_first() function.
That behaviour is problematic if one has multiple SPIFFS partitions.

This change allows a user to pass the label argument (defaults to NULL)
to UpdateClass::begin() so a specific SPIFFS partition can be updated.

Additionally, ArduinoOTA can set this partition label using the
new method ArduinoOTAClass::setPartitionLabel which is optional.

This change does not break compatibility.
2020-11-02 18:49:24 +02:00
3cbfa2ffef Add partition label argument to SPIFFS (#4443)
* Add partition label argument to SPIFFSSPIFFS currently assumes there is only ever one partition.This change allows a user to pass the label argument (defaults to NULL)to SPIFFS::begin() so a specific SPIFFS partition can be referenced.This change does not break compatibility.
2020-11-02 18:47:36 +02:00
360e04fa36 Fixing BLE GATT Characteristic notification and Characteristic Descriptor read (#4464)
* BLERemoteChar: fix descriptor 2902 write for characteristic notifications

When registering a notification on a characteristic, the 2902 descriptor
(CCCD) value is set to 1 (or 2 for indication).
According to the BLUETOOTH CORE SPECIFICATION Version 5.2, Revision Date
2019-12-31, section 4.12.3 "Write Characteristic Descriptors" (page 1588),
the characteristic descriptor write must expect a response.
Currently, the descriptor write is performed without expecting a reponse,
which prevents the notification to be functional with some BLE stacks.
This commit modify the write to expect the response.

Signed-off-by: Jimmy Durand Wesolowski <jimmy.durand.wesolowski@commsolid.com>

* BLERemoteChar: forward GATT client event to characteristic descriptors

This commits prevents a permanent wait when calling BLERemoteDescriptor
readValue function, on the m_semaphoreReadDescrEvt semaphore.

ESP32 BLE stack calls to remote characteristic
- notification,
- value read
- value write
and remote characteristic descriptor
- value read
are asynchronous.

When such a call is performed by this library, a semaphore is taken prior
to the BLE stack read or write operation, and waited on after it.

Releasing the semaphore is done by the characteristic event handling
function (gattClientEventHandler), when the appropriate event is received.

However, the characteristic descriptor events are discarded, and the
value read semaphore is never released.

This commits forwards the GATT client events from the remote
characteristic down to their remote characteristic descriptor, and
implements their event handling.

Adding a semaphore for the remote characteristic descriptor value write
will be done in a separate commit.

Signed-off-by: Jimmy Durand Wesolowski <jimmy.durand.wesolowski@commsolid.com>

* BLERemoteDescriptor: add semaphore to characteristic descriptor write

This adds a semaphore to characteristic descriptor value write, to mimic
the value read function, and to ensure completion of the operation before
we carry on.

Signed-off-by: Jimmy Durand Wesolowski <jimmy.durand.wesolowski@commsolid.com>

Co-authored-by: Jimmy Durand Wesolowski <jimmy.durand.wesolowski@commsolid.com>
2020-11-02 18:36:25 +02:00
57145ade6f Small description comment correction (#4471)
esp8266 --> esp32
2020-11-02 18:35:23 +02:00
f39024675c Don't convert to null-terminated string prior to writeValue (#4473)
fixes: #4472
2020-11-02 18:34:57 +02:00
f7fb00632e #4293 added missing '<tr>' (#4450)
Fixes issue #4293
2020-10-27 15:35:54 +02:00
7e40de226f Fixes #4435 - WiFiClient improperly treats zero data available for read as an error (#4448) 2020-10-27 12:01:41 +02:00
ae240a3902 Add flash helper constructor to Uri 2020-10-19 16:20:49 +02:00
1287c52933 Add missing "-mlongcalls" flag to PlatformIO build script (#4420)
Fixes possible issues with assembly files in external libraries
2020-10-16 21:58:05 +03:00
25bd585c25 Corrections of Stream.Find, FindUntil and added FindMulti - like AVR-Core Libraries (#3442)
* Corrections of Find, FindUntil and FindMulti

Find has some bug that is not working with Ethernet.find() so, I copied code from Stream.h and Stream.cpp in AVR-CORE library and now it's working perfectly.
I don't know where was the error, but an Ethernet.find compiled to MEGA2560 was working but not working when compiled to esp32, after corrections of code (copy of AVR-Core libraries) it's working perfect.
So probably has some error on original ESP32-Core library.

Below is part of code that was working with MEGA2560 and not with ESP32 libraries.
client.find never return TRUE with ESP32 original library and with AVR it's works.

boolean esp32_fw_update(EthernetClient &client, DecodedHeader &header, const String &field_filename, const String &field_crc) {

  char bound[header.boundary.length()+3];
  char term[]="\r\n";
  
  strcpy(bound,header.boundary.c_str());
  strcat(bound,term);
  while (client.find(bound)) { 
    String line=client.readStringUntil('\r');

* Update Stream.h

* Update Stream.cpp

Co-authored-by: Me No Dev <me-no-dev@users.noreply.github.com>
2020-10-14 15:20:40 +03:00
d79a1f3d10 Add an aditional (void *) arg to the RMT callback (much like Ticker() et.al.). (#3345)
* Add an aditional (void *) arg to the RMT callback - to allow more flexible handling of the callback (e.g. by passing a private struct or a class pointer). Same pattern as used by the Ticker() and many others. Example updated & new example with a trapoline added.

* Fix example for new API

* Fix lint warnings

* Add a second missed example.

* Correct timeout & improve socket error handling.
2020-10-14 14:41:50 +03:00
831f0ac29a Rename eep -> partitions.bin & hex -> bin (#4143)
This is in line with the
[arduino platform specification](https://arduino.github.io/arduino-cli/platform-specification/#recipes-for-extraction-of-executable-files-and-other-binary-data)
specifying that the file extension after recipe.objcopy is arbitrary and
that the AVR platform uses `eep` & `hex`, while the esp32 platform seems
to have file extensions `partition.bin` & `bin`
2020-10-14 14:34:14 +03:00
ee3bb16c77 Fix support for following redirects added by ee88c42c3b (#4240) (#4385) 2020-10-14 14:32:47 +03:00
d8dca9c73b bugfix (#4389) 2020-10-14 14:30:32 +03:00
c3f3497048 fixed some typos (#4395) 2020-10-14 14:27:49 +03:00
18c3345451 fix typos in WiFiSTA.cpp (#4396)
* fix typos

* made return value description a bit more helpful
2020-10-14 14:27:19 +03:00
b07f1c11fe Updated Readme.md (#4400)
* Updated Readme.md

Added links to latest release. Made it look a lot cleaner.

* Update README.md
2020-10-14 14:26:41 +03:00
2685a5dd7b Certificate isn't be free in case parse failure. (#4412)
I met problem while I was working with the WiFiClientSecure.
I tried to found the source of the problem, and I found it in the sll_client.cpp.
Please check my contribution.

I've open this problem in #4335 but received no response.
2020-10-14 14:25:26 +03:00
675a40b257 Fix Not by reference. But the value was updated. (#3279) 2020-10-03 03:41:03 +03:00
3570d48eb9 Added the DoIT ESPduino-32 board (#1520) 2020-10-03 03:06:40 +03:00
f76ec4f50b adds debugging to dnsserver (#1046) 2020-10-03 02:59:55 +03:00
fb6d5ad234 Add Inex OpenKB Board (#4002)
Please add OpenKB Board Product from INEX Co. Ltd.

https://inex.co.th/shop/openkb.html
2020-10-03 02:20:10 +03:00
219ff3005b Add missing slashes in HTTPUpdate examples (#4238)
I spent quite a while today figuring out how to get an OTA update over HTTPS on a custom port working. A part of my problem was not putting a slash before the .bin filename, since it wasn't there in the example. This produced invalid HTTP requests. Adding the slash would make it clear that it needs to be there.

Given that the URL in line 53 contains the same words "server" and "file.bin", one might assume that in line 55, the slash after the port number would get added automatically, however I have found out that without a slash you get an invalid request. Adding the slash removes any doubt.
2020-10-03 02:13:27 +03:00
ccab428e4d Added definitions for TTGO-LoRA32-V2.1.6 (#4205) 2020-10-03 02:06:11 +03:00
d2d24a14e0 add board WiFiduino32 (#4218) 2020-10-03 02:04:10 +03:00
af11921535 Add support for S.ODI_Ultra_v1.0 (#4372)
Add a new Dev Board S.ODI Ultra v1 in esp32 library
2020-10-03 01:59:53 +03:00
82112384ca Fix missing headers when compiling as IDF component with Cmake (#4377)
* HttpsOTAUpdate introduced new IDF component requirements.
These have been added to CMakeLists.txt to correct compilation errors when using Cmake.
2020-10-01 15:45:52 +03:00
99aa866477 Update MDNSResponder::addService to return a boolean (#4365)
I was playing with the mDNS service and noticed the method MDNSResponder::addService could return a Boolean with the way it is implemented just like other functions in this library.

This would be handy to know at a higher level weather or not the service was added correctly to the mDNS server of the ESP32.
2020-10-01 15:44:24 +03:00
82670b96f8 Fix for missed scan response data (BLEScan). (#4358)
This is a fix for missing scan responses after a first successfull scan.

While running the BLE_scan.ino sketch with wantDuplicates=false, i got
only one result with correct advertising and scan response length (31,26):

pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks(), false);
pBLEScan->start(scanTime, false);
...
[W][BLEScan.cpp:109] handleGAPEvent(): bytes length: 31 + 26, addr type: 1

All following calls to start() just returned the advertising data without
scan response data:

pBLEScan->start(scanTime, false);
[W][BLEScan.cpp:109] handleGAPEvent(): bytes length: 31 + 0, addr type: 1

With "wantDuplicates=true" i got:

pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks(), true);
pBLEScan->start(scanTime, false);
[W][BLEScan.cpp:109] handleGAPEvent(): bytes length: 31 + 26, addr type: 1
[W][BLEScan.cpp:109] handleGAPEvent(): bytes length: 31 + 26, addr type: 1
[W][BLEScan.cpp:73] handleGAPEvent(): ESP_GAP_SEARCH_INQ_CMPL_EVT
Devices found: 1
Scan done!
pBLEScan->start(scanTime, false);
[W][BLEScan.cpp:109] handleGAPEvent(): bytes length: 31 + 0, addr type: 1
[W][BLEScan.cpp:109] handleGAPEvent(): bytes length: 0 + 26, addr type: 1
[W][BLEScan.cpp:109] handleGAPEvent(): bytes length: 31 + 0, addr type: 1
[W][BLEScan.cpp:109] handleGAPEvent(): bytes length: 0 + 26, addr type: 1

Explicitly initializing m_scan_params.scan_duplicate of BLEScan solves
this issue (In my case the un-initialized value was
m_scan_params.scan_duplicate == 1073599044).

Co-authored-by: Me No Dev <me-no-dev@users.noreply.github.com>
2020-10-01 15:43:30 +03:00
9e7b13e46d WebServer.handleClient delay (#4350)
* If WebServer.handleClient is run in a tight loop, it will starve other processes.  So, if there is no connection, throw in a delay(1).  Fixes #4348

* Made a variable to control the delay behavior
2020-10-01 15:42:23 +03:00
2243081f85 add I2C_RX_FIFO_OVF_INT_ST handling to i2c_isr_handler_default (#4342)
Fixes crash on ESP32 when I2C FiFo overflows and interrupt function is unable to handle crash and throws this error:
[E][esp32-hal-i2c.c:1013] i2c_isr_handler_default(): unknown int=4

Co-authored-by: 0xDEADBEEF <0xde4dbeef@gmail.com>
2020-10-01 15:40:42 +03:00
1f4491f4ee Updated AzureIoT submodule. (#4322) 2020-10-01 15:38:56 +03:00
aa529eb5a0 Fix getString() freeze on empty responses (#4317) 2020-10-01 15:36:23 +03:00
a9cb7c6d6f mismatched parameter names. Fixes #4310 (#4313) 2020-10-01 15:35:40 +03:00
45d47e2be0 Fix duplicated pin constant (#4282)
G22 was defined twice, changing the first one to G21
2020-10-01 15:31:56 +03:00
99c94bb482 Set SD state to idle before unregister (reduces power) (#4272) 2020-10-01 15:31:16 +03:00
f98fc7ee9f fix hwSerial tx only flush (#4263) 2020-10-01 15:30:45 +03:00
0957776855 Reinit updater md5 related fields (#4260)
MD5 cleanup on begin
Typos
2020-10-01 15:29:58 +03:00
d93245d0f5 add m5stack-core2 board (#4255)
* add m5stack-core2 board
2020-10-01 15:28:40 +03:00
c917ed2504 shallow clone to make installation faster (#4246)
shallow clone (board and submodules) to make installation faster
2020-10-01 14:43:48 +03:00
ee88c42c3b Add support for following redirects in HTTPClient (#4240) 2020-10-01 14:41:54 +03:00
837cc3d271 Added SparkFun ESP32 Thing Plus board (#4224) 2020-10-01 14:39:39 +03:00
9b2ae12fb7 Added D pin numbers (#4220)
Source: https://wiki.dfrobot.com/FireBeetle_ESP32_IOT_Microcontroller(V3.0)__Supports_Wi-Fi_&_Bluetooth__SKU__DFR0478
2020-10-01 14:39:01 +03:00
86e221d087 Update HelloServer.ino (#4219)
Change name esp8266 for esp32 in welcome message
2020-10-01 14:38:26 +03:00
663effa00e Update Parsing.cpp (#4217)
* Update Parsing.cpp

When uploading TLS cert files the end of file "-----END CERTIFICATE-----" (or any kind of file with the sequence "CRLF--") is taken as posible end boundary. Then it is compared to the start boundary string. As it is expected, comparison turns to be false, and the whole end boundary string is put to _currentUpload->buf through _uploadWriteByte(). Here you have the problem: if you read boundary.length() bytes from HTTP request and you have some of the actual end boundary bytes in it, when you put all those bytes into _currentUpload->buf you are making a mistake. You will miss the actual end boundary string because some of those bytes were put in _currentUpload->buf.

* Update Parsing.cpp
2020-10-01 14:37:59 +03:00
6f237a8415 Fix ttgo twatch & tbeam board definition error (#4212) 2020-10-01 14:36:32 +03:00
c3c38a8eb5 Enable precompiled libraries (#4209)
The latest versions of Arduino IDE shifted the responsibility for precompiled libraries support to the core developers, which breaks precompiled library support in esp32 Arduino core. See https://github.com/arduino/ArduinoCore-avr/pull/52 for more details:

```
In this new version of the builder we are not doing any heuristics to find the right spot where the ldflags should be inserted (this was causing many bugs on its own); instead, we fully trust the core makers to add explicit support to precompiled libs.
```

This chage re-enables precompiled library support in the esp32 Arduino core.
2020-10-01 14:32:20 +03:00
8fcc914853 Added facility to invert the polarity of input UART bits. (#4200) 2020-10-01 13:58:48 +03:00
d03f8f1277 Update pins_arduino.h (#4190) 2020-10-01 13:54:01 +03:00
882b12c44e rmdir causes issues in SPIFFS. Fixes #4138, albeit not very cleanly (#4154)
SPIFFS causes crashes if you attempt to rmdir. Since there are no true directories in spiffs, this ought to be a noop. It looks like @me-no-dev worked around this by using unlink instead of rmdir, which works in fatfs and doesn't panic spiffs. This behavior is not universal. In order to get littlefs working, it would be good to get this back to conformity. Rather than digging deep into the upstream spiffs, I just check the mountpoint and noop if it is "/spiffs". So, if the user has changed the mountpoint, this will not work, but I think it's a pretty good tradeoff.
2020-10-01 13:52:24 +03:00
93d850f783 Fixed comment with correct FQDN (#4152) 2020-10-01 13:51:36 +03:00
4f48caca2c Set scan_duplicate in BLE scan params (#4126)
This value is uninitialised and as such can be a random (and invalid) value. It's needs to be set per the espressif documentation here:

https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/bluetooth/esp_gap_ble.html#_CPPv4N21esp_ble_scan_params_t14scan_duplicateE

This PR sets it to DUPLICATE_DISABLE. Chosen as this is needed to ensure all scan data is populated in the scan callback, per this comment in the IDF:

https://github.com/espressif/esp-idf/blob/master/components/bt/host/bluedroid/stack/btm/btm_ble_gap.c#L3591

"//if scan duplicate is enabled, the adv packet without scan response is allowed to report to higher layer"

We **don't** want it to report to the higher layer (ie BLEScan.cpp) **unless** it has the active scan response.

Seems to resolve #3770 #3677 and possibly others.
2020-10-01 13:45:45 +03:00
80e9e42c3b Fix issue #3522 (WiFi does not restart after stopped) (#4114)
This commit fixes issue https://github.com/espressif/arduino-esp32/issues/3522 where WiFi service fails to start after a WiFi.disconnect(true) or a WiFi.mode(WIFI_OFF).
2020-09-30 15:34:10 +03:00
494061af26 WebServer: Fix OOB write (#4088)
Successful exploitation could lead to arbitrary code execution.

The bug can be reproduced by running the following in a browser:
```
const formData = new FormData();
for (let i = 0;i < 33;++i) { formData.append("foo", i.toString()); }
await fetch("http://esp.local", { method: 'POST', body: formData });
```
2020-09-30 15:28:28 +03:00
2fd3d042b2 Fix #4046 Details below: (#4086)
Informed by the discussion in the bug and the code in 'that other branch'
the fix was clear.  Just set a flag if we start handling a write, and
use that flag to guard the long write complete call.
2020-09-30 15:27:35 +03:00
b551310c37 Minor change but could confuse some (#4084) 2020-09-30 15:26:38 +03:00
f30edd040e Update CaptivePortal.ino (#4080)
* Update CaptivePortal.ino

Illegal SSID used for SoftAP

* Fixed ordering problem.  Now actually works
2020-09-30 15:26:15 +03:00
b7c5e502e7 Add static pin support (#4078) 2020-09-30 15:25:42 +03:00
fa8a1c38d5 fix #4071 (#4072)
SPIFFS File object evaluates as true even if the file could not be opened.
2020-09-30 15:24:59 +03:00
d56267bd8c Update GetChipID.ino (#4070)
Co-authored-by: Me No Dev <me-no-dev@users.noreply.github.com>
2020-09-30 15:24:29 +03:00
1f6b0b35f8 Have BLECLient gattc event handlers verify conn_id (#4064)
Co-authored-by: Me No Dev <me-no-dev@users.noreply.github.com>
2020-09-30 15:21:59 +03:00
342b9cf2d8 Fix handling of registerForNotify in BLERemoteCharacteristic.cpp (#4063) 2020-09-30 15:20:28 +03:00
11d071b1c8 Fix to allow more than one certificate to be loaded (espressif#3248). (#4056)
Co-authored-by: Mark Hale <mark.hale@physics.org>
2020-09-30 15:19:41 +03:00
f48d9016fd Update T_Watch board properties and add revision selection (#4025)
Co-authored-by: lewis he <lewisxhe@outlook.com>
2020-09-30 15:18:17 +03:00
a55265f74b Fix clockCyclesPerMicrosecond Change from fixed value to current value (#3993) 2020-09-30 15:16:20 +03:00
c1a7198e7d Don't change owner if take() doesnt succeed (#3987) 2020-09-30 15:15:47 +03:00
4d4a1fde36 Added HealthyPi 4 Board Support (#3985)
Co-authored-by: Ashwin <ashwin@circuitects.com>
2020-09-30 15:14:39 +03:00
d219e56872 Update pins_arduino.h (#3908)
Update in accordance with Firebeetle's official firebeetle32 pins_arduino.h. Without it, digital pins weren't definable, and analogue pins didnt line up.

Taken from http://download.dfrobot.top/FireBeetle/DFRobot_FireBeetle-ESP32-0.0.9.zip
2020-09-30 15:07:26 +03:00
19ccc479c3 WIFI_PS_MAX_MODEM feature requested #3896 (#3900) 2020-09-30 15:06:58 +03:00
c18d50cb91 Use esp_partition_* functions in Updater.cpp (#3898)
Background

The current implementation of Update() uses the spi_flash_* api to write and read from flash. These functions ignore the partition->encrypted flag and always write raw data to flash even if the partition is marked as encrypted.

Changes in this PR

Update() now uses the esp_partition_* api.
Wrapper functions for esp_partition_* added to ESP.cpp. This was done to maintain a consistent approach to the way the spi_flash_* functions were used. I note though that not all of the esp-idf functions are used are wrapped, for example esp_ota_get_next_update_partition() so it may be that these should not be added?
The current implementation of Update() changes the first (magic) byte of firmware to 0xFF on write, and then when the firmware is completely written changes it back to ESP_IMAGE_HEADER_MAGIC. This works without erasing the sector because flash bits can be changed from 1->0 (but not 0->1). If the flash is encrypted then the actual data written to flash will not be all ones, so this approach will not work. In addition, encrypted flash must be written in 16 byte blocks. So, instead of changing the first byte the changed code stashes the first 16 bytes, and starts writing at the 17th byte, leaving the first 16 bytes as 0xFF. Then, in _enablePartition() the stashed bytes can be successfully written.
Benefits

Whilst it's not possible to use encrypted flash directly from either the Arduino IDE or PIO it's reasonably straightforward to compile and flash a bootloader with the necessary support from a simple esp-idf project and then use ArduinoOTA for subsequent updates. This PR enables the use of this workflow until such time as encrypted flash is supported, and is a first (small) step toward adding support.
Regardless of the above, the esp_partition_* api is recommended over the api_flash_* api.
Application code should mostly use these esp_partition_* API functions instead of lower level spi_flash_* API functions. Partition table API functions do bounds checking and calculate correct offsets in flash, based on data stored in a partition table.
2020-09-30 15:06:19 +03:00
80418fadcf Fixes UART detach. Fixes #3878 (#3894)
* Fixes UART detach.  Fixes #3878

* 0 is not a good holder value for pins!

* 0 is not a good holder value for pins!
2020-09-30 15:04:18 +03:00
8b6d020352 added new board Logsens V1p1 (#3880)
* Added new board variant for Imbrios LogSens V1.1

Imbrios LogSens V1.1 new board variant

* added new board Imbrios LogSens V1.1

Added new board details: Imbrios LogSens V1.1
2020-09-30 15:01:51 +03:00
5197916983 Fix BLEClient disconnect bug (#3876)
By default the disconnect is broadcasted to every clients. So if you call disconnect on one connected client, they'll all be disconnected if we don't filter the event by conn_id.
2020-09-30 15:01:02 +03:00
7e9d42da68 ESP.getChipModel() and ESP.getChipCores() (#3847)
* ESP.getChipModel() returns model of the chip

* ESP.getChipCores() returns the core count.

* Example gives chip model, revision and core count.

* Read efuse for chipmodel

Co-authored-by: Martijn Scheepers <ms@SDNengineering.nl>
2020-09-30 14:57:36 +03:00
e34e0b45de Fixed bug where mutex would not be unlocked (#3837)
Fixed bug where uartResizeRxBuffer() did not unlock mutex if creation of queue failed.
2020-09-30 14:56:41 +03:00
ef2b54547e Fix issue #3833, data parsing of Eddystone TLM data frame (#3836)
* Fix issue #3833, data parsing of Eddystone TLM data frame    
Add Beacon scanner example to show usage of BLEEddystoneTLM class and  BLEEddystoneURL class     
Add EddystoneTLM beacon example    
Add EddystoneURL beacon example

* Fix buffer size for .toString()
2020-09-30 14:55:58 +03:00
9856f0cc28 Update RMTLoopback.ino (#3823)
BUGFIX: avoids assertion in xEventGroupWaitBits()
(/home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/freertos/event_groups.c:350 (xEventGroupWaitBits)- assert failed!)
2020-09-30 14:52:22 +03:00
daa8c55667 add new board mpython (#3814) 2020-09-30 14:49:57 +03:00
af7ec4ead1 fix EEPROM class example (#3786) 2020-09-30 14:43:05 +03:00
9e65ed1af1 Process compiler.libraries.ldflags (#3783)
Add support for the v1.8.6 compiler.libraries.ldflags:

https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification

This fixes the issue reported here:

https://community.bosch-sensortec.com/t5/MEMS-sensors-forum/BSEC-1-4-7-4-compilation-error-on-ESP32-1-0-3-rc1/td-p/9120
2020-09-30 14:42:04 +03:00
7a92f89d12 Set TLS cert options before calling connect on client, so verify works (#3774)
When connecting using transportTraits, the CA and client certificates are ignored after the initial _client->connect() is called. This is because on connect, WiFiClientSecure will call start_ssl_client with _CA_Cert and other cert options set to null unless setCACert, setCertificate etc. are called before connect. Running _transportTraits->verify after connect therefore does exactly nothing. It's easy to verify that this is the case by passing a CACert to HTTPClient with verbose logging enabled - the logs will say "WARNING: Use certificates for a more secure communication!" which is only present when both PSK and CA are null. This change fixes the issue.
2020-09-30 14:41:03 +03:00
5871ca9ce9 UpdateClass::printError now accepts the Print object (#3763) 2020-09-30 14:39:25 +03:00
0dfa5babc2 fix typo in WiFiMulti (#3737) 2020-09-30 14:37:21 +03:00
e4b2ce4e81 DNS resolving timeout change to prevent stack overlapping (#3731)
Real DNS resolving timeout used by lwip library is 14[s] (7[s] for DNS1 + 7[s] for DNS2). Function WiFiGenericClass::hostByName() has timeout set to lower value (only 4[s]), so callback function may be called after this low timeout and it may overlappe stack memory used now by other function.
Fixes #3722
2020-09-30 14:35:53 +03:00
7af4490fcc Update SPI.h 2020-09-30 14:34:37 +03:00
4204869ec9 Extend Print class for 64bit integers. (#3688)
* Extend Print class for 64bit integers.

modulo 32bit and 64bit tuned for code size.

* Fix 32bit long used in long long printNumber.
2020-09-30 14:31:36 +03:00
ab23e8a656 Greatly reduces error rate (half, or 0 zero errors, depends on in/out ranges) for round-trip mapping at the same performance. (#3655)
(Based on "improved_map" from ESP8266's Servo.cpp)
2020-09-30 14:28:51 +03:00
5999b7ba46 removed double delete of characteristics (#3521) 2020-09-30 14:25:31 +03:00
7b613c1238 Added documentation regarding delay() resolution in esp-idf component (#3014) 2020-09-30 14:17:53 +03:00
cee2359e33 Update pins_arduino.h (#4211)
fix some mistake
2020-09-28 10:24:06 +03:00
37a7fb3d6a Update PlatformIO CI script (#4307) 2020-08-31 18:06:34 +03:00
9d547a8a44 Provisioning fixes for: 1.Space 2.Provisioned (#4291) 2020-08-25 11:03:06 +03:00
1fd5cd79c5 Add OTA update feature
This sketch provide functionality for OTA firmware upgrade.
2020-08-25 11:01:58 +03:00
4d98cea085 Add Wire:setPins(sda, scl)
Fixes: https://github.com/espressif/arduino-esp32/issues/3779
2020-07-19 02:21:15 +03:00
b92c58d74b M5Stack's product offering includes various ESP32-based camera devices. (#4030)
They are all broadly similar, all being based on the ESP32-D0WD core, but have
some subtle differences between variants around PSRAM inclusion and camera pin
mappings.

The ESP32CAM "unit" product (SKU: U007) has no PSRAM and maps the
"Pixel Data 0" (Y2 GPIO/OV2640 D2) camera pin to IO17 rather than IO32 as is
the case with most other M5Stack ESP32 camera devices.

The ESP32CAM also requires the "hmirror" and "vflip" camera configuration
bits setting in order to capture a true image.

The relevant M5Stack pin configuration documentation can be found here:
https://docs.m5stack.com/#/en/unit/esp32cam?id=pinmap
2020-06-01 01:41:56 +03:00
35d9759fa6 Fix for issue 3974 m_connectedCount incorrectly decremented when no connection exists
There is no need to decrement if nothing was removed from removePeerDevice

Reference issue:
#3974
2020-06-01 01:35:01 +03:00
09bff5027d Add a new board of KITS for IoT education (#3703)
* Add 'KITS Edu ESP32' board definition

add 'KITS Edu ESP32' board definition

* Modify board name

the board name was modified.

* Change the board name

Finally, we decided the board name.

- 'KITS ESP32 EDU'

Co-authored-by: Hamson Park <hamson.park@koreaits.com>
Co-authored-by: Hamson Park <hspark3235@gmail.com>
2020-05-29 11:46:25 +03:00
79f77afc98 update M5Camera pins (#4021)
* change m5camera pins

* add M5Camera version B pins

* add M5Camera version B pins
2020-05-22 12:59:33 +03:00
594ee6d249 Update SD_MMC.cpp (#4020)
According to ESP-IDF API
dc14d027ce/docs/en/api-reference/peripherals/sdmmc_host.rst :

"To configure the bus width, set the width field of :cpp:class:`sdmmc_slot_config_t`. For example, to set 1-line mode:

sdmmc_slot_config_t slot = SDMMC_SLOT_CONFIG_DEFAULT();
slot.width = 1;
"
2020-05-22 11:07:40 +03:00
934841e236 Added missing wifi_provisioning dependency. (#4003)
Co-authored-by: Paul <Paul.Martinsen@NumberEightInnovation.com>
2020-05-22 10:30:21 +03:00
49b76649f1 HardwareSerial bugfix & improvement (#3713)
Co-authored-by: Me No Dev <me-no-dev@users.noreply.github.com>
2020-05-05 17:55:58 +03:00
5d9bb5cf50 Allow using custom linker scripts (#3735)
Co-authored-by: Ivan Kravets <me@ikravets.com>
2020-05-04 16:47:14 +03:00
c8215315ae Add M5Stack-ATOM Board (#3883)
* Add M5Stack-ATOM Board

* Add M5Stack-ATOM Board

* Add M5Stack-ATOM Board

Co-authored-by: Me No Dev <me-no-dev@users.noreply.github.com>
2020-04-23 13:39:31 +03:00
4d118b36a2 Minor modifications in provisioning (#3919) 2020-04-21 14:39:26 +03:00
2c9b648502 Add support of unified provisioning to Arduino
1. WiFiProv.ino sketch is added that allows arduino users to do provisioning via SoftAP or BLE. WiFi.beginProvision( ) API is designed for provisioning in Arduino.
2. In WiFiProv.h provisioning class is defined.
3. WiFiProv.cpp contains implementation for provisioning class.
4. README.md file is added which contains detail information for working.
2020-04-15 23:37:55 +03:00
5508689ea3 Update install-platformio-esp32.sh 2020-04-13 12:47:34 +03:00
0f772270fb add new board Handbit (#3807)
* add handbit

* add handbit pins_arduino

* Update boards.txt
2020-03-12 10:16:50 +02:00
13e02063d6 Move _STREAM_BOUNDARY before _STREAM_PART (#3720)
The boundary delimiter (_STREAM_BOUNDARY) needs to be send before the
body part (_STREAM_PART) too follow RFC2046. This caused ffplay/ffmpeg
to fail to open the MJPEG stream.
2020-02-14 11:03:38 +02:00
9b75c65fc7 Add Senses's WEIZEN board from Senses IoT platform (#3687)
* Add Senses's WEIZEN board from Senses IoT platform

* Add Senses's WEIZEN board (updated variant)
2020-01-29 17:08:14 +02:00
109ba7a3b4 Revert "std::shared_ptr Memory Leak (#3680)" (#3682)
This reverts commit b2c678877c.
2020-01-29 12:30:08 +02:00
b2c678877c std::shared_ptr Memory Leak (#3680)
* std::shared_ptr Memory Leak

clientSocketHande and _rxBuffer are std::shared_ptr, the stop() call was not correctly releasing them and the operator= had similar problems fix for #3679

* operator= second attempt

* operator= third time
2020-01-29 12:18:54 +02:00
ed220bd042 Minimize HardwareSerial Receive and Transmit delays (#3664)
* Minimize HardwareSerial Receive and Transmit delays

* Remove uartRxFifoToQueue from esp-hal-uart.h

Co-authored-by: Me No Dev <me-no-dev@users.noreply.github.com>
2020-01-27 00:38:06 +02:00
80f9f9aeec fix removeApbChangeCallback() error in spiStopBus() (#3675)
* fix removeApbChangeCallback() error in spiStopBus()

spiStartBus() was using spiStopBus() to init the hardware, one of spiStopBus() functions is to unregister the runtime CPU clock speed change callback. But, spiStartBus() only wanted to init the hardware.  This patch separates the hardware init into a standalone function spiInitBus() that both spiStartBus() and spiStopBus() call.

* Update esp32-hal-spi.c

capitalization problem
2020-01-27 00:20:19 +02:00
b50a1755c8 Use python3 in CI 2020-01-25 15:26:16 +02:00
bb0a194bb7 fix WiFiClient.connected() (#3654)
WiFiClient.connected() was hanging thinking there was still a connection when the remote had already closed. The one-liner in this patch addresses recv() returning 0 and errno==128. I couldn't find the corresponding errno for 128 but its caught by the case statement which includes EPIPE, ENOTCONN, ECONNRESET and ECONNABORTED so I assume its one of those. Broken pipe maybe?
```c
[D][WiFiClient.cpp:511] connected(): Disconnected: RES: 0, ERR: 128
```
EDIT: added comment to reflect that recv() can set errno when it returns 0.
2020-01-21 12:36:03 +02:00
ed59ae6482 Update README.md (#3653) 2020-01-21 12:35:05 +02:00
b4a9684a74 Fix SerialBT.flush (#3579)
* Fix flush

flush should not flush the read buffer, it should wait till all output is drained from the write buffer.

* Update BluetoothSerial.cpp

Co-authored-by: Me No Dev <me-no-dev@users.noreply.github.com>
2020-01-20 22:34:57 +02:00
1977370e6f IDF release/v3.3 (#3339)
* IDF release/v3.3 46b12a560

* fix build

* IDF release/v3.3 367c3c09c
2020-01-20 22:07:04 +02:00
307b1368dd Implement BTSerial onData to dynamically receive packets from SPP (#3649) 2020-01-20 19:43:52 +02:00
32d5654aa6 Implement rmtLoop to be able to continuously send pulses (#3650)
Number of pulses is limited to the reserved RMT memory for the channel. Very useful for PWM, Servo and other repeatable signals.
2020-01-20 19:43:13 +02:00
7637a739cc Fix recent commit d8b2098 (PR #3377) which includes esp_adc_cal component but does not update CMakeLists.txt (#3648) 2020-01-20 18:40:40 +02:00
cd85239252 Added file.close to examples (#3611) 2020-01-20 16:47:40 +02:00
ac9d04a400 Add BLEDevice::stopAdvertising() helper method to compliment startAdvertising(). (#3624) 2020-01-20 16:31:12 +02:00
2195109ecc Added the channel parameter to the scan fucntion in order to select which channel to scan. (#3638)
The default value is 0 (= all channels) to preserve backward compatibility.
2020-01-20 16:13:10 +02:00
8d938c849d Add HONEYLemon board (#3640)
* add board HONEYLemon
2020-01-20 16:12:02 +02:00
cb005fc8b5 Extend BLEDevice::setPower() to include powerType parameter. It's optional and set to ESP_BLE_PWR_TYPE_DEFAULT for compatibility. (#3623)
Extend BLEDevice::setPower() to include powerType parameter. It's optional and set to ESP_BLE_PWR_TYPE_DEFAULT for compatibility.
2020-01-20 16:09:02 +02:00
89351e3ade Update WiFiClient.cpp (#3608)
fixed the connected() function so that it only checks errno if recv returns a value of -1.

"in the even of an error, errno is set to indicate the error" --manpage

This fixes the ESP32 Webserver when dealing with a modern webserver with a slow SD card.
2020-01-20 16:08:17 +02:00
86de90fe24 Added partition and flash size menus for VintLabs boards (#3602)
add the partition and flash size menus for the VintLabs board definitions.
2020-01-20 16:07:53 +02:00
5960cd3e2a update coreESP32 boards.txt (#3569) 2020-01-20 16:06:55 +02:00
82e208c8c9 Fixed incorrect board name for TinyPICO - You can now use this to detect it's a TinyPICO at compile time.... (#3567)
#ifdef ARDUINO_TINYPICO
   // It's a TinyPICO!
#endif
2020-01-20 16:06:25 +02:00
e7c9813625 Added Piranha ESP-32 and Metro ESP-32 boards (#3542)
Added two boards from iarduino.ru based on ESP-32
2020-01-20 16:06:06 +02:00
dd78794311 Update CaptivePortal.ino (#3628)
Small change to insure wifi starts off and avoid crashing
2020-01-20 16:04:21 +02:00
0607d36734 HardwareSerial::write(const char*, ...) API compatibility to AVR, ESP8266, et al (#3585)
* API compatibility to AVR, ESP8266, et al

* Add non-blocking HardwareSerial::read(buffer, size) extension (ESP8266 portability)

* Refactor for fewer indirect calls.
2020-01-20 15:54:50 +02:00
6e77f7f3e5 Setting loging level to VERBOSE on Semaphore::take (#3545) 2020-01-20 15:50:19 +02:00
915d45de7d Defined BLE setAdvertisementType (#3535)
Currently we have no way to set BLE Advertisement Type.
We have an initial value of ADV_TYPE_IND and the member is private.

iBeacon should advertise with ADV_TYPE_NONCONN_IND.
esp-idf's example code specifies this value.

93a8603c54/examples/bluetooth/bluedroid/ble/ble_ibeacon/main/ibeacon_demo.c (L57)
2020-01-20 15:42:38 +02:00
lj
c2b37d95e0 Updated BLERemoteCharacteristic to exposre esp_gatt_auth_req_t parame… (#3531)
* Updated BLERemoteCharacteristic to exposre esp_gatt_auth_req_t parameter for readValue and writeValue.

* Updated BLERemoteCharacteristic/Descriptor to expose a setAuth method to allow tweaking the authentication request type for that remotecharacteristic/descriptor without the need to add auth on each read/write.
2020-01-20 15:40:13 +02:00
2f13a960ac Add WIFI_REASON_CONNECTION_FAIL in WiFiGeneric.cpp (#3529)
`WIFI_REASON_CONNECTION_FAIL` has been added to `wifi_err_reason_t` some time ago:  
cec3fca4ad/tools/sdk/include/esp32/esp_wifi_types.h (L95)

But it was still missing from `system_event_reasons` in `WiFiGeneric.cpp` sometimes causing panics here:  
cec3fca4ad/libraries/WiFi/src/WiFiGeneric.cpp (L348)
2020-01-20 15:38:58 +02:00
579e04be25 Cleanup SPI_Multiple_Buses (#3527)
* Utilize prepoc symbols for SPI pins
* Adjusts for GPIO pins when ALTERNATE_PINS is set
2020-01-20 15:37:47 +02:00
5443d7ca93 Add TTGO T Journal Camera module & improve commenting (#3515)
Added pinout for TTGO T Journal device and improved the intent of comments.
2020-01-20 15:33:38 +02:00
7b3c1dfd50 Fix inability to use all buffers in RMT (#3512)
With the >= used let's say you have four RMT inputs, each using 2 channels wide for their receive buffer. This is 4*2 = 8 buffers which is the number of hardware buffers (MAX_CHANNELS). But, for the fourth input the starting buffer will be 6 (this is correct, the buffers used for each input are 0-1, 2-3, 4-5, 6-7). But, 6+2 = 8 which  is MAX_CHANNELS. This is valid but the >= would match against it and abort. It is correct to only abort if the value i+j is only greater than MAX_CHANNELS. Thus, a simple one character fix. Delete the equals sign.
2020-01-20 15:31:44 +02:00
85ef51ffbc BLE: reception support multiple service data (#3502)
* BLE: reception support multiple service data

* fix prev commit, i not inicialized
2020-01-20 15:30:29 +02:00
36075257c2 WString explicit converters to reduce Flash size (#3497)
* WString explicit converters to reduce Flash size

This is a port from the same patch for ESP8266: https://github.com/esp8266/Arduino/pull/6759/files
2020-01-20 15:29:16 +02:00
7de1717640 Fix replacing of headers with overlapping names. Fixes issue #3483 (#3487)
If two headers with overlapping names are added while replace == true, like in:
```cpp
http.addHeader("api_token",  "pMXFOLpinQqajaRQJYMeWObg2XYmcX1");
http.addHeader("token", "1234");
```
then replacing went wrong. This is fixed with this PR.
2020-01-20 15:27:51 +02:00
8869d39d79 Created variant for LilyGo TTGO LoRa32-OLED V2 (#3479)
Hi,

I have added a variant for the LilyGo TTGO LoRa32-OLED V2, which is similar to the LilyGo TTGO LoRa32-OLED V1 but with a different pinout. This will be useful for PlatformIO users, specially because I am also adding the board there as well.

Cheers.
2020-01-20 15:24:19 +02:00
Bob
cfe8526ec8 Add Uri with support for regexUri and globUri (#3441)
* Add Uri with support for staticUri, regexUri and globUri

* Add newline to end of files

* Update example

* Suppress gcc warnings (unused params)
2020-01-20 15:21:01 +02:00
c09ec5bd3d Added MGBOT IOTIK 32A and IOTIK 32B boards (#3427) 2020-01-20 15:19:35 +02:00
d8b2098461 Use IDF's ADC Driver and Add analogReadMilliVolts (#3377) 2020-01-20 15:18:56 +02:00
3fc974f3aa bugfix(touchpad):swap touch8 and touch9 #3584 (#3620) 2020-01-09 08:11:40 +02:00
9ad860758c Fix Memory leak in addApbChangeCallback() (#3560)
* `ledcWriteTone()` added a `apbcallback()` evertime the tone value was non zero.  
* `addApbChangeCallback()` did not detect duplicate callbacks.
* changed the apbcallback list to a double link to support roll forward, roll back execution.  This made the sequences of clock change callback start with the newest registered -> to oldest on the `before` then oldest -> newest after the clock change.  This made the UART debug log output have minimal gibberish during the clock change.
* change how the UART callback handled the MUTEX because if any `apbchangeCallback()` executed a `log_x()` a deadlock would occur.

This fixes #3555
2019-12-30 21:35:29 +02:00
cec3fca4ad Fix BluetoothSerial crash when restart (#3471)
* Update esp32-hal-bt.c

BluetoothSerial crash when restart:  this is because the BT controller remains in state  ESP_BT_CONTROLLER_STATUS_INITED instead of state  ESP_BT_CONTROLLER_STATUS_IDLE after the end() method.
in file esp_bt.h it is specified

> @brief Enable BT controller.
>                Due to a known issue, you cannot call esp_bt_controller_enable() a second time
>                 to change the controller mode dynamically. To change controller mode, call
>                esp_bt_controller_disable() and then call esp_bt_controller_enable() with the new mode.

after **esp_bt_controller_disable()** the controller remains in state INITED so we do call the **esp_bt_controller_deinit()** function to put the controller into state IDLE.

i have modified the **esp32-hal-bt.c** file
line 57 and next
(i have insert the esp_bt_controller_deinit() function so the controller go into Idle state)
```c++
bool btStop(){
    if(esp_bt_controller_get_status() == ESP_BT_CONTROLLER_STATUS_IDLE){
		log_i("bt stopped");
        return true;
    }
    if(esp_bt_controller_get_status() == ESP_BT_CONTROLLER_STATUS_ENABLED){
		log_i("bt enabled");
        if (esp_bt_controller_disable()) {
            log_e("BT Disable failed");
            return false;
        }
        while(esp_bt_controller_get_status() == ESP_BT_CONTROLLER_STATUS_ENABLED);
    }
    if(esp_bt_controller_get_status() == ESP_BT_CONTROLLER_STATUS_INITED){
		log_i("inited");
		if (esp_bt_controller_deinit()) {
			log_e("BT deint failed");
			return false;
		}
		while (esp_bt_controller_get_status() == ESP_BT_CONTROLLER_STATUS_INITED);
        return true;
    }
    log_e("BT Stop failed");
    return false;
}
```

* Update esp32-hal-bt.c

remove while to avoid infinite loop
2019-11-11 18:31:09 +01:00
dac493fb92 SPI: Fix discarded-qalifiers warning when compiling with all warnings (#3458)
* SPI: Fix discarded-qalifiers warning when compiling with all warnings

This fixes an error introduced with changeset b847f41 which
tightened the use of const for read-only data. The helper
funtion __transferBytes also requires the const qualifier on
outgoing data. Without this change a warning is displayed
when compiling with the Arduino IDE set to display "All"
compiler warnings.

Tests:
 - Build an ESP32 SPI sketch that uses static const data to send
   to an SPI device using the SPI.transferBytes() API

* SPI:Ensure all local functions are marked static

This audits all functions in the esp32-hal-xpi.c module and
ensures that any functions entirely local to the module are
marked as static.

Tests:
 - Build with Arduino set to show all warnings and ensure none
   are displayed

* SPI: Remove unused local __spiTranslate24 function

This removes the __spiTranslate24() function which is unused.
2019-11-11 17:44:49 +01:00
bc3d11364f Fixed incorrect usage of xEventGroupWaitBits (#3446)
* Fixed incorrect usage of xEventGroupWaitBits

* Added parentheses and `!= 0`
2019-11-11 17:34:01 +01:00
f41beb92bf Fixed so configTime will not crash if tcpip is not initialized (#3470) 2019-11-11 15:50:56 +01:00
8c4ca5a235 Update BLE_client.ino (#3463)
fix typo
2019-11-11 15:49:34 +01:00
b3085d4a8b Add menu items Partition Scheme and Debug Level for node32s (#3455) 2019-11-11 15:47:26 +01:00
547c2d3346 Root CA of webserver has changed, minor changes (#3447) 2019-11-11 15:45:26 +01:00
7d2632c024 Implement Tx only Flush (#3433)
* add option to Flush() to only clear txQueue

Add the option to cause Flush() to just wait for tx data to clear the tx fifo and uart, leave the rx queue and rx fifo as is.

* support tx only flush()

* support tx only Flush()

* support txOnly for Flush()

* compatibility to Stream()

* compatibility for Stream()

* default value error

* default value error

* Update esp32-hal-uart.h

* Update esp32-hal-uart.c

* Update HardwareSerial.cpp

* sp

* correctly implement flushTxOnly()
2019-11-11 15:37:35 +01:00
e59355df71 Docs for lib builder (#3415)
* Docs for lib builder

* Typos and such
2019-11-11 15:30:52 +01:00
ec63d09e54 Fix WiFiGeneric event handler (#3412) 2019-11-11 14:24:50 +01:00
xk
188560e7f3 Some event log messages were off by one. (#3391)
This event name was missing in the list:
d5e2bb12ca/tools/sdk/include/esp32/esp_event_legacy.h (L43)

E.g., it was giving
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 24 - ETH_GOT_IP
When it should have been
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 24 - ETH_DISCONNECTED
2019-11-11 14:21:24 +01:00
91e095f5a7 Add an error message in case of invalid configured dependency mbedTLS. (#3364)
Especially if the user wants to use the library as component in IDF,
there are some pitfalls while doing make menuconfig. One is this missing
dependency which will now fail with a better error message with a hint to
the user how to fix it.

refs #2154 #3215
2019-10-17 09:48:36 +03:00
c8d8dc2265 Added partition size options for TinyPICO (#3358) 2019-10-15 01:32:40 +03:00
b847f41e24 SPI: Ensure all read-only data pointers are marked as const (#3356)
This changes all SPI functions that take data pointers which are
not modified so that the declaration is const. This allows them
to be used with const data (i.e. held in flash). No functional
changes are required.

The defnitions of spiWrite() and spiTransferBytes()  in
esp-hal-spi.h/c have been updated to be consistent.

Tests:
 - Build a simple sketch using SPI.writePattern() and
   SPI.transferBytes()  which uses const data and verify that the
   attached device functions as expected.
2019-10-14 20:39:27 +03:00
611ba8ea8a Update README.md (#3353) 2019-10-14 20:38:04 +03:00
0cab2483e6 Added a description README.md for libraries (#3349) 2019-10-14 20:37:09 +03:00
Luc
79e4339582 Remove warnings if no debug enabled (#3334) 2019-10-08 10:35:42 +03:00
a35035f827 fix authrization problem (#3329)
I compiled the sample "WebServer -> HttpAdvancedAuth". But the right username and password can not login in. I found the file "Webserver.h" may be have some problem. So I fix it. Please check it.
2019-10-08 10:34:36 +03:00
9ef3e2d2a6 Allow sketches to have custom partitions (#3328)
Add a file named `partitions.csv` to your sketch folder and define the partitions inside. In order to not get `Sketch too big`, please select appropriate partition scheme from the board menu
2019-10-07 02:07:15 +03:00
0cdfb0b193 Add support for WiFi long range mode (#3190)
* Add support for WiFi long range mode

* Update WiFiGeneric.cpp
2019-10-06 17:43:15 +03:00
e50613622e Fix typo in SPIFFS and FFAT examples (#3322)
* fix typo in SPIFFS example

* fix typo in FFAT example
2019-10-06 17:29:28 +03:00
24b277ad92 Add readFloat to BLE (#3321)
* Add readFloat

* Add readFloat to BLE
2019-10-06 17:28:53 +03:00
c2b3f2d6af Make yield() overridable (#2991) 2019-10-04 12:49:39 +03:00
8fb8e7d060 CI can be used on windows desktop with msys 2019-10-02 20:03:43 +03:00
048b26547a Update boards_manager.md 2019-10-02 16:06:15 +03:00
b10ed77aaf Update boards_manager.md 2019-10-02 15:58:58 +03:00
4638628873 Wait for client.available() to prevent ESP32 crashes (#3154)
* Wait for client.available() to prevent ESP32 crashes

* Removed user-specific SSID & passphrase
2019-10-02 14:45:42 +03:00
6f70e27011 Base64::encode : const correctness / String by reference passing (#3314)
Avoid passing String by-value, which is slightly less efficient
as it involves a full copy-constructor/tempstring creation.
2019-10-02 14:29:24 +03:00
d0b064a1ee Update CI scripts for better error handling (#3316) 2019-10-02 11:58:02 +03:00
85c77a9c3f Fix CI Builds for Linux (#3313) 2019-10-01 23:13:08 +03:00
c8e3f0c732 Support Pi 4 on 64bit kernel 2019-10-01 22:15:13 +03:00
5ad468f9dc Add ARM toolchain 2019-10-01 21:48:03 +03:00
38c4c06108 Support for Master mode, Pin and SSP (#3219)
* 20190916 - initial: support for Master mode, Pin and SSP

* 20190916 - initial: Add example app for Master mode

* 20190916 - initial: Force another build

* 20190916 - connect would use resolved address as preference and remove now redundant _remote_address

* 20190916 - rework set/reset/default pin logic

* 20190916 - cleanup: remove static vars, add/use constants, fix typos

* 20190916 - fix build issues and implement geoup events for status verification.

* 20190916 - remove extra lines,misc

* 20190916 - rework ESP_BT_GAP_DISC_RES_EVT, added SPP_DISCONNECTED bit for disconnect event. + timeout for disconnect()

* 20190916 - Small log change to improve log sequencing

* 20190916 - remove static from local vars

* 20190916 - Limited scope and duration for the scan, log device address during scan in info mode as it is very difficult to find out sometimes. Fixed get_name_from_eir() not resetting the name when called.

* 20190916 - break property for loop during scan when name matches.

* 20190916 - misc

* 20190916 - SPP_DISCONNECT state updates

* 20190916 - formatting, remove some strange syntax from initiator code

* 20190916 - Add comments to the example about connect(...) usage and timeouts

* 20190916 - fix disconnect() without timeout

* 20190916 - Add example comment to view BT address and name during connect(name)

* 20190916 - wording in example comments

* 20190916 - rework connect() and disconnect() methods to help with concurrency and more authoritative status returned back to caller. Automatic disconnect in connect() methods

* 20190916 - optimize code

* 20190916 - optimize code - more

* 20190916 - add timeout for pin set

* 20190916 - change scan mode to ESP_BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE

* 20190916 - update example code slightly

* 20190916 - increase READY_TIMEOUT to 10 secs

* 20190916 - typo in example and move waitForConnect() to static area

* 20190916 - update example comments

* 20190916 - update example comments

* 20190916 - update example comments

* 20190916 - add new example to remove paired devices from ESP32

* 20190916 - correct typo in example

* 20190916 - update example comment, add remove_bond_device() method for convenience.

* 20190916 - reword example comment.

* 20190916 - rename remove_bond_device()

* 20190916 - rename removePairedDevice() to unpairDevice()

* 20190916 - code review changes

* 20190916 - fix return value in setup() od example
2019-10-01 17:34:46 +03:00
b334b2c2f9 Add config, menu partition Wrover (#3147)
* add config, menu partition Wrover

* fix all boards
2019-10-01 17:10:16 +03:00
8a46697168 Fix for issue_3209. (#3210)
#include "esp32-hal-log.h" is mandatory is order to build BLEDevice.cpp.
It can't be left up to a compiler variable.
2019-10-01 16:32:47 +03:00
270a2759d9 Add pages action (#3311)
* Add script to handle updates to the docs folder

* Create gh-pages.yml

* Update on-pages.sh
2019-10-01 16:04:20 +03:00
01d9345d28 Update development JSON location 2019-10-01 12:14:07 +03:00
71e3d515f3 Fix BLEUUID toString (#3289)
uuid16 is Missing first 4 characters.
uuid is Missing last 2 characters.
2019-10-01 11:54:21 +03:00
64cfb33deb Add Added unimplemented getCharacteristicsByHandle function (#3277)
* Add Added unimplemented getCharacteristicsByHandle function

Defined in BLERemoteService.h
But, Not included in BLERemoteService.cpp

* Delete log output
2019-10-01 11:43:59 +03:00
5f1dff7dad IDF release/v3.2 d3e562907 (#3292) 2019-10-01 11:21:44 +03:00
40ebee1cb1 Update BluetoothSerial.cpp (#3308) 2019-10-01 11:10:31 +03:00
ed96d2a1b7 Use Github Actions for release (#3309)
* move scripts and tone down travis

* Update and rename main.yml to push.yml

* Create release.yml
2019-10-01 10:44:04 +03:00
caa391ab34 More efficient CI builds (#3303)
* More efficient CI builds

* Update main.yml
2019-09-30 12:10:48 +03:00
3b71e136e1 Builder scripts update (#3300) 2019-09-30 02:01:29 +03:00
1c77790a5b allow the examples to build in a more strict env (#3299) 2019-09-29 23:47:02 +03:00
5bff89f0be Fixed issue-3153 - Allocating enough memory to construct the entire UUID as a String. (#3297) 2019-09-29 23:03:48 +03:00
9bbd720d4c Update BLEDevice.cpp (#3267)
Pretty sure this was a typo as the deinit doesn't actually allow for reinit if that is an ifndef.  Changed in my local copy and can now deinit and reinit just fine.  Also, not sure why we are checking for the architecture here.  Just curious.
2019-09-26 21:50:16 +03:00
589bb7032d Update WiFiScan.h (#3266)
Add an accessor function for the useful wifi data
2019-09-26 21:03:08 +03:00
f8c06894c5 Better cleanup on mount failures, as the idf api now seems to assign handle and mountpoint before failing. Fixes #3265 (#3282) 2019-09-26 19:12:52 +03:00
a5c873b786 Update README.md 2019-09-24 23:32:13 +03:00
895a150840 Update README.md 2019-09-24 23:23:42 +03:00
ca88fdc273 Fixed FFat::end. Fixes #3244 (#3245)
* Fixed FFat::end. Fixes #3244

* Missed the handle check in format
2019-09-24 23:23:03 +03:00
f32083a6d0 Fix timerRestart
Closes: https://github.com/espressif/arduino-esp32/issues/2944

Thanks @atanisoft
2019-09-24 19:25:27 +03:00
b30e55efff Added partition size option for Pico Kit (#3258)
The original boards.txt was missing a menu option to select the FLASH partitioning options.
2019-09-24 19:21:35 +03:00
0ac2de7aab Add partition schemes to adafruit featheresp32 (#3255)
* Add partition schemes to adafruit featheresp32

* Removed minimal partition scheme
2019-09-24 19:21:08 +03:00
0eec630314 Add missing env to PIO CI build 2019-09-24 18:49:17 +03:00
731fd19bdf Update get.py
Enable insecure download for CI
2019-09-24 17:20:58 +03:00
298c6104a2 Added board defintion for VintLabs boards (#3252) 2019-09-24 12:26:15 +03:00
8ea12f89f3 Update pins (#3249) 2019-09-23 10:14:33 +03:00
b3ba80d570 nvs_handle is an int, was assigning NULL. Also cleaned up end to ensure no memory leak. (#3246) 2019-09-22 23:31:38 +03:00
Luc
a5935ce1cc Add sample for Time date for FatFS like SPIFFS (#3234) 2019-09-22 09:38:24 +03:00
96d6975bd5 Changed WeMosBat.name (#3240)
The old version would crash the Stino plugin, which appears not to support quotes in board names
2019-09-22 09:37:45 +03:00
9eaeeb660c Change the first argument of SPI::wrteBytes to be const (#3242)
fixes: https://github.com/espressif/arduino-esp32/issues/3241
2019-09-22 09:36:32 +03:00
e22d8b6787 Update stale messages for easier filtering 2019-09-21 16:12:22 +03:00
Luc
56fe2dbaff Fix F_Fat::format return false when succeed (#3220)
this is due to ussage of esp_err_t result; instead of boolean, ESP_OK =0 so it is false
2019-09-21 02:34:25 +03:00
06a399b84a Extend logging of ArduinoOTA (#3217) 2019-09-16 19:54:21 +03:00
4ce2cc3c1d Fix HTTP Client with SSL (#3216) 2019-09-16 19:14:32 +03:00
7588 changed files with 1286685 additions and 327922 deletions

27
.github/scripts/check-cmakelists.sh vendored Executable file
View File

@ -0,0 +1,27 @@
#!/bin/bash
#
# This script is for Travis. It checks all non-examples source files in libraries/ and cores/ are listed in
# CMakeLists.txt for the cmake-based IDF component
#
# If you see an error running this script, edit CMakeLists.txt and add any new source files into your PR
#
set -e
# pull all submodules
git submodule update --init --recursive
# find all source files in repo
REPO_SRCS=`find cores/esp32/ libraries/ -name 'examples' -prune -o -name '*.c' -print -o -name '*.cpp' -print | sort`
# find all source files named in CMakeLists.txt COMPONENT_SRCS
CMAKE_SRCS=`cmake --trace-expand -C CMakeLists.txt 2>&1 | grep set\(srcs | cut -d'(' -f3 | sed 's/ )//' | sed 's/srcs //' | tr ' ;' '\n' | sort`
if ! diff -u0 --label "Repo Files" --label "srcs" <(echo "$REPO_SRCS") <(echo "$CMAKE_SRCS"); then
echo "Source files in repo (-) and source files in CMakeLists.txt (+) don't match"
echo "Edit CMakeLists.txt as appropriate to add/remove source files from COMPONENT_SRCS"
exit 1
fi
echo "CMakeLists.txt and repo source files match"
exit 0

36
.github/scripts/install-arduino-core-esp32.sh vendored Executable file
View File

@ -0,0 +1,36 @@
#!/bin/bash
export ARDUINO_ESP32_PATH="$ARDUINO_USR_PATH/hardware/espressif/esp32"
if [ ! -d "$ARDUINO_ESP32_PATH" ]; then
echo "Installing ESP32 Arduino Core ..."
script_init_path="$PWD"
mkdir -p "$ARDUINO_USR_PATH/hardware/espressif"
cd "$ARDUINO_USR_PATH/hardware/espressif"
echo "Installing Python Serial ..."
pip install pyserial > /dev/null
if [ "$OS_IS_WINDOWS" == "1" ]; then
echo "Installing Python Requests ..."
pip install requests > /dev/null
fi
if [ "$GITHUB_REPOSITORY" == "espressif/arduino-esp32" ]; then
echo "Linking Core..."
ln -s $GITHUB_WORKSPACE esp32
else
echo "Cloning Core Repository..."
git clone https://github.com/espressif/arduino-esp32.git esp32 > /dev/null 2>&1
fi
#echo "Updating Submodules ..."
cd esp32
#git submodule update --init --recursive > /dev/null 2>&1
echo "Installing Platform Tools ..."
cd tools && python get.py
cd $script_init_path
echo "ESP32 Arduino has been installed in '$ARDUINO_ESP32_PATH'"
echo ""
fi

238
.github/scripts/install-arduino-ide.sh vendored Executable file
View File

@ -0,0 +1,238 @@
#!/bin/bash
#OSTYPE: 'linux-gnu', ARCH: 'x86_64' => linux64
#OSTYPE: 'msys', ARCH: 'x86_64' => win32
#OSTYPE: 'darwin18', ARCH: 'i386' => macos
OSBITS=`arch`
if [[ "$OSTYPE" == "linux"* ]]; then
export OS_IS_LINUX="1"
ARCHIVE_FORMAT="tar.xz"
if [[ "$OSBITS" == "i686" ]]; then
OS_NAME="linux32"
elif [[ "$OSBITS" == "x86_64" ]]; then
OS_NAME="linux64"
elif [[ "$OSBITS" == "armv7l" || "$OSBITS" == "aarch64" ]]; then
OS_NAME="linuxarm"
else
OS_NAME="$OSTYPE-$OSBITS"
echo "Unknown OS '$OS_NAME'"
exit 1
fi
elif [[ "$OSTYPE" == "darwin"* ]]; then
export OS_IS_MACOS="1"
ARCHIVE_FORMAT="zip"
OS_NAME="macosx"
elif [[ "$OSTYPE" == "cygwin" ]] || [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "win32" ]]; then
export OS_IS_WINDOWS="1"
ARCHIVE_FORMAT="zip"
OS_NAME="windows"
else
OS_NAME="$OSTYPE-$OSBITS"
echo "Unknown OS '$OS_NAME'"
exit 1
fi
export OS_NAME
ARDUINO_BUILD_DIR="$HOME/.arduino/build.tmp"
ARDUINO_CACHE_DIR="$HOME/.arduino/cache.tmp"
if [ "$OS_IS_MACOS" == "1" ]; then
export ARDUINO_IDE_PATH="/Applications/Arduino.app/Contents/Java"
export ARDUINO_USR_PATH="$HOME/Documents/Arduino"
elif [ "$OS_IS_WINDOWS" == "1" ]; then
export ARDUINO_IDE_PATH="$HOME/arduino_ide"
export ARDUINO_USR_PATH="$HOME/Documents/Arduino"
else
export ARDUINO_IDE_PATH="$HOME/arduino_ide"
export ARDUINO_USR_PATH="$HOME/Arduino"
fi
# Updated as of Nov 3rd 2020
ARDUINO_IDE_URL="https://github.com/espressif/arduino-esp32/releases/download/1.0.4/arduino-nightly-"
# Currently not working
#ARDUINO_IDE_URL="https://www.arduino.cc/download.php?f=/arduino-nightly-"
if [ ! -d "$ARDUINO_IDE_PATH" ]; then
echo "Installing Arduino IDE on $OS_NAME ..."
echo "Downloading '$ARDUINO_IDE_URL$OS_NAME.$ARCHIVE_FORMAT' to 'arduino.$ARCHIVE_FORMAT' ..."
if [ "$OS_IS_LINUX" == "1" ]; then
wget -O "arduino.$ARCHIVE_FORMAT" "$ARDUINO_IDE_URL$OS_NAME.$ARCHIVE_FORMAT" > /dev/null 2>&1
echo "Extracting 'arduino.$ARCHIVE_FORMAT' ..."
tar xf "arduino.$ARCHIVE_FORMAT" > /dev/null
mv arduino-nightly "$ARDUINO_IDE_PATH"
else
curl -o "arduino.$ARCHIVE_FORMAT" -L "$ARDUINO_IDE_URL$OS_NAME.$ARCHIVE_FORMAT" > /dev/null 2>&1
echo "Extracting 'arduino.$ARCHIVE_FORMAT' ..."
unzip "arduino.$ARCHIVE_FORMAT" > /dev/null
if [ "$OS_IS_MACOS" == "1" ]; then
mv "Arduino.app" "/Applications/Arduino.app"
else
mv arduino-nightly "$ARDUINO_IDE_PATH"
fi
fi
rm -rf "arduino.$ARCHIVE_FORMAT"
mkdir -p "$ARDUINO_USR_PATH/libraries"
mkdir -p "$ARDUINO_USR_PATH/hardware"
echo "Arduino IDE Installed in '$ARDUINO_IDE_PATH'"
echo ""
fi
function build_sketch(){ # build_sketch <fqbn> <path-to-ino> [extra-options]
if [ "$#" -lt 2 ]; then
echo "ERROR: Illegal number of parameters"
echo "USAGE: build_sketch <fqbn> <path-to-ino> [extra-options]"
return 1
fi
local fqbn="$1"
local sketch="$2"
local xtra_opts="$3"
local win_opts=""
if [ "$OS_IS_WINDOWS" == "1" ]; then
local ctags_version=`ls "$ARDUINO_IDE_PATH/tools-builder/ctags/"`
local preprocessor_version=`ls "$ARDUINO_IDE_PATH/tools-builder/arduino-preprocessor/"`
win_opts="-prefs=runtime.tools.ctags.path=$ARDUINO_IDE_PATH/tools-builder/ctags/$ctags_version -prefs=runtime.tools.arduino-preprocessor.path=$ARDUINO_IDE_PATH/tools-builder/arduino-preprocessor/$preprocessor_version"
fi
#echo ""
#echo "Compiling '"$(basename "$sketch")"' ..."
mkdir -p "$ARDUINO_BUILD_DIR"
mkdir -p "$ARDUINO_CACHE_DIR"
$ARDUINO_IDE_PATH/arduino-builder -compile -logger=human -core-api-version=10810 \
-fqbn=$fqbn \
-warnings="all" \
-tools "$ARDUINO_IDE_PATH/tools-builder" \
-tools "$ARDUINO_IDE_PATH/tools" \
-built-in-libraries "$ARDUINO_IDE_PATH/libraries" \
-hardware "$ARDUINO_IDE_PATH/hardware" \
-hardware "$ARDUINO_USR_PATH/hardware" \
-libraries "$ARDUINO_USR_PATH/libraries" \
-build-cache "$ARDUINO_CACHE_DIR" \
-build-path "$ARDUINO_BUILD_DIR" \
$win_opts $xtra_opts "$sketch"
}
function count_sketches() # count_sketches <examples-path> <target-mcu>
{
local examples="$1"
local target="$2"
rm -rf sketches.txt
if [ ! -d "$examples" ]; then
touch sketches.txt
return 0
fi
local sketches=$(find $examples -name *.ino)
local sketchnum=0
for sketch in $sketches; do
local sketchdir=$(dirname $sketch)
local sketchdirname=$(basename $sketchdir)
local sketchname=$(basename $sketch)
if [[ "$sketchdirname.ino" != "$sketchname" ]]; then
continue
elif [[ -f "$sketchdir/.skip.$target" ]]; then
continue
else
echo $sketch >> sketches.txt
sketchnum=$(($sketchnum + 1))
fi
done
return $sketchnum
}
function build_sketches() # build_sketches <fqbn> <target-mcu> <examples-path> <chunk> <total-chunks> [extra-options]
{
local fqbn=$1
local target="$2"
local examples=$3
local chunk_idex=$4
local chunks_num=$5
local xtra_opts=$6
if [ "$#" -lt 3 ]; then
echo "ERROR: Illegal number of parameters"
echo "USAGE: build_sketches <fqbn> <target-mcu <examples-path> [<chunk> <total-chunks>] [extra-options]"
return 1
fi
if [ "$#" -lt 5 ]; then
chunk_idex="0"
chunks_num="1"
xtra_opts=$4
fi
if [ "$chunks_num" -le 0 ]; then
echo "ERROR: Chunks count must be positive number"
return 1
fi
if [ "$chunk_idex" -ge "$chunks_num" ] && [ "$chunks_num" -ge 2 ]; then
echo "ERROR: Chunk index must be less than chunks count"
return 1
fi
set +e
count_sketches "$examples" "$target"
local sketchcount=$?
set -e
local sketches=$(cat sketches.txt)
rm -rf sketches.txt
local chunk_size=$(( $sketchcount / $chunks_num ))
local all_chunks=$(( $chunks_num * $chunk_size ))
if [ "$all_chunks" -lt "$sketchcount" ]; then
chunk_size=$(( $chunk_size + 1 ))
fi
local start_index=0
local end_index=0
if [ "$chunk_idex" -ge "$chunks_num" ]; then
start_index=$chunk_idex
end_index=$sketchcount
else
start_index=$(( $chunk_idex * $chunk_size ))
if [ "$sketchcount" -le "$start_index" ]; then
echo "Skipping job"
return 0
fi
end_index=$(( $(( $chunk_idex + 1 )) * $chunk_size ))
if [ "$end_index" -gt "$sketchcount" ]; then
end_index=$sketchcount
fi
fi
local start_num=$(( $start_index + 1 ))
echo "Found $sketchcount Sketches for target '$target'";
echo "Chunk Index : $chunk_idex"
echo "Chunk Count : $chunks_num"
echo "Chunk Size : $chunk_size"
echo "Start Sketch: $start_num"
echo "End Sketch : $end_index"
local sketchnum=0
for sketch in $sketches; do
local sketchdir=$(dirname $sketch)
local sketchdirname=$(basename $sketchdir)
local sketchname=$(basename $sketch)
if [ "${sketchdirname}.ino" != "$sketchname" ] \
|| [ -f "$sketchdir/.skip.$target" ]; then
continue
fi
sketchnum=$(($sketchnum + 1))
if [ "$sketchnum" -le "$start_index" ] \
|| [ "$sketchnum" -gt "$end_index" ]; then
continue
fi
echo ""
echo "Building Sketch Index $(($sketchnum - 1)) - $sketchdirname"
build_sketch "$fqbn" "$sketch" "$xtra_opts"
local result=$?
if [ $result -ne 0 ]; then
return $result
fi
done
return 0
}

175
.github/scripts/install-platformio-esp32.sh vendored Executable file
View File

@ -0,0 +1,175 @@
#!/bin/bash
export PLATFORMIO_ESP32_PATH="$HOME/.platformio/packages/framework-arduinoespressif32"
PLATFORMIO_ESP32_URL="https://github.com/platformio/platform-espressif32.git#feature/arduino-idf-master"
XTENSA32_TOOLCHAIN_VERSION="8.4.0+2021r1"
XTENSA32S2_TOOLCHAIN_VERSION="8.4.0+2021r1"
RISCV_TOOLCHAIN_VERSION="8.4.0+2021r1"
ESPTOOLPY_VERSION="~1.30100.0"
ESPRESSIF_ORGANIZATION_NAME="espressif"
echo "Installing Python Wheel ..."
pip install wheel > /dev/null 2>&1
echo "Installing PlatformIO ..."
pip install -U https://github.com/platformio/platformio/archive/master.zip > /dev/null 2>&1
echo "Installing Platform ESP32 ..."
python -m platformio platform install $PLATFORMIO_ESP32_URL > /dev/null 2>&1
echo "Replacing the package versions ..."
replace_script="import json; import os;"
replace_script+="fp=open(os.path.expanduser('~/.platformio/platforms/espressif32/platform.json'), 'r+');"
replace_script+="data=json.load(fp);"
# Use framework sources from the repository
replace_script+="data['packages']['framework-arduinoespressif32']['version'] = '*';"
replace_script+="del data['packages']['framework-arduinoespressif32']['owner'];"
# Use toolchain packages from the "espressif" organization
replace_script+="data['packages']['toolchain-xtensa-esp32']['owner']='$ESPRESSIF_ORGANIZATION_NAME';"
replace_script+="data['packages']['toolchain-xtensa-esp32s2']['owner']='$ESPRESSIF_ORGANIZATION_NAME';"
replace_script+="data['packages']['toolchain-riscv32-esp']['owner']='$ESPRESSIF_ORGANIZATION_NAME';"
# Update versions to use the upstream
replace_script+="data['packages']['toolchain-xtensa-esp32']['version']='$XTENSA32_TOOLCHAIN_VERSION';"
replace_script+="data['packages']['toolchain-xtensa-esp32s2']['version']='$XTENSA32S2_TOOLCHAIN_VERSION';"
replace_script+="data['packages']['toolchain-riscv32-esp']['version']='$RISCV_TOOLCHAIN_VERSION';"
# esptool.py may require an upstream version (for now platformio is the owner)
replace_script+="data['packages']['tool-esptoolpy']['version']='$ESPTOOLPY_VERSION';"
# Save results
replace_script+="fp.seek(0);fp.truncate();json.dump(data, fp, indent=2);fp.close()"
python -c "$replace_script"
if [ "$GITHUB_REPOSITORY" == "espressif/arduino-esp32" ]; then
echo "Linking Core..."
ln -s $GITHUB_WORKSPACE "$PLATFORMIO_ESP32_PATH"
else
echo "Cloning Core Repository ..."
git clone --recursive https://github.com/espressif/arduino-esp32.git "$PLATFORMIO_ESP32_PATH" > /dev/null 2>&1
fi
echo "PlatformIO for ESP32 has been installed"
echo ""
function build_pio_sketch(){ # build_pio_sketch <board> <options> <path-to-ino>
if [ "$#" -lt 3 ]; then
echo "ERROR: Illegal number of parameters"
echo "USAGE: build_pio_sketch <board> <options> <path-to-ino>"
return 1
fi
local board="$1"
local options="$2"
local sketch="$3"
local sketch_dir=$(dirname "$sketch")
echo ""
echo "Compiling '"$(basename "$sketch")"' ..."
python -m platformio ci --board "$board" "$sketch_dir" --project-option="$options"
}
function count_sketches() # count_sketches <examples-path>
{
local examples="$1"
rm -rf sketches.txt
if [ ! -d "$examples" ]; then
touch sketches.txt
return 0
fi
local sketches=$(find $examples -name *.ino)
local sketchnum=0
for sketch in $sketches; do
local sketchdir=$(dirname $sketch)
local sketchdirname=$(basename $sketchdir)
local sketchname=$(basename $sketch)
if [[ "${sketchdirname}.ino" != "$sketchname" ]]; then
continue
fi;
if [[ -f "$sketchdir/.test.skip" ]]; then
continue
fi
echo $sketch >> sketches.txt
sketchnum=$(($sketchnum + 1))
done
return $sketchnum
}
function build_pio_sketches() # build_pio_sketches <board> <options> <examples-path> <chunk> <total-chunks>
{
if [ "$#" -lt 3 ]; then
echo "ERROR: Illegal number of parameters"
echo "USAGE: build_pio_sketches <board> <options> <examples-path> [<chunk> <total-chunks>]"
return 1
fi
local board=$1
local options="$2"
local examples=$3
local chunk_idex=$4
local chunks_num=$5
if [ "$#" -lt 5 ]; then
chunk_idex="0"
chunks_num="1"
fi
if [ "$chunks_num" -le 0 ]; then
echo "ERROR: Chunks count must be positive number"
return 1
fi
if [ "$chunk_idex" -ge "$chunks_num" ]; then
echo "ERROR: Chunk index must be less than chunks count"
return 1
fi
set +e
count_sketches "$examples"
local sketchcount=$?
set -e
local sketches=$(cat sketches.txt)
rm -rf sketches.txt
local chunk_size=$(( $sketchcount / $chunks_num ))
local all_chunks=$(( $chunks_num * $chunk_size ))
if [ "$all_chunks" -lt "$sketchcount" ]; then
chunk_size=$(( $chunk_size + 1 ))
fi
local start_index=$(( $chunk_idex * $chunk_size ))
if [ "$sketchcount" -le "$start_index" ]; then
echo "Skipping job"
return 0
fi
local end_index=$(( $(( $chunk_idex + 1 )) * $chunk_size ))
if [ "$end_index" -gt "$sketchcount" ]; then
end_index=$sketchcount
fi
local start_num=$(( $start_index + 1 ))
echo "Found $sketchcount Sketches";
echo "Chunk Count : $chunks_num"
echo "Chunk Size : $chunk_size"
echo "Start Sketch: $start_num"
echo "End Sketch : $end_index"
local sketchnum=0
for sketch in $sketches; do
local sketchdir=$(dirname $sketch)
local sketchdirname=$(basename $sketchdir)
local sketchname=$(basename $sketch)
if [ "${sketchdirname}.ino" != "$sketchname" ] \
|| [ -f "$sketchdir/.test.skip" ]; then
continue
fi
sketchnum=$(($sketchnum + 1))
if [ "$sketchnum" -le "$start_index" ] \
|| [ "$sketchnum" -gt "$end_index" ]; then
continue
fi
build_pio_sketch "$board" "$options" "$sketch"
local result=$?
if [ $result -ne 0 ]; then
return $result
fi
done
return 0
}

143
.github/scripts/on-pages.sh vendored Normal file
View File

@ -0,0 +1,143 @@
#/bin/bash
set -e
function get_file_size(){
local file="$1"
if [[ "$OSTYPE" == "darwin"* ]]; then
eval `stat -s "$file"`
local res="$?"
echo "$st_size"
return $res
else
stat --printf="%s" "$file"
return $?
fi
}
#git_remove_from_pages <file>
function git_remove_from_pages(){
local path=$1
local info=`curl -s -k -H "Authorization: token $GITHUB_TOKEN" -H "Accept: application/vnd.github.v3.object+json" -X GET "https://api.github.com/repos/$GITHUB_REPOSITORY/contents/$path?ref=gh-pages"`
local type=`echo "$info" | jq -r '.type'`
if [ ! $type == "file" ]; then
if [ ! $type == "null" ]; then
echo "Wrong type '$type'"
else
echo "File is not on Pages"
fi
return 0
fi
local sha=`echo "$info" | jq -r '.sha'`
local message="Deleting "$(basename $path)
local json="{\"branch\":\"gh-pages\",\"message\":\"$message\",\"sha\":\"$sha\"}"
echo "$json" | curl -s -k -H "Authorization: token $GITHUB_TOKEN" -H "Accept: application/vnd.github.v3.raw+json" -X DELETE --data @- "https://api.github.com/repos/$GITHUB_REPOSITORY/contents/$path"
}
function git_upload_to_pages(){
local path=$1
local src=$2
if [ ! -f "$src" ]; then
>&2 echo "Input is not a file! Aborting..."
return 1
fi
local info=`curl -s -k -H "Authorization: token $GITHUB_TOKEN" -H "Accept: application/vnd.github.v3.object+json" -X GET "https://api.github.com/repos/$GITHUB_REPOSITORY/contents/$path?ref=gh-pages"`
local type=`echo "$info" | jq -r '.type'`
local message=$(basename $path)
local sha=""
local content=""
if [ $type == "file" ]; then
sha=`echo "$info" | jq -r '.sha'`
sha=",\"sha\":\"$sha\""
message="Updating $message"
elif [ ! $type == "null" ]; then
>&2 echo "Wrong type '$type'"
return 1
else
message="Creating $message"
fi
content=`base64 -i "$src"`
data="{\"branch\":\"gh-pages\",\"message\":\"$message\",\"content\":\"$content\"$sha}"
echo "$data" | curl -s -k -H "Authorization: token $GITHUB_TOKEN" -H "Accept: application/vnd.github.v3.raw+json" -X PUT --data @- "https://api.github.com/repos/$GITHUB_REPOSITORY/contents/$path"
}
function git_safe_upload_to_pages(){
local path=$1
local file="$2"
local name=$(basename "$file")
local size=`get_file_size "$file"`
local upload_res=`git_upload_to_pages "$path" "$file"`
if [ $? -ne 0 ]; then
>&2 echo "ERROR: Failed to upload '$name' ($?)"
return 1
fi
up_size=`echo "$upload_res" | jq -r '.content.size'`
if [ $up_size -ne $size ]; then
>&2 echo "ERROR: Uploaded size does not match! $up_size != $size"
#git_delete_asset
return 1
fi
echo "$upload_res" | jq -r '.content.download_url'
return $?
}
git_safe_upload_to_pages "index.md" "README.md"
# At some point github stopped providing a list of edited file
# but we also stopped havong documentation in md format,
# so we can skip this portion safely and update just the index
# EVENT_JSON=`cat $GITHUB_EVENT_PATH`
# echo "GITHUB_EVENT_PATH: $GITHUB_EVENT_PATH"
# echo "EVENT_JSON: $EVENT_JSON"
# pages_added=`echo "$EVENT_JSON" | jq -r '.commits[].added[]'`
# echo "added: $pages_added"
# pages_modified=`echo "$EVENT_JSON" | jq -r '.commits[].modified[]'`
# echo "modified: $pages_modified"
# pages_removed=`echo "$EVENT_JSON" | jq -r '.commits[].removed[]'`
# echo "removed: $pages_removed"
# for page in $pages_added; do
# if [[ $page != "README.md" && $page != "docs/"* ]]; then
# continue
# fi
# echo "Adding '$page' to pages ..."
# if [[ $page == "README.md" ]]; then
# git_safe_upload_to_pages "index.md" "README.md"
# else
# git_safe_upload_to_pages "$page" "$page"
# fi
# done
# for page in $pages_modified; do
# if [[ $page != "README.md" && $page != "docs/"* ]]; then
# continue
# fi
# echo "Modifying '$page' ..."
# if [[ $page == "README.md" ]]; then
# git_safe_upload_to_pages "index.md" "README.md"
# else
# git_safe_upload_to_pages "$page" "$page"
# fi
# done
# for page in $pages_removed; do
# if [[ $page != "README.md" && $page != "docs/"* ]]; then
# continue
# fi
# echo "Removing '$page' from pages ..."
# if [[ $page == "README.md" ]]; then
# git_remove_from_pages "README.md" > /dev/null
# else
# git_remove_from_pages "$page" > /dev/null
# fi
# done
echo
echo "DONE!"

104
.github/scripts/on-push.sh vendored Executable file
View File

@ -0,0 +1,104 @@
#!/bin/bash
set -e
if [ ! -z "$TRAVIS_TAG" ]; then
echo "Skipping Test: Tagged build"
exit 0
fi
if [ ! -z "$GITHUB_WORKSPACE" ]; then
export TRAVIS_BUILD_DIR="$GITHUB_WORKSPACE"
export TRAVIS_REPO_SLUG="$GITHUB_REPOSITORY"
elif [ ! -z "$TRAVIS_BUILD_DIR" ]; then
export GITHUB_WORKSPACE="$TRAVIS_BUILD_DIR"
export GITHUB_REPOSITORY="$TRAVIS_REPO_SLUG"
else
export GITHUB_WORKSPACE="$PWD"
export GITHUB_REPOSITORY="espressif/arduino-esp32"
fi
CHUNK_INDEX=$1
CHUNKS_CNT=$2
BUILD_PIO=0
if [ "$#" -lt 2 ] || [ "$CHUNKS_CNT" -le 0 ]; then
CHUNK_INDEX=0
CHUNKS_CNT=1
elif [ "$CHUNK_INDEX" -gt "$CHUNKS_CNT" ] && [ "$CHUNKS_CNT" -ge 2 ]; then
CHUNK_INDEX=$CHUNKS_CNT
elif [ "$CHUNK_INDEX" -eq "$CHUNKS_CNT" ]; then
BUILD_PIO=1
fi
#echo "Updating submodules ..."
#git -C "$GITHUB_WORKSPACE" submodule update --init --recursive > /dev/null 2>&1
if [ "$BUILD_PIO" -eq 0 ]; then
# ArduinoIDE ESP32 Test
TARGET="esp32"
FQBN="espressif:esp32:esp32:PSRAM=enabled,PartitionScheme=huge_app"
source ./.github/scripts/install-arduino-ide.sh
source ./.github/scripts/install-arduino-core-esp32.sh
if [ "$OS_IS_WINDOWS" == "1" ]; then
build_sketch "$FQBN" "$ARDUINO_ESP32_PATH/libraries/WiFiClientSecure/examples/WiFiClientSecure/WiFiClientSecure.ino" && \
build_sketch "$FQBN" "$ARDUINO_ESP32_PATH/libraries/BLE/examples/BLE_server/BLE_server.ino" && \
build_sketch "$FQBN" "$ARDUINO_ESP32_PATH/libraries/ESP32/examples/Camera/CameraWebServer/CameraWebServer.ino"
elif [ "$OS_IS_MACOS" == "1" ]; then
build_sketch "$FQBN" "$ARDUINO_ESP32_PATH/libraries/WiFi/examples/WiFiClient/WiFiClient.ino" && \
build_sketch "$FQBN" "$ARDUINO_ESP32_PATH/libraries/WiFiClientSecure/examples/WiFiClientSecure/WiFiClientSecure.ino" && \
build_sketch "$FQBN" "$ARDUINO_ESP32_PATH/libraries/BluetoothSerial/examples/SerialToSerialBT/SerialToSerialBT.ino" && \
build_sketch "$FQBN" "$ARDUINO_ESP32_PATH/libraries/BLE/examples/BLE_server/BLE_server.ino" && \
build_sketch "$FQBN" "$ARDUINO_ESP32_PATH/libraries/ESP32/examples/Camera/CameraWebServer/CameraWebServer.ino"
else
# CMake Test
if [ "$CHUNK_INDEX" -eq 0 ]; then
bash "$ARDUINO_ESP32_PATH/.github/scripts/check-cmakelists.sh"
fi
build_sketches "$FQBN" "$TARGET" "$ARDUINO_ESP32_PATH/libraries" "$CHUNK_INDEX" "$CHUNKS_CNT"
fi
# ArduinoIDE ESP32S2 Test
TARGET="esp32s2"
FQBN="espressif:esp32:esp32s2:PSRAM=enabled,PartitionScheme=huge_app"
if [ "$OS_IS_WINDOWS" == "1" ]; then
build_sketch "$FQBN" "$ARDUINO_ESP32_PATH/libraries/WiFi/examples/WiFiClient/WiFiClient.ino" && \
build_sketch "$FQBN" "$ARDUINO_ESP32_PATH/libraries/WiFiClientSecure/examples/WiFiClientSecure/WiFiClientSecure.ino"
elif [ "$OS_IS_MACOS" == "1" ]; then
build_sketch "$FQBN" "$ARDUINO_ESP32_PATH/libraries/WiFi/examples/WiFiClient/WiFiClient.ino" && \
build_sketch "$FQBN" "$ARDUINO_ESP32_PATH/libraries/WiFiClientSecure/examples/WiFiClientSecure/WiFiClientSecure.ino"
else
build_sketches "$FQBN" "$TARGET" "$ARDUINO_ESP32_PATH/libraries" "$CHUNK_INDEX" "$CHUNKS_CNT"
fi
# ArduinoIDE ESP32C3 Test
TARGET="esp32c3"
FQBN="espressif:esp32:esp32c3:PartitionScheme=huge_app"
if [ "$OS_IS_WINDOWS" == "1" ]; then
build_sketch "$FQBN" "$ARDUINO_ESP32_PATH/libraries/WiFi/examples/WiFiClient/WiFiClient.ino" && \
build_sketch "$FQBN" "$ARDUINO_ESP32_PATH/libraries/WiFiClientSecure/examples/WiFiClientSecure/WiFiClientSecure.ino"
elif [ "$OS_IS_MACOS" == "1" ]; then
build_sketch "$FQBN" "$ARDUINO_ESP32_PATH/libraries/WiFi/examples/WiFiClient/WiFiClient.ino" && \
build_sketch "$FQBN" "$ARDUINO_ESP32_PATH/libraries/WiFiClientSecure/examples/WiFiClientSecure/WiFiClientSecure.ino"
else
build_sketches "$FQBN" "$TARGET" "$ARDUINO_ESP32_PATH/libraries" "$CHUNK_INDEX" "$CHUNKS_CNT"
fi
else
source ./.github/scripts/install-platformio-esp32.sh
# PlatformIO ESP32 Test
BOARD="esp32dev"
OPTIONS="board_build.partitions = huge_app.csv"
build_pio_sketch "$BOARD" "$OPTIONS" "$PLATFORMIO_ESP32_PATH/libraries/WiFi/examples/WiFiClient/WiFiClient.ino" && \
build_pio_sketch "$BOARD" "$OPTIONS" "$PLATFORMIO_ESP32_PATH/libraries/WiFiClientSecure/examples/WiFiClientSecure/WiFiClientSecure.ino" && \
build_pio_sketch "$BOARD" "$OPTIONS" "$PLATFORMIO_ESP32_PATH/libraries/BluetoothSerial/examples/SerialToSerialBT/SerialToSerialBT.ino" && \
build_pio_sketch "$BOARD" "$OPTIONS" "$PLATFORMIO_ESP32_PATH/libraries/BLE/examples/BLE_server/BLE_server.ino" && \
build_pio_sketch "$BOARD" "$OPTIONS" "$PLATFORMIO_ESP32_PATH/libraries/ESP32/examples/Camera/CameraWebServer/CameraWebServer.ino"
# PlatformIO ESP32 Test
# OPTIONS="board_build.mcu = esp32s2"
# build_pio_sketch "$BOARD" "$OPTIONS" "$PLATFORMIO_ESP32_PATH/libraries/WiFi/examples/WiFiClient/WiFiClient.ino" && \
# build_pio_sketch "$BOARD" "$OPTIONS" "$PLATFORMIO_ESP32_PATH/libraries/WiFiClientSecure/examples/WiFiClientSecure/WiFiClientSecure.ino"
python -m platformio ci --board "$BOARD" "$PLATFORMIO_ESP32_PATH/libraries/WiFi/examples/WiFiClient" --project-option="board_build.mcu = esp32s2" --project-option="board_build.partitions = huge_app.csv"
#build_pio_sketches "$BOARD" "$OPTIONS" "$PLATFORMIO_ESP32_PATH/libraries"
fi

404
.github/scripts/on-release.sh vendored Executable file
View File

@ -0,0 +1,404 @@
#!/bin/bash
if [ ! $GITHUB_EVENT_NAME == "release" ]; then
echo "Wrong event '$GITHUB_EVENT_NAME'!"
exit 1
fi
EVENT_JSON=`cat $GITHUB_EVENT_PATH`
action=`echo $EVENT_JSON | jq -r '.action'`
if [ ! $action == "published" ]; then
echo "Wrong action '$action'. Exiting now..."
exit 0
fi
draft=`echo $EVENT_JSON | jq -r '.release.draft'`
if [ $draft == "true" ]; then
echo "It's a draft release. Exiting now..."
exit 0
fi
RELEASE_PRE=`echo $EVENT_JSON | jq -r '.release.prerelease'`
RELEASE_TAG=`echo $EVENT_JSON | jq -r '.release.tag_name'`
RELEASE_BRANCH=`echo $EVENT_JSON | jq -r '.release.target_commitish'`
RELEASE_ID=`echo $EVENT_JSON | jq -r '.release.id'`
RELEASE_BODY=`echo $EVENT_JSON | jq -r '.release.body'`
OUTPUT_DIR="$GITHUB_WORKSPACE/build"
PACKAGE_NAME="esp32-$RELEASE_TAG"
PACKAGE_JSON_MERGE="$GITHUB_WORKSPACE/.github/scripts/merge_packages.py"
PACKAGE_JSON_TEMPLATE="$GITHUB_WORKSPACE/package/package_esp32_index.template.json"
PACKAGE_JSON_DEV="package_esp32_dev_index.json"
PACKAGE_JSON_REL="package_esp32_index.json"
echo "Event: $GITHUB_EVENT_NAME, Repo: $GITHUB_REPOSITORY, Path: $GITHUB_WORKSPACE, Ref: $GITHUB_REF"
echo "Action: $action, Branch: $RELEASE_BRANCH, ID: $RELEASE_ID"
echo "Tag: $RELEASE_TAG, Draft: $draft, Pre-Release: $RELEASE_PRE"
function get_file_size(){
local file="$1"
if [[ "$OSTYPE" == "darwin"* ]]; then
eval `stat -s "$file"`
local res="$?"
echo "$st_size"
return $res
else
stat --printf="%s" "$file"
return $?
fi
}
function git_upload_asset(){
local name=$(basename "$1")
# local mime=$(file -b --mime-type "$1")
curl -k -X POST -sH "Authorization: token $GITHUB_TOKEN" -H "Content-Type: application/octet-stream" --data-binary @"$1" "https://uploads.github.com/repos/$GITHUB_REPOSITORY/releases/$RELEASE_ID/assets?name=$name"
}
function git_safe_upload_asset(){
local file="$1"
local name=$(basename "$file")
local size=`get_file_size "$file"`
local upload_res=`git_upload_asset "$file"`
if [ $? -ne 0 ]; then
>&2 echo "ERROR: Failed to upload '$name' ($?)"
return 1
fi
up_size=`echo "$upload_res" | jq -r '.size'`
if [ $up_size -ne $size ]; then
>&2 echo "ERROR: Uploaded size does not match! $up_size != $size"
#git_delete_asset
return 1
fi
echo "$upload_res" | jq -r '.browser_download_url'
return $?
}
function git_upload_to_pages(){
local path=$1
local src=$2
if [ ! -f "$src" ]; then
>&2 echo "Input is not a file! Aborting..."
return 1
fi
local info=`curl -s -k -H "Authorization: token $GITHUB_TOKEN" -H "Accept: application/vnd.github.v3.object+json" -X GET "https://api.github.com/repos/$GITHUB_REPOSITORY/contents/$path?ref=gh-pages"`
local type=`echo "$info" | jq -r '.type'`
local message=$(basename $path)
local sha=""
local content=""
if [ $type == "file" ]; then
sha=`echo "$info" | jq -r '.sha'`
sha=",\"sha\":\"$sha\""
message="Updating $message"
elif [ ! $type == "null" ]; then
>&2 echo "Wrong type '$type'"
return 1
else
message="Creating $message"
fi
content=`base64 -i "$src"`
data="{\"branch\":\"gh-pages\",\"message\":\"$message\",\"content\":\"$content\"$sha}"
echo "$data" | curl -s -k -H "Authorization: token $GITHUB_TOKEN" -H "Accept: application/vnd.github.v3.raw+json" -X PUT --data @- "https://api.github.com/repos/$GITHUB_REPOSITORY/contents/$path"
}
function git_safe_upload_to_pages(){
local path=$1
local file="$2"
local name=$(basename "$file")
local size=`get_file_size "$file"`
local upload_res=`git_upload_to_pages "$path" "$file"`
if [ $? -ne 0 ]; then
>&2 echo "ERROR: Failed to upload '$name' ($?)"
return 1
fi
up_size=`echo "$upload_res" | jq -r '.content.size'`
if [ $up_size -ne $size ]; then
>&2 echo "ERROR: Uploaded size does not match! $up_size != $size"
#git_delete_asset
return 1
fi
echo "$upload_res" | jq -r '.content.download_url'
return $?
}
function merge_package_json(){
local jsonLink=$1
local jsonOut=$2
local old_json=$OUTPUT_DIR/oldJson.json
local merged_json=$OUTPUT_DIR/mergedJson.json
echo "Downloading previous JSON $jsonLink ..."
curl -L -o "$old_json" "https://github.com/$GITHUB_REPOSITORY/releases/download/$jsonLink?access_token=$GITHUB_TOKEN" 2>/dev/null
if [ $? -ne 0 ]; then echo "ERROR: Download Failed! $?"; exit 1; fi
echo "Creating new JSON ..."
set +e
stdbuf -oL python "$PACKAGE_JSON_MERGE" "$jsonOut" "$old_json" > "$merged_json"
set -e
set -v
if [ ! -s $merged_json ]; then
rm -f "$merged_json"
echo "Nothing to merge"
else
rm -f "$jsonOut"
mv "$merged_json" "$jsonOut"
echo "JSON data successfully merged"
fi
rm -f "$old_json"
set +v
}
set -e
##
## PACKAGE ZIP
##
mkdir -p "$OUTPUT_DIR"
PKG_DIR="$OUTPUT_DIR/$PACKAGE_NAME"
PACKAGE_ZIP="$PACKAGE_NAME.zip"
echo "Updating submodules ..."
git -C "$GITHUB_WORKSPACE" submodule update --init --recursive > /dev/null 2>&1
mkdir -p "$PKG_DIR/tools"
# Copy all core files to the package folder
echo "Copying files for packaging ..."
cp -f "$GITHUB_WORKSPACE/boards.txt" "$PKG_DIR/"
cp -f "$GITHUB_WORKSPACE/programmers.txt" "$PKG_DIR/"
cp -Rf "$GITHUB_WORKSPACE/cores" "$PKG_DIR/"
cp -Rf "$GITHUB_WORKSPACE/libraries" "$PKG_DIR/"
cp -Rf "$GITHUB_WORKSPACE/variants" "$PKG_DIR/"
cp -f "$GITHUB_WORKSPACE/tools/espota.exe" "$PKG_DIR/tools/"
cp -f "$GITHUB_WORKSPACE/tools/espota.py" "$PKG_DIR/tools/"
cp -f "$GITHUB_WORKSPACE/tools/esptool.py" "$PKG_DIR/tools/"
cp -f "$GITHUB_WORKSPACE/tools/gen_esp32part.py" "$PKG_DIR/tools/"
cp -f "$GITHUB_WORKSPACE/tools/gen_esp32part.exe" "$PKG_DIR/tools/"
cp -Rf "$GITHUB_WORKSPACE/tools/partitions" "$PKG_DIR/tools/"
cp -Rf "$GITHUB_WORKSPACE/tools/sdk" "$PKG_DIR/tools/"
cp -f $GITHUB_WORKSPACE/tools/platformio-build*.py "$PKG_DIR/tools/"
# Remove unnecessary files in the package folder
echo "Cleaning up folders ..."
find "$PKG_DIR" -name '*.DS_Store' -exec rm -f {} \;
find "$PKG_DIR" -name '*.git*' -type f -delete
# Replace tools locations in platform.txt
echo "Generating platform.txt..."
cat "$GITHUB_WORKSPACE/platform.txt" | \
sed "s/version=.*/version=$ver$extent/g" | \
sed 's/runtime.tools.xtensa-esp32-elf-gcc.path={runtime.platform.path}\/tools\/xtensa-esp32-elf//g' | \
sed 's/runtime.tools.xtensa-esp32s2-elf-gcc.path={runtime.platform.path}\/tools\/xtensa-esp32s2-elf//g' | \
sed 's/tools.esptool_py.path={runtime.platform.path}\/tools\/esptool/tools.esptool_py.path=\{runtime.tools.esptool_py.path\}/g' \
> "$PKG_DIR/platform.txt"
# Add header with version information
echo "Generating core_version.h ..."
ver_define=`echo $RELEASE_TAG | tr "[:lower:].\055" "[:upper:]_"`
ver_hex=`git -C "$GITHUB_WORKSPACE" rev-parse --short=8 HEAD 2>/dev/null`
echo \#define ARDUINO_ESP32_GIT_VER 0x$ver_hex > "$PKG_DIR/cores/esp32/core_version.h"
echo \#define ARDUINO_ESP32_GIT_DESC `git -C "$GITHUB_WORKSPACE" describe --tags 2>/dev/null` >> "$PKG_DIR/cores/esp32/core_version.h"
echo \#define ARDUINO_ESP32_RELEASE_$ver_define >> "$PKG_DIR/cores/esp32/core_version.h"
echo \#define ARDUINO_ESP32_RELEASE \"$ver_define\" >> "$PKG_DIR/cores/esp32/core_version.h"
# Compress package folder
echo "Creating ZIP ..."
pushd "$OUTPUT_DIR" >/dev/null
zip -qr "$PACKAGE_ZIP" "$PACKAGE_NAME"
if [ $? -ne 0 ]; then echo "ERROR: Failed to create $PACKAGE_ZIP ($?)"; exit 1; fi
# Calculate SHA-256
echo "Calculating SHA sum ..."
PACKAGE_PATH="$OUTPUT_DIR/$PACKAGE_ZIP"
PACKAGE_SHA=`shasum -a 256 "$PACKAGE_ZIP" | cut -f 1 -d ' '`
PACKAGE_SIZE=`get_file_size "$PACKAGE_ZIP"`
popd >/dev/null
rm -rf "$PKG_DIR"
echo "'$PACKAGE_ZIP' Created! Size: $PACKAGE_SIZE, SHA-256: $PACKAGE_SHA"
echo
# Upload package to release page
echo "Uploading package to release page ..."
PACKAGE_URL=`git_safe_upload_asset "$PACKAGE_PATH"`
echo "Package Uploaded"
echo "Download URL: $PACKAGE_URL"
echo
##
## PACKAGE JSON
##
# Construct JQ argument with package data
jq_arg=".packages[0].platforms[0].version = \"$RELEASE_TAG\" | \
.packages[0].platforms[0].url = \"$PACKAGE_URL\" |\
.packages[0].platforms[0].archiveFileName = \"$PACKAGE_ZIP\" |\
.packages[0].platforms[0].size = \"$PACKAGE_SIZE\" |\
.packages[0].platforms[0].checksum = \"SHA-256:$PACKAGE_SHA\""
# Generate package JSONs
echo "Genarating $PACKAGE_JSON_DEV ..."
cat "$PACKAGE_JSON_TEMPLATE" | jq "$jq_arg" > "$OUTPUT_DIR/$PACKAGE_JSON_DEV"
if [ "$RELEASE_PRE" == "false" ]; then
echo "Genarating $PACKAGE_JSON_REL ..."
cat "$PACKAGE_JSON_TEMPLATE" | jq "$jq_arg" > "$OUTPUT_DIR/$PACKAGE_JSON_REL"
fi
# Figure out the last release or pre-release
echo "Getting previous releases ..."
releasesJson=`curl -sH "Authorization: token $GITHUB_TOKEN" "https://api.github.com/repos/$GITHUB_REPOSITORY/releases" 2>/dev/null`
if [ $? -ne 0 ]; then echo "ERROR: Get Releases Failed! ($?)"; exit 1; fi
set +e
prev_release=$(echo "$releasesJson" | jq -e -r ". | map(select(.draft == false and .prerelease == false)) | sort_by(.published_at | - fromdateiso8601) | .[0].tag_name")
prev_any_release=$(echo "$releasesJson" | jq -e -r ". | map(select(.draft == false)) | sort_by(.published_at | - fromdateiso8601) | .[0].tag_name")
prev_branch_release=$(echo "$releasesJson" | jq -e -r ". | map(select(.draft == false and .prerelease == false and .target_commitish == \"$RELEASE_BRANCH\")) | sort_by(.published_at | - fromdateiso8601) | .[0].tag_name")
prev_branch_any_release=$(echo "$releasesJson" | jq -e -r ". | map(select(.draft == false and .target_commitish == \"$RELEASE_BRANCH\")) | sort_by(.published_at | - fromdateiso8601) | .[0].tag_name")
shopt -s nocasematch
if [ "$prev_release" == "$RELEASE_TAG" ]; then
prev_release=$(echo "$releasesJson" | jq -e -r ". | map(select(.draft == false and .prerelease == false)) | sort_by(.published_at | - fromdateiso8601) | .[1].tag_name")
fi
if [ "$prev_any_release" == "$RELEASE_TAG" ]; then
prev_any_release=$(echo "$releasesJson" | jq -e -r ". | map(select(.draft == false)) | sort_by(.published_at | - fromdateiso8601) | .[1].tag_name")
fi
if [ "$prev_branch_release" == "$RELEASE_TAG" ]; then
prev_branch_release=$(echo "$releasesJson" | jq -e -r ". | map(select(.draft == false and .prerelease == false and .target_commitish == \"$RELEASE_BRANCH\")) | sort_by(.published_at | - fromdateiso8601) | .[1].tag_name")
fi
if [ "$prev_branch_any_release" == "$RELEASE_TAG" ]; then
prev_branch_any_release=$(echo "$releasesJson" | jq -e -r ". | map(select(.draft == false and .target_commitish == \"$RELEASE_BRANCH\")) | sort_by(.published_at | - fromdateiso8601) | .[1].tag_name")
fi
shopt -u nocasematch
set -e
echo "Previous Release: $prev_release"
echo "Previous (any)release: $prev_any_release"
echo
# Merge package JSONs with previous releases
if [ ! -z "$prev_any_release" ] && [ "$prev_any_release" != "null" ]; then
echo "Merging with JSON from $prev_any_release ..."
merge_package_json "$prev_any_release/$PACKAGE_JSON_DEV" "$OUTPUT_DIR/$PACKAGE_JSON_DEV"
fi
if [ "$RELEASE_PRE" == "false" ]; then
if [ ! -z "$prev_release" ] && [ "$prev_release" != "null" ]; then
echo "Merging with JSON from $prev_release ..."
merge_package_json "$prev_release/$PACKAGE_JSON_REL" "$OUTPUT_DIR/$PACKAGE_JSON_REL"
fi
fi
# Upload package JSONs
echo "Uploading $PACKAGE_JSON_DEV ..."
echo "Download URL: "`git_safe_upload_asset "$OUTPUT_DIR/$PACKAGE_JSON_DEV"`
echo "Pages URL: "`git_safe_upload_to_pages "$PACKAGE_JSON_DEV" "$OUTPUT_DIR/$PACKAGE_JSON_DEV"`
echo
if [ "$RELEASE_PRE" == "false" ]; then
echo "Uploading $PACKAGE_JSON_REL ..."
echo "Download URL: "`git_safe_upload_asset "$OUTPUT_DIR/$PACKAGE_JSON_REL"`
echo "Pages URL: "`git_safe_upload_to_pages "$PACKAGE_JSON_REL" "$OUTPUT_DIR/$PACKAGE_JSON_REL"`
echo
fi
##
## RELEASE NOTES
##
# Create release notes
echo "Preparing release notes ..."
releaseNotes=""
# Process annotated tags
relNotesRaw=`git -C "$GITHUB_WORKSPACE" show -s --format=%b $RELEASE_TAG`
readarray -t msgArray <<<"$relNotesRaw"
arrLen=${#msgArray[@]}
if [ $arrLen > 3 ] && [ "${msgArray[0]:0:3}" == "tag" ]; then
ind=3
while [ $ind -lt $arrLen ]; do
if [ $ind -eq 3 ]; then
releaseNotes="#### ${msgArray[ind]}"
releaseNotes+=$'\r\n'
else
oneLine="$(echo -e "${msgArray[ind]}" | sed -e 's/^[[:space:]]*//')"
if [ ${#oneLine} -gt 0 ]; then
if [ "${oneLine:0:2}" == "* " ]; then oneLine=$(echo ${oneLine/\*/-}); fi
if [ "${oneLine:0:2}" != "- " ]; then releaseNotes+="- "; fi
releaseNotes+="$oneLine"
releaseNotes+=$'\r\n'
fi
fi
let ind=$ind+1
done
fi
# Append Commit Messages
echo
echo "Previous Branch Release: $prev_branch_release"
echo "Previous Branch (any)release: $prev_branch_any_release"
echo
commitFile="$OUTPUT_DIR/commits.txt"
COMMITS_SINCE_RELEASE="$prev_branch_any_release"
if [ "$RELEASE_PRE" == "false" ]; then
COMMITS_SINCE_RELEASE="$prev_branch_release"
fi
if [ ! -z "$COMMITS_SINCE_RELEASE" ] && [ "$COMMITS_SINCE_RELEASE" != "null" ]; then
echo "Getting commits since $COMMITS_SINCE_RELEASE ..."
git -C "$GITHUB_WORKSPACE" log --oneline -n 500 "$COMMITS_SINCE_RELEASE..HEAD" > "$commitFile"
elif [ "$RELEASE_BRANCH" != "master" ]; then
echo "Getting all commits on branch '$RELEASE_BRANCH' ..."
git -C "$GITHUB_WORKSPACE" log --oneline -n 500 --cherry-pick --left-only --no-merges HEAD...origin/master > "$commitFile"
else
echo "Getting all commits on master ..."
git -C "$GITHUB_WORKSPACE" log --oneline -n 500 --no-merges > "$commitFile"
fi
releaseNotes+=$'\r\n##### Commits\r\n'
IFS=$'\n'
for next in `cat $commitFile`
do
IFS=' ' read -r commitId commitMsg <<< "$next"
commitLine="- [$commitId](https://github.com/$GITHUB_REPOSITORY/commit/$commitId) $commitMsg"
releaseNotes+="$commitLine"
releaseNotes+=$'\r\n'
done
rm -f $commitFile
# Prepend the original release body
if [ "${RELEASE_BODY: -1}" == $'\r' ]; then
RELEASE_BODY="${RELEASE_BODY:0:-1}"
else
RELEASE_BODY="$RELEASE_BODY"
fi
RELEASE_BODY+=$'\r\n'
releaseNotes="$RELEASE_BODY$releaseNotes"
# Update release page
echo "Updating release notes ..."
releaseNotes=$(printf '%s' "$releaseNotes" | python -c 'import json,sys; print(json.dumps(sys.stdin.read()))')
releaseNotes=${releaseNotes:1:-1}
curlData="{\"body\": \"$releaseNotes\"}"
releaseData=`curl --data "$curlData" "https://api.github.com/repos/$GITHUB_REPOSITORY/releases/$RELEASE_ID?access_token=$GITHUB_TOKEN" 2>/dev/null`
if [ $? -ne 0 ]; then echo "ERROR: Updating Release Failed: $?"; exit 1; fi
echo "Release notes successfully updated"
echo
##
## SUBMODULE VERSIONS
##
# Upload submodules versions
echo "Generating submodules.txt ..."
git -C "$GITHUB_WORKSPACE" submodule status > "$OUTPUT_DIR/submodules.txt"
echo "Uploading submodules.txt ..."
echo "Download URL: "`git_safe_upload_asset "$OUTPUT_DIR/submodules.txt"`
echo ""
set +e
##
## DONE
##
echo "DONE!"

19
.github/stale.yml vendored
View File

@ -12,12 +12,9 @@ onlyLabels: []
# Issues or Pull Requests with these labels will never be considered stale. Set to `[]` to disable
exemptLabels:
- pinned
- security
- "to be implemented"
- "for reference"
- "move to PR"
- "enhancement"
- "Type: For reference"
- "Type: To be implemented"
- "Type: Feature request"
# Set to true to ignore issues in a project (defaults to false)
exemptProjects: false
@ -29,21 +26,21 @@ exemptMilestones: false
exemptAssignees: false
# Label to use when marking as stale
staleLabel: stale
staleLabel: "Status: Stale"
# Comment to post when marking as stale. Set to `false` to disable
markComment: >
This issue has been automatically marked as stale because it has not had
[STALE_SET] This issue has been automatically marked as stale because it has not had
recent activity. It will be closed in 14 days if no further activity occurs. Thank you
for your contributions.
# Comment to post when removing the stale label.
# unmarkComment: >
# Your comment here.
unmarkComment: >
[STALE_CLR] This issue has been removed from the stale queue. Please ensure activity to keep it openin the future.
# Comment to post when closing a stale Issue or Pull Request.
closeComment: >
This stale issue has been automatically closed. Thank you for your contributions.
[STALE_DEL] This stale issue has been automatically closed. Thank you for your contributions.
# Limit the number of actions per hour, from 1-30. Default is 30
limitPerRun: 30

23
.github/workflows/gh-pages.yml vendored Normal file
View File

@ -0,0 +1,23 @@
name: GitHub Pages CI
on:
push:
branches:
- master
- pages
paths:
- 'README.md'
- '.github/scripts/on-pages.sh'
- '.github/workflows/gh-pages.yml'
jobs:
build-pages:
name: Build GitHub Pages
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Copy Files
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: bash ./.github/scripts/on-pages.sh

View File

@ -1,376 +0,0 @@
name: ESP32 Arduino CI
on:
push:
branches:
- master
- release/*
pull_request:
jobs:
build-arduino-0:
name: Build Arduino IDE Tests 0
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Pull submodules
run: git submodule update --init --recursive
- name: Run CMake Check
run: ./tools/ci/check-cmakelists.sh
- name: Install Arduino IDE
env:
#ESP32_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/prep-arduino-ide.sh
- name: Test Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/test-arduino-ide.sh 0 18
- name: Sketch Sizes
run: cat size.log
build-arduino-1:
name: Build Arduino IDE Tests 1
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Pull submodules
run: git submodule update --init --recursive
- name: Install Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/prep-arduino-ide.sh
- name: Test Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/test-arduino-ide.sh 1 18
- name: Sketch Sizes
run: cat size.log
build-arduino-2:
name: Build Arduino IDE Tests 2
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Pull submodules
run: git submodule update --init --recursive
- name: Install Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/prep-arduino-ide.sh
- name: Test Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/test-arduino-ide.sh 2 18
- name: Sketch Sizes
run: cat size.log
build-arduino-3:
name: Build Arduino IDE Tests 3
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Pull submodules
run: git submodule update --init --recursive
- name: Install Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/prep-arduino-ide.sh
- name: Test Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/test-arduino-ide.sh 3 18
- name: Sketch Sizes
run: cat size.log
build-arduino-4:
name: Build Arduino IDE Tests 4
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Pull submodules
run: git submodule update --init --recursive
- name: Install Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/prep-arduino-ide.sh
- name: Test Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/test-arduino-ide.sh 4 18
- name: Sketch Sizes
run: cat size.log
build-arduino-5:
name: Build Arduino IDE Tests 5
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Pull submodules
run: git submodule update --init --recursive
- name: Install Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/prep-arduino-ide.sh
- name: Test Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/test-arduino-ide.sh 5 18
- name: Sketch Sizes
run: cat size.log
build-arduino-6:
name: Build Arduino IDE Tests 6
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Pull submodules
run: git submodule update --init --recursive
- name: Install Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/prep-arduino-ide.sh
- name: Test Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/test-arduino-ide.sh 6 18
- name: Sketch Sizes
run: cat size.log
build-arduino-7:
name: Build Arduino IDE Tests 7
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Pull submodules
run: git submodule update --init --recursive
- name: Install Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/prep-arduino-ide.sh
- name: Test Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/test-arduino-ide.sh 7 18
- name: Sketch Sizes
run: cat size.log
build-arduino-8:
name: Build Arduino IDE Tests 8
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Pull submodules
run: git submodule update --init --recursive
- name: Install Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/prep-arduino-ide.sh
- name: Test Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/test-arduino-ide.sh 8 18
- name: Sketch Sizes
run: cat size.log
build-arduino-9:
name: Build Arduino IDE Tests 9
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Pull submodules
run: git submodule update --init --recursive
- name: Install Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/prep-arduino-ide.sh
- name: Test Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/test-arduino-ide.sh 9 18
- name: Sketch Sizes
run: cat size.log
build-arduino-10:
name: Build Arduino IDE Tests 10
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Pull submodules
run: git submodule update --init --recursive
- name: Install Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/prep-arduino-ide.sh
- name: Test Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/test-arduino-ide.sh 10 18
- name: Sketch Sizes
run: cat size.log
build-arduino-11:
name: Build Arduino IDE Tests 11
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Pull submodules
run: git submodule update --init --recursive
- name: Install Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/prep-arduino-ide.sh
- name: Test Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/test-arduino-ide.sh 11 18
- name: Sketch Sizes
run: cat size.log
build-arduino-12:
name: Build Arduino IDE Tests 12
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Pull submodules
run: git submodule update --init --recursive
- name: Install Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/prep-arduino-ide.sh
- name: Test Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/test-arduino-ide.sh 12 18
- name: Sketch Sizes
run: cat size.log
build-arduino-13:
name: Build Arduino IDE Tests 13
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Pull submodules
run: git submodule update --init --recursive
- name: Install Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/prep-arduino-ide.sh
- name: Test Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/test-arduino-ide.sh 13 18
- name: Sketch Sizes
run: cat size.log
build-arduino-14:
name: Build Arduino IDE Tests 14
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Pull submodules
run: git submodule update --init --recursive
- name: Install Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/prep-arduino-ide.sh
- name: Test Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/test-arduino-ide.sh 14 18
- name: Sketch Sizes
run: cat size.log
build-arduino-15:
name: Build Arduino IDE Tests 15
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Pull submodules
run: git submodule update --init --recursive
- name: Install Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/prep-arduino-ide.sh
- name: Test Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/test-arduino-ide.sh 15 18
- name: Sketch Sizes
run: cat size.log
build-arduino-16:
name: Build Arduino IDE Tests 16
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Pull submodules
run: git submodule update --init --recursive
- name: Install Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/prep-arduino-ide.sh
- name: Test Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/test-arduino-ide.sh 16 18
- name: Sketch Sizes
run: cat size.log
build-arduino-17:
name: Build Arduino IDE Tests 17
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Pull submodules
run: git submodule update --init --recursive
- name: Install Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/prep-arduino-ide.sh
- name: Test Arduino IDE
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/test-arduino-ide.sh 17 18
- name: Sketch Sizes
run: cat size.log
build-platformio:
name: Build PlatformIO Tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Pull submodules
run: git submodule update --init --recursive
- name: Install Python Wheel
run: pip install wheel
- name: Install GCC Toolchain
run: cd tools && python get.py
- name: Install PlatformIO
env:
TRAVIS_BUILD_DIR: ${{ github.workspace }}
run: ./tools/ci/prep-platformio.sh
- name: Test PlatformIO
run: ./tools/ci/test-platformio.sh

58
.github/workflows/push.yml vendored Normal file
View File

@ -0,0 +1,58 @@
name: ESP32 Arduino CI
on:
push:
branches:
- master
- release/*
pull_request:
jobs:
# Ubuntu
build-arduino-linux:
name: Arduino ${{ matrix.chunk }} on ubuntu-latest
runs-on: ubuntu-latest
strategy:
matrix:
chunk: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
steps:
- uses: actions/checkout@v1
- uses: actions/setup-python@v1
with:
python-version: '3.x'
- name: Build Sketches
run: bash ./.github/scripts/on-push.sh ${{ matrix.chunk }} 15
# Windows and MacOS
build-arduino-win-mac:
name: Arduino on ${{ matrix.os }}
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [windows-latest, macOS-latest]
steps:
- uses: actions/checkout@v1
- uses: actions/setup-python@v1
with:
python-version: '3.x'
- name: Build Sketches
run: bash ./.github/scripts/on-push.sh
# PlatformIO on Windows, Ubuntu and Mac
build-platformio:
name: PlatformIO on ${{ matrix.os }}
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macOS-latest]
steps:
- uses: actions/checkout@v1
- uses: actions/setup-python@v1
with:
python-version: '3.x'
- name: Build Sketches
run: bash ./.github/scripts/on-push.sh 1 1 #equal and non-zero to trigger PIO

22
.github/workflows/release.yml vendored Normal file
View File

@ -0,0 +1,22 @@
name: ESP32 Arduino Release
on:
release:
types: published
jobs:
build:
name: Publish Release
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
with:
fetch-depth: 0
- uses: actions/setup-python@v1
with:
python-version: '3.x'
- name: Build Release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: bash ./.github/scripts/on-release.sh

13
.gitignore vendored
View File

@ -1,9 +1,12 @@
tools/xtensa-esp32-elf
tools/xtensa-esp32s2-elf
tools/riscv32-esp-elf
tools/dist
tools/esptool
tools/esptool.exe
tools/mkspiffs/mkspiffs
tools/mkspiffs/mkspiffs.exe
tools/mkspiffs
tools/mklittlefs
tools/mkfatfs.exe
.DS_Store
#Ignore files built by Visual Studio/Visual Micro
@ -12,3 +15,9 @@ tools/mkspiffs/mkspiffs.exe
.vs/
__vm/
*.vcxproj*
.vscode/
platform.sloeber.txt
boards.sloeber.txt
# Ignore docs build (Sphinx)
docs/build

3
.gitmodules vendored
View File

@ -1,3 +0,0 @@
[submodule "libraries/AzureIoT"]
path = libraries/AzureIoT
url = https://github.com/VSChina/ESP32_AzureIoT_Arduino

View File

@ -21,42 +21,27 @@ jobs:
- name: "Build Arduino 0"
if: tag IS blank AND (type = pull_request OR (type = push AND branch = master))
stage: build
script: $TRAVIS_BUILD_DIR/tools/ci/build-tests.sh 0 4
script: $TRAVIS_BUILD_DIR/.github/scripts/on-push.sh 0 10
- name: "Build Arduino 1"
if: tag IS blank AND (type = pull_request OR (type = push AND branch = master))
stage: build
script: $TRAVIS_BUILD_DIR/tools/ci/build-tests.sh 1 4
script: $TRAVIS_BUILD_DIR/.github/scripts/on-push.sh 1 10
- name: "Build Arduino 2"
if: tag IS blank AND (type = pull_request OR (type = push AND branch = master))
stage: build
script: $TRAVIS_BUILD_DIR/tools/ci/build-tests.sh 2 4
script: $TRAVIS_BUILD_DIR/.github/scripts/on-push.sh 2 10
- name: "Build Arduino 3"
if: tag IS blank AND (type = pull_request OR (type = push AND branch = master))
stage: build
script: $TRAVIS_BUILD_DIR/tools/ci/build-tests.sh 3 4
script: $TRAVIS_BUILD_DIR/.github/scripts/on-push.sh 3 10
- name: "Build PlatformIO"
if: tag IS blank AND (type = pull_request OR (type = push AND branch = master))
stage: build
script: $TRAVIS_BUILD_DIR/tools/ci/build-tests.sh 4 4
- name: "Package & Deploy"
if: tag IS present
stage: deploy
env:
- secure: "l/4Dt+KQ/mACtGAHDUsPr66fUte840PZoQ4xpPikqWZI0uARu4l+Ym7+sHinnT6fBqrj8AJeBYGz4nFa8NK4LutZn9mSD40w+sxl0wSV4oHV8rzKe3Cd8+sMG3+o33yWoikMNjSvqa73Q0rm+SgrlInNdZbuAyixL+a2alaWSnGPm4F2xwUGj+S33TOy5P/Xp77CYtCV5S8vzyk/eEdNhoF0GYePJVdfuzCOUjXMyT5OWxORkzzQ7Hnn/Ka/RDfV8Si4HgujLQBrK5q6iPnNBFqBSqilYBepSMn4opnOBpIm0SCgePz7XQEFC83buA7GUcnCnfg38bf+dCwHaODf1d1PmqVRYt2QmfinexXtM4afAtL0iBUDtvrfnXHzwW9w82VeZhpbJSVh9DUQvB0IlsZeCz9J9PUBAi3N+SMX+9l+BomYwRUlPuKY+Ef2JKk9q6mxtUkky5R0daAlVxEhpVdQks1rT+T+NMoDMemxQ3SKEiqAHh6EgHecruszffmZ71uLX9MpERpew0qN+UFiafws+jkTjx+3yF9yut0Hf9sMbeAYzzkGzRqJTUEBJ6B29Cql8M0yRXCNN/8wuuTHhG8esstozga4ZQoIVrq7mEAgup376PTcNfr1+imbbWVQ7lJdYIuDe6OS5V3OX6np11vgK/DbhfyzvQv9Z1zAGnM="
- REMOTE_URL=https://github.com/$TRAVIS_REPO_SLUG/releases/download/$TRAVIS_TAG
script: bash $TRAVIS_BUILD_DIR/tools/ci/build-release.sh -a$ESP32_GITHUB_TOKEN
before_deploy: git submodule update --init
deploy:
- provider: script
skip_cleanup: true
script: bash $TRAVIS_BUILD_DIR/tools/ci/deploy-release.sh -t$TRAVIS_TAG -a$ESP32_GITHUB_TOKEN -s$TRAVIS_REPO_SLUG -drelease
on:
tags: true
script: $TRAVIS_BUILD_DIR/.github/scripts/on-push.sh 1 1
notifications:
email:

View File

@ -15,6 +15,7 @@ set(CORE_SRCS
cores/esp32/esp32-hal-spi.c
cores/esp32/esp32-hal-time.c
cores/esp32/esp32-hal-timer.c
cores/esp32/esp32-hal-tinyusb.c
cores/esp32/esp32-hal-touch.c
cores/esp32/esp32-hal-uart.c
cores/esp32/esp32-hal-rmt.c
@ -31,6 +32,8 @@ set(CORE_SRCS
cores/esp32/stdlib_noniso.c
cores/esp32/Stream.cpp
cores/esp32/StreamString.cpp
cores/esp32/USB.cpp
cores/esp32/USBCDC.cpp
cores/esp32/wiring_pulse.c
cores/esp32/wiring_shift.c
cores/esp32/WMath.cpp
@ -41,6 +44,9 @@ set(LIBRARY_SRCS
libraries/ArduinoOTA/src/ArduinoOTA.cpp
libraries/AsyncUDP/src/AsyncUDP.cpp
libraries/BluetoothSerial/src/BluetoothSerial.cpp
libraries/BluetoothSerial/src/BTAddress.cpp
libraries/BluetoothSerial/src/BTAdvertisedDeviceSet.cpp
libraries/BluetoothSerial/src/BTScanResultsSet.cpp
libraries/DNSServer/src/DNSServer.cpp
libraries/EEPROM/src/EEPROM.cpp
libraries/ESPmDNS/src/ESPmDNS.cpp
@ -49,8 +55,14 @@ set(LIBRARY_SRCS
libraries/FS/src/vfs_api.cpp
libraries/HTTPClient/src/HTTPClient.cpp
libraries/HTTPUpdate/src/HTTPUpdate.cpp
libraries/LittleFS/src/LittleFS.cpp
libraries/NetBIOS/src/NetBIOS.cpp
libraries/Preferences/src/Preferences.cpp
libraries/RainMaker/src/RMaker.cpp
libraries/RainMaker/src/RMakerNode.cpp
libraries/RainMaker/src/RMakerParam.cpp
libraries/RainMaker/src/RMakerDevice.cpp
libraries/RainMaker/src/RMakerType.cpp
libraries/SD_MMC/src/SD_MMC.cpp
libraries/SD/src/SD.cpp
libraries/SD/src/sd_diskio.cpp
@ -60,6 +72,7 @@ set(LIBRARY_SRCS
libraries/SPI/src/SPI.cpp
libraries/Ticker/src/Ticker.cpp
libraries/Update/src/Updater.cpp
libraries/Update/src/HttpsOTAUpdate.cpp
libraries/WebServer/src/WebServer.cpp
libraries/WebServer/src/Parsing.cpp
libraries/WebServer/src/detail/mimetable.cpp
@ -75,69 +88,10 @@ set(LIBRARY_SRCS
libraries/WiFi/src/WiFiServer.cpp
libraries/WiFi/src/WiFiSTA.cpp
libraries/WiFi/src/WiFiUdp.cpp
libraries/WiFiProv/src/WiFiProv.cpp
libraries/Wire/src/Wire.cpp
)
set(AZURE_SRCS
libraries/AzureIoT/src/az_iot/azureiotcerts.c
libraries/AzureIoT/src/az_iot/c-utility/pal/agenttime.c
libraries/AzureIoT/src/az_iot/c-utility/pal/dns_async.c
libraries/AzureIoT/src/az_iot/c-utility/pal/freertos/lock.c
libraries/AzureIoT/src/az_iot/c-utility/pal/freertos/threadapi.c
libraries/AzureIoT/src/az_iot/c-utility/pal/freertos/tickcounter.c
libraries/AzureIoT/src/az_iot/c-utility/pal/lwip/sntp_lwip.c
libraries/AzureIoT/src/az_iot/c-utility/pal/socket_async.c
libraries/AzureIoT/src/az_iot/c-utility/pal/src/platform_openssl_compact.c
libraries/AzureIoT/src/az_iot/c-utility/pal/src/tlsio_openssl_compact.c
libraries/AzureIoT/src/az_iot/c-utility/pal/tlsio_options.c
libraries/AzureIoT/src/az_iot/c-utility/src/base64.c
libraries/AzureIoT/src/az_iot/c-utility/src/buffer.c
libraries/AzureIoT/src/az_iot/c-utility/src/connection_string_parser.c
libraries/AzureIoT/src/az_iot/c-utility/src/consolelogger.c
libraries/AzureIoT/src/az_iot/c-utility/src/constbuffer.c
libraries/AzureIoT/src/az_iot/c-utility/src/constmap.c
libraries/AzureIoT/src/az_iot/c-utility/src/crt_abstractions.c
libraries/AzureIoT/src/az_iot/c-utility/src/doublylinkedlist.c
libraries/AzureIoT/src/az_iot/c-utility/src/gballoc.c
libraries/AzureIoT/src/az_iot/c-utility/src/gb_stdio.c
libraries/AzureIoT/src/az_iot/c-utility/src/gb_time.c
libraries/AzureIoT/src/az_iot/c-utility/src/hmac.c
libraries/AzureIoT/src/az_iot/c-utility/src/hmacsha256.c
libraries/AzureIoT/src/az_iot/c-utility/src/httpapiex.c
libraries/AzureIoT/src/az_iot/c-utility/src/httpapiexsas.c
libraries/AzureIoT/src/az_iot/c-utility/src/httpheaders.c
libraries/AzureIoT/src/az_iot/c-utility/src/http_proxy_io.c
libraries/AzureIoT/src/az_iot/c-utility/src/map.c
libraries/AzureIoT/src/az_iot/c-utility/src/optionhandler.c
libraries/AzureIoT/src/az_iot/c-utility/src/sastoken.c
libraries/AzureIoT/src/az_iot/c-utility/src/sha1.c
libraries/AzureIoT/src/az_iot/c-utility/src/sha224.c
libraries/AzureIoT/src/az_iot/c-utility/src/sha384-512.c
libraries/AzureIoT/src/az_iot/c-utility/src/singlylinkedlist.c
libraries/AzureIoT/src/az_iot/c-utility/src/strings.c
libraries/AzureIoT/src/az_iot/c-utility/src/string_tokenizer.c
libraries/AzureIoT/src/az_iot/c-utility/src/urlencode.c
libraries/AzureIoT/src/az_iot/c-utility/src/usha.c
libraries/AzureIoT/src/az_iot/c-utility/src/vector.c
libraries/AzureIoT/src/az_iot/c-utility/src/xio.c
libraries/AzureIoT/src/az_iot/c-utility/src/xlogging.c
libraries/AzureIoT/src/az_iot/iothub_client/src/blob.c
libraries/AzureIoT/src/az_iot/iothub_client/src/iothub_client_authorization.c
libraries/AzureIoT/src/az_iot/iothub_client/src/iothub_client.c
libraries/AzureIoT/src/az_iot/iothub_client/src/iothub_client_ll.c
libraries/AzureIoT/src/az_iot/iothub_client/src/iothub_client_retry_control.c
libraries/AzureIoT/src/az_iot/iothub_client/src/iothub_message.c
libraries/AzureIoT/src/az_iot/iothub_client/src/iothubtransport.c
libraries/AzureIoT/src/az_iot/iothub_client/src/iothubtransportmqtt.c
libraries/AzureIoT/src/az_iot/iothub_client/src/iothubtransport_mqtt_common.c
libraries/AzureIoT/src/az_iot/iothub_client/src/version.c
libraries/AzureIoT/src/az_iot/umqtt/src/mqtt_client.c
libraries/AzureIoT/src/az_iot/umqtt/src/mqtt_codec.c
libraries/AzureIoT/src/az_iot/umqtt/src/mqtt_message.c
libraries/AzureIoT/src/AzureIotHub.cpp
libraries/AzureIoT/src/Esp32MQTTClient.cpp
)
set(BLE_SRCS
libraries/BLE/src/BLE2902.cpp
libraries/BLE/src/BLE2904.cpp
@ -170,14 +124,12 @@ set(BLE_SRCS
libraries/BLE/src/GeneralUtils.cpp
)
set(COMPONENT_SRCS ${CORE_SRCS} ${LIBRARY_SRCS} ${AZURE_SRCS} ${BLE_SRCS})
set(COMPONENT_ADD_INCLUDEDIRS
variants/esp32/
set(includedirs
variants/${IDF_TARGET}/
cores/esp32/
libraries/ArduinoOTA/src
libraries/AsyncUDP/src
libraries/AzureIoT/src
libraries/BLE/src
libraries/BluetoothSerial/src
libraries/DNSServer/src
@ -188,8 +140,10 @@ set(COMPONENT_ADD_INCLUDEDIRS
libraries/FS/src
libraries/HTTPClient/src
libraries/HTTPUpdate/src
libraries/LittleFS/src
libraries/NetBIOS/src
libraries/Preferences/src
libraries/RainMaker/src
libraries/SD_MMC/src
libraries/SD/src
libraries/SimpleBLE/src
@ -200,17 +154,57 @@ set(COMPONENT_ADD_INCLUDEDIRS
libraries/WebServer/src
libraries/WiFiClientSecure/src
libraries/WiFi/src
libraries/WiFiProv/src
libraries/Wire/src
)
set(COMPONENT_PRIV_INCLUDEDIRS cores/esp32/libb64)
set(srcs ${CORE_SRCS} ${LIBRARY_SRCS} ${BLE_SRCS})
set(priv_includes cores/esp32/libb64)
set(requires spi_flash mbedtls mdns esp_adc_cal wifi_provisioning nghttp)
set(priv_requires fatfs nvs_flash app_update spiffs bootloader_support openssl bt esp_ipc)
set(COMPONENT_REQUIRES spi_flash mbedtls mdns ethernet)
set(COMPONENT_PRIV_REQUIRES fatfs nvs_flash app_update spiffs bootloader_support openssl bt)
idf_component_register(INCLUDE_DIRS ${includedirs} PRIV_INCLUDE_DIRS ${priv_includes} SRCS ${srcs} REQUIRES ${requires} PRIV_REQUIRES ${priv_requires})
register_component()
string(TOUPPER ${CONFIG_IDF_TARGET} idf_target_caps)
target_compile_options(${COMPONENT_TARGET} PUBLIC
-DARDUINO=10812
-DARDUINO_${idf_target_caps}_DEV
-DARDUINO_ARCH_ESP32
-DARDUINO_BOARD="${idf_target_caps}_DEV"
-DARDUINO_VARIANT="${CONFIG_IDF_TARGET}"
-DESP32)
set_source_files_properties(libraries/AzureIoT/src/az_iot/iothub_client/src/iothubtransport_mqtt_common.c
PROPERTIES COMPILE_FLAGS
-Wno-maybe-uninitialized
)
if(CONFIG_AUTOSTART_ARDUINO)
# in autostart mode, arduino-esp32 contains app_main() function and needs to
# reference setup() and loop() in the main component. If we add main
# component to priv_requires then we create a large circular dependency
# (arduino-esp32 -> main -> arduino-esp32) and can get linker errors, so
# instead we add setup() and loop() to the undefined symbols list so the
# linker will always include them.
#
# (As they are C++ symbol, we need to add the C++ mangled names.)
target_link_libraries(${COMPONENT_LIB} INTERFACE "-u _Z5setupv -u _Z4loopv")
endif()
# This function adds a dependency on the given component if the component is included into the build.
function(maybe_add_component component_name)
idf_build_get_property(components BUILD_COMPONENTS)
if (${component_name} IN_LIST components)
idf_component_get_property(lib_name ${component_name} COMPONENT_LIB)
target_link_libraries(${COMPONENT_LIB} PUBLIC ${lib_name})
endif()
endfunction()
if(IDF_TARGET MATCHES "esp32" AND CONFIG_ESP_RMAKER_TASK_STACK)
maybe_add_component(esp_rainmaker)
maybe_add_component(qrcode)
endif()
if(IDF_TARGET MATCHES "esp32s2|esp32s3" AND CONFIG_TINYUSB_ENABLED)
maybe_add_component(arduino_tinyusb)
endif()
if(NOT CONFIG_ARDUINO_SELECTIVE_COMPILATION OR CONFIG_ARDUINO_SELECTIVE_ArduinoOTA)
maybe_add_component(esp_https_ota)
endif()
if(NOT CONFIG_ARDUINO_SELECTIVE_COMPILATION OR CONFIG_ARDUINO_SELECTIVE_LITTLEFS)
maybe_add_component(esp_littlefs)
endif()

50
CONTRIBUTING.rst Normal file
View File

@ -0,0 +1,50 @@
Contributions Guide
===================
We welcome contributions to the Arduino ESP32 project!
How to Contribute
-----------------
Contributions to Arduino ESP32 - fixing bugs, adding features, adding documentation - are welcome. We accept contributions via `Github Pull Requests <https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-requests>`_.
Before Contributing
-------------------
Before sending us a Pull Request, please consider this list of points:
* Is the contribution entirely your own work, or already licensed under an LGPL 2.1 compatible Open Source License? If not then we unfortunately cannot accept it.
* Is the code adequately commented for people to understand how it is structured?
* Is there documentation or examples that go with code contributions?
* Are comments and documentation written in clear English, with no spelling or grammar errors?
* Example contributions are also welcome.
* If the contribution contains multiple commits, are they grouped together into logical changes (one major change per pull request)? Are any commits with names like "fixed typo" `squashed into previous commits <https://eli.thegreenplace.net/2014/02/19/squashing-github-pull-requests-into-a-single-commit/>`_?
* If you're unsure about any of these points, please open the Pull Request anyhow and then ask us for feedback.
Pull Request Process
--------------------
After you open the Pull Request, there will probably be some discussion in the comments field of the request itself.
Once the Pull Request is ready to merge, it will first be merged into our internal git system for in-house automated testing.
If this process passes, it will be merged onto the public github repository.
Legal Part
----------
Before a contribution can be accepted, you will need to sign our :doc:`contributor-agreement`. You will be prompted for this automatically as part of the Pull Request process.
Related Documents
-----------------
.. toctree::
:maxdepth: 1
contributor-agreement

View File

@ -5,7 +5,7 @@ config ENABLE_ARDUINO_DEPENDS
select LWIP_SO_RCVBUF
select ETHERNET
select WIFI_ENABLED
select ESP32_PHY_CALIBRATION_AND_DATA_STORAGE
select ESP32_PHY_CALIBRATION_AND_DATA_STORAGE if IDF_TARGET_ESP32
select MEMMAP_SMP
default "y"
@ -40,6 +40,12 @@ config ARDUINO_RUNNING_CORE
default 1 if ARDUINO_RUN_CORE1
default -1 if ARDUINO_RUN_NO_AFFINITY
config ARDUINO_LOOP_STACK_SIZE
int "Loop thread stack size"
default 8192
help
Amount of stack available for the Arduino task.
choice ARDUINO_EVENT_RUNNING_CORE
bool "Core on which Arduino's event handler is running"
default ARDUINO_EVENT_RUN_CORE1
@ -76,12 +82,27 @@ choice ARDUINO_UDP_RUNNING_CORE
endchoice
config ARDUINO_UDP_TASK_PRIORITY
int "Priority of the UDP task"
default 3
help
Select at what priority you want the UDP task to run.
config ARDUINO_UDP_RUNNING_CORE
int
default 0 if ARDUINO_UDP_RUN_CORE0
default 1 if ARDUINO_UDP_RUN_CORE1
default -1 if ARDUINO_UDP_RUN_NO_AFFINITY
config ARDUINO_ISR_IRAM
bool "Run interrupts in IRAM"
default "n"
help
Enabling this option will Attach all interrupts with the IRAm flag.
It will also make some HAL function, like, digitalRead/Write and more
be loaded into IRAM for access inside ISRs.
Beware that this is a very dangerous setting. Enable it only if you
are fully aware of the consequences.
config DISABLE_HAL_LOCKS
bool "Disable mutex locks for HAL"
@ -250,6 +271,12 @@ config ARDUINO_SELECTIVE_HTTPClient
select ARDUINO_SELECTIVE_WiFiClientSecure
default y
config ARDUINO_SELECTIVE_LITTLEFS
bool "Enable LITTLEFS"
depends on ARDUINO_SELECTIVE_COMPILATION
select ARDUINO_SELECTIVE_FS
default y
config ARDUINO_SELECTIVE_NetBIOS
bool "Enable NetBIOS"
depends on ARDUINO_SELECTIVE_COMPILATION
@ -316,6 +343,12 @@ config ARDUINO_SELECTIVE_WiFiClientSecure
select ARDUINO_SELECTIVE_WiFi
default y
config ARDUINO_SELECTIVE_WiFiProv
bool "Enable WiFiProv"
depends on ARDUINO_SELECTIVE_COMPILATION
select ARDUINO_SELECTIVE_WiFi
default y
config ARDUINO_SELECTIVE_Wire
bool "Enable Wire"
depends on ARDUINO_SELECTIVE_COMPILATION

View File

@ -1,52 +1,54 @@
# Arduino core for ESP32 WiFi chip [![Build Status](https://travis-ci.org/espressif/arduino-esp32.svg?branch=master)](https://travis-ci.org/espressif/arduino-esp32)
# Arduino core for the ESP32
[![Build Status](https://travis-ci.org/espressif/arduino-esp32.svg?branch=master)](https://travis-ci.org/espressif/arduino-esp32) ![](https://github.com/espressif/arduino-esp32/workflows/ESP32%20Arduino%20CI/badge.svg) [![Documentation Status](https://readthedocs.com/projects/espressif-arduino-esp32/badge/?version=latest)](https://docs.espressif.com/projects/arduino-esp32/en/latest/?badge=latest)
### Need help or have a question? Join the chat at [![https://gitter.im/espressif/arduino-esp32](https://badges.gitter.im/espressif/arduino-esp32.svg)](https://gitter.im/espressif/arduino-esp32?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
## Contents
- [ESP32-S2 and ESP32-C3 Support](#esp32-s2-and-esp32-c3-support)
- [Development Status](#development-status)
- [Installation Instructions](#installation-instructions)
- [Decoding Exceptions](#decoding-exceptions)
- [Issue/Bug report template](#issuebug-report-template)
- [ESP32Dev Board PINMAP](#esp32dev-board-pinmap)
## Development Status
[Latest stable release ![Release Version](https://img.shields.io/github/release/espressif/arduino-esp32.svg?style=plastic) ![Release Date](https://img.shields.io/github/release-date/espressif/arduino-esp32.svg?style=plastic)](https://github.com/espressif/arduino-esp32/releases/latest/) ![Downloads](https://img.shields.io/github/downloads/espressif/arduino-esp32/latest/total.svg?style=plastic)
### ESP32-S2 and ESP32-C3 Support
[Latest development release ![Development Version](https://img.shields.io/github/release/espressif/arduino-esp32/all.svg?style=plastic) ![Development Date](https://img.shields.io/github/release-date-pre/espressif/arduino-esp32.svg?style=plastic)](https://github.com/espressif/arduino-esp32/releases/latest/) ![Downloads](https://img.shields.io/github/downloads-pre/espressif/arduino-esp32/latest/total.svg?style=plastic)
If you want to test ESP32-S2 and/or ESP32-C3 through the board manager, please use the development release link:
Most of the framework is implemented. Most noticeable is the missing analogWrite. While analogWrite is on it's way, there are a few other options that you can use:
- 16 channels [LEDC](cores/esp32/esp32-hal-ledc.h) which is PWM
- 8 channels [SigmaDelta](cores/esp32/esp32-hal-sigmadelta.h) which uses SigmaDelta modulation
- 2 channels [DAC](cores/esp32/esp32-hal-dac.h) which gives real analog output
```
https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_dev_index.json
```
## Installation Instructions
- Using Arduino IDE Boards Manager (preferred)
+ [Instructions for Boards Manager](docs/arduino-ide/boards_manager.md)
- Using Arduino IDE with the development repository
+ [Instructions for Windows](docs/arduino-ide/windows.md)
+ [Instructions for Mac](docs/arduino-ide/mac.md)
+ [Instructions for Debian/Ubuntu Linux](docs/arduino-ide/debian_ubuntu.md)
+ [Instructions for Fedora](docs/arduino-ide/fedora.md)
+ [Instructions for openSUSE](docs/arduino-ide/opensuse.md)
- [Using PlatformIO](docs/platformio.md)
- [Building with make](docs/make.md)
- [Using as ESP-IDF component](docs/esp-idf_component.md)
- [Using OTAWebUpdater](docs/OTAWebUpdate/OTAWebUpdate.md)
Now you can install the latest 2.0.0 version from the boards manager.
#### Decoding exceptions
### Development Status
Latest Stable Release [![Release Version](https://img.shields.io/github/release/espressif/arduino-esp32.svg?style=plastic)](https://github.com/espressif/arduino-esp32/releases/latest/) [![Release Date](https://img.shields.io/github/release-date/espressif/arduino-esp32.svg?style=plastic)](https://github.com/espressif/arduino-esp32/releases/latest/) [![Downloads](https://img.shields.io/github/downloads/espressif/arduino-esp32/latest/total.svg?style=plastic)](https://github.com/espressif/arduino-esp32/releases/latest/)
Latest Development Release [![Release Version](https://img.shields.io/github/release/espressif/arduino-esp32/all.svg?style=plastic)](https://github.com/espressif/arduino-esp32/releases/latest/) [![Release Date](https://img.shields.io/github/release-date-pre/espressif/arduino-esp32.svg?style=plastic)](https://github.com/espressif/arduino-esp32/releases/latest/) [![Downloads](https://img.shields.io/github/downloads-pre/espressif/arduino-esp32/latest/total.svg?style=plastic)](https://github.com/espressif/arduino-esp32/releases/latest/)
### Documentation
You can use [Arduino-ESP32 Online Documentation](https://docs.espressif.com/projects/arduino-esp32/en/latest/) to get all information about this project.
* [Getting Started](https://docs.espressif.com/projects/arduino-esp32/en/latest/getting_started.html)
* [Installing (Windows, Linux and macOS)](https://docs.espressif.com/projects/arduino-esp32/en/latest/installing.html)
* [Libraries](https://docs.espressif.com/projects/arduino-esp32/en/latest/libraries.html)
* [ESP-IDF as Component](https://docs.espressif.com/projects/arduino-esp32/en/latest/esp-idf_component.html)
* [FAQ](https://docs.espressif.com/projects/arduino-esp32/en/latest/faq.html)
* [Troubleshooting](https://docs.espressif.com/projects/arduino-esp32/en/latest/troubleshooting.html)
### Decoding exceptions
You can use [EspExceptionDecoder](https://github.com/me-no-dev/EspExceptionDecoder) to get meaningful call trace.
#### Issue/Bug report template
### Issue/Bug report template
Before reporting an issue, make sure you've searched for similar one that was already created. Also make sure to go through all the issues labelled as [for reference](https://github.com/espressif/arduino-esp32/issues?utf8=%E2%9C%93&q=is%3Aissue%20label%3A%22for%20reference%22%20).
Finally, if you're sure no one else had the issue, follow the [ISSUE_TEMPLATE](docs/ISSUE_TEMPLATE.md) while reporting any issue.
Finally, if you are sure no one else had the issue, follow the [issue template](docs/ISSUE_TEMPLATE.md) while reporting any issue.
### Contributing
## ESP32Dev Board PINMAP
We welcome contributions to the Arduino ESP32 project!
![Pin Functions](docs/esp32_pinmap.png)
## Hint
Sometimes to program ESP32 via serial you must keep GPIO0 LOW during the programming process
See [contributing](https://docs.espressif.com/projects/arduino-esp32/en/latest/contributing.html) in the documentation for more information on how to contribute to the project.

View File

@ -1,19 +0,0 @@
build: off
environment:
matrix:
- PLATFORMIO_CI_SRC: "libraries/WiFi/examples/WiFiClient"
- PLATFORMIO_CI_SRC: "libraries/WiFi/examples/WiFiClientBasic"
- PLATFORMIO_CI_SRC: "libraries/WiFi/examples/WiFiClientEvents"
- PLATFORMIO_CI_SRC: "libraries/WiFi/examples/WiFiIPv6"
- PLATFORMIO_CI_SRC: "libraries/WiFi/examples/WiFiScan"
- PLATFORMIO_CI_SRC: "libraries/WiFi/examples/WiFiSmartConfig"
install:
- cmd: git submodule update --init --recursive
- cmd: SET PATH=%PATH%;C:\Python27\Scripts
- cmd: pip install -U https://github.com/platformio/platformio/archive/develop.zip
- cmd: platformio platform install https://github.com/platformio/platform-espressif32.git#feature/stage
test_script:
- cmd: platformio ci -b esp32dev -b nano32 -b node32s

5625
boards.txt

File diff suppressed because it is too large Load Diff

View File

@ -29,6 +29,7 @@
#include <string.h>
#include <inttypes.h>
#include "esp_arduino_version.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
@ -78,7 +79,7 @@
#define interrupts() sei()
#define noInterrupts() cli()
#define clockCyclesPerMicrosecond() ( F_CPU / 1000000L )
#define clockCyclesPerMicrosecond() ( (long int)getCpuFrequencyMhz() )
#define clockCyclesToMicroseconds(a) ( (a) / clockCyclesPerMicrosecond() )
#define microsecondsToClockCycles(a) ( (a) * clockCyclesPerMicrosecond() )
@ -88,7 +89,7 @@
#define bitRead(value, bit) (((value) >> (bit)) & 0x01)
#define bitSet(value, bit) ((value) |= (1UL << (bit)))
#define bitClear(value, bit) ((value) &= ~(1UL << (bit)))
#define bitWrite(value, bit, bitvalue) (bitvalue ? bitSet(value, bit) : bitClear(value, bit))
#define bitWrite(value, bit, bitvalue) ((bitvalue) ? bitSet(value, bit) : bitClear(value, bit))
// avr-libc defines _NOP() since 1.6.2
#ifndef _NOP
@ -98,13 +99,23 @@
#define bit(b) (1UL << (b))
#define _BV(b) (1UL << (b))
#define digitalPinToPort(pin) (((pin)>31)?1:0)
#define digitalPinToBitMask(pin) (1UL << (((pin)>31)?((pin)-32):(pin)))
#define digitalPinToTimer(pin) (0)
#define analogInPinToBit(P) (P)
#if SOC_GPIO_PIN_COUNT <= 32
#define digitalPinToPort(pin) (0)
#define digitalPinToBitMask(pin) (1UL << (pin))
#define portOutputRegister(port) ((volatile uint32_t*)GPIO_OUT_REG)
#define portInputRegister(port) ((volatile uint32_t*)GPIO_IN_REG)
#define portModeRegister(port) ((volatile uint32_t*)GPIO_ENABLE_REG)
#elif SOC_GPIO_PIN_COUNT <= 64
#define digitalPinToPort(pin) (((pin)>31)?1:0)
#define digitalPinToBitMask(pin) (1UL << (((pin)>31)?((pin)-32):(pin)))
#define portOutputRegister(port) ((volatile uint32_t*)((port)?GPIO_OUT1_REG:GPIO_OUT_REG))
#define portInputRegister(port) ((volatile uint32_t*)((port)?GPIO_IN1_REG:GPIO_IN_REG))
#define portModeRegister(port) ((volatile uint32_t*)((port)?GPIO_ENABLE1_REG:GPIO_ENABLE_REG))
#else
#error SOC_GPIO_PIN_COUNT > 64 not implemented
#endif
#define NOT_A_PIN -1
#define NOT_A_PORT -1
@ -115,10 +126,12 @@ typedef bool boolean;
typedef uint8_t byte;
typedef unsigned int word;
#ifdef __cplusplus
void setup(void);
void loop(void);
long random(long, long);
#endif
void randomSeed(unsigned long);
long map(long, long, long, long, long);
@ -162,7 +175,7 @@ using std::min;
using ::round;
uint16_t makeWord(uint16_t w);
uint16_t makeWord(byte h, byte l);
uint16_t makeWord(uint8_t h, uint8_t l);
#define word(...) makeWord(__VA_ARGS__)

View File

@ -19,12 +19,10 @@
#include "Arduino.h"
#include "Esp.h"
#include "rom/spi_flash.h"
#include "esp_sleep.h"
#include "esp_spi_flash.h"
#include <memory>
#include <soc/soc.h>
#include <soc/efuse_reg.h>
#include <esp_partition.h>
extern "C" {
#include "esp_ota_ops.h"
@ -32,6 +30,26 @@ extern "C" {
}
#include <MD5Builder.h>
#include "esp_system.h"
#ifdef ESP_IDF_VERSION_MAJOR // IDF 4+
#if CONFIG_IDF_TARGET_ESP32 // ESP32/PICO-D4
#include "esp32/rom/spi_flash.h"
#include "soc/efuse_reg.h"
#define ESP_FLASH_IMAGE_BASE 0x1000 // Flash offset containing flash size and spi mode
#elif CONFIG_IDF_TARGET_ESP32S2
#include "esp32s2/rom/spi_flash.h"
#define ESP_FLASH_IMAGE_BASE 0x1000
#elif CONFIG_IDF_TARGET_ESP32C3
#include "esp32c3/rom/spi_flash.h"
#define ESP_FLASH_IMAGE_BASE 0x0000 // Esp32c3 is located at 0x0000
#else
#error Target CONFIG_IDF_TARGET is not supported
#endif
#else // ESP32 Before IDF 4.0
#include "rom/spi_flash.h"
#define ESP_FLASH_IMAGE_BASE 0x1000
#endif
/**
* User-defined Literals
* usage:
@ -121,24 +139,36 @@ uint32_t EspClass::getMaxAllocHeap(void)
uint32_t EspClass::getPsramSize(void)
{
if(psramFound()){
multi_heap_info_t info;
heap_caps_get_info(&info, MALLOC_CAP_SPIRAM);
return info.total_free_bytes + info.total_allocated_bytes;
}
return 0;
}
uint32_t EspClass::getFreePsram(void)
{
if(psramFound()){
return heap_caps_get_free_size(MALLOC_CAP_SPIRAM);
}
return 0;
}
uint32_t EspClass::getMinFreePsram(void)
{
if(psramFound()){
return heap_caps_get_minimum_free_size(MALLOC_CAP_SPIRAM);
}
return 0;
}
uint32_t EspClass::getMaxAllocPsram(void)
{
if(psramFound()){
return heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM);
}
return 0;
}
static uint32_t sketchSize(sketchSize_t response) {
@ -218,6 +248,43 @@ uint8_t EspClass::getChipRevision(void)
return chip_info.revision;
}
const char * EspClass::getChipModel(void)
{
#if CONFIG_IDF_TARGET_ESP32
uint32_t chip_ver = REG_GET_FIELD(EFUSE_BLK0_RDATA3_REG, EFUSE_RD_CHIP_VER_PKG);
uint32_t pkg_ver = chip_ver & 0x7;
switch (pkg_ver) {
case EFUSE_RD_CHIP_VER_PKG_ESP32D0WDQ6 :
return "ESP32-D0WDQ6";
case EFUSE_RD_CHIP_VER_PKG_ESP32D0WDQ5 :
return "ESP32-D0WDQ5";
case EFUSE_RD_CHIP_VER_PKG_ESP32D2WDQ5 :
return "ESP32-D2WDQ5";
case EFUSE_RD_CHIP_VER_PKG_ESP32PICOD2 :
return "ESP32-PICO-D2";
case EFUSE_RD_CHIP_VER_PKG_ESP32PICOD4 :
return "ESP32-PICO-D4";
case EFUSE_RD_CHIP_VER_PKG_ESP32PICOV302 :
return "ESP32-PICO-V3-02";
default:
return "Unknown";
}
#elif CONFIG_IDF_TARGET_ESP32S2
return "ESP32-S2";
#elif CONFIG_IDF_TARGET_ESP32S3
return "ESP32-S3";
#elif CONFIG_IDF_TARGET_ESP32C3
return "ESP32-C3";
#endif
}
uint8_t EspClass::getChipCores(void)
{
esp_chip_info_t chip_info;
esp_chip_info(&chip_info);
return chip_info.cores;
}
const char * EspClass::getSdkVersion(void)
{
return esp_get_idf_version();
@ -226,7 +293,7 @@ const char * EspClass::getSdkVersion(void)
uint32_t EspClass::getFlashChipSize(void)
{
esp_image_header_t fhdr;
if(flashRead(0x1000, (uint32_t*)&fhdr, sizeof(esp_image_header_t)) && fhdr.magic != ESP_IMAGE_HEADER_MAGIC) {
if(flashRead(ESP_FLASH_IMAGE_BASE, (uint32_t*)&fhdr, sizeof(esp_image_header_t)) && fhdr.magic != ESP_IMAGE_HEADER_MAGIC) {
return 0;
}
return magicFlashChipSize(fhdr.spi_size);
@ -235,7 +302,7 @@ uint32_t EspClass::getFlashChipSize(void)
uint32_t EspClass::getFlashChipSpeed(void)
{
esp_image_header_t fhdr;
if(flashRead(0x1000, (uint32_t*)&fhdr, sizeof(esp_image_header_t)) && fhdr.magic != ESP_IMAGE_HEADER_MAGIC) {
if(flashRead(ESP_FLASH_IMAGE_BASE, (uint32_t*)&fhdr, sizeof(esp_image_header_t)) && fhdr.magic != ESP_IMAGE_HEADER_MAGIC) {
return 0;
}
return magicFlashChipSpeed(fhdr.spi_speed);
@ -244,7 +311,7 @@ uint32_t EspClass::getFlashChipSpeed(void)
FlashMode_t EspClass::getFlashChipMode(void)
{
esp_image_header_t fhdr;
if(flashRead(0x1000, (uint32_t*)&fhdr, sizeof(esp_image_header_t)) && fhdr.magic != ESP_IMAGE_HEADER_MAGIC) {
if(flashRead(ESP_FLASH_IMAGE_BASE, (uint32_t*)&fhdr, sizeof(esp_image_header_t)) && fhdr.magic != ESP_IMAGE_HEADER_MAGIC) {
return FM_UNKNOWN;
}
return magicFlashChipMode(fhdr.spi_mode);
@ -309,6 +376,20 @@ bool EspClass::flashRead(uint32_t offset, uint32_t *data, size_t size)
return spi_flash_read(offset, (uint32_t*) data, size) == ESP_OK;
}
bool EspClass::partitionEraseRange(const esp_partition_t *partition, uint32_t offset, size_t size)
{
return esp_partition_erase_range(partition, offset, size) == ESP_OK;
}
bool EspClass::partitionWrite(const esp_partition_t *partition, uint32_t offset, uint32_t *data, size_t size)
{
return esp_partition_write(partition, offset, data, size) == ESP_OK;
}
bool EspClass::partitionRead(const esp_partition_t *partition, uint32_t offset, uint32_t *data, size_t size)
{
return esp_partition_read(partition, offset, data, size) == ESP_OK;
}
uint64_t EspClass::getEfuseMac(void)
{

View File

@ -21,6 +21,8 @@
#define ESP_H
#include <Arduino.h>
#include <esp_partition.h>
#include <hal/cpu_hal.h>
/**
* AVR macros for WDT managment
@ -75,6 +77,8 @@ public:
uint32_t getMaxAllocPsram();
uint8_t getChipRevision();
const char * getChipModel();
uint8_t getChipCores();
uint32_t getCpuFreqMHz(){ return getCpuFrequencyMhz(); }
inline uint32_t getCycleCount() __attribute__((always_inline));
const char * getSdkVersion();
@ -97,15 +101,17 @@ public:
bool flashWrite(uint32_t offset, uint32_t *data, size_t size);
bool flashRead(uint32_t offset, uint32_t *data, size_t size);
bool partitionEraseRange(const esp_partition_t *partition, uint32_t offset, size_t size);
bool partitionWrite(const esp_partition_t *partition, uint32_t offset, uint32_t *data, size_t size);
bool partitionRead(const esp_partition_t *partition, uint32_t offset, uint32_t *data, size_t size);
uint64_t getEfuseMac();
};
uint32_t IRAM_ATTR EspClass::getCycleCount()
uint32_t ARDUINO_ISR_ATTR EspClass::getCycleCount()
{
uint32_t ccount;
__asm__ __volatile__("esync; rsr %0,ccount":"=a" (ccount));
return ccount;
return cpu_hal_get_cycle_count();
}
extern EspClass ESP;

View File

@ -16,7 +16,7 @@ extern "C"
extern void __attachInterruptFunctionalArg(uint8_t pin, voidFuncPtrArg userFunc, void * arg, int intr_type, bool functional);
}
void IRAM_ATTR interruptFunctional(void* arg)
void ARDUINO_ISR_ATTR interruptFunctional(void* arg)
{
InterruptArgStructure* localArg = (InterruptArgStructure*)arg;
if (localArg->interruptFunction)

View File

@ -6,6 +6,8 @@
#include "pins_arduino.h"
#include "HardwareSerial.h"
#if CONFIG_IDF_TARGET_ESP32
#ifndef RX1
#define RX1 9
#endif
@ -22,15 +24,33 @@
#define TX2 17
#endif
#else
#ifndef RX1
#define RX1 18
#endif
#ifndef TX1
#define TX1 17
#endif
#endif
#if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_SERIAL)
#if ARDUINO_SERIAL_PORT //Serial used for USB CDC
HardwareSerial Serial0(0);
#else
HardwareSerial Serial(0);
#endif
HardwareSerial Serial1(1);
#if CONFIG_IDF_TARGET_ESP32
HardwareSerial Serial2(2);
#endif
#endif
HardwareSerial::HardwareSerial(int uart_nr) : _uart_nr(uart_nr), _uart(NULL) {}
void HardwareSerial::begin(unsigned long baud, uint32_t config, int8_t rxPin, int8_t txPin, bool invert, unsigned long timeout_ms)
void HardwareSerial::begin(unsigned long baud, uint32_t config, int8_t rxPin, int8_t txPin, bool invert, unsigned long timeout_ms, uint8_t rxfifo_full_thrhd)
{
if(0 > _uart_nr || _uart_nr > 2) {
log_e("Serial number is invalid, please use 0, 1 or 2");
@ -40,19 +60,30 @@ void HardwareSerial::begin(unsigned long baud, uint32_t config, int8_t rxPin, in
end();
}
if(_uart_nr == 0 && rxPin < 0 && txPin < 0) {
#if CONFIG_IDF_TARGET_ESP32
rxPin = 3;
txPin = 1;
#elif CONFIG_IDF_TARGET_ESP32S2
rxPin = 44;
txPin = 43;
#elif CONFIG_IDF_TARGET_ESP32C3
rxPin = 20;
txPin = 21;
#endif
}
if(_uart_nr == 1 && rxPin < 0 && txPin < 0) {
rxPin = RX1;
txPin = TX1;
}
#if CONFIG_IDF_TARGET_ESP32
if(_uart_nr == 2 && rxPin < 0 && txPin < 0) {
rxPin = RX2;
txPin = TX2;
}
_uart = uartBegin(_uart_nr, baud ? baud : 9600, config, rxPin, txPin, 256, invert);
#endif
_uart = uartBegin(_uart_nr, baud ? baud : 9600, config, rxPin, txPin, 256, invert, rxfifo_full_thrhd);
_tx_pin = txPin;
_rx_pin = rxPin;
if(!baud) {
uartStartDetectBaudrate(_uart);
@ -66,10 +97,12 @@ void HardwareSerial::begin(unsigned long baud, uint32_t config, int8_t rxPin, in
if(detectedBaudRate) {
delay(100); // Give some time...
_uart = uartBegin(_uart_nr, detectedBaudRate, config, rxPin, txPin, 256, invert);
_uart = uartBegin(_uart_nr, detectedBaudRate, config, rxPin, txPin, 256, invert, rxfifo_full_thrhd);
} else {
log_e("Could not detect baudrate. Serial data at the port must be present within the timeout for detection to be possible");
_uart = NULL;
_tx_pin = 255;
_rx_pin = 255;
}
}
}
@ -84,7 +117,9 @@ void HardwareSerial::end()
if(uartGetDebug() == _uart_nr) {
uartSetDebug(0);
}
uartEnd(_uart);
delay(10);
log_v("pins %d %d",_tx_pin, _rx_pin);
uartEnd(_uart, _tx_pin, _rx_pin);
_uart = 0;
}
@ -101,7 +136,7 @@ void HardwareSerial::setDebugOutput(bool en)
uartSetDebug(_uart);
} else {
if(uartGetDebug() == _uart_nr) {
uartSetDebug(0);
uartSetDebug(NULL);
}
}
}
@ -131,11 +166,34 @@ int HardwareSerial::read(void)
return -1;
}
void HardwareSerial::flush()
// read characters into buffer
// terminates if size characters have been read, or no further are pending
// returns the number of characters placed in the buffer
// the buffer is NOT null terminated.
size_t HardwareSerial::read(uint8_t *buffer, size_t size)
{
size_t avail = available();
if (size < avail) {
avail = size;
}
size_t count = 0;
while(count < avail) {
*buffer++ = uartRead(_uart);
count++;
}
return count;
}
void HardwareSerial::flush(void)
{
uartFlush(_uart);
}
void HardwareSerial::flush(bool txOnly)
{
uartFlushTxOnly(_uart, txOnly);
}
size_t HardwareSerial::write(uint8_t c)
{
uartWrite(_uart, c);
@ -156,3 +214,8 @@ HardwareSerial::operator bool() const
{
return true;
}
void HardwareSerial::setRxInvert(bool invert)
{
uartSetRxInvert(_uart, invert);
}

View File

@ -55,17 +55,26 @@ class HardwareSerial: public Stream
public:
HardwareSerial(int uart_nr);
void begin(unsigned long baud, uint32_t config=SERIAL_8N1, int8_t rxPin=-1, int8_t txPin=-1, bool invert=false, unsigned long timeout_ms = 20000UL);
void begin(unsigned long baud, uint32_t config=SERIAL_8N1, int8_t rxPin=-1, int8_t txPin=-1, bool invert=false, unsigned long timeout_ms = 20000UL, uint8_t rxfifo_full_thrhd = 112);
void end();
void updateBaudRate(unsigned long baud);
int available(void);
int availableForWrite(void);
int peek(void);
int read(void);
size_t read(uint8_t *buffer, size_t size);
inline size_t read(char * buffer, size_t size)
{
return read((uint8_t*) buffer, size);
}
void flush(void);
void flush( bool txOnly);
size_t write(uint8_t);
size_t write(const uint8_t *buffer, size_t size);
inline size_t write(const char * buffer, size_t size)
{
return write((uint8_t*) buffer, size);
}
inline size_t write(const char * s)
{
return write((uint8_t*) s, strlen(s));
@ -92,15 +101,32 @@ public:
size_t setRxBufferSize(size_t);
void setDebugOutput(bool);
void setRxInvert(bool);
protected:
int _uart_nr;
uart_t* _uart;
uint8_t _tx_pin;
uint8_t _rx_pin;
};
extern void serialEventRun(void) __attribute__((weak));
#if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_SERIAL)
#ifndef ARDUINO_SERIAL_PORT
#define ARDUINO_SERIAL_PORT 0
#endif
#if ARDUINO_SERIAL_PORT //Serial used for USB CDC
#include "USB.h"
#include "USBCDC.h"
extern HardwareSerial Serial0;
#else
extern HardwareSerial Serial;
#endif
extern HardwareSerial Serial1;
#if CONFIG_IDF_TARGET_ESP32
extern HardwareSerial Serial2;
#endif
#endif
#endif // HardwareSerial_h

View File

@ -21,7 +21,21 @@
#include <WString.h>
#include <Stream.h>
#include "esp_system.h"
#ifdef ESP_IDF_VERSION_MAJOR // IDF 4+
#if CONFIG_IDF_TARGET_ESP32 // ESP32/PICO-D4
#include "esp32/rom/md5_hash.h"
#elif CONFIG_IDF_TARGET_ESP32S2
#include "esp32s2/rom/md5_hash.h"
#elif CONFIG_IDF_TARGET_ESP32C3
#include "esp32c3/rom/md5_hash.h"
#else
#error Target CONFIG_IDF_TARGET is not supported
#endif
#else // ESP32 Before IDF 4.0
#include "rom/md5_hash.h"
#endif
class MD5Builder
{

View File

@ -111,18 +111,12 @@ size_t Print::print(unsigned int n, int base)
size_t Print::print(long n, int base)
{
if(base == 0) {
return write(n);
} else if(base == 10) {
if(n < 0) {
int t = print('-');
int t = 0;
if (base == 10 && n < 0) {
t = print('-');
n = -n;
return printNumber(n, 10) + t;
}
return printNumber(n, 10);
} else {
return printNumber(n, base);
}
return printNumber(static_cast<unsigned long>(n), base) + t;
}
size_t Print::print(unsigned long n, int base)
@ -134,6 +128,25 @@ size_t Print::print(unsigned long n, int base)
}
}
size_t Print::print(long long n, int base)
{
int t = 0;
if (base == 10 && n < 0) {
t = print('-');
n = -n;
}
return printNumber(static_cast<unsigned long long>(n), base) + t;
}
size_t Print::print(unsigned long long n, int base)
{
if (base == 0) {
return write(n);
} else {
return printNumber(n, base);
}
}
size_t Print::print(double n, int digits)
{
return printFloat(n, digits);
@ -226,6 +239,20 @@ size_t Print::println(unsigned long num, int base)
return n;
}
size_t Print::println(long long num, int base)
{
size_t n = print(num, base);
n += println();
return n;
}
size_t Print::println(unsigned long long num, int base)
{
size_t n = print(num, base);
n += println();
return n;
}
size_t Print::println(double num, int digits)
{
size_t n = print(num, digits);
@ -251,7 +278,7 @@ size_t Print::println(struct tm * timeinfo, const char * format)
size_t Print::printNumber(unsigned long n, uint8_t base)
{
char buf[8 * sizeof(long) + 1]; // Assumes 8-bit chars plus zero byte.
char buf[8 * sizeof(n) + 1]; // Assumes 8-bit chars plus zero byte.
char *str = &buf[sizeof(buf) - 1];
*str = '\0';
@ -262,11 +289,34 @@ size_t Print::printNumber(unsigned long n, uint8_t base)
}
do {
unsigned long m = n;
char c = n % base;
n /= base;
*--str = c < 10 ? c + '0' : c + 'A' - 10;
} while (n);
return write(str);
}
size_t Print::printNumber(unsigned long long n, uint8_t base)
{
char buf[8 * sizeof(n) + 1]; // Assumes 8-bit chars plus zero byte.
char* str = &buf[sizeof(buf) - 1];
*str = '\0';
// prevent crash if called with base == 1
if (base < 2) {
base = 10;
}
do {
auto m = n;
n /= base;
char c = m - base * n;
*--str = c < 10 ? c + '0' : c + 'A' - 10;
} while(n);
} while (n);
return write(str);
}

View File

@ -36,6 +36,7 @@ class Print
private:
int write_error;
size_t printNumber(unsigned long, uint8_t);
size_t printNumber(unsigned long long, uint8_t);
size_t printFloat(double, uint8_t);
protected:
void setWriteError(int err = 1)
@ -72,6 +73,11 @@ public:
}
size_t printf(const char * format, ...) __attribute__ ((format (printf, 2, 3)));
// add availableForWrite to make compatible with Arduino Print.h
// default to zero, meaning "a single write may block"
// should be overriden by subclasses with buffering
virtual int availableForWrite() { return 0; }
size_t print(const __FlashStringHelper *);
size_t print(const String &);
size_t print(const char[]);
@ -81,6 +87,8 @@ public:
size_t print(unsigned int, int = DEC);
size_t print(long, int = DEC);
size_t print(unsigned long, int = DEC);
size_t print(long long, int = DEC);
size_t print(unsigned long long, int = DEC);
size_t print(double, int = 2);
size_t print(const Printable&);
size_t print(struct tm * timeinfo, const char * format = NULL);
@ -94,6 +102,8 @@ public:
size_t println(unsigned int, int = DEC);
size_t println(long, int = DEC);
size_t println(unsigned long, int = DEC);
size_t println(long long, int = DEC);
size_t println(unsigned long long, int = DEC);
size_t println(double, int = 2);
size_t println(const Printable&);
size_t println(struct tm * timeinfo, const char * format = NULL);

View File

@ -89,7 +89,7 @@ unsigned long Stream::getTimeout(void) {
// find returns true if the target string is found
bool Stream::find(const char *target)
{
return findUntil(target, (char*) "");
return findUntil(target, strlen(target), NULL, 0);
}
// reads data from the stream until the target string of given length is found
@ -110,35 +110,78 @@ bool Stream::findUntil(const char *target, const char *terminator)
// returns true if target string is found, false if terminated or timed out
bool Stream::findUntil(const char *target, size_t targetLen, const char *terminator, size_t termLen)
{
size_t index = 0; // maximum target string length is 64k bytes!
size_t termIndex = 0;
int c;
if(*target == 0) {
return true; // return true if target is a null string
}
while((c = timedRead()) > 0) {
if(c != target[index]) {
index = 0; // reset index if any char does not match
}
if(c == target[index]) {
//////Serial.print("found "); Serial.write(c); Serial.print("index now"); Serial.println(index+1);
if(++index >= targetLen) { // return true if all chars in the target match
return true;
}
}
if(termLen > 0 && c == terminator[termIndex]) {
if(++termIndex >= termLen) {
return false; // return false if terminate string found before target string
}
if (terminator == NULL) {
MultiTarget t[1] = {{target, targetLen, 0}};
return findMulti(t, 1) == 0 ? true : false;
} else {
termIndex = 0;
MultiTarget t[2] = {{target, targetLen, 0}, {terminator, termLen, 0}};
return findMulti(t, 2) == 0 ? true : false;
}
}
int Stream::findMulti( struct Stream::MultiTarget *targets, int tCount) {
// any zero length target string automatically matches and would make
// a mess of the rest of the algorithm.
for (struct MultiTarget *t = targets; t < targets+tCount; ++t) {
if (t->len <= 0)
return t - targets;
}
while (1) {
int c = timedRead();
if (c < 0)
return -1;
for (struct MultiTarget *t = targets; t < targets+tCount; ++t) {
// the simple case is if we match, deal with that first.
if (c == t->str[t->index]) {
if (++t->index == t->len)
return t - targets;
else
continue;
}
// if not we need to walk back and see if we could have matched further
// down the stream (ie '1112' doesn't match the first position in '11112'
// but it will match the second position so we can't just reset the current
// index to 0 when we find a mismatch.
if (t->index == 0)
continue;
int origIndex = t->index;
do {
--t->index;
// first check if current char works against the new current index
if (c != t->str[t->index])
continue;
// if it's the only char then we're good, nothing more to check
if (t->index == 0) {
t->index++;
break;
}
// otherwise we need to check the rest of the found string
int diff = origIndex - t->index;
size_t i;
for (i = 0; i < t->index; ++i) {
if (t->str[i] != t->str[i + diff])
break;
}
// if we successfully got through the previous loop then our current
// index is good.
if (i == t->index) {
t->index++;
break;
}
// otherwise we just try the next index
} while (t->index);
}
}
return false;
// unreachable
return -1;
}
// returns the first valid (long) integer value from the current position.

View File

@ -60,6 +60,7 @@ public:
void setTimeout(unsigned long timeout); // sets maximum milliseconds to wait for stream data, default is 1 second
unsigned long getTimeout(void);
bool find(const char *target); // reads data from the stream until the target string is found
bool find(uint8_t *target)
{
@ -123,6 +124,17 @@ protected:
// this allows format characters (typically commas) in values to be ignored
float parseFloat(char skipChar); // as above but the given skipChar is ignored
struct MultiTarget {
const char *str; // string you're searching for
size_t len; // length of string you're searching for
size_t index; // index used by the search routine.
};
// This allows you to search for an arbitrary number of strings.
// Returns index of the target that is found first or -1 if timeout occurs.
int findMulti(struct MultiTarget *targets, int tCount);
};
#endif

337
cores/esp32/USB.cpp Normal file
View File

@ -0,0 +1,337 @@
// Copyright 2015-2020 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "esp32-hal.h"
#include "esp32-hal-tinyusb.h"
#include "USB.h"
#if CONFIG_TINYUSB_ENABLED
#ifndef USB_VID
#define USB_VID USB_ESPRESSIF_VID
#endif
#ifndef USB_PID
#define USB_PID 0x0002
#endif
#ifndef USB_MANUFACTURER
#define USB_MANUFACTURER "Espressif Systems"
#endif
#ifndef USB_PRODUCT
#define USB_PRODUCT ARDUINO_BOARD
#endif
#ifndef USB_SERIAL
#define USB_SERIAL "0"
#endif
#if CFG_TUD_DFU_RUNTIME
static uint16_t load_dfu_descriptor(uint8_t * dst, uint8_t * itf)
{
#define DFU_ATTR_CAN_DOWNLOAD 1
#define DFU_ATTR_CAN_UPLOAD 2
#define DFU_ATTR_MANIFESTATION_TOLERANT 4
#define DFU_ATTR_WILL_DETACH 8
#define DFU_ATTRS (DFU_ATTR_CAN_DOWNLOAD | DFU_ATTR_CAN_UPLOAD | DFU_ATTR_MANIFESTATION_TOLERANT)
uint8_t str_index = tinyusb_add_string_descriptor("TinyUSB DFU_RT");
uint8_t descriptor[TUD_DFU_RT_DESC_LEN] = {
// Interface number, string index, attributes, detach timeout, transfer size */
TUD_DFU_RT_DESCRIPTOR(*itf, str_index, DFU_ATTRS, 700, 64)
};
*itf+=1;
memcpy(dst, descriptor, TUD_DFU_RT_DESC_LEN);
return TUD_DFU_RT_DESC_LEN;
}
// Invoked on DFU_DETACH request to reboot to the bootloader
void tud_dfu_runtime_reboot_to_dfu_cb(void)
{
usb_persist_restart(RESTART_BOOTLOADER_DFU);
}
#endif /* CFG_TUD_DFU_RUNTIME */
ESP_EVENT_DEFINE_BASE(ARDUINO_USB_EVENTS);
static esp_event_loop_handle_t arduino_usb_event_loop_handle = NULL;
esp_err_t arduino_usb_event_post(esp_event_base_t event_base, int32_t event_id, void *event_data, size_t event_data_size, TickType_t ticks_to_wait){
if(arduino_usb_event_loop_handle == NULL){
return ESP_FAIL;
}
return esp_event_post_to(arduino_usb_event_loop_handle, event_base, event_id, event_data, event_data_size, ticks_to_wait);
}
esp_err_t arduino_usb_event_handler_register_with(esp_event_base_t event_base, int32_t event_id, esp_event_handler_t event_handler, void *event_handler_arg){
if(arduino_usb_event_loop_handle == NULL){
return ESP_FAIL;
}
return esp_event_handler_register_with(arduino_usb_event_loop_handle, event_base, event_id, event_handler, event_handler_arg);
}
static bool tinyusb_device_mounted = false;
static bool tinyusb_device_suspended = false;
// Invoked when device is mounted (configured)
void tud_mount_cb(void){
tinyusb_device_mounted = true;
arduino_usb_event_data_t p = {0};
arduino_usb_event_post(ARDUINO_USB_EVENTS, ARDUINO_USB_STARTED_EVENT, &p, sizeof(arduino_usb_event_data_t), portMAX_DELAY);
}
// Invoked when device is unmounted
void tud_umount_cb(void){
tinyusb_device_mounted = false;
arduino_usb_event_data_t p = {0};
arduino_usb_event_post(ARDUINO_USB_EVENTS, ARDUINO_USB_STOPPED_EVENT, &p, sizeof(arduino_usb_event_data_t), portMAX_DELAY);
}
// Invoked when usb bus is suspended
// Within 7ms, device must draw an average of current less than 2.5 mA from bus
void tud_suspend_cb(bool remote_wakeup_en){
tinyusb_device_suspended = true;
arduino_usb_event_data_t p = {0};
p.suspend.remote_wakeup_en = remote_wakeup_en;
arduino_usb_event_post(ARDUINO_USB_EVENTS, ARDUINO_USB_SUSPEND_EVENT, &p, sizeof(arduino_usb_event_data_t), portMAX_DELAY);
}
// Invoked when usb bus is resumed
void tud_resume_cb(void){
tinyusb_device_suspended = false;
arduino_usb_event_data_t p = {0};
arduino_usb_event_post(ARDUINO_USB_EVENTS, ARDUINO_USB_RESUME_EVENT, &p, sizeof(arduino_usb_event_data_t), portMAX_DELAY);
}
ESPUSB::ESPUSB(size_t task_stack_size, uint8_t event_task_priority)
:vid(USB_VID)
,pid(USB_PID)
,product_name(USB_PRODUCT)
,manufacturer_name(USB_MANUFACTURER)
,serial_number(USB_SERIAL)
,fw_version(0x0100)
,usb_version(0x0200)// at least 2.1 or 3.x for BOS & webUSB
,usb_class(TUSB_CLASS_MISC)
,usb_subclass(MISC_SUBCLASS_COMMON)
,usb_protocol(MISC_PROTOCOL_IAD)
,usb_attributes(TUSB_DESC_CONFIG_ATT_SELF_POWERED)
,usb_power_ma(500)
,webusb_enabled(false)
,webusb_url("https://espressif.github.io/arduino-esp32/webusb.html")
,_started(false)
,_task_stack_size(task_stack_size)
,_event_task_priority(event_task_priority)
{
if (!arduino_usb_event_loop_handle) {
esp_event_loop_args_t event_task_args = {
.queue_size = 5,
.task_name = "arduino_usb_events",
.task_priority = _event_task_priority,
.task_stack_size = _task_stack_size,
.task_core_id = tskNO_AFFINITY
};
if (esp_event_loop_create(&event_task_args, &arduino_usb_event_loop_handle) != ESP_OK) {
log_e("esp_event_loop_create failed");
}
}
}
ESPUSB::~ESPUSB(){
if (arduino_usb_event_loop_handle) {
esp_event_loop_delete(arduino_usb_event_loop_handle);
arduino_usb_event_loop_handle = NULL;
}
}
bool ESPUSB::begin(){
if(!_started){
tinyusb_device_config_t tinyusb_device_config = {
.vid = vid,
.pid = pid,
.product_name = product_name.c_str(),
.manufacturer_name = manufacturer_name.c_str(),
.serial_number = serial_number.c_str(),
.fw_version = fw_version,
.usb_version = usb_version,
.usb_class = usb_class,
.usb_subclass = usb_subclass,
.usb_protocol = usb_protocol,
.usb_attributes = usb_attributes,
.usb_power_ma = usb_power_ma,
.webusb_enabled = webusb_enabled,
.webusb_url = webusb_url.c_str()
};
_started = tinyusb_init(&tinyusb_device_config) == ESP_OK;
}
return _started;
}
void ESPUSB::onEvent(esp_event_handler_t callback){
onEvent(ARDUINO_USB_ANY_EVENT, callback);
}
void ESPUSB::onEvent(arduino_usb_event_t event, esp_event_handler_t callback){
arduino_usb_event_handler_register_with(ARDUINO_USB_EVENTS, event, callback, this);
}
ESPUSB::operator bool() const
{
return _started && tinyusb_device_mounted;
}
bool ESPUSB::enableDFU(){
#if CFG_TUD_DFU_RUNTIME
return tinyusb_enable_interface(USB_INTERFACE_DFU, TUD_DFU_RT_DESC_LEN, load_dfu_descriptor) == ESP_OK;
#endif /* CFG_TUD_DFU_RUNTIME */
return false;
}
bool ESPUSB::VID(uint16_t v){
if(!_started){
vid = v;
}
return !_started;
}
uint16_t ESPUSB::VID(void){
return vid;
}
bool ESPUSB::PID(uint16_t p){
if(!_started){
pid = p;
}
return !_started;
}
uint16_t ESPUSB::PID(void){
return pid;
}
bool ESPUSB::firmwareVersion(uint16_t version){
if(!_started){
fw_version = version;
}
return !_started;
}
uint16_t ESPUSB::firmwareVersion(void){
return fw_version;
}
bool ESPUSB::usbVersion(uint16_t version){
if(!_started){
usb_version = version;
}
return !_started;
}
uint16_t ESPUSB::usbVersion(void){
return usb_version;
}
bool ESPUSB::usbPower(uint16_t mA){
if(!_started){
usb_power_ma = mA;
}
return !_started;
}
uint16_t ESPUSB::usbPower(void){
return usb_power_ma;
}
bool ESPUSB::usbClass(uint8_t _class){
if(!_started){
usb_class = _class;
}
return !_started;
}
uint8_t ESPUSB::usbClass(void){
return usb_class;
}
bool ESPUSB::usbSubClass(uint8_t subClass){
if(!_started){
usb_subclass = subClass;
}
return !_started;
}
uint8_t ESPUSB::usbSubClass(void){
return usb_subclass;
}
bool ESPUSB::usbProtocol(uint8_t protocol){
if(!_started){
usb_protocol = protocol;
}
return !_started;
}
uint8_t ESPUSB::usbProtocol(void){
return usb_protocol;
}
bool ESPUSB::usbAttributes(uint8_t attr){
if(!_started){
usb_attributes = attr;
}
return !_started;
}
uint8_t ESPUSB::usbAttributes(void){
return usb_attributes;
}
bool ESPUSB::webUSB(bool enabled){
if(!_started){
webusb_enabled = enabled;
if(enabled && usb_version < 0x0210){
usb_version = 0x0210;
}
}
return !_started;
}
bool ESPUSB::webUSB(void){
return webusb_enabled;
}
bool ESPUSB::productName(const char * name){
if(!_started){
product_name = name;
}
return !_started;
}
const char * ESPUSB::productName(void){
return product_name.c_str();
}
bool ESPUSB::manufacturerName(const char * name){
if(!_started){
manufacturer_name = name;
}
return !_started;
}
const char * ESPUSB::manufacturerName(void){
return manufacturer_name.c_str();
}
bool ESPUSB::serialNumber(const char * name){
if(!_started){
serial_number = name;
}
return !_started;
}
const char * ESPUSB::serialNumber(void){
return serial_number.c_str();
}
bool ESPUSB::webUSBURL(const char * name){
if(!_started){
webusb_url = name;
}
return !_started;
}
const char * ESPUSB::webUSBURL(void){
return webusb_url.c_str();
}
ESPUSB USB;
#endif /* CONFIG_TINYUSB_ENABLED */

118
cores/esp32/USB.h Normal file
View File

@ -0,0 +1,118 @@
// Copyright 2015-2020 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "sdkconfig.h"
#if CONFIG_TINYUSB_ENABLED
#include "Arduino.h"
#include "USBCDC.h"
#include "esp_event.h"
ESP_EVENT_DECLARE_BASE(ARDUINO_USB_EVENTS);
typedef enum {
ARDUINO_USB_ANY_EVENT = ESP_EVENT_ANY_ID,
ARDUINO_USB_STARTED_EVENT = 0,
ARDUINO_USB_STOPPED_EVENT,
ARDUINO_USB_SUSPEND_EVENT,
ARDUINO_USB_RESUME_EVENT,
ARDUINO_USB_MAX_EVENT,
} arduino_usb_event_t;
typedef union {
struct {
bool remote_wakeup_en;
} suspend;
} arduino_usb_event_data_t;
class ESPUSB {
public:
ESPUSB(size_t event_task_stack_size=2048, uint8_t event_task_priority=5);
~ESPUSB();
void onEvent(esp_event_handler_t callback);
void onEvent(arduino_usb_event_t event, esp_event_handler_t callback);
bool VID(uint16_t v);
uint16_t VID(void);
bool PID(uint16_t p);
uint16_t PID(void);
bool firmwareVersion(uint16_t version);
uint16_t firmwareVersion(void);
bool usbVersion(uint16_t version);
uint16_t usbVersion(void);
bool usbPower(uint16_t mA);
uint16_t usbPower(void);
bool usbClass(uint8_t _class);
uint8_t usbClass(void);
bool usbSubClass(uint8_t subClass);
uint8_t usbSubClass(void);
bool usbProtocol(uint8_t protocol);
uint8_t usbProtocol(void);
bool usbAttributes(uint8_t attr);
uint8_t usbAttributes(void);
bool webUSB(bool enabled);
bool webUSB(void);
bool productName(const char * name);
const char * productName(void);
bool manufacturerName(const char * name);
const char * manufacturerName(void);
bool serialNumber(const char * name);
const char * serialNumber(void);
bool webUSBURL(const char * name);
const char * webUSBURL(void);
bool enableDFU();
bool begin();
operator bool() const;
private:
uint16_t vid;
uint16_t pid;
String product_name;
String manufacturer_name;
String serial_number;
uint16_t fw_version;
uint16_t usb_version;
uint8_t usb_class;
uint8_t usb_subclass;
uint8_t usb_protocol;
uint8_t usb_attributes;
uint16_t usb_power_ma;
bool webusb_enabled;
String webusb_url;
bool _started;
size_t _task_stack_size;
uint8_t _event_task_priority;
};
extern ESPUSB USB;
#endif /* CONFIG_TINYUSB_ENABLED */

373
cores/esp32/USBCDC.cpp Normal file
View File

@ -0,0 +1,373 @@
// Copyright 2015-2020 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "esp32-hal.h"
#include "esp32-hal-tinyusb.h"
#include "USB.h"
#include "USBCDC.h"
#if CONFIG_TINYUSB_ENABLED
ESP_EVENT_DEFINE_BASE(ARDUINO_USB_CDC_EVENTS);
esp_err_t arduino_usb_event_post(esp_event_base_t event_base, int32_t event_id, void *event_data, size_t event_data_size, TickType_t ticks_to_wait);
esp_err_t arduino_usb_event_handler_register_with(esp_event_base_t event_base, int32_t event_id, esp_event_handler_t event_handler, void *event_handler_arg);
#if CFG_TUD_CDC
#define MAX_USB_CDC_DEVICES 2
USBCDC * devices[MAX_USB_CDC_DEVICES] = {NULL, NULL};
static uint16_t load_cdc_descriptor(uint8_t * dst, uint8_t * itf)
{
uint8_t str_index = tinyusb_add_string_descriptor("TinyUSB CDC");
// Interface number, string index, attributes, detach timeout, transfer size */
uint8_t descriptor[TUD_CDC_DESC_LEN] = {
// Interface number, string index, EP notification address and size, EP data address (out, in) and size.
TUD_CDC_DESCRIPTOR(*itf, str_index, 0x85, 64, 0x03, 0x84, 64)
};
*itf+=2;
memcpy(dst, descriptor, TUD_CDC_DESC_LEN);
return TUD_CDC_DESC_LEN;
}
// Invoked when line state DTR & RTS are changed via SET_CONTROL_LINE_STATE
void tud_cdc_line_state_cb(uint8_t itf, bool dtr, bool rts)
{
//isr_log_v("itf: %u, dtr: %u, rts: %u", itf, dtr, rts);
if(itf < MAX_USB_CDC_DEVICES && devices[itf] != NULL){
devices[itf]->_onLineState(dtr, rts);
}
}
// Invoked when line coding is change via SET_LINE_CODING
void tud_cdc_line_coding_cb(uint8_t itf, cdc_line_coding_t const* p_line_coding)
{
//isr_log_v("itf: %u, bit_rate: %u, data_bits: %u, stop_bits: %u, parity: %u", itf, p_line_coding->bit_rate, p_line_coding->data_bits, p_line_coding->stop_bits, p_line_coding->parity);
if(itf < MAX_USB_CDC_DEVICES && devices[itf] != NULL){
devices[itf]->_onLineCoding(p_line_coding->bit_rate, p_line_coding->stop_bits, p_line_coding->parity, p_line_coding->data_bits);
}
}
// Invoked when received new data
void tud_cdc_rx_cb(uint8_t itf)
{
//isr_log_v("itf: %u", itf);
if(itf < MAX_USB_CDC_DEVICES && devices[itf] != NULL){
devices[itf]->_onRX();
}
}
// Invoked when received send break
void tud_cdc_send_break_cb(uint8_t itf, uint16_t duration_ms){
//isr_log_v("itf: %u, duration_ms: %u", itf, duration_ms);
}
// Invoked when space becomes available in TX buffer
void tud_cdc_tx_complete_cb(uint8_t itf){
//isr_log_v("itf: %u", itf);
if(itf < MAX_USB_CDC_DEVICES && devices[itf] != NULL){
xSemaphoreGive(devices[itf]->tx_sem);
devices[itf]->_onTX();
}
}
static size_t tinyusb_cdc_write(uint8_t itf, const uint8_t *buffer, size_t size){
if(itf >= MAX_USB_CDC_DEVICES){
return 0;
}
if(!tud_cdc_n_connected(itf)){
return 0;
}
size_t tosend = size, sofar = 0;
while(tosend){
uint32_t space = tud_cdc_n_write_available(itf);
if(!space){
delay(1);
continue;
}
if(tosend < space){
space = tosend;
}
uint32_t sent = tud_cdc_n_write(itf, buffer + sofar, space);
if(!sent){
return sofar;
}
sofar += sent;
tosend -= sent;
tud_cdc_n_write_flush(itf);
xSemaphoreTake(devices[itf]->tx_sem, portMAX_DELAY);
}
return sofar;
}
static void ARDUINO_ISR_ATTR cdc0_write_char(char c)
{
tinyusb_cdc_write(0, (const uint8_t *)&c, 1);
}
//void tud_cdc_rx_wanted_cb(uint8_t itf, char wanted_char);
static void usb_unplugged_cb(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data){
((USBCDC*)arg)->_onUnplugged();
}
USBCDC::USBCDC(uint8_t itfn) : itf(itfn), bit_rate(0), stop_bits(0), parity(0), data_bits(0), dtr(false), rts(false), connected(false), reboot_enable(true), rx_queue(NULL) {
tinyusb_enable_interface(USB_INTERFACE_CDC, TUD_CDC_DESC_LEN, load_cdc_descriptor);
if(itf < MAX_USB_CDC_DEVICES){
devices[itf] = this;
tx_sem = NULL;
arduino_usb_event_handler_register_with(ARDUINO_USB_EVENTS, ARDUINO_USB_STOPPED_EVENT, usb_unplugged_cb, this);
}
}
void USBCDC::onEvent(esp_event_handler_t callback){
onEvent(ARDUINO_USB_CDC_ANY_EVENT, callback);
}
void USBCDC::onEvent(arduino_usb_cdc_event_t event, esp_event_handler_t callback){
arduino_usb_event_handler_register_with(ARDUINO_USB_CDC_EVENTS, event, callback, this);
}
size_t USBCDC::setRxBufferSize(size_t rx_queue_len){
if(rx_queue){
return 0;
}
rx_queue = xQueueCreate(rx_queue_len, sizeof(uint8_t));
if(!rx_queue){
return 0;
}
return rx_queue_len;
}
void USBCDC::begin(unsigned long baud)
{
setRxBufferSize(256);//default if not preset
if(tx_sem == NULL){
tx_sem = xSemaphoreCreateBinary();
xSemaphoreTake(tx_sem, 0);
}
}
void USBCDC::end()
{
if (tx_sem != NULL) {
vSemaphoreDelete(tx_sem);
tx_sem = NULL;
}
}
void USBCDC::_onUnplugged(void){
if(connected){
connected = false;
dtr = false;
rts = false;
arduino_usb_cdc_event_data_t p = {0};
arduino_usb_event_post(ARDUINO_USB_CDC_EVENTS, ARDUINO_USB_CDC_DISCONNECTED_EVENT, &p, sizeof(arduino_usb_cdc_event_data_t), portMAX_DELAY);
}
}
enum { CDC_LINE_IDLE, CDC_LINE_1, CDC_LINE_2, CDC_LINE_3 };
void USBCDC::_onLineState(bool _dtr, bool _rts){
static uint8_t lineState = CDC_LINE_IDLE;
dtr = _dtr;
rts = _rts;
if(reboot_enable){
if(!dtr && rts){
if(lineState == CDC_LINE_IDLE){
lineState++;
} else {
lineState = CDC_LINE_IDLE;
}
} else if(dtr && rts){
if(lineState == CDC_LINE_1){
lineState++;
} else {
lineState = CDC_LINE_IDLE;
}
} else if(dtr && !rts){
if(lineState == CDC_LINE_2){
lineState++;
} else {
lineState = CDC_LINE_IDLE;
}
} else if(!dtr && !rts){
if(lineState == CDC_LINE_3){
usb_persist_restart(RESTART_BOOTLOADER);
} else {
lineState = CDC_LINE_IDLE;
}
}
}
if(lineState == CDC_LINE_IDLE){
if(dtr && rts && !connected){
connected = true;
arduino_usb_cdc_event_data_t p = {0};
arduino_usb_event_post(ARDUINO_USB_CDC_EVENTS, ARDUINO_USB_CDC_CONNECTED_EVENT, &p, sizeof(arduino_usb_cdc_event_data_t), portMAX_DELAY);
} else if(!dtr && !rts && connected){
connected = false;
arduino_usb_cdc_event_data_t p = {0};
arduino_usb_event_post(ARDUINO_USB_CDC_EVENTS, ARDUINO_USB_CDC_DISCONNECTED_EVENT, &p, sizeof(arduino_usb_cdc_event_data_t), portMAX_DELAY);
}
arduino_usb_cdc_event_data_t l = {0};
l.line_state.dtr = dtr;
l.line_state.rts = rts;
arduino_usb_event_post(ARDUINO_USB_CDC_EVENTS, ARDUINO_USB_CDC_LINE_STATE_EVENT, &l, sizeof(arduino_usb_cdc_event_data_t), portMAX_DELAY);
}
}
void USBCDC::_onLineCoding(uint32_t _bit_rate, uint8_t _stop_bits, uint8_t _parity, uint8_t _data_bits){
if(bit_rate != _bit_rate || data_bits != _data_bits || stop_bits != _stop_bits || parity != _parity){
// ArduinoIDE sends LineCoding with 1200bps baud to reset the device
if(_bit_rate == 1200){
usb_persist_restart(RESTART_BOOTLOADER);
} else {
bit_rate = _bit_rate;
data_bits = _data_bits;
stop_bits = _stop_bits;
parity = _parity;
arduino_usb_cdc_event_data_t p = {0};
p.line_coding.bit_rate = bit_rate;
p.line_coding.data_bits = data_bits;
p.line_coding.stop_bits = stop_bits;
p.line_coding.parity = parity;
arduino_usb_event_post(ARDUINO_USB_CDC_EVENTS, ARDUINO_USB_CDC_LINE_CODING_EVENT, &p, sizeof(arduino_usb_cdc_event_data_t), portMAX_DELAY);
}
}
}
void USBCDC::_onRX(){
uint8_t buf[CONFIG_TINYUSB_CDC_RX_BUFSIZE+1];
uint32_t count = tud_cdc_n_read(itf, buf, CONFIG_TINYUSB_CDC_RX_BUFSIZE);
for(uint32_t i=0; i<count; i++){
if(rx_queue == NULL || !xQueueSend(rx_queue, buf+i, 0)){
return;
}
}
arduino_usb_cdc_event_data_t p = {0};
p.rx.len = count;
arduino_usb_event_post(ARDUINO_USB_CDC_EVENTS, ARDUINO_USB_CDC_RX_EVENT, &p, sizeof(arduino_usb_cdc_event_data_t), portMAX_DELAY);
}
void USBCDC::_onTX(){
arduino_usb_cdc_event_data_t p = {0};
arduino_usb_event_post(ARDUINO_USB_CDC_EVENTS, ARDUINO_USB_CDC_TX_EVENT, &p, sizeof(arduino_usb_cdc_event_data_t), portMAX_DELAY);
}
void USBCDC::enableReboot(bool enable){
reboot_enable = enable;
}
bool USBCDC::rebootEnabled(void){
return reboot_enable;
}
int USBCDC::available(void)
{
if(itf >= MAX_USB_CDC_DEVICES || rx_queue == NULL){
return -1;
}
return uxQueueMessagesWaiting(rx_queue);
}
int USBCDC::peek(void)
{
if(itf >= MAX_USB_CDC_DEVICES || rx_queue == NULL){
return -1;
}
uint8_t c;
if(xQueuePeek(rx_queue, &c, 0)) {
return c;
}
return -1;
}
int USBCDC::read(void)
{
if(itf >= MAX_USB_CDC_DEVICES || rx_queue == NULL){
return -1;
}
uint8_t c = 0;
if(xQueueReceive(rx_queue, &c, 0)) {
return c;
}
return -1;
}
size_t USBCDC::read(uint8_t *buffer, size_t size)
{
if(itf >= MAX_USB_CDC_DEVICES || rx_queue == NULL){
return -1;
}
uint8_t c = 0;
size_t count = 0;
while(count < size && xQueueReceive(rx_queue, &c, 0)){
buffer[count++] = c;
}
return count;
}
void USBCDC::flush(void)
{
if(itf >= MAX_USB_CDC_DEVICES){
return;
}
tud_cdc_n_write_flush(itf);
}
int USBCDC::availableForWrite(void)
{
if(itf >= MAX_USB_CDC_DEVICES){
return -1;
}
return tud_cdc_n_write_available(itf);
}
size_t USBCDC::write(const uint8_t *buffer, size_t size)
{
return tinyusb_cdc_write(itf, buffer, size);
}
size_t USBCDC::write(uint8_t c)
{
return write(&c, 1);
}
uint32_t USBCDC::baudRate()
{
return bit_rate;
}
void USBCDC::setDebugOutput(bool en)
{
if(en) {
uartSetDebug(NULL);
ets_install_putc1((void (*)(char)) &cdc0_write_char);
} else {
ets_install_putc1(NULL);
}
}
USBCDC::operator bool() const
{
if(itf >= MAX_USB_CDC_DEVICES){
return false;
}
return connected;
}
#if ARDUINO_SERIAL_PORT //Serial used for USB CDC
USBCDC Serial(0);
#endif
#endif /* CONFIG_TINYUSB_CDC_ENABLED */
#endif /* CONFIG_TINYUSB_ENABLED */

136
cores/esp32/USBCDC.h Normal file
View File

@ -0,0 +1,136 @@
// Copyright 2015-2020 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <inttypes.h>
#include "Stream.h"
#include "esp32-hal.h"
#if CONFIG_TINYUSB_CDC_ENABLED
#include "esp_event.h"
ESP_EVENT_DECLARE_BASE(ARDUINO_USB_CDC_EVENTS);
typedef enum {
ARDUINO_USB_CDC_ANY_EVENT = ESP_EVENT_ANY_ID,
ARDUINO_USB_CDC_CONNECTED_EVENT = 0,
ARDUINO_USB_CDC_DISCONNECTED_EVENT,
ARDUINO_USB_CDC_LINE_STATE_EVENT,
ARDUINO_USB_CDC_LINE_CODING_EVENT,
ARDUINO_USB_CDC_RX_EVENT,
ARDUINO_USB_CDC_TX_EVENT,
ARDUINO_USB_CDC_MAX_EVENT,
} arduino_usb_cdc_event_t;
typedef union {
struct {
bool dtr;
bool rts;
} line_state;
struct {
uint32_t bit_rate;
uint8_t stop_bits; ///< 0: 1 stop bit - 1: 1.5 stop bits - 2: 2 stop bits
uint8_t parity; ///< 0: None - 1: Odd - 2: Even - 3: Mark - 4: Space
uint8_t data_bits; ///< can be 5, 6, 7, 8 or 16
} line_coding;
struct {
size_t len;
} rx;
} arduino_usb_cdc_event_data_t;
class USBCDC: public Stream
{
public:
USBCDC(uint8_t itf=0);
void onEvent(esp_event_handler_t callback);
void onEvent(arduino_usb_cdc_event_t event, esp_event_handler_t callback);
size_t setRxBufferSize(size_t);
void begin(unsigned long baud=0);
void end();
int available(void);
int availableForWrite(void);
int peek(void);
int read(void);
size_t read(uint8_t *buffer, size_t size);
size_t write(uint8_t);
size_t write(const uint8_t *buffer, size_t size);
void flush(void);
inline size_t read(char * buffer, size_t size)
{
return read((uint8_t*) buffer, size);
}
inline size_t write(const char * buffer, size_t size)
{
return write((uint8_t*) buffer, size);
}
inline size_t write(const char * s)
{
return write((uint8_t*) s, strlen(s));
}
inline size_t write(unsigned long n)
{
return write((uint8_t) n);
}
inline size_t write(long n)
{
return write((uint8_t) n);
}
inline size_t write(unsigned int n)
{
return write((uint8_t) n);
}
inline size_t write(int n)
{
return write((uint8_t) n);
}
uint32_t baudRate();
void setDebugOutput(bool);
operator bool() const;
void enableReboot(bool enable);
bool rebootEnabled(void);
//internal methods
void _onDFU(void);
void _onLineState(bool _dtr, bool _rts);
void _onLineCoding(uint32_t _bit_rate, uint8_t _stop_bits, uint8_t _parity, uint8_t _data_bits);
void _onRX(void);
void _onTX(void);
void _onUnplugged(void);
xSemaphoreHandle tx_sem;
protected:
uint8_t itf;
uint32_t bit_rate;
uint8_t stop_bits; ///< 0: 1 stop bit - 1: 1.5 stop bits - 2: 2 stop bits
uint8_t parity; ///< 0: None - 1: Odd - 2: Even - 3: Mark - 4: Space
uint8_t data_bits; ///< can be 5, 6, 7, 8 or 16
bool dtr;
bool rts;
bool connected;
bool reboot_enable;
xQueueHandle rx_queue;
};
#if ARDUINO_SERIAL_PORT //Serial used for USB CDC
extern USBCDC Serial;
#endif
#endif /* CONFIG_TINYUSB_CDC_ENABLED */

View File

@ -43,6 +43,7 @@ class UDP: public Stream
public:
virtual uint8_t begin(uint16_t) =0; // initialize, start listening on specified port. Returns 1 if successful, 0 if there are no sockets available to use
virtual uint8_t beginMulticast(IPAddress, uint16_t) { return 0; } // initialize, start listening on specified multicast IP address and port. Returns 1 if successful, 0 on failure
virtual void stop() =0; // Finish with the UDP socket
// Sending UDP packets

View File

@ -27,6 +27,7 @@ extern "C" {
#include <stdlib.h>
#include "esp_system.h"
}
#include "esp32-hal-log.h"
void randomSeed(unsigned long seed)
{
@ -66,19 +67,22 @@ long random(long howsmall, long howbig)
}
long map(long x, long in_min, long in_max, long out_min, long out_max) {
long divisor = (in_max - in_min);
const long dividend = out_max - out_min;
const long divisor = in_max - in_min;
const long delta = x - in_min;
if(divisor == 0){
log_e("Invalid map input range, min == max");
return -1; //AVR returns -1, SAM returns 0
}
return (x - in_min) * (out_max - out_min) / divisor + out_min;
return (delta * dividend + (divisor / 2)) / divisor + out_min;
}
unsigned int makeWord(unsigned int w)
uint16_t makeWord(uint16_t w)
{
return w;
}
unsigned int makeWord(unsigned char h, unsigned char l)
uint16_t makeWord(uint8_t h, uint8_t l)
{
return (h << 8) | l;
}

View File

@ -59,9 +59,7 @@ String::String(StringSumHelper &&rval) {
String::String(char c) {
init();
char buf[2];
buf[0] = c;
buf[1] = 0;
char buf[] = { c, '\0' };
*this = buf;
}
@ -130,9 +128,9 @@ String::~String() {
inline void String::init(void) {
setSSO(false);
setBuffer(nullptr);
setCapacity(0);
setLen(0);
setBuffer(nullptr);
}
void String::invalidate(void) {
@ -168,8 +166,8 @@ unsigned char String::changeBuffer(unsigned int maxStrLen) {
free(wbuffer());
uint16_t oldLen = len();
setSSO(true);
setLen(oldLen);
memcpy(wbuffer(), temp, maxStrLen);
setLen(oldLen);
return 1;
}
}
@ -193,8 +191,8 @@ unsigned char String::changeBuffer(unsigned int maxStrLen) {
}
setSSO(false);
setCapacity(newSize - 1);
setLen(oldLen); // Needed in case of SSO where len() never existed
setBuffer(newbuffer);
setLen(oldLen); // Needed in case of SSO where len() never existed
return 1;
}
return 0;
@ -209,8 +207,8 @@ String & String::copy(const char *cstr, unsigned int length) {
invalidate();
return *this;
}
setLen(length);
memmove(wbuffer(), cstr, length + 1);
setLen(length);
return *this;
}
@ -219,8 +217,8 @@ String & String::copy(const __FlashStringHelper *pstr, unsigned int length) {
invalidate();
return *this;
}
setLen(length);
memcpy_P(wbuffer(), (PGM_P)pstr, length + 1); // We know wbuffer() cannot ever be in PROGMEM, so memcpy safe here
setLen(length);
return *this;
}
@ -250,8 +248,8 @@ void String::move(String &rhs) {
setLen(rhs.len());
rhs.setSSO(false);
rhs.setCapacity(0);
rhs.setLen(0);
rhs.setBuffer(nullptr);
rhs.setLen(0);
}
#endif
@ -290,10 +288,11 @@ String & String::operator =(const char *cstr) {
return *this;
}
String & String::operator = (const __FlashStringHelper *pstr)
{
if (pstr) copy(pstr, strlen_P((PGM_P)pstr));
else invalidate();
String & String::operator =(const __FlashStringHelper *pstr) {
if(pstr)
copy(pstr, strlen_P((PGM_P)pstr));
else
invalidate();
return *this;
}
@ -347,22 +346,18 @@ unsigned char String::concat(const char *cstr) {
}
unsigned char String::concat(char c) {
char buf[2];
buf[0] = c;
buf[1] = 0;
char buf[] = { c, '\0' };
return concat(buf, 1);
}
unsigned char String::concat(unsigned char num) {
char buf[1 + 3 * sizeof(unsigned char)];
sprintf(buf, "%d", num);
return concat(buf, strlen(buf));
return concat(buf, sprintf(buf, "%d", num));
}
unsigned char String::concat(int num) {
char buf[2 + 3 * sizeof(int)];
sprintf(buf, "%d", num);
return concat(buf, strlen(buf));
return concat(buf, sprintf(buf, "%d", num));
}
unsigned char String::concat(unsigned int num) {
@ -373,8 +368,7 @@ unsigned char String::concat(unsigned int num) {
unsigned char String::concat(long num) {
char buf[2 + 3 * sizeof(long)];
sprintf(buf, "%ld", num);
return concat(buf, strlen(buf));
return concat(buf, sprintf(buf, "%ld", num));
}
unsigned char String::concat(unsigned long num) {
@ -555,7 +549,7 @@ unsigned char String::equalsConstantTime(const String &s2) const {
//at this point lengths are the same
if(len() == 0)
return 1;
//at this point lenghts are the same and non-zero
//at this point lengths are the same and non-zero
const char *p1 = buffer();
const char *p2 = s2.buffer();
unsigned int equalchars = 0;
@ -744,6 +738,7 @@ void String::replace(const String& find, const String& replace) {
}
} else if(diff < 0) {
char *writeTo = wbuffer();
unsigned int l = len();
while((foundAt = strstr(readFrom, find.buffer())) != NULL) {
unsigned int n = foundAt - readFrom;
memmove(writeTo, readFrom, n);
@ -751,9 +746,10 @@ void String::replace(const String& find, const String& replace) {
memmove(writeTo, replace.buffer(), replace.len());
writeTo += replace.len();
readFrom = foundAt + find.len();
setLen(len() + diff);
l += diff;
}
memmove(writeTo, readFrom, strlen(readFrom)+1);
setLen(l);
} else {
unsigned int size = len(); // compute size needed for result
while((foundAt = strstr(readFrom, find.buffer())) != NULL) {
@ -796,8 +792,8 @@ void String::remove(unsigned int index, unsigned int count) {
}
char *writeTo = wbuffer() + index;
unsigned int newlen = len() - count;
setLen(newlen);
memmove(writeTo, wbuffer() + index + count, newlen - index);
setLen(newlen);
wbuffer()[newlen] = 0;
}
@ -827,9 +823,9 @@ void String::trim(void) {
while(isspace(*end) && end >= begin)
end--;
unsigned int newlen = end + 1 - begin;
setLen(newlen);
if(begin > buffer())
memmove(wbuffer(), begin, newlen);
setLen(newlen);
wbuffer()[newlen] = 0;
}

View File

@ -203,8 +203,20 @@ class String {
unsigned char equalsIgnoreCase(const String &s) const;
unsigned char equalsConstantTime(const String &s) const;
unsigned char startsWith(const String &prefix) const;
unsigned char startsWith(const char *prefix) const {
return this->startsWith(String(prefix));
}
unsigned char startsWith(const __FlashStringHelper *prefix) const {
return this->startsWith(String(prefix));
}
unsigned char startsWith(const String &prefix, unsigned int offset) const;
unsigned char endsWith(const String &suffix) const;
unsigned char endsWith(const char *suffix) const {
return this->endsWith(String(suffix));
}
unsigned char endsWith(const __FlashStringHelper * suffix) const {
return this->endsWith(String(suffix));
}
// character access
char charAt(unsigned int index) const;
@ -238,7 +250,22 @@ class String {
// modification
void replace(char find, char replace);
void replace(const String& find, const String& replace);
void replace(const String &find, const String &replace);
void replace(const char *find, const String &replace) {
this->replace(String(find), replace);
}
void replace(const __FlashStringHelper *find, const String &replace) {
this->replace(String(find), replace);
}
void replace(const char *find, const char *replace) {
this->replace(String(find), String(replace));
}
void replace(const __FlashStringHelper *find, const char *replace) {
this->replace(String(find), String(replace));
}
void replace(const __FlashStringHelper *find, const __FlashStringHelper *replace) {
this->replace(String(find), String(replace));
}
void remove(unsigned int index);
void remove(unsigned int index, unsigned int count);
void toLowerCase(void);
@ -254,8 +281,8 @@ class String {
// Contains the string info when we're not in SSO mode
struct _ptr {
char * buff;
uint16_t cap;
uint16_t len;
uint32_t cap;
uint32_t len;
};
// This allows strings up up to 11 (10 + \0 termination) without any extra space.
enum { SSOSIZE = sizeof(struct _ptr) + 4 - 1 }; // Characters to allocate space for SSO, must be 12 or more
@ -264,7 +291,11 @@ class String {
unsigned char len : 7; // Ensure only one byte is allocated by GCC for the bitfields
unsigned char isSSO : 1;
} __attribute__((packed)); // Ensure that GCC doesn't expand the flag byte to a 32-bit word for alignment issues
enum { CAPACITY_MAX = 65535 }; // If typeof(cap) changed from uint16_t, be sure to update this enum to the max value storable in the type
#ifdef BOARD_HAS_PSRAM
enum { CAPACITY_MAX = 3145728 };
#else
enum { CAPACITY_MAX = 65535 };
#endif
union {
struct _ptr ptr;
struct _sso sso;
@ -274,7 +305,17 @@ class String {
inline unsigned int len() const { return isSSO() ? sso.len : ptr.len; }
inline unsigned int capacity() const { return isSSO() ? (unsigned int)SSOSIZE - 1 : ptr.cap; } // Size of max string not including terminal NUL
inline void setSSO(bool set) { sso.isSSO = set; }
inline void setLen(int len) { if (isSSO()) sso.len = len; else ptr.len = len; }
inline void setLen(int len) {
if (isSSO()) {
sso.len = len;
sso.buff[len] = 0;
} else {
ptr.len = len;
if (ptr.buff) {
ptr.buff[len] = 0;
}
}
}
inline void setCapacity(int cap) { if (!isSSO()) ptr.cap = cap; }
inline void setBuffer(char *buff) { if (!isSSO()) ptr.buff = buff; }
// Buffer accessor functions

View File

@ -31,11 +31,11 @@ extern "C" {
/**
* convert input data to base64
* @param data uint8_t *
* @param data const uint8_t *
* @param length size_t
* @return String
*/
String base64::encode(uint8_t * data, size_t length)
String base64::encode(const uint8_t * data, size_t length)
{
size_t size = base64_encode_expected_len(length) + 1;
char * buffer = (char *) malloc(size);
@ -54,10 +54,10 @@ String base64::encode(uint8_t * data, size_t length)
/**
* convert input data to base64
* @param text String
* @param text const String&
* @return String
*/
String base64::encode(String text)
String base64::encode(const String& text)
{
return base64::encode((uint8_t *) text.c_str(), text.length());
}

View File

@ -4,8 +4,8 @@
class base64
{
public:
static String encode(uint8_t * data, size_t length);
static String encode(String text);
static String encode(const uint8_t * data, size_t length);
static String encode(const String& text);
private:
};

View File

@ -15,103 +15,81 @@
#include "esp32-hal-adc.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "rom/ets_sys.h"
#include "esp_attr.h"
#include "esp_intr.h"
#include "soc/rtc_io_reg.h"
#include "soc/rtc_cntl_reg.h"
#include "driver/adc.h"
#include "esp_system.h"
#ifdef ESP_IDF_VERSION_MAJOR // IDF 4+
#if CONFIG_IDF_TARGET_ESP32 // ESP32/PICO-D4
#include "esp_adc_cal.h"
#include "soc/sens_reg.h"
#include "soc/rtc_io_reg.h"
#include "esp32/rom/ets_sys.h"
#include "esp_intr_alloc.h"
#define DEFAULT_VREF 1100
static esp_adc_cal_characteristics_t *__analogCharacteristics[2] = {NULL, NULL};
static uint16_t __analogVRef = 0;
static uint8_t __analogVRefPin = 0;
#elif CONFIG_IDF_TARGET_ESP32S2
#include "esp32s2/rom/ets_sys.h"
#include "soc/sens_reg.h"
#include "soc/rtc_io_reg.h"
#elif CONFIG_IDF_TARGET_ESP32C3
#include "esp32c3/rom/ets_sys.h"
#else
#error Target CONFIG_IDF_TARGET is not supported
#endif
#else // ESP32 Before IDF 4.0
#include "rom/ets_sys.h"
#include "esp_intr.h"
#endif
static uint8_t __analogAttenuation = 3;//11db
static uint8_t __analogWidth = 3;//12 bits
static uint8_t __analogCycles = 8;
static uint8_t __analogSamples = 0;//1 sample
static uint8_t __analogClockDiv = 1;
static adc_attenuation_t __pin_attenuation[SOC_GPIO_PIN_COUNT];
// Width of returned answer ()
static uint8_t __analogReturnedWidth = 12;
void __analogSetClockDiv(uint8_t clockDiv){
if(!clockDiv){
clockDiv = 1;
}
__analogClockDiv = clockDiv;
#if CONFIG_IDF_TARGET_ESP32 || CONFIG_IDF_TARGET_ESP32S2
adc_set_clk_div(__analogClockDiv);
#endif
}
void __analogSetAttenuation(adc_attenuation_t attenuation)
{
__analogAttenuation = attenuation & 3;
}
#if CONFIG_IDF_TARGET_ESP32
void __analogSetWidth(uint8_t bits){
if(bits < 9){
bits = 9;
} else if(bits > 12){
bits = 12;
}
__analogReturnedWidth = bits;
__analogWidth = bits - 9;
SET_PERI_REG_BITS(SENS_SAR_START_FORCE_REG, SENS_SAR1_BIT_WIDTH, __analogWidth, SENS_SAR1_BIT_WIDTH_S);
SET_PERI_REG_BITS(SENS_SAR_READ_CTRL_REG, SENS_SAR1_SAMPLE_BIT, __analogWidth, SENS_SAR1_SAMPLE_BIT_S);
SET_PERI_REG_BITS(SENS_SAR_START_FORCE_REG, SENS_SAR2_BIT_WIDTH, __analogWidth, SENS_SAR2_BIT_WIDTH_S);
SET_PERI_REG_BITS(SENS_SAR_READ_CTRL2_REG, SENS_SAR2_SAMPLE_BIT, __analogWidth, SENS_SAR2_SAMPLE_BIT_S);
adc1_config_width(__analogWidth);
}
#endif
void __analogSetCycles(uint8_t cycles){
__analogCycles = cycles;
SET_PERI_REG_BITS(SENS_SAR_READ_CTRL_REG, SENS_SAR1_SAMPLE_CYCLE, __analogCycles, SENS_SAR1_SAMPLE_CYCLE_S);
SET_PERI_REG_BITS(SENS_SAR_READ_CTRL2_REG, SENS_SAR2_SAMPLE_CYCLE, __analogCycles, SENS_SAR2_SAMPLE_CYCLE_S);
}
void __analogSetSamples(uint8_t samples){
if(!samples){
return;
}
__analogSamples = samples - 1;
SET_PERI_REG_BITS(SENS_SAR_READ_CTRL_REG, SENS_SAR1_SAMPLE_NUM, __analogSamples, SENS_SAR1_SAMPLE_NUM_S);
SET_PERI_REG_BITS(SENS_SAR_READ_CTRL2_REG, SENS_SAR2_SAMPLE_NUM, __analogSamples, SENS_SAR2_SAMPLE_NUM_S);
}
void __analogSetClockDiv(uint8_t clockDiv){
if(!clockDiv){
return;
}
__analogClockDiv = clockDiv;
SET_PERI_REG_BITS(SENS_SAR_READ_CTRL_REG, SENS_SAR1_CLK_DIV, __analogClockDiv, SENS_SAR1_CLK_DIV_S);
SET_PERI_REG_BITS(SENS_SAR_READ_CTRL2_REG, SENS_SAR2_CLK_DIV, __analogClockDiv, SENS_SAR2_CLK_DIV_S);
}
void __analogSetAttenuation(adc_attenuation_t attenuation)
{
__analogAttenuation = attenuation & 3;
uint32_t att_data = 0;
int i = 10;
while(i--){
att_data |= __analogAttenuation << (i * 2);
}
WRITE_PERI_REG(SENS_SAR_ATTEN1_REG, att_data & 0xFFFF);//ADC1 has 8 channels
WRITE_PERI_REG(SENS_SAR_ATTEN2_REG, att_data);
}
void IRAM_ATTR __analogInit(){
void __analogInit(){
static bool initialized = false;
if(initialized){
return;
}
__analogSetAttenuation(__analogAttenuation);
__analogSetCycles(__analogCycles);
__analogSetSamples(__analogSamples + 1);//in samples
__analogSetClockDiv(__analogClockDiv);
__analogSetWidth(__analogWidth + 9);//in bits
SET_PERI_REG_MASK(SENS_SAR_READ_CTRL_REG, SENS_SAR1_DATA_INV);
SET_PERI_REG_MASK(SENS_SAR_READ_CTRL2_REG, SENS_SAR2_DATA_INV);
SET_PERI_REG_MASK(SENS_SAR_MEAS_START1_REG, SENS_MEAS1_START_FORCE_M); //SAR ADC1 controller (in RTC) is started by SW
SET_PERI_REG_MASK(SENS_SAR_MEAS_START1_REG, SENS_SAR1_EN_PAD_FORCE_M); //SAR ADC1 pad enable bitmap is controlled by SW
SET_PERI_REG_MASK(SENS_SAR_MEAS_START2_REG, SENS_MEAS2_START_FORCE_M); //SAR ADC2 controller (in RTC) is started by SW
SET_PERI_REG_MASK(SENS_SAR_MEAS_START2_REG, SENS_SAR2_EN_PAD_FORCE_M); //SAR ADC2 pad enable bitmap is controlled by SW
CLEAR_PERI_REG_MASK(SENS_SAR_MEAS_WAIT2_REG, SENS_FORCE_XPD_SAR_M); //force XPD_SAR=0, use XPD_FSM
SET_PERI_REG_BITS(SENS_SAR_MEAS_WAIT2_REG, SENS_FORCE_XPD_AMP, 0x2, SENS_FORCE_XPD_AMP_S); //force XPD_AMP=0
CLEAR_PERI_REG_MASK(SENS_SAR_MEAS_CTRL_REG, 0xfff << SENS_AMP_RST_FB_FSM_S); //clear FSM
SET_PERI_REG_BITS(SENS_SAR_MEAS_WAIT1_REG, SENS_SAR_AMP_WAIT1, 0x1, SENS_SAR_AMP_WAIT1_S);
SET_PERI_REG_BITS(SENS_SAR_MEAS_WAIT1_REG, SENS_SAR_AMP_WAIT2, 0x1, SENS_SAR_AMP_WAIT2_S);
SET_PERI_REG_BITS(SENS_SAR_MEAS_WAIT2_REG, SENS_SAR_AMP_WAIT3, 0x1, SENS_SAR_AMP_WAIT3_S);
while (GET_PERI_REG_BITS2(SENS_SAR_SLAVE_ADDR1_REG, 0x7, SENS_MEAS_STATUS_S) != 0); //wait det_fsm==
initialized = true;
__analogSetClockDiv(__analogClockDiv);
#if CONFIG_IDF_TARGET_ESP32
__analogSetWidth(__analogWidth + 9);//in bits
#endif
for(int i=0; i<SOC_GPIO_PIN_COUNT; i++){
__pin_attenuation[i] = ADC_ATTENDB_MAX;
}
}
void __analogSetPinAttenuation(uint8_t pin, adc_attenuation_t attenuation)
@ -120,23 +98,24 @@ void __analogSetPinAttenuation(uint8_t pin, adc_attenuation_t attenuation)
if(channel < 0 || attenuation > 3){
return ;
}
__analogInit();
if(channel > 7){
SET_PERI_REG_BITS(SENS_SAR_ATTEN2_REG, 3, attenuation, ((channel - 10) * 2));
if(channel > 9){
adc2_config_channel_atten(channel - 10, attenuation);
} else {
SET_PERI_REG_BITS(SENS_SAR_ATTEN1_REG, 3, attenuation, (channel * 2));
adc1_config_channel_atten(channel, attenuation);
}
__analogInit();
__pin_attenuation[pin] = attenuation;
}
bool IRAM_ATTR __adcAttachPin(uint8_t pin){
bool __adcAttachPin(uint8_t pin){
int8_t channel = digitalPinToAnalogChannel(pin);
if(channel < 0){
return false;//not adc pin
log_e("Pin %u is not ADC pin!", pin);
return false;
}
int8_t pad = digitalPinToTouchChannel(pin);
if(pad >= 0){
#if CONFIG_IDF_TARGET_ESP32
uint32_t touch = READ_PERI_REG(SENS_SAR_TOUCH_ENABLE_REG);
if(touch & (1 << pad)){
touch &= ~((1 << (pad + SENS_TOUCH_PAD_OUTEN2_S))
@ -144,130 +123,154 @@ bool IRAM_ATTR __adcAttachPin(uint8_t pin){
| (1 << (pad + SENS_TOUCH_PAD_WORKEN_S)));
WRITE_PERI_REG(SENS_SAR_TOUCH_ENABLE_REG, touch);
}
} else if(pin == 25){
#endif
}
#if CONFIG_IDF_TARGET_ESP32 || CONFIG_IDF_TARGET_ESP32S2
else if(pin == 25){
CLEAR_PERI_REG_MASK(RTC_IO_PAD_DAC1_REG, RTC_IO_PDAC1_XPD_DAC | RTC_IO_PDAC1_DAC_XPD_FORCE);//stop dac1
} else if(pin == 26){
CLEAR_PERI_REG_MASK(RTC_IO_PAD_DAC2_REG, RTC_IO_PDAC2_XPD_DAC | RTC_IO_PDAC2_DAC_XPD_FORCE);//stop dac2
}
#endif
pinMode(pin, ANALOG);
__analogInit();
__analogSetPinAttenuation(pin, (__pin_attenuation[pin] != ADC_ATTENDB_MAX)?__pin_attenuation[pin]:__analogAttenuation);
return true;
}
bool IRAM_ATTR __adcStart(uint8_t pin){
int8_t channel = digitalPinToAnalogChannel(pin);
if(channel < 0){
return false;//not adc pin
}
if(channel > 9){
channel -= 10;
CLEAR_PERI_REG_MASK(SENS_SAR_MEAS_START2_REG, SENS_MEAS2_START_SAR_M);
SET_PERI_REG_BITS(SENS_SAR_MEAS_START2_REG, SENS_SAR2_EN_PAD, (1 << channel), SENS_SAR2_EN_PAD_S);
SET_PERI_REG_MASK(SENS_SAR_MEAS_START2_REG, SENS_MEAS2_START_SAR_M);
} else {
CLEAR_PERI_REG_MASK(SENS_SAR_MEAS_START1_REG, SENS_MEAS1_START_SAR_M);
SET_PERI_REG_BITS(SENS_SAR_MEAS_START1_REG, SENS_SAR1_EN_PAD, (1 << channel), SENS_SAR1_EN_PAD_S);
SET_PERI_REG_MASK(SENS_SAR_MEAS_START1_REG, SENS_MEAS1_START_SAR_M);
}
return true;
}
bool IRAM_ATTR __adcBusy(uint8_t pin){
int8_t channel = digitalPinToAnalogChannel(pin);
if(channel < 0){
return false;//not adc pin
}
if(channel > 7){
return (GET_PERI_REG_MASK(SENS_SAR_MEAS_START2_REG, SENS_MEAS2_DONE_SAR) == 0);
}
return (GET_PERI_REG_MASK(SENS_SAR_MEAS_START1_REG, SENS_MEAS1_DONE_SAR) == 0);
}
uint16_t IRAM_ATTR __adcEnd(uint8_t pin)
{
uint16_t value = 0;
int8_t channel = digitalPinToAnalogChannel(pin);
if(channel < 0){
return 0;//not adc pin
}
if(channel > 7){
while (GET_PERI_REG_MASK(SENS_SAR_MEAS_START2_REG, SENS_MEAS2_DONE_SAR) == 0); //wait for conversion
value = GET_PERI_REG_BITS2(SENS_SAR_MEAS_START2_REG, SENS_MEAS2_DATA_SAR, SENS_MEAS2_DATA_SAR_S);
} else {
while (GET_PERI_REG_MASK(SENS_SAR_MEAS_START1_REG, SENS_MEAS1_DONE_SAR) == 0); //wait for conversion
value = GET_PERI_REG_BITS2(SENS_SAR_MEAS_START1_REG, SENS_MEAS1_DATA_SAR, SENS_MEAS1_DATA_SAR_S);
}
// Shift result if necessary
uint8_t from = __analogWidth + 9;
if (from == __analogReturnedWidth) {
return value;
}
if (from > __analogReturnedWidth) {
return value >> (from - __analogReturnedWidth);
}
return value << (__analogReturnedWidth - from);
}
uint16_t IRAM_ATTR __analogRead(uint8_t pin)
{
if(!__adcAttachPin(pin) || !__adcStart(pin)){
return 0;
}
return __adcEnd(pin);
}
void __analogReadResolution(uint8_t bits)
{
if(!bits || bits > 16){
return;
}
#if CONFIG_IDF_TARGET_ESP32
__analogSetWidth(bits); // hadware from 9 to 12
__analogReturnedWidth = bits; // software from 1 to 16
#endif
}
int __hallRead() //hall sensor without LNA
uint16_t __analogRead(uint8_t pin)
{
int Sens_Vp0;
int Sens_Vn0;
int Sens_Vp1;
int Sens_Vn1;
int8_t channel = digitalPinToAnalogChannel(pin);
int value = 0;
esp_err_t r = ESP_OK;
if(channel < 0){
log_e("Pin %u is not ADC pin!", pin);
return value;
}
__adcAttachPin(pin);
if(channel > 9){
channel -= 10;
r = adc2_get_raw( channel, __analogWidth, &value);
if ( r == ESP_OK ) {
return value;
} else if ( r == ESP_ERR_INVALID_STATE ) {
log_e("GPIO%u: %s: ADC2 not initialized yet.", pin, esp_err_to_name(r));
} else if ( r == ESP_ERR_TIMEOUT ) {
log_e("GPIO%u: %s: ADC2 is in use by Wi-Fi. Please see https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/adc.html#adc-limitations for more info", pin, esp_err_to_name(r));
} else {
log_e("GPIO%u: %s", pin, esp_err_to_name(r));
}
} else {
return adc1_get_raw(channel);
}
return value;
}
uint32_t __analogReadMilliVolts(uint8_t pin){
int8_t channel = digitalPinToAnalogChannel(pin);
if(channel < 0){
log_e("Pin %u is not ADC pin!", pin);
return 0;
}
#if CONFIG_IDF_TARGET_ESP32
if(!__analogVRef){
if (esp_adc_cal_check_efuse(ESP_ADC_CAL_VAL_EFUSE_TP) == ESP_OK) {
log_d("eFuse Two Point: Supported");
__analogVRef = DEFAULT_VREF;
}
if (esp_adc_cal_check_efuse(ESP_ADC_CAL_VAL_EFUSE_VREF) == ESP_OK) {
log_d("eFuse Vref: Supported");
__analogVRef = DEFAULT_VREF;
}
if(!__analogVRef){
__analogVRef = DEFAULT_VREF;
if(__analogVRefPin){
esp_adc_cal_characteristics_t chars;
if(adc_vref_to_gpio(ADC_UNIT_2, __analogVRefPin) == ESP_OK){
__analogVRef = __analogRead(__analogVRefPin);
esp_adc_cal_characterize(1, __analogAttenuation, __analogWidth, DEFAULT_VREF, &chars);
__analogVRef = esp_adc_cal_raw_to_voltage(__analogVRef, &chars);
log_d("Vref to GPIO%u: %u", __analogVRefPin, __analogVRef);
}
}
}
}
uint8_t unit = 1;
if(channel > 9){
unit = 2;
}
uint16_t adc_reading = __analogRead(pin);
if(__analogCharacteristics[unit - 1] == NULL){
__analogCharacteristics[unit - 1] = calloc(1, sizeof(esp_adc_cal_characteristics_t));
if(__analogCharacteristics[unit - 1] == NULL){
return 0;
}
esp_adc_cal_value_t val_type = esp_adc_cal_characterize(unit, __analogAttenuation, __analogWidth, __analogVRef, __analogCharacteristics[unit - 1]);
if (val_type == ESP_ADC_CAL_VAL_EFUSE_TP) {
log_i("ADC%u: Characterized using Two Point Value: %u\n", unit, __analogCharacteristics[unit - 1]->vref);
} else if (val_type == ESP_ADC_CAL_VAL_EFUSE_VREF) {
log_i("ADC%u: Characterized using eFuse Vref: %u\n", unit, __analogCharacteristics[unit - 1]->vref);
} else if(__analogVRef != DEFAULT_VREF){
log_i("ADC%u: Characterized using Vref to GPIO%u: %u\n", unit, __analogVRefPin, __analogCharacteristics[unit - 1]->vref);
} else {
log_i("ADC%u: Characterized using Default Vref: %u\n", unit, __analogCharacteristics[unit - 1]->vref);
}
}
return esp_adc_cal_raw_to_voltage(adc_reading, __analogCharacteristics[unit - 1]);
#else
uint16_t adc_reading = __analogRead(pin);
uint16_t max_reading = 8191;
uint16_t max_mv = 1100;
switch(__analogAttenuation){
case 3: max_mv = 3900; break;
case 2: max_mv = 2200; break;
case 1: max_mv = 1500; break;
default: break;
}
return (adc_reading * max_mv) / max_reading;
#endif
}
#if CONFIG_IDF_TARGET_ESP32
void __analogSetVRefPin(uint8_t pin){
if(pin <25 || pin > 27){
pin = 0;
}
__analogVRefPin = pin;
}
int __hallRead() //hall sensor using idf read
{
pinMode(36, ANALOG);
pinMode(39, ANALOG);
SET_PERI_REG_MASK(SENS_SAR_TOUCH_CTRL1_REG, SENS_XPD_HALL_FORCE_M); // hall sens force enable
SET_PERI_REG_MASK(RTC_IO_HALL_SENS_REG, RTC_IO_XPD_HALL); // xpd hall
SET_PERI_REG_MASK(SENS_SAR_TOUCH_CTRL1_REG, SENS_HALL_PHASE_FORCE_M); // phase force
CLEAR_PERI_REG_MASK(RTC_IO_HALL_SENS_REG, RTC_IO_HALL_PHASE); // hall phase
Sens_Vp0 = __analogRead(36);
Sens_Vn0 = __analogRead(39);
SET_PERI_REG_MASK(RTC_IO_HALL_SENS_REG, RTC_IO_HALL_PHASE);
Sens_Vp1 = __analogRead(36);
Sens_Vn1 = __analogRead(39);
SET_PERI_REG_BITS(SENS_SAR_MEAS_WAIT2_REG, SENS_FORCE_XPD_SAR, 0, SENS_FORCE_XPD_SAR_S);
CLEAR_PERI_REG_MASK(SENS_SAR_TOUCH_CTRL1_REG, SENS_XPD_HALL_FORCE);
CLEAR_PERI_REG_MASK(SENS_SAR_TOUCH_CTRL1_REG, SENS_HALL_PHASE_FORCE);
return (Sens_Vp1 - Sens_Vp0) - (Sens_Vn1 - Sens_Vn0);
__analogSetWidth(12);
return hall_sensor_read();
}
#endif
extern uint16_t analogRead(uint8_t pin) __attribute__ ((weak, alias("__analogRead")));
extern uint32_t analogReadMilliVolts(uint8_t pin) __attribute__ ((weak, alias("__analogReadMilliVolts")));
extern void analogReadResolution(uint8_t bits) __attribute__ ((weak, alias("__analogReadResolution")));
extern void analogSetWidth(uint8_t bits) __attribute__ ((weak, alias("__analogSetWidth")));
extern void analogSetCycles(uint8_t cycles) __attribute__ ((weak, alias("__analogSetCycles")));
extern void analogSetSamples(uint8_t samples) __attribute__ ((weak, alias("__analogSetSamples")));
extern void analogSetClockDiv(uint8_t clockDiv) __attribute__ ((weak, alias("__analogSetClockDiv")));
extern void analogSetAttenuation(adc_attenuation_t attenuation) __attribute__ ((weak, alias("__analogSetAttenuation")));
extern void analogSetPinAttenuation(uint8_t pin, adc_attenuation_t attenuation) __attribute__ ((weak, alias("__analogSetPinAttenuation")));
extern int hallRead() __attribute__ ((weak, alias("__hallRead")));
extern bool adcAttachPin(uint8_t pin) __attribute__ ((weak, alias("__adcAttachPin")));
extern bool adcStart(uint8_t pin) __attribute__ ((weak, alias("__adcStart")));
extern bool adcBusy(uint8_t pin) __attribute__ ((weak, alias("__adcBusy")));
extern uint16_t adcEnd(uint8_t pin) __attribute__ ((weak, alias("__adcEnd")));
#if CONFIG_IDF_TARGET_ESP32
extern void analogSetVRefPin(uint8_t pin) __attribute__ ((weak, alias("__analogSetVRefPin")));
extern void analogSetWidth(uint8_t bits) __attribute__ ((weak, alias("__analogSetWidth")));
extern int hallRead() __attribute__ ((weak, alias("__hallRead")));
#endif

View File

@ -30,7 +30,8 @@ typedef enum {
ADC_0db,
ADC_2_5db,
ADC_6db,
ADC_11db
ADC_11db,
ADC_ATTENDB_MAX
} adc_attenuation_t;
/*
@ -38,6 +39,11 @@ typedef enum {
* */
uint16_t analogRead(uint8_t pin);
/*
* Get MilliVolts value for pin
* */
uint32_t analogReadMilliVolts(uint8_t pin);
/*
* Set the resolution of analogRead return values. Default is 12 bits (range from 0 to 4096).
* If between 9 and 12, it will equal the set hardware resolution, else value will be shifted.
@ -47,31 +53,6 @@ uint16_t analogRead(uint8_t pin);
*/
void analogReadResolution(uint8_t bits);
/*
* Sets the sample bits and read resolution
* Default is 12bit (0 - 4095)
* Range is 9 - 12
* */
void analogSetWidth(uint8_t bits);
/*
* Set number of cycles per sample
* Default is 8 and seems to do well
* Range is 1 - 255
* */
void analogSetCycles(uint8_t cycles);
/*
* Set number of samples in the range.
* Default is 1
* Range is 1 - 255
* This setting splits the range into
* "samples" pieces, which could look
* like the sensitivity has been multiplied
* that many times
* */
void analogSetSamples(uint8_t samples);
/*
* Set the divider for the ADC clock.
* Default is 1
@ -91,40 +72,30 @@ void analogSetAttenuation(adc_attenuation_t attenuation);
* */
void analogSetPinAttenuation(uint8_t pin, adc_attenuation_t attenuation);
/*
* Get value for HALL sensor (without LNA)
* connected to pins 36(SVP) and 39(SVN)
* */
int hallRead();
/*
* Non-Blocking API (almost)
*
* Note: ADC conversion can run only for single pin at a time.
* That means that if you want to run ADC on two pins on the same bus,
* you need to run them one after another. Probably the best use would be
* to start conversion on both buses in parallel.
* */
/*
* Attach pin to ADC (will also clear any other analog mode that could be on)
* */
bool adcAttachPin(uint8_t pin);
#if CONFIG_IDF_TARGET_ESP32
/*
* Start ADC conversion on attached pin's bus
* Sets the sample bits and read resolution
* Default is 12bit (0 - 4095)
* Range is 9 - 12
* */
bool adcStart(uint8_t pin);
void analogSetWidth(uint8_t bits);
/*
* Check if conversion on the pin's ADC bus is currently running
* Set pin to use for ADC calibration if the esp is not already calibrated (25, 26 or 27)
* */
bool adcBusy(uint8_t pin);
void analogSetVRefPin(uint8_t pin);
/*
* Get the result of the conversion (will wait if it have not finished)
* Get value for HALL sensor (without LNA)
* connected to pins 36(SVP) and 39(SVN)
* */
uint16_t adcEnd(uint8_t pin);
int hallRead();
#endif
#ifdef __cplusplus
}

View File

@ -18,11 +18,12 @@
bool btInUse(){ return true; }
#ifdef CONFIG_BLUEDROID_ENABLED
#include "esp_bt.h"
#ifdef CONFIG_CLASSIC_BT_ENABLED
#ifdef CONFIG_BTDM_CONTROLLER_MODE_BTDM
#define BT_MODE ESP_BT_MODE_BTDM
#elif defined(CONFIG_BTDM_CONTROLLER_MODE_BR_EDR_ONLY)
#define BT_MODE ESP_BT_MODE_CLASSIC_BT
#else
#define BT_MODE ESP_BT_MODE_BLE
#endif
@ -65,13 +66,21 @@ bool btStop(){
while(esp_bt_controller_get_status() == ESP_BT_CONTROLLER_STATUS_ENABLED);
}
if(esp_bt_controller_get_status() == ESP_BT_CONTROLLER_STATUS_INITED){
if (esp_bt_controller_deinit()) {
log_e("BT deint failed");
return false;
}
vTaskDelay(1);
if (esp_bt_controller_get_status() != ESP_BT_CONTROLLER_STATUS_IDLE) {
return false;
}
return true;
}
log_e("BT Stop failed");
return false;
}
#else
#else // CONFIG_BT_ENABLED
bool btStarted()
{
return false;
@ -86,6 +95,6 @@ bool btStop()
{
return false;
}
#endif
#endif
#endif // CONFIG_BT_ENABLED

View File

@ -16,24 +16,39 @@
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "freertos/task.h"
#include "freertos/xtensa_timer.h"
#include "esp_attr.h"
#include "esp_log.h"
#include "soc/rtc.h"
#include "soc/rtc_cntl_reg.h"
#include "rom/rtc.h"
#include "soc/apb_ctrl_reg.h"
#include "soc/efuse_reg.h"
#include "esp32-hal.h"
#include "esp32-hal-cpu.h"
#include "esp_system.h"
#ifdef ESP_IDF_VERSION_MAJOR // IDF 4+
#if CONFIG_IDF_TARGET_ESP32 // ESP32/PICO-D4
#include "freertos/xtensa_timer.h"
#include "esp32/rom/rtc.h"
#elif CONFIG_IDF_TARGET_ESP32S2
#include "freertos/xtensa_timer.h"
#include "esp32s2/rom/rtc.h"
#elif CONFIG_IDF_TARGET_ESP32C3
#include "esp32c3/rom/rtc.h"
#else
#error Target CONFIG_IDF_TARGET is not supported
#endif
#else // ESP32 Before IDF 4.0
#include "rom/rtc.h"
#endif
typedef struct apb_change_cb_s {
struct apb_change_cb_s * prev;
struct apb_change_cb_s * next;
void * arg;
apb_change_cb_t cb;
} apb_change_t;
const uint32_t MHZ = 1000000;
static apb_change_t * apb_change_callbacks = NULL;
static xSemaphoreHandle apb_change_lock = NULL;
@ -53,10 +68,20 @@ static void triggerApbChangeCallback(apb_change_ev_t ev_type, uint32_t old_apb,
initApbChangeCallback();
xSemaphoreTake(apb_change_lock, portMAX_DELAY);
apb_change_t * r = apb_change_callbacks;
if( r != NULL ){
if(ev_type == APB_BEFORE_CHANGE )
while(r != NULL){
r->cb(r->arg, ev_type, old_apb, new_apb);
r=r->next;
}
else { // run backwards through chain
while(r->next != NULL) r = r->next; // find first added
while( r != NULL){
r->cb(r->arg, ev_type, old_apb, new_apb);
r=r->prev;
}
}
}
xSemaphoreGive(apb_change_lock);
}
@ -68,6 +93,7 @@ bool addApbChangeCallback(void * arg, apb_change_cb_t cb){
return false;
}
c->next = NULL;
c->prev = NULL;
c->arg = arg;
c->cb = cb;
xSemaphoreTake(apb_change_lock, portMAX_DELAY);
@ -75,18 +101,20 @@ bool addApbChangeCallback(void * arg, apb_change_cb_t cb){
apb_change_callbacks = c;
} else {
apb_change_t * r = apb_change_callbacks;
if(r->cb != cb || r->arg != arg){
while(r->next){
r = r->next;
if(r->cb == cb && r->arg == arg){
// look for duplicate callbacks
while( (r != NULL ) && !((r->cb == cb) && ( r->arg == arg))) r = r->next;
if (r) {
log_e("duplicate func=%08X arg=%08X",c->cb,c->arg);
free(c);
goto unlock_and_exit;
xSemaphoreGive(apb_change_lock);
return false;
}
else {
c->next = apb_change_callbacks;
apb_change_callbacks-> prev = c;
apb_change_callbacks = c;
}
}
r->next = c;
}
}
unlock_and_exit:
xSemaphoreGive(apb_change_lock);
return true;
}
@ -95,34 +123,35 @@ bool removeApbChangeCallback(void * arg, apb_change_cb_t cb){
initApbChangeCallback();
xSemaphoreTake(apb_change_lock, portMAX_DELAY);
apb_change_t * r = apb_change_callbacks;
if(r == NULL){
// look for matching callback
while( (r != NULL ) && !((r->cb == cb) && ( r->arg == arg))) r = r->next;
if ( r == NULL ) {
log_e("not found func=%08X arg=%08X",cb,arg);
xSemaphoreGive(apb_change_lock);
return false;
}
if(r->cb == cb && r->arg == arg){
else {
// patch links
if(r->prev) r->prev->next = r->next;
else { // this is first link
apb_change_callbacks = r->next;
}
if(r->next) r->next->prev = r->prev;
free(r);
} else {
while(r->next && (r->next->cb != cb || r->next->arg != arg)){
r = r->next;
}
if(r->next == NULL || r->next->cb != cb || r->next->arg != arg){
xSemaphoreGive(apb_change_lock);
return false;
}
apb_change_t * c = r->next;
r->next = c->next;
free(c);
}
xSemaphoreGive(apb_change_lock);
return true;
}
static uint32_t calculateApb(rtc_cpu_freq_config_t * conf){
#if CONFIG_IDF_TARGET_ESP32C3
return APB_CLK_FREQ;
#else
if(conf->freq_mhz >= 80){
return 80 * MHZ;
}
return (conf->source_freq_mhz * MHZ) / conf->div;
#endif
}
void esp_timer_impl_update_apb_freq(uint32_t apb_ticks_per_us); //private in IDF
@ -132,6 +161,7 @@ bool setCpuFrequencyMhz(uint32_t cpu_freq_mhz){
uint32_t capb, apb;
//Get XTAL Frequency and calculate min CPU MHz
rtc_xtal_freq_t xtal = rtc_clk_xtal_freq_get();
#if CONFIG_IDF_TARGET_ESP32
if(xtal > RTC_XTAL_FREQ_AUTO){
if(xtal < RTC_XTAL_FREQ_40M) {
if(cpu_freq_mhz <= xtal && cpu_freq_mhz != xtal && cpu_freq_mhz != (xtal/2)){
@ -143,6 +173,7 @@ bool setCpuFrequencyMhz(uint32_t cpu_freq_mhz){
return false;
}
}
#endif
if(cpu_freq_mhz > xtal && cpu_freq_mhz != 240 && cpu_freq_mhz != 160 && cpu_freq_mhz != 80){
if(xtal >= RTC_XTAL_FREQ_40M){
log_e("Bad frequency: %u MHz! Options are: 240, 160, 80, %u, %u and %u MHz", cpu_freq_mhz, xtal, xtal/2, xtal/4);
@ -151,6 +182,7 @@ bool setCpuFrequencyMhz(uint32_t cpu_freq_mhz){
}
return false;
}
#if CONFIG_IDF_TARGET_ESP32
//check if cpu supports the frequency
if(cpu_freq_mhz == 240){
//Check if ESP32 is rated for a CPU frequency of 160MHz only
@ -160,6 +192,7 @@ bool setCpuFrequencyMhz(uint32_t cpu_freq_mhz){
cpu_freq_mhz = 160;
}
}
#endif
//Get current CPU clock configuration
rtc_clk_cpu_freq_get_config(&cconf);
//return if frequency has not changed
@ -186,15 +219,19 @@ bool setCpuFrequencyMhz(uint32_t cpu_freq_mhz){
//Update REF_TICK (uncomment if REF_TICK is different than 1MHz)
//if(conf.freq_mhz < 80){
// ESP_REG(APB_CTRL_XTAL_TICK_CONF_REG) = conf.freq_mhz / (REF_CLK_FREQ / MHZ) - 1;
//}
// }
//Update APB Freq REG
rtc_clk_apb_freq_update(apb);
//Update esp_timer divisor
esp_timer_impl_update_apb_freq(apb / MHZ);
}
//Update FreeRTOS Tick Divisor
#if CONFIG_IDF_TARGET_ESP32C3
#else
uint32_t fcpu = (conf.freq_mhz >= 80)?(conf.freq_mhz * MHZ):(apb);
_xt_tick_divisor = fcpu / XT_TICK_PER_SEC;
#endif
//Call peripheral functions after the APB change
if(apb_change_callbacks){
triggerApbChangeCallback(APB_AFTER_CHANGE, capb, apb);

View File

@ -12,43 +12,52 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#include "esp32-hal-dac.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "rom/ets_sys.h"
#include "esp_attr.h"
#include "esp_intr.h"
#include "soc/rtc_io_reg.h"
#include "soc/rtc_cntl_reg.h"
#include "soc/sens_reg.h"
#include "esp32-hal.h"
void IRAM_ATTR __dacWrite(uint8_t pin, uint8_t value)
#if CONFIG_IDF_TARGET_ESP32
#include "soc/rtc_io_reg.h"
#define DAC1 25
#define DAC2 26
#elif CONFIG_IDF_TARGET_ESP32S2
#include "soc/rtc_io_reg.h"
#define DAC1 17
#define DAC2 18
#elif CONFIG_IDF_TARGET_ESP32C3
#define NODAC
#else
#error Target CONFIG_IDF_TARGET is not supported
#endif
#ifndef NODAC
#include "esp_attr.h"
#include "soc/rtc_cntl_reg.h"
#include "soc/rtc_io_periph.h"
#include "soc/sens_reg.h"
#include "soc/sens_struct.h"
#include "driver/dac.h"
void ARDUINO_ISR_ATTR __dacWrite(uint8_t pin, uint8_t value)
{
if(pin < 25 || pin > 26){
if(pin < DAC1 || pin > DAC2){
return;//not dac pin
}
pinMode(pin, ANALOG);
uint8_t channel = pin - 25;
//Disable Tone
uint8_t channel = pin - DAC1;
#if CONFIG_IDF_TARGET_ESP32
CLEAR_PERI_REG_MASK(SENS_SAR_DAC_CTRL1_REG, SENS_SW_TONE_EN);
if (channel) {
//Disable Channel Tone
CLEAR_PERI_REG_MASK(SENS_SAR_DAC_CTRL2_REG, SENS_DAC_CW_EN2_M);
//Set the Dac value
SET_PERI_REG_BITS(RTC_IO_PAD_DAC2_REG, RTC_IO_PDAC2_DAC, value, RTC_IO_PDAC2_DAC_S); //dac_output
//Channel output enable
SET_PERI_REG_MASK(RTC_IO_PAD_DAC2_REG, RTC_IO_PDAC2_XPD_DAC | RTC_IO_PDAC2_DAC_XPD_FORCE);
} else {
//Disable Channel Tone
CLEAR_PERI_REG_MASK(SENS_SAR_DAC_CTRL2_REG, SENS_DAC_CW_EN1_M);
//Set the Dac value
SET_PERI_REG_BITS(RTC_IO_PAD_DAC1_REG, RTC_IO_PDAC1_DAC, value, RTC_IO_PDAC1_DAC_S); //dac_output
//Channel output enable
SET_PERI_REG_MASK(RTC_IO_PAD_DAC1_REG, RTC_IO_PDAC1_XPD_DAC | RTC_IO_PDAC1_DAC_XPD_FORCE);
#elif CONFIG_IDF_TARGET_ESP32S2
SENS.sar_dac_ctrl1.dac_clkgate_en = 1;
#endif
RTCIO.pad_dac[channel].dac_xpd_force = 1;
RTCIO.pad_dac[channel].xpd_dac = 1;
if (channel == 0) {
SENS.sar_dac_ctrl2.dac_cw_en1 = 0;
} else if (channel == 1) {
SENS.sar_dac_ctrl2.dac_cw_en2 = 0;
}
RTCIO.pad_dac[channel].dac = value;
}
extern void dacWrite(uint8_t pin, uint8_t value) __attribute__ ((weak, alias("__dacWrite")));
#endif

View File

@ -13,20 +13,47 @@
// limitations under the License.
#include "esp32-hal-gpio.h"
#include "pins_arduino.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "rom/ets_sys.h"
#include "esp_attr.h"
#include "esp_intr.h"
#include "rom/gpio.h"
#include "soc/gpio_reg.h"
#include "soc/io_mux_reg.h"
#include "soc/gpio_struct.h"
#include "driver/gpio.h"
#include "esp_system.h"
#ifdef ESP_IDF_VERSION_MAJOR // IDF 4+
#if CONFIG_IDF_TARGET_ESP32 // ESP32/PICO-D4
#include "esp32/rom/ets_sys.h"
#include "esp32/rom/gpio.h"
#include "esp_intr_alloc.h"
#include "soc/rtc_io_reg.h"
#define GPIO_FUNC 2
#elif CONFIG_IDF_TARGET_ESP32S2
#include "esp32s2/rom/ets_sys.h"
#include "esp32s2/rom/gpio.h"
#include "esp_intr_alloc.h"
#include "soc/periph_defs.h"
#include "soc/rtc_io_reg.h"
#define GPIO_FUNC 1
#else
#define USE_ESP_IDF_GPIO 1
#endif
#else // ESP32 Before IDF 4.0
#include "rom/ets_sys.h"
#include "rom/gpio.h"
#include "esp_intr.h"
#endif
#if CONFIG_IDF_TARGET_ESP32
const int8_t esp32_adc2gpio[20] = {36, 37, 38, 39, 32, 33, 34, 35, -1, -1, 4, 0, 2, 15, 13, 12, 14, 27, 25, 26};
#elif CONFIG_IDF_TARGET_ESP32S2
const int8_t esp32_adc2gpio[20] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
#endif
const DRAM_ATTR esp32_gpioMux_t esp32_gpioMux[GPIO_PIN_COUNT]={
const DRAM_ATTR esp32_gpioMux_t esp32_gpioMux[SOC_GPIO_PIN_COUNT]={
#if CONFIG_IDF_TARGET_ESP32
{0x44, 11, 11, 1},
{0x88, -1, -1, -1},
{0x40, 12, 12, 2},
@ -59,14 +86,64 @@ const DRAM_ATTR esp32_gpioMux_t esp32_gpioMux[GPIO_PIN_COUNT]={
{0, -1, -1, -1},
{0, -1, -1, -1},
{0, -1, -1, -1},
{0x1c, 9, 4, 9},
{0x20, 8, 5, 8},
{0x1c, 9, 4, 8},
{0x20, 8, 5, 9},
{0x14, 4, 6, -1},
{0x18, 5, 7, -1},
{0x04, 0, 0, -1},
{0x08, 1, 1, -1},
{0x0c, 2, 2, -1},
{0x10, 3, 3, -1}
#elif CONFIG_IDF_TARGET_ESP32S2
{0x04, 0, -1, -1},
{0x08, 1, 0, 1},
{0x0c, 2, 1, 2},
{0x10, 3, 2, 3},
{0x14, 4, 3, 4},
{0x18, 5, 4, 5},
{0x1c, 6, 5, 6},
{0x20, 7, 6, 7},
{0x24, 8, 7, 8},
{0x28, 9, 8, 9},//FSPI_HD
{0x2c, 10, 9, 10},//FSPI_CS0 / FSPI_D4
{0x30, 11, 10, 11},//FSPI_D / FSPI_D5
{0x34, 12, 11, 12},//FSPI_CLK / FSPI_D6
{0x38, 13, 12, 13},//FSPI_Q / FSPI_D7
{0x3c, 14, 13, 14},//FSPI_WP / FSPI_DQS
{0x40, 15, 14, -1},//32K+ / RTS0
{0x44, 16, 15, -1},//32K- / CTS0
{0x48, 17, 16, -1},//DAC1 / TXD1
{0x4c, 18, 17, -1},//DAC2 / RXD1
{0x50, 19, 18, -1},//USB D- / RTS1
{0x54, 20, 19, -1},//USB D+ / CTS1
{0x58, 21, -1, -1},//SDA?
{ 0, -1, -1, -1},//UNAVAILABLE
{ 0, -1, -1, -1},//UNAVAILABLE
{ 0, -1, -1, -1},//UNAVAILABLE
{ 0, -1, -1, -1},//UNAVAILABLE
{0x6c, -1, -1, -1},//RESERVED SPI_CS1
{0x70, -1, -1, -1},//RESERVED SPI_HD
{0x74, -1, -1, -1},//RESERVED SPI_WP
{0x78, -1, -1, -1},//RESERVED SPI_CS0
{0x7c, -1, -1, -1},//RESERVED SPI_CLK
{0x80, -1, -1, -1},//RESERVED SPI_Q
{0x84, -1, -1, -1},//RESERVED SPI_D
{0x88, -1, -1, -1},//FSPI_HD
{0x8c, -1, -1, -1},//FSPI_CS0
{0x90, -1, -1, -1},//FSPI_D
{0x94, -1, -1, -1},//FSPI_CLK
{0x98, -1, -1, -1},//FSPI_Q
{0x9c, -1, -1, -1},//FSPI_WP
{0xa0, -1, -1, -1},//MTCK
{0xa4, -1, -1, -1},//MTDO
{0xa8, -1, -1, -1},//MTDI
{0xac, -1, -1, -1},//MTMS
{0xb0, -1, -1, -1},//TXD0
{0xb4, -1, -1, -1},//RXD0
{0xb8, -1, -1, -1},//SCL?
{0xbc, -1, -1, -1},//INPUT ONLY
{0, -1, -1, -1}
#endif
};
typedef void (*voidFuncPtr)(void);
@ -76,56 +153,95 @@ typedef struct {
void* arg;
bool functional;
} InterruptHandle_t;
static InterruptHandle_t __pinInterruptHandlers[GPIO_PIN_COUNT] = {0,};
static InterruptHandle_t __pinInterruptHandlers[SOC_GPIO_PIN_COUNT] = {0,};
#include "driver/rtc_io.h"
extern void IRAM_ATTR __pinMode(uint8_t pin, uint8_t mode)
extern void ARDUINO_ISR_ATTR __pinMode(uint8_t pin, uint8_t mode)
{
#if USE_ESP_IDF_GPIO
if (!GPIO_IS_VALID_GPIO(pin)) {
return;
}
gpio_config_t conf = {
.pin_bit_mask = (1ULL<<pin), /*!< GPIO pin: set with bit mask, each bit maps to a GPIO */
.mode = GPIO_MODE_DISABLE, /*!< GPIO mode: set input/output mode */
.pull_up_en = GPIO_PULLUP_DISABLE, /*!< GPIO pull-up */
.pull_down_en = GPIO_PULLDOWN_DISABLE, /*!< GPIO pull-down */
.intr_type = GPIO_INTR_DISABLE /*!< GPIO interrupt type */
};
if (mode < 0x20) {//io
conf.mode = mode & (INPUT | OUTPUT);
if (mode & OPEN_DRAIN) {
conf.mode |= GPIO_MODE_DEF_OD;
}
if (mode & PULLUP) {
conf.pull_up_en = GPIO_PULLUP_ENABLE;
}
if (mode & PULLDOWN) {
conf.pull_down_en = GPIO_PULLDOWN_ENABLE;
}
}
gpio_config(&conf);
if(mode == SPECIAL){
#if CONFIG_IDF_TARGET_ESP32
PIN_FUNC_SELECT(GPIO_PIN_MUX_REG[pin], (uint32_t)(((pin)==RX||(pin)==TX)?0:1));
#elif CONFIG_IDF_TARGET_ESP32S2
PIN_FUNC_SELECT(GPIO_PIN_MUX_REG[pin], (uint32_t)(((pin)==RX||(pin)==TX)?0:2));
#endif
} else if(mode == ANALOG){
#if !CONFIG_IDF_TARGET_ESP32C3
//adc_gpio_init(ADC_UNIT_1, ADC_CHANNEL_0);
#endif
} else if(mode >= 0x20 && mode < ANALOG) {//function
PIN_FUNC_SELECT(GPIO_PIN_MUX_REG[pin], mode >> 5);
}
#else
if(!digitalPinIsValid(pin)) {
return;
}
uint32_t rtc_reg = rtc_gpio_desc[pin].reg;
int8_t rtc_io = esp32_gpioMux[pin].rtc;
uint32_t rtc_reg = (rtc_io != -1)?rtc_io_desc[rtc_io].reg:0;
if(mode == ANALOG) {
if(!rtc_reg) {
return;//not rtc pin
}
//lock rtc
uint32_t reg_val = ESP_REG(rtc_reg);
if(reg_val & rtc_gpio_desc[pin].mux){
return;//already in adc mode
#if CONFIG_IDF_TARGET_ESP32S2
SENS.sar_io_mux_conf.iomux_clk_gate_en = 1;
#endif
SET_PERI_REG_MASK(rtc_io_desc[rtc_io].reg, (rtc_io_desc[rtc_io].mux));
SET_PERI_REG_BITS(rtc_io_desc[rtc_io].reg, RTC_IO_TOUCH_PAD1_FUN_SEL_V, 0, rtc_io_desc[rtc_io].func);
RTCIO.pin[rtc_io].pad_driver = 0;//OD = 1
RTCIO.enable_w1tc.w1tc = (1U << rtc_io);
CLEAR_PERI_REG_MASK(rtc_io_desc[rtc_io].reg, rtc_io_desc[rtc_io].ie);
if (rtc_io_desc[rtc_io].pullup) {
CLEAR_PERI_REG_MASK(rtc_io_desc[rtc_io].reg, rtc_io_desc[rtc_io].pullup);
}
reg_val &= ~(
(RTC_IO_TOUCH_PAD1_FUN_SEL_V << rtc_gpio_desc[pin].func)
|rtc_gpio_desc[pin].ie
|rtc_gpio_desc[pin].pullup
|rtc_gpio_desc[pin].pulldown);
ESP_REG(RTC_GPIO_ENABLE_W1TC_REG) = (1 << (rtc_gpio_desc[pin].rtc_num + RTC_GPIO_ENABLE_W1TC_S));
ESP_REG(rtc_reg) = reg_val | rtc_gpio_desc[pin].mux;
//unlock rtc
ESP_REG(DR_REG_IO_MUX_BASE + esp32_gpioMux[pin].reg) = ((uint32_t)2 << MCU_SEL_S) | ((uint32_t)2 << FUN_DRV_S) | FUN_IE;
if (rtc_io_desc[rtc_io].pulldown) {
CLEAR_PERI_REG_MASK(rtc_io_desc[rtc_io].reg, rtc_io_desc[rtc_io].pulldown);
}
ESP_REG(DR_REG_IO_MUX_BASE + esp32_gpioMux[pin].reg) = ((uint32_t)GPIO_FUNC << MCU_SEL_S) | ((uint32_t)2 << FUN_DRV_S) | FUN_IE;
return;
}
//RTC pins PULL settings
if(rtc_reg) {
//lock rtc
ESP_REG(rtc_reg) = ESP_REG(rtc_reg) & ~(rtc_gpio_desc[pin].mux);
ESP_REG(rtc_reg) = ESP_REG(rtc_reg) & ~(rtc_io_desc[rtc_io].mux);
if(mode & PULLUP) {
ESP_REG(rtc_reg) = (ESP_REG(rtc_reg) | rtc_gpio_desc[pin].pullup) & ~(rtc_gpio_desc[pin].pulldown);
ESP_REG(rtc_reg) = (ESP_REG(rtc_reg) | rtc_io_desc[rtc_io].pullup) & ~(rtc_io_desc[rtc_io].pulldown);
} else if(mode & PULLDOWN) {
ESP_REG(rtc_reg) = (ESP_REG(rtc_reg) | rtc_gpio_desc[pin].pulldown) & ~(rtc_gpio_desc[pin].pullup);
ESP_REG(rtc_reg) = (ESP_REG(rtc_reg) | rtc_io_desc[rtc_io].pulldown) & ~(rtc_io_desc[rtc_io].pullup);
} else {
ESP_REG(rtc_reg) = ESP_REG(rtc_reg) & ~(rtc_gpio_desc[pin].pullup | rtc_gpio_desc[pin].pulldown);
ESP_REG(rtc_reg) = ESP_REG(rtc_reg) & ~(rtc_io_desc[rtc_io].pullup | rtc_io_desc[rtc_io].pulldown);
}
//unlock rtc
}
uint32_t pinFunction = 0, pinControl = 0;
//lock gpio
if(mode & INPUT) {
if(pin < 32) {
GPIO.enable_w1tc = ((uint32_t)1 << pin);
@ -133,9 +249,8 @@ extern void IRAM_ATTR __pinMode(uint8_t pin, uint8_t mode)
GPIO.enable1_w1tc.val = ((uint32_t)1 << (pin - 32));
}
} else if(mode & OUTPUT) {
if(pin > 33){
//unlock gpio
return;//pins above 33 can be only inputs
if(pin >= NUM_OUPUT_PINS){
return;
} else if(pin < 32) {
GPIO.enable_w1ts = ((uint32_t)1 << pin);
} else {
@ -153,9 +268,13 @@ extern void IRAM_ATTR __pinMode(uint8_t pin, uint8_t mode)
pinFunction |= FUN_IE;//input enable but required for output as well?
if(mode & (INPUT | OUTPUT)) {
pinFunction |= ((uint32_t)2 << MCU_SEL_S);
pinFunction |= ((uint32_t)PIN_FUNC_GPIO << MCU_SEL_S);
} else if(mode == SPECIAL) {
pinFunction |= ((uint32_t)(((pin)==1||(pin)==3)?0:1) << MCU_SEL_S);
#if CONFIG_IDF_TARGET_ESP32
pinFunction |= ((uint32_t)(((pin)==RX||(pin)==TX)?0:1) << MCU_SEL_S);
#elif CONFIG_IDF_TARGET_ESP32S2
pinFunction |= ((uint32_t)(((pin)==RX||(pin)==TX)?0:2) << MCU_SEL_S);
#endif
} else {
pinFunction |= ((uint32_t)(mode >> 5) << MCU_SEL_S);
}
@ -167,39 +286,67 @@ extern void IRAM_ATTR __pinMode(uint8_t pin, uint8_t mode)
}
GPIO.pin[pin].val = pinControl;
//unlock gpio
#endif
}
extern void IRAM_ATTR __digitalWrite(uint8_t pin, uint8_t val)
extern void ARDUINO_ISR_ATTR __digitalWrite(uint8_t pin, uint8_t val)
{
#if USE_ESP_IDF_GPIO
gpio_set_level((gpio_num_t)pin, val);
#elif CONFIG_IDF_TARGET_ESP32C3
if (val) {
GPIO.out_w1ts.out_w1ts = (1 << pin);
} else {
GPIO.out_w1tc.out_w1tc = (1 << pin);
}
#else
if(val) {
if(pin < 32) {
GPIO.out_w1ts = ((uint32_t)1 << pin);
} else if(pin < 34) {
} else if(pin < NUM_OUPUT_PINS) {
GPIO.out1_w1ts.val = ((uint32_t)1 << (pin - 32));
}
} else {
if(pin < 32) {
GPIO.out_w1tc = ((uint32_t)1 << pin);
} else if(pin < 34) {
} else if(pin < NUM_OUPUT_PINS) {
GPIO.out1_w1tc.val = ((uint32_t)1 << (pin - 32));
}
}
#endif
}
extern int IRAM_ATTR __digitalRead(uint8_t pin)
extern int ARDUINO_ISR_ATTR __digitalRead(uint8_t pin)
{
#if USE_ESP_IDF_GPIO
return gpio_get_level((gpio_num_t)pin);
#elif CONFIG_IDF_TARGET_ESP32C3
return (GPIO.in.data >> pin) & 0x1;
#else
if(pin < 32) {
return (GPIO.in >> pin) & 0x1;
} else if(pin < 40) {
} else if(pin < GPIO_PIN_COUNT) {
return (GPIO.in1.val >> (pin - 32)) & 0x1;
}
return 0;
#endif
}
#if USE_ESP_IDF_GPIO
static void ARDUINO_ISR_ATTR __onPinInterrupt(void * arg) {
InterruptHandle_t * isr = (InterruptHandle_t*)arg;
if(isr->fn) {
if(isr->arg){
((voidFuncPtrArg)isr->fn)(isr->arg);
} else {
isr->fn();
}
}
}
#else
static intr_handle_t gpio_intr_handle = NULL;
static void IRAM_ATTR __onPinInterrupt()
static void ARDUINO_ISR_ATTR __onPinInterrupt()
{
uint32_t gpio_intr_status_l=0;
uint32_t gpio_intr_status_h=0;
@ -238,6 +385,7 @@ static void IRAM_ATTR __onPinInterrupt()
} while(++pin<GPIO_PIN_COUNT);
}
}
#endif
extern void cleanupFunctional(void* arg);
@ -246,8 +394,17 @@ extern void __attachInterruptFunctionalArg(uint8_t pin, voidFuncPtrArg userFunc,
static bool interrupt_initialized = false;
if(!interrupt_initialized) {
#if USE_ESP_IDF_GPIO
esp_err_t err = gpio_install_isr_service((int)ARDUINO_ISR_FLAG);
interrupt_initialized = (err == ESP_OK) || (err == ESP_ERR_INVALID_STATE);
#else
interrupt_initialized = true;
esp_intr_alloc(ETS_GPIO_INTR_SOURCE, (int)ESP_INTR_FLAG_IRAM, __onPinInterrupt, NULL, &gpio_intr_handle);
esp_intr_alloc(ETS_GPIO_INTR_SOURCE, (int)ARDUINO_ISR_FLAG, __onPinInterrupt, NULL, &gpio_intr_handle);
#endif
}
if(!interrupt_initialized) {
log_e("GPIO ISR Service Failed To Start");
return;
}
// if new attach without detach remove old info
@ -259,14 +416,27 @@ extern void __attachInterruptFunctionalArg(uint8_t pin, voidFuncPtrArg userFunc,
__pinInterruptHandlers[pin].arg = arg;
__pinInterruptHandlers[pin].functional = functional;
#if USE_ESP_IDF_GPIO
gpio_set_intr_type((gpio_num_t)pin, (gpio_int_type_t)(intr_type & 0x7));
if(intr_type & 0x8){
gpio_wakeup_enable((gpio_num_t)pin, (gpio_int_type_t)(intr_type & 0x7));
}
gpio_isr_handler_add((gpio_num_t)pin, __onPinInterrupt, &__pinInterruptHandlers[pin]);
gpio_intr_enable((gpio_num_t)pin);
#else
esp_intr_disable(gpio_intr_handle);
#if CONFIG_IDF_TARGET_ESP32
if(esp_intr_get_cpu(gpio_intr_handle)) { //APP_CPU
#endif
GPIO.pin[pin].int_ena = 1;
#if CONFIG_IDF_TARGET_ESP32
} else { //PRO_CPU
GPIO.pin[pin].int_ena = 4;
}
#endif
GPIO.pin[pin].int_type = intr_type;
esp_intr_enable(gpio_intr_handle);
#endif
}
extern void __attachInterruptArg(uint8_t pin, voidFuncPtrArg userFunc, void * arg, int intr_type)
@ -280,7 +450,13 @@ extern void __attachInterrupt(uint8_t pin, voidFuncPtr userFunc, int intr_type)
extern void __detachInterrupt(uint8_t pin)
{
#if USE_ESP_IDF_GPIO
gpio_intr_disable((gpio_num_t)pin);
gpio_isr_handler_remove((gpio_num_t)pin);
gpio_wakeup_disable((gpio_num_t)pin);
#else
esp_intr_disable(gpio_intr_handle);
#endif
if (__pinInterruptHandlers[pin].functional && __pinInterruptHandlers[pin].arg)
{
cleanupFunctional(__pinInterruptHandlers[pin].arg);
@ -289,9 +465,13 @@ extern void __detachInterrupt(uint8_t pin)
__pinInterruptHandlers[pin].arg = NULL;
__pinInterruptHandlers[pin].functional = false;
#if USE_ESP_IDF_GPIO
gpio_set_intr_type((gpio_num_t)pin, GPIO_INTR_DISABLE);
#else
GPIO.pin[pin].int_ena = 0;
GPIO.pin[pin].int_type = 0;
esp_intr_enable(gpio_intr_handle);
#endif
}

View File

@ -25,6 +25,17 @@ extern "C" {
#endif
#include "esp32-hal.h"
#include "soc/soc_caps.h"
#if (CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32S3)
#define NUM_OUPUT_PINS 46
#define PIN_DAC1 17
#define PIN_DAC2 18
#else
#define NUM_OUPUT_PINS 34
#define PIN_DAC1 25
#define PIN_DAC2 26
#endif
#define LOW 0x0
#define HIGH 0x1
@ -64,15 +75,15 @@ typedef struct {
int8_t touch; /*!< Touch Channel number (-1 if not Touch pin) */
} esp32_gpioMux_t;
extern const esp32_gpioMux_t esp32_gpioMux[40];
extern const esp32_gpioMux_t esp32_gpioMux[SOC_GPIO_PIN_COUNT];
extern const int8_t esp32_adc2gpio[20];
#define digitalPinIsValid(pin) ((pin) < 40 && esp32_gpioMux[(pin)].reg)
#define digitalPinCanOutput(pin) ((pin) < 34 && esp32_gpioMux[(pin)].reg)
#define digitalPinToRtcPin(pin) (((pin) < 40)?esp32_gpioMux[(pin)].rtc:-1)
#define digitalPinToAnalogChannel(pin) (((pin) < 40)?esp32_gpioMux[(pin)].adc:-1)
#define digitalPinToTouchChannel(pin) (((pin) < 40)?esp32_gpioMux[(pin)].touch:-1)
#define digitalPinToDacChannel(pin) (((pin) == 25)?0:((pin) == 26)?1:-1)
#define digitalPinIsValid(pin) ((pin) < SOC_GPIO_PIN_COUNT && esp32_gpioMux[(pin)].reg)
#define digitalPinCanOutput(pin) ((pin) < NUM_OUPUT_PINS && esp32_gpioMux[(pin)].reg)
#define digitalPinToRtcPin(pin) (((pin) < SOC_GPIO_PIN_COUNT)?esp32_gpioMux[(pin)].rtc:-1)
#define digitalPinToAnalogChannel(pin) (((pin) < SOC_GPIO_PIN_COUNT)?esp32_gpioMux[(pin)].adc:-1)
#define digitalPinToTouchChannel(pin) (((pin) < SOC_GPIO_PIN_COUNT)?esp32_gpioMux[(pin)].touch:-1)
#define digitalPinToDacChannel(pin) (((pin) == PIN_DAC1)?0:((pin) == PIN_DAC2)?1:-1)
void pinMode(uint8_t pin, uint8_t mode);
void digitalWrite(uint8_t pin, uint8_t val);

View File

@ -18,13 +18,31 @@
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "freertos/event_groups.h"
#include "rom/ets_sys.h"
#include "driver/periph_ctrl.h"
#include "soc/i2c_reg.h"
#include "soc/i2c_struct.h"
#include "soc/dport_reg.h"
#include "esp_attr.h"
#include "esp32-hal-cpu.h" // cpu clock change support 31DEC2018
#include "esp_system.h"
#ifdef ESP_IDF_VERSION_MAJOR // IDF 4+
#if CONFIG_IDF_TARGET_ESP32 // ESP32/PICO-D4
#include "soc/dport_reg.h"
#include "esp32/rom/ets_sys.h"
#elif CONFIG_IDF_TARGET_ESP32S2
#include "soc/dport_reg.h"
#include "esp32s2/rom/ets_sys.h"
#elif CONFIG_IDF_TARGET_ESP32C3
#include "esp32c3/rom/ets_sys.h"
#else
#error Target CONFIG_IDF_TARGET is not supported
#endif
#else // ESP32 Before IDF 4.0
#include "rom/ets_sys.h"
#endif
#if CONFIG_IDF_TARGET_ESP32
//#define I2C_DEV(i) (volatile i2c_dev_t *)((i)?DR_REG_I2C1_EXT_BASE:DR_REG_I2C_EXT_BASE)
//#define I2C_DEV(i) ((i2c_dev_t *)(REG_I2C_BASE(i)))
#define I2C_SCL_IDX(p) ((p==0)?I2CEXT0_SCL_OUT_IDX:((p==1)?I2CEXT1_SCL_OUT_IDX:0))
@ -227,7 +245,7 @@ static i2c_t _i2c_bus_array[2] = {
/* Stickbreaker ISR mode debug support
*/
static void IRAM_ATTR i2cDumpCmdQueue(i2c_t *i2c)
static void ARDUINO_ISR_ATTR i2cDumpCmdQueue(i2c_t *i2c)
{
#if (ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_ERROR)&&(defined ENABLE_I2C_DEBUG_BUFFER)
static const char * const cmdName[] ={"RSTART","WRITE","READ","STOP","END"};
@ -357,7 +375,7 @@ static void i2cDumpInts(uint8_t num)
#endif
#if (ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_INFO)&&(defined ENABLE_I2C_DEBUG_BUFFER)
static void IRAM_ATTR i2cDumpStatus(i2c_t * i2c){
static void ARDUINO_ISR_ATTR i2cDumpStatus(i2c_t * i2c){
typedef union {
struct {
uint32_t ack_rec: 1; /*This register stores the value of ACK bit.*/
@ -431,7 +449,7 @@ if(i != fifoPos){// actual data
}
#endif
static void IRAM_ATTR i2cTriggerDumps(i2c_t * i2c, uint8_t trigger, const char locus[]){
static void ARDUINO_ISR_ATTR i2cTriggerDumps(i2c_t * i2c, uint8_t trigger, const char locus[]){
#if (ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_INFO)&&(defined ENABLE_I2C_DEBUG_BUFFER)
if( trigger ){
log_i("%s",locus);
@ -478,7 +496,7 @@ static void i2cApbChangeCallback(void * arg, apb_change_ev_t ev_type, uint32_t o
}
/* End of CPU Clock change Support
*/
static void IRAM_ATTR i2cSetCmd(i2c_t * i2c, uint8_t index, uint8_t op_code, uint8_t byte_num, bool ack_val, bool ack_exp, bool ack_check)
static void ARDUINO_ISR_ATTR i2cSetCmd(i2c_t * i2c, uint8_t index, uint8_t op_code, uint8_t byte_num, bool ack_val, bool ack_exp, bool ack_check)
{
I2C_COMMAND_t cmd;
cmd.val=0;
@ -491,7 +509,7 @@ static void IRAM_ATTR i2cSetCmd(i2c_t * i2c, uint8_t index, uint8_t op_code, uin
}
static void IRAM_ATTR fillCmdQueue(i2c_t * i2c, bool INTS)
static void ARDUINO_ISR_ATTR fillCmdQueue(i2c_t * i2c, bool INTS)
{
/* this function is called on initial i2cProcQueue() or when a I2C_END_DETECT_INT occurs
*/
@ -649,7 +667,7 @@ static void IRAM_ATTR fillCmdQueue(i2c_t * i2c, bool INTS)
}
}
static void IRAM_ATTR fillTxFifo(i2c_t * i2c)
static void ARDUINO_ISR_ATTR fillTxFifo(i2c_t * i2c)
{
/*
12/01/2017 The Fifo's are independent, 32 bytes of tx and 32 bytes of Rx.
@ -741,7 +759,7 @@ static void IRAM_ATTR fillTxFifo(i2c_t * i2c)
}
static void IRAM_ATTR emptyRxFifo(i2c_t * i2c)
static void ARDUINO_ISR_ATTR emptyRxFifo(i2c_t * i2c)
{
uint32_t d, cnt=0, moveCnt;
@ -800,7 +818,7 @@ static void IRAM_ATTR emptyRxFifo(i2c_t * i2c)
#endif
}
static void IRAM_ATTR i2cIsrExit(i2c_t * i2c,const uint32_t eventCode,bool Fatal)
static void ARDUINO_ISR_ATTR i2cIsrExit(i2c_t * i2c,const uint32_t eventCode,bool Fatal)
{
switch(eventCode) {
@ -845,7 +863,7 @@ static void IRAM_ATTR i2cIsrExit(i2c_t * i2c,const uint32_t eventCode,bool Fatal
}
static void IRAM_ATTR i2c_update_error_byte_cnt(i2c_t * i2c)
static void ARDUINO_ISR_ATTR i2c_update_error_byte_cnt(i2c_t * i2c)
{
/* i2c_update_error_byte_cnt 07/18/2018
Only called after an error has occurred, so, most of the time this function is never used.
@ -892,7 +910,7 @@ static void IRAM_ATTR i2c_update_error_byte_cnt(i2c_t * i2c)
i2c->errorByteCnt = bc;
}
static void IRAM_ATTR i2c_isr_handler_default(void* arg)
static void ARDUINO_ISR_ATTR i2c_isr_handler_default(void* arg)
{
i2c_t* p_i2c = (i2c_t*) arg; // recover data
uint32_t activeInt = p_i2c->dev->int_status.val&0x7FF;
@ -945,6 +963,14 @@ static void IRAM_ATTR i2c_isr_handler_default(void* arg)
activeInt &=~I2C_RXFIFO_FULL_INT_ST;
}
if(activeInt & I2C_RXFIFO_OVF_INT_ST) {
emptyRxFifo(p_i2c);
p_i2c->dev->int_clr.rx_fifo_full=1;
p_i2c->dev->int_ena.rx_fifo_full=1; //why?
activeInt &=~I2C_RXFIFO_OVF_INT_ST;
}
if (activeInt & I2C_ACK_ERR_INT_ST_M) {//fatal error, abort i2c service
if (p_i2c->mode == I2C_MASTER) {
i2c_update_error_byte_cnt(p_i2c); // calc which byte caused ack Error, check if address or data
@ -1239,7 +1265,7 @@ i2c_err_t i2cProcQueue(i2c_t * i2c, uint32_t *readCount, uint16_t timeOutMillis)
if(!i2c->intr_handle) { // create ISR for either peripheral
// log_i("create ISR %d",i2c->num);
uint32_t ret = 0;
uint32_t flags = ESP_INTR_FLAG_IRAM | //< ISR can be called if cache is disabled
uint32_t flags = ARDUINO_ISR_FLAG | //< ISR can be called if cache is disabled
ESP_INTR_FLAG_LOWMED | //< Low and medium prio interrupts. These can be handled in C.
ESP_INTR_FLAG_SHARED; //< Reduce resource requirements, Share interrupts
@ -1757,7 +1783,137 @@ uint32_t i2cGetStatus(i2c_t * i2c){
}
else return 0;
}
#else
#include "driver/i2c.h"
#define ACK_CHECK_EN 1 /*!< I2C master will check ack from slave*/
#define ACK_CHECK_DIS 0 /*!< I2C master will not check ack from slave */
#define ACK_VAL 0x0 /*!< I2C ack value */
#define NACK_VAL 0x1 /*!< I2C nack value */
struct i2c_struct_t {
i2c_port_t num;
};
static i2c_t * i2c_ports[2] = {NULL, NULL};
i2c_t * i2cInit(uint8_t i2c_num, int8_t sda, int8_t scl, uint32_t clk_speed){
if(i2c_num >= SOC_I2C_NUM){
return NULL;
}
if(!clk_speed){
//originally does not change the speed, but getFrequency and setFrequency need to be implemented first.
clk_speed = 100000;
}
i2c_t * out = NULL;
if(i2c_ports[i2c_num] == NULL){
out = (i2c_t*)malloc(sizeof(i2c_t));
if(out == NULL){
log_e("malloc failed");
return NULL;
}
out->num = (i2c_port_t)i2c_num;
i2c_ports[i2c_num] = out;
} else {
out = i2c_ports[i2c_num];
i2c_driver_delete((i2c_port_t)i2c_num);
}
i2c_config_t conf = { };
conf.mode = I2C_MODE_MASTER;
conf.scl_io_num = (gpio_num_t)scl;
conf.sda_io_num = (gpio_num_t)sda;
conf.scl_pullup_en = GPIO_PULLUP_ENABLE;
conf.sda_pullup_en = GPIO_PULLUP_ENABLE;
conf.master.clk_speed = clk_speed;
esp_err_t ret = i2c_param_config(out->num, &conf);
if (ret != ESP_OK) {
log_e("i2c_param_config failed");
free(out);
i2c_ports[i2c_num] = NULL;
return NULL;
}
ret = i2c_driver_install(out->num, conf.mode, 0, 0, 0);
if (ret != ESP_OK) {
log_e("i2c_driver_install failed");
free(out);
i2c_ports[i2c_num] = NULL;
return NULL;
}
return out;
}
i2c_err_t i2cWrite(i2c_t * i2c, uint16_t address, uint8_t* buff, uint16_t size, bool sendStop, uint16_t timeOutMillis){
esp_err_t ret = ESP_OK;
i2c_cmd_handle_t cmd = i2c_cmd_link_create();
i2c_master_start(cmd);
i2c_master_write_byte(cmd, (address << 1) | I2C_MASTER_WRITE, ACK_CHECK_EN);
i2c_master_write(cmd, buff, size, ACK_CHECK_EN);
//if send stop?
i2c_master_stop(cmd);
ret = i2c_master_cmd_begin(i2c->num, cmd, timeOutMillis / portTICK_RATE_MS);
i2c_cmd_link_delete(cmd);
return ret;
}
i2c_err_t i2cRead(i2c_t * i2c, uint16_t address, uint8_t* buff, uint16_t size, bool sendStop, uint16_t timeOutMillis, uint32_t *readCount){
esp_err_t ret = ESP_OK;
i2c_cmd_handle_t cmd = i2c_cmd_link_create();
i2c_master_start(cmd);
i2c_master_write_byte(cmd, (address << 1) | I2C_MASTER_READ, ACK_CHECK_EN);
if (size > 1) {
i2c_master_read(cmd, buff, size - 1, ACK_VAL);
}
i2c_master_read_byte(cmd, buff + size - 1, NACK_VAL);
i2c_master_stop(cmd);
ret = i2c_master_cmd_begin(i2c->num, cmd, timeOutMillis / portTICK_RATE_MS);
i2c_cmd_link_delete(cmd);
if(ret == ESP_OK){
*readCount = size;
}
return ret;
}
void i2cRelease(i2c_t *i2c){
log_w("");
return;
}
i2c_err_t i2cFlush(i2c_t *i2c){
esp_err_t ret = i2c_reset_tx_fifo(i2c->num);
if(ret != ESP_OK){
return ret;
}
return i2c_reset_rx_fifo(i2c->num);
}
i2c_err_t i2cSetFrequency(i2c_t * i2c, uint32_t clk_speed){
log_w("");
return ESP_OK;
}
uint32_t i2cGetFrequency(i2c_t * i2c){
log_w("");
return 0;
}
uint32_t i2cGetStatus(i2c_t * i2c){
log_w("");
return 0;
}
//Functions below should be used only if well understood
//Might be deprecated and removed in future
i2c_err_t i2cAttachSCL(i2c_t * i2c, int8_t scl){
return ESP_FAIL;
}
i2c_err_t i2cDetachSCL(i2c_t * i2c, int8_t scl){
return ESP_FAIL;
}
i2c_err_t i2cAttachSDA(i2c_t * i2c, int8_t sda){
return ESP_FAIL;
}
i2c_err_t i2cDetachSDA(i2c_t * i2c, int8_t sda){
return ESP_FAIL;
}
#endif /* CONFIG_IDF_TARGET_ESP32 */
/* todo
22JUL18

View File

@ -16,11 +16,32 @@
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "rom/ets_sys.h"
#include "esp32-hal-matrix.h"
#include "soc/dport_reg.h"
#include "soc/ledc_reg.h"
#include "soc/ledc_struct.h"
#include "driver/periph_ctrl.h"
#include "esp_system.h"
#ifdef ESP_IDF_VERSION_MAJOR // IDF 4+
#if CONFIG_IDF_TARGET_ESP32 // ESP32/PICO-D4
#include "soc/dport_reg.h"
#include "esp32/rom/ets_sys.h"
#define LAST_CHAN (15)
#elif CONFIG_IDF_TARGET_ESP32S2
#include "soc/dport_reg.h"
#include "esp32s2/rom/ets_sys.h"
#define LAST_CHAN (7)
#define LEDC_DIV_NUM_HSTIMER0_V LEDC_CLK_DIV_LSTIMER0_V
#elif CONFIG_IDF_TARGET_ESP32C3
#include "esp32c3/rom/ets_sys.h"
#define LAST_CHAN (7)
#define LEDC_DIV_NUM_HSTIMER0_V LEDC_CLK_DIV_LSTIMER0_V
#else
#error Target CONFIG_IDF_TARGET is not supported
#endif
#else // ESP32 Before IDF 4.0
#include "rom/ets_sys.h"
#endif
#if CONFIG_DISABLE_HAL_LOCKS
#define LEDC_MUTEX_LOCK()
@ -28,7 +49,7 @@
#else
#define LEDC_MUTEX_LOCK() do {} while (xSemaphoreTake(_ledc_sys_lock, portMAX_DELAY) != pdPASS)
#define LEDC_MUTEX_UNLOCK() xSemaphoreGive(_ledc_sys_lock)
xSemaphoreHandle _ledc_sys_lock;
xSemaphoreHandle _ledc_sys_lock = NULL;
#endif
/*
@ -55,18 +76,19 @@ xSemaphoreHandle _ledc_sys_lock;
static void _on_apb_change(void * arg, apb_change_ev_t ev_type, uint32_t old_apb, uint32_t new_apb){
if(ev_type == APB_AFTER_CHANGE && old_apb != new_apb){
uint32_t iarg = (uint32_t)arg;
uint8_t chan = iarg;
uint8_t group=(chan/8), timer=((chan/2)%4);
uint16_t iarg = *(uint16_t*)arg;
uint8_t chan = 0;
old_apb /= 1000000;
new_apb /= 1000000;
while(iarg){ // run though all active channels, adjusting timing configurations
if(iarg & 1) {// this channel is active
uint8_t group=(chan/8), timer=((chan/2)%4);
if(LEDC_TIMER(group, timer).conf.tick_sel){
LEDC_MUTEX_LOCK();
uint32_t old_div = LEDC_TIMER(group, timer).conf.clock_divider;
uint32_t div_num = (new_apb * old_div) / old_apb;
if(div_num > LEDC_DIV_NUM_HSTIMER0_V){
new_apb = REF_CLK_FREQ / 1000000;
div_num = (new_apb * old_div) / old_apb;
div_num = ((REF_CLK_FREQ /1000000) * old_div) / old_apb;
if(div_num > LEDC_DIV_NUM_HSTIMER0_V) {
div_num = LEDC_DIV_NUM_HSTIMER0_V;//lowest clock possible
}
@ -77,6 +99,13 @@ static void _on_apb_change(void * arg, apb_change_ev_t ev_type, uint32_t old_apb
LEDC_TIMER(group, timer).conf.clock_divider = div_num;
LEDC_MUTEX_UNLOCK();
}
else {
log_d("using REF_CLK chan=%d",chan);
}
}
iarg = iarg >> 1;
chan++;
}
}
}
@ -85,11 +114,13 @@ static void _ledcSetupTimer(uint8_t chan, uint32_t div_num, uint8_t bit_num, boo
{
uint8_t group=(chan/8), timer=((chan/2)%4);
static bool tHasStarted = false;
static uint16_t _activeChannels = 0;
if(!tHasStarted) {
tHasStarted = true;
DPORT_SET_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG, DPORT_LEDC_CLK_EN);
DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, DPORT_LEDC_RST);
periph_module_enable(PERIPH_LEDC_MODULE);
LEDC.conf.apb_clk_sel = 1;//LS use apb clock
addApbChangeCallback((void*)&_activeChannels, _on_apb_change);
#if !CONFIG_DISABLE_HAL_LOCKS
_ledc_sys_lock = xSemaphoreCreateMutex();
#endif
@ -98,15 +129,18 @@ static void _ledcSetupTimer(uint8_t chan, uint32_t div_num, uint8_t bit_num, boo
LEDC_TIMER(group, timer).conf.clock_divider = div_num;//18 bit (10.8) This register is used to configure parameter for divider in timer the least significant eight bits represent the decimal part.
LEDC_TIMER(group, timer).conf.duty_resolution = bit_num;//5 bit This register controls the range of the counter in timer. the counter range is [0 2**bit_num] the max bit width for counter is 20.
LEDC_TIMER(group, timer).conf.tick_sel = apb_clk;//apb clock
#if CONFIG_IDF_TARGET_ESP32
if(group) {
#endif
LEDC_TIMER(group, timer).conf.low_speed_update = 1;//This bit is only useful for low speed timer channels, reserved for high speed timers
#if CONFIG_IDF_TARGET_ESP32
}
#endif
LEDC_TIMER(group, timer).conf.pause = 0;
LEDC_TIMER(group, timer).conf.rst = 1;//This bit is used to reset timer the counter will be 0 after reset.
LEDC_TIMER(group, timer).conf.rst = 0;
LEDC_MUTEX_UNLOCK();
uint32_t iarg = chan;
addApbChangeCallback((void*)iarg, _on_apb_change);
_activeChannels |= (1 << chan); // mark as active for APB callback
}
//max div_num 0x3FFFF (262143)
@ -166,17 +200,21 @@ static void _ledcSetupChannel(uint8_t chan, uint8_t idle_level)
LEDC_CHAN(group, channel).duty.duty = 0;
LEDC_CHAN(group, channel).conf0.sig_out_en = 0;//This is the output enable control bit for channel
LEDC_CHAN(group, channel).conf1.duty_start = 0;//When duty_num duty_cycle and duty_scale has been configured. these register won't take effect until set duty_start. this bit is automatically cleared by hardware.
#if CONFIG_IDF_TARGET_ESP32
if(group) {
#endif
LEDC_CHAN(group, channel).conf0.low_speed_update = 1;
#if CONFIG_IDF_TARGET_ESP32
} else {
LEDC_CHAN(group, channel).conf0.clk_en = 0;
}
#endif
LEDC_MUTEX_UNLOCK();
}
double ledcSetup(uint8_t chan, double freq, uint8_t bit_num)
{
if(chan > 15) {
if(chan > LAST_CHAN) {
return 0;
}
double res_freq = _ledcSetupTimerFreq(chan, freq, bit_num);
@ -186,7 +224,7 @@ double ledcSetup(uint8_t chan, double freq, uint8_t bit_num)
void ledcWrite(uint8_t chan, uint32_t duty)
{
if(chan > 15) {
if(chan > LAST_CHAN) {
return;
}
uint8_t group=(chan/8), channel=(chan%8);
@ -195,26 +233,34 @@ void ledcWrite(uint8_t chan, uint32_t duty)
if(duty) {
LEDC_CHAN(group, channel).conf0.sig_out_en = 1;//This is the output enable control bit for channel
LEDC_CHAN(group, channel).conf1.duty_start = 1;//When duty_num duty_cycle and duty_scale has been configured. these register won't take effect until set duty_start. this bit is automatically cleared by hardware.
#if CONFIG_IDF_TARGET_ESP32
if(group) {
#endif
LEDC_CHAN(group, channel).conf0.low_speed_update = 1;
#if CONFIG_IDF_TARGET_ESP32
} else {
LEDC_CHAN(group, channel).conf0.clk_en = 1;
}
#endif
} else {
LEDC_CHAN(group, channel).conf0.sig_out_en = 0;//This is the output enable control bit for channel
LEDC_CHAN(group, channel).conf1.duty_start = 0;//When duty_num duty_cycle and duty_scale has been configured. these register won't take effect until set duty_start. this bit is automatically cleared by hardware.
#if CONFIG_IDF_TARGET_ESP32
if(group) {
#endif
LEDC_CHAN(group, channel).conf0.low_speed_update = 1;
#if CONFIG_IDF_TARGET_ESP32
} else {
LEDC_CHAN(group, channel).conf0.clk_en = 0;
}
#endif
}
LEDC_MUTEX_UNLOCK();
}
uint32_t ledcRead(uint8_t chan)
{
if(chan > 15) {
if(chan > LAST_CHAN) {
return 0;
}
return LEDC.channel_group[chan/8].channel[chan%8].duty.duty >> 4;
@ -230,7 +276,7 @@ double ledcReadFreq(uint8_t chan)
double ledcWriteTone(uint8_t chan, double freq)
{
if(chan > 15) {
if(chan > LAST_CHAN) {
return 0;
}
if(!freq) {
@ -257,14 +303,27 @@ double ledcWriteNote(uint8_t chan, note_t note, uint8_t octave){
void ledcAttachPin(uint8_t pin, uint8_t chan)
{
if(chan > 15) {
if(chan > LAST_CHAN) {
return;
}
pinMode(pin, OUTPUT);
#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3
pinMatrixOutAttach(pin, LEDC_LS_SIG_OUT0_IDX + chan, false, false);
#else
pinMatrixOutAttach(pin, ((chan/8)?LEDC_LS_SIG_OUT0_IDX:LEDC_HS_SIG_OUT0_IDX) + (chan%8), false, false);
#endif
}
void ledcDetachPin(uint8_t pin)
{
pinMatrixOutDetach(pin, false, false);
}
double ledcChangeFrequency(uint8_t chan, double freq, uint8_t bit_num)
{
if (chan > 15) {
return 0;
}
double res_freq = _ledcSetupTimerFreq(chan, freq, bit_num);
return res_freq;
}

View File

@ -35,6 +35,7 @@ uint32_t ledcRead(uint8_t channel);
double ledcReadFreq(uint8_t channel);
void ledcAttachPin(uint8_t pin, uint8_t channel);
void ledcDetachPin(uint8_t pin);
double ledcChangeFrequency(uint8_t channel, double freq, uint8_t resolution_bits);
#ifdef __cplusplus

View File

@ -20,6 +20,7 @@ extern "C"
#endif
#include "sdkconfig.h"
#include "esp_timer.h"
#define ARDUHAL_LOG_LEVEL_NONE (0)
#define ARDUHAL_LOG_LEVEL_ERROR (1)
@ -36,6 +37,9 @@ extern "C"
#define ARDUHAL_LOG_LEVEL CONFIG_ARDUHAL_LOG_DEFAULT_LEVEL
#else
#define ARDUHAL_LOG_LEVEL CORE_DEBUG_LEVEL
#ifdef USE_ESP_IDF_LOG
#define LOG_LOCAL_LEVEL CORE_DEBUG_LEVEL
#endif
#endif
#ifndef CONFIG_ARDUHAL_LOG_COLORS
@ -71,62 +75,100 @@ extern "C"
#define ARDUHAL_LOG_RESET_COLOR
#endif
const char * pathToFileName(const char * path);
int log_printf(const char *fmt, ...);
#define ARDUHAL_SHORT_LOG_FORMAT(letter, format) ARDUHAL_LOG_COLOR_ ## letter format ARDUHAL_LOG_RESET_COLOR "\r\n"
#define ARDUHAL_LOG_FORMAT(letter, format) ARDUHAL_LOG_COLOR_ ## letter "[" #letter "][%s:%u] %s(): " format ARDUHAL_LOG_RESET_COLOR "\r\n", pathToFileName(__FILE__), __LINE__, __FUNCTION__
#define ARDUHAL_LOG_FORMAT(letter, format) ARDUHAL_LOG_COLOR_ ## letter "[%6u][" #letter "][%s:%u] %s(): " format ARDUHAL_LOG_RESET_COLOR "\r\n", (unsigned long) (esp_timer_get_time() / 1000ULL), pathToFileName(__FILE__), __LINE__, __FUNCTION__
#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_VERBOSE
#ifndef USE_ESP_IDF_LOG
#define log_v(format, ...) log_printf(ARDUHAL_LOG_FORMAT(V, format), ##__VA_ARGS__)
#define isr_log_v(format, ...) ets_printf(ARDUHAL_LOG_FORMAT(V, format), ##__VA_ARGS__)
#else
#define log_v(format, ...) do {ESP_LOG_LEVEL_LOCAL(ESP_LOG_VERBOSE, TAG, format, ##__VA_ARGS__);}while(0)
#define isr_log_v(format, ...) do {ets_printf(LOG_FORMAT(V, format), esp_log_timestamp(), TAG, ##__VA_ARGS__);}while(0)
#endif
#else
#define log_v(format, ...)
#define isr_log_v(format, ...)
#endif
#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG
#ifndef USE_ESP_IDF_LOG
#define log_d(format, ...) log_printf(ARDUHAL_LOG_FORMAT(D, format), ##__VA_ARGS__)
#define isr_log_d(format, ...) ets_printf(ARDUHAL_LOG_FORMAT(D, format), ##__VA_ARGS__)
#else
#define log_d(format, ...) do {ESP_LOG_LEVEL_LOCAL(ESP_LOG_DEBUG, TAG, format, ##__VA_ARGS__);}while(0)
#define isr_log_d(format, ...) do {ets_printf(LOG_FORMAT(D, format), esp_log_timestamp(), TAG, ##__VA_ARGS__);}while(0)
#endif
#else
#define log_d(format, ...)
#define isr_log_d(format, ...)
#endif
#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_INFO
#ifndef USE_ESP_IDF_LOG
#define log_i(format, ...) log_printf(ARDUHAL_LOG_FORMAT(I, format), ##__VA_ARGS__)
#define isr_log_i(format, ...) ets_printf(ARDUHAL_LOG_FORMAT(I, format), ##__VA_ARGS__)
#else
#define log_i(format, ...) do {ESP_LOG_LEVEL_LOCAL(ESP_LOG_INFO, TAG, format, ##__VA_ARGS__);}while(0)
#define isr_log_i(format, ...) do {ets_printf(LOG_FORMAT(I, format), esp_log_timestamp(), TAG, ##__VA_ARGS__);}while(0)
#endif
#else
#define log_i(format, ...)
#define isr_log_i(format, ...)
#endif
#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_WARN
#ifndef USE_ESP_IDF_LOG
#define log_w(format, ...) log_printf(ARDUHAL_LOG_FORMAT(W, format), ##__VA_ARGS__)
#define isr_log_w(format, ...) ets_printf(ARDUHAL_LOG_FORMAT(W, format), ##__VA_ARGS__)
#else
#define log_w(format, ...) do {ESP_LOG_LEVEL_LOCAL(ESP_LOG_WARN, TAG, format, ##__VA_ARGS__);}while(0)
#define isr_log_w(format, ...) do {ets_printf(LOG_FORMAT(W, format), esp_log_timestamp(), TAG, ##__VA_ARGS__);}while(0)
#endif
#else
#define log_w(format, ...)
#define isr_log_w(format, ...)
#endif
#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_ERROR
#ifndef USE_ESP_IDF_LOG
#define log_e(format, ...) log_printf(ARDUHAL_LOG_FORMAT(E, format), ##__VA_ARGS__)
#define isr_log_e(format, ...) ets_printf(ARDUHAL_LOG_FORMAT(E, format), ##__VA_ARGS__)
#else
#define log_e(format, ...) do {log_to_esp(TAG, ESP_LOG_ERROR, format, ##__VA_ARGS__);}while(0)
#define isr_log_e(format, ...) do {ets_printf(LOG_FORMAT(E, format), esp_log_timestamp(), TAG, ##__VA_ARGS__);}while(0)
#endif
#else
#define log_e(format, ...)
#define isr_log_e(format, ...)
#endif
#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_NONE
#ifndef USE_ESP_IDF_LOG
#define log_n(format, ...) log_printf(ARDUHAL_LOG_FORMAT(E, format), ##__VA_ARGS__)
#define isr_log_n(format, ...) ets_printf(ARDUHAL_LOG_FORMAT(E, format), ##__VA_ARGS__)
#else
#define log_n(format, ...) do {ESP_LOG_LEVEL_LOCAL(ESP_LOG_ERROR, TAG, format, ##__VA_ARGS__);}while(0)
#define isr_log_n(format, ...) do {ets_printf(LOG_FORMAT(E, format), esp_log_timestamp(), TAG, ##__VA_ARGS__);}while(0)
#endif
#else
#define log_n(format, ...)
#define isr_log_n(format, ...)
#endif
#include "esp_log.h"
#ifdef USE_ESP_IDF_LOG
#ifndef TAG
#define TAG "ARDUINO"
#endif
//#define log_n(format, ...) myLog(ESP_LOG_NONE, format, ##__VA_ARGS__)
#else
#ifdef CONFIG_ARDUHAL_ESP_LOG
#undef ESP_LOGE
#undef ESP_LOGW
@ -150,6 +192,7 @@ int log_printf(const char *fmt, ...);
#define ESP_EARLY_LOGD(tag, ...) isr_log_d(__VA_ARGS__)
#define ESP_EARLY_LOGV(tag, ...) isr_log_v(__VA_ARGS__)
#endif
#endif
#ifdef __cplusplus
}

View File

@ -14,33 +14,47 @@
#include "esp32-hal-matrix.h"
#include "esp_attr.h"
#include "esp_system.h"
#ifdef ESP_IDF_VERSION_MAJOR // IDF 4+
#if CONFIG_IDF_TARGET_ESP32 // ESP32/PICO-D4
#include "esp32/rom/gpio.h"
#elif CONFIG_IDF_TARGET_ESP32S2
#include "esp32s2/rom/gpio.h"
#elif CONFIG_IDF_TARGET_ESP32C3
#include "esp32c3/rom/gpio.h"
#else
#error Target CONFIG_IDF_TARGET is not supported
#endif
#else // ESP32 Before IDF 4.0
#include "rom/gpio.h"
#endif
#define MATRIX_DETACH_OUT_SIG 0x100
#define MATRIX_DETACH_IN_LOW_PIN 0x30
#define MATRIX_DETACH_IN_LOW_HIGH 0x38
void IRAM_ATTR pinMatrixOutAttach(uint8_t pin, uint8_t function, bool invertOut, bool invertEnable)
void ARDUINO_ISR_ATTR pinMatrixOutAttach(uint8_t pin, uint8_t function, bool invertOut, bool invertEnable)
{
gpio_matrix_out(pin, function, invertOut, invertEnable);
}
void IRAM_ATTR pinMatrixOutDetach(uint8_t pin, bool invertOut, bool invertEnable)
void ARDUINO_ISR_ATTR pinMatrixOutDetach(uint8_t pin, bool invertOut, bool invertEnable)
{
gpio_matrix_out(pin, MATRIX_DETACH_OUT_SIG, invertOut, invertEnable);
}
void IRAM_ATTR pinMatrixInAttach(uint8_t pin, uint8_t signal, bool inverted)
void ARDUINO_ISR_ATTR pinMatrixInAttach(uint8_t pin, uint8_t signal, bool inverted)
{
gpio_matrix_in(pin, signal, inverted);
}
void IRAM_ATTR pinMatrixInDetach(uint8_t signal, bool high, bool inverted)
void ARDUINO_ISR_ATTR pinMatrixInDetach(uint8_t signal, bool high, bool inverted)
{
gpio_matrix_in(high?MATRIX_DETACH_IN_LOW_HIGH:MATRIX_DETACH_IN_LOW_PIN, signal, inverted);
}
/*
void IRAM_ATTR intrMatrixAttach(uint32_t source, uint32_t inum){
void ARDUINO_ISR_ATTR intrMatrixAttach(uint32_t source, uint32_t inum){
intr_matrix_set(PRO_CPU_NUM, source, inum);
}
*/

View File

@ -31,24 +31,55 @@
#include "soc/rtc.h"
#include "soc/rtc_cntl_reg.h"
#include "soc/apb_ctrl_reg.h"
#include "rom/rtc.h"
#include "esp_task_wdt.h"
#include "esp32-hal.h"
#include "esp_system.h"
#ifdef ESP_IDF_VERSION_MAJOR // IDF 4+
#if CONFIG_IDF_TARGET_ESP32 // ESP32/PICO-D4
#include "esp32/rom/rtc.h"
#elif CONFIG_IDF_TARGET_ESP32S2
#include "esp32s2/rom/rtc.h"
#include "driver/temp_sensor.h"
#elif CONFIG_IDF_TARGET_ESP32C3
#include "esp32c3/rom/rtc.h"
#include "driver/temp_sensor.h"
#else
#error Target CONFIG_IDF_TARGET is not supported
#endif
#else // ESP32 Before IDF 4.0
#include "rom/rtc.h"
#endif
//Undocumented!!! Get chip temperature in Farenheit
//Source: https://github.com/pcbreflux/espressif/blob/master/esp32/arduino/sketchbook/ESP32_int_temp_sensor/ESP32_int_temp_sensor.ino
#ifdef CONFIG_IDF_TARGET_ESP32
uint8_t temprature_sens_read();
float temperatureRead()
{
return (temprature_sens_read() - 32) / 1.8;
}
#else
float temperatureRead()
{
float result = NAN;
temp_sensor_config_t tsens = TSENS_CONFIG_DEFAULT();
temp_sensor_set_config(tsens);
temp_sensor_start();
temp_sensor_read_celsius(&result);
temp_sensor_stop();
return result;
}
#endif
void yield()
void __yield()
{
vPortYield();
}
void yield() __attribute__ ((weak, alias("__yield")));
#if CONFIG_AUTOSTART_ARDUINO
extern TaskHandle_t loopTaskHandle;
@ -129,12 +160,12 @@ BaseType_t xTaskCreateUniversal( TaskFunction_t pxTaskCode,
#endif
}
unsigned long IRAM_ATTR micros()
unsigned long ARDUINO_ISR_ATTR micros()
{
return (unsigned long) (esp_timer_get_time());
}
unsigned long IRAM_ATTR millis()
unsigned long ARDUINO_ISR_ATTR millis()
{
return (unsigned long) (esp_timer_get_time() / 1000ULL);
}
@ -144,17 +175,17 @@ void delay(uint32_t ms)
vTaskDelay(ms / portTICK_PERIOD_MS);
}
void IRAM_ATTR delayMicroseconds(uint32_t us)
void ARDUINO_ISR_ATTR delayMicroseconds(uint32_t us)
{
uint32_t m = micros();
uint64_t m = (uint64_t)esp_timer_get_time();
if(us){
uint32_t e = (m + us);
uint64_t e = (m + us);
if(m > e){ //overflow
while(micros() > e){
while((uint64_t)esp_timer_get_time() > e){
NOP();
}
}
while(micros() < e){
while((uint64_t)esp_timer_get_time() < e){
NOP();
}
}
@ -196,7 +227,7 @@ void initArduino()
#ifdef F_CPU
setCpuFrequencyMhz(F_CPU/1000000);
#endif
#if CONFIG_SPIRAM_SUPPORT
#if CONFIG_SPIRAM_SUPPORT || CONFIG_SPIRAM
psramInit();
#endif
esp_log_level_set("*", CONFIG_LOG_DEFAULT_LEVEL);
@ -225,7 +256,7 @@ void initArduino()
}
//used by hal log
const char * IRAM_ATTR pathToFileName(const char * path)
const char * ARDUINO_ISR_ATTR pathToFileName(const char * path)
{
size_t i = 0;
size_t pos = 0;

View File

@ -1,11 +1,37 @@
// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "esp32-hal.h"
#if CONFIG_SPIRAM_SUPPORT
#include "esp_spiram.h"
#if CONFIG_SPIRAM_SUPPORT || CONFIG_SPIRAM
#include "soc/efuse_reg.h"
#include "esp_heap_caps.h"
#include "esp_system.h"
#ifdef ESP_IDF_VERSION_MAJOR // IDF 4+
#if CONFIG_IDF_TARGET_ESP32 // ESP32/PICO-D4
#include "esp32/spiram.h"
#elif CONFIG_IDF_TARGET_ESP32S2
#include "esp32s2/spiram.h"
#include "esp32s2/rom/cache.h"
#else
#error Target CONFIG_IDF_TARGET is not supported
#endif
#else // ESP32 Before IDF 4.0
#include "esp_spiram.h"
#endif
static volatile bool spiramDetected = false;
static volatile bool spiramFailed = false;
@ -17,6 +43,7 @@ bool psramInit(){
if (spiramFailed) {
return false;
}
#if CONFIG_IDF_TARGET_ESP32
uint32_t chip_ver = REG_GET_FIELD(EFUSE_BLK0_RDATA3_REG, EFUSE_RD_CHIP_VER_PKG);
uint32_t pkg_ver = chip_ver & 0x7;
if (pkg_ver == EFUSE_RD_CHIP_VER_PKG_ESP32D2WDQ5 || pkg_ver == EFUSE_RD_CHIP_VER_PKG_ESP32PICOD2) {
@ -24,14 +51,21 @@ bool psramInit(){
log_w("PSRAM not supported!");
return false;
}
esp_spiram_init_cache();
#elif CONFIG_IDF_TARGET_ESP32S2
extern void esp_config_data_cache_mode(void);
esp_config_data_cache_mode();
Cache_Enable_DCache(0);
#endif
if (esp_spiram_init() != ESP_OK) {
spiramFailed = true;
log_w("PSRAM init failed!");
#if CONFIG_IDF_TARGET_ESP32
pinMatrixOutDetach(16, false, false);
pinMatrixOutDetach(17, false, false);
#endif
return false;
}
esp_spiram_init_cache();
if (!esp_spiram_test()) {
spiramFailed = true;
log_e("PSRAM test failed!");
@ -42,31 +76,34 @@ bool psramInit(){
log_e("PSRAM could not be added to the heap!");
return false;
}
#if CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL && !CONFIG_ARDUINO_ISR_IRAM
heap_caps_malloc_extmem_enable(CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL);
#endif
#endif
spiramDetected = true;
log_d("PSRAM enabled");
return true;
}
bool IRAM_ATTR psramFound(){
bool ARDUINO_ISR_ATTR psramFound(){
return spiramDetected;
}
void IRAM_ATTR *ps_malloc(size_t size){
void ARDUINO_ISR_ATTR *ps_malloc(size_t size){
if(!spiramDetected){
return NULL;
}
return heap_caps_malloc(size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
}
void IRAM_ATTR *ps_calloc(size_t n, size_t size){
void ARDUINO_ISR_ATTR *ps_calloc(size_t n, size_t size){
if(!spiramDetected){
return NULL;
}
return heap_caps_calloc(n, size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
}
void IRAM_ATTR *ps_realloc(void *ptr, size_t size){
void ARDUINO_ISR_ATTR *ps_realloc(void *ptr, size_t size){
if(!spiramDetected){
return NULL;
}
@ -79,19 +116,19 @@ bool psramInit(){
return false;
}
bool IRAM_ATTR psramFound(){
bool ARDUINO_ISR_ATTR psramFound(){
return false;
}
void IRAM_ATTR *ps_malloc(size_t size){
void ARDUINO_ISR_ATTR *ps_malloc(size_t size){
return NULL;
}
void IRAM_ATTR *ps_calloc(size_t n, size_t size){
void ARDUINO_ISR_ATTR *ps_calloc(size_t n, size_t size){
return NULL;
}
void IRAM_ATTR *ps_realloc(void *ptr, size_t size){
void ARDUINO_ISR_ATTR *ps_realloc(void *ptr, size_t size){
return NULL;
}

View File

@ -19,6 +19,17 @@
extern "C" {
#endif
#include "sdkconfig.h"
#ifndef BOARD_HAS_PSRAM
#ifdef CONFIG_SPIRAM_SUPPORT
#undef CONFIG_SPIRAM_SUPPORT
#endif
#ifdef CONFIG_SPIRAM
#undef CONFIG_SPIRAM
#endif
#endif
bool psramInit();
bool psramFound();

View File

@ -19,22 +19,36 @@
#include "esp32-hal.h"
#include "esp8266-compat.h"
#include "soc/gpio_reg.h"
#include "soc/gpio_reg.h"
#include "esp32-hal-rmt.h"
#include "driver/periph_ctrl.h"
#include "soc/rmt_struct.h"
#include "driver/periph_ctrl.h"
#include "esp_intr_alloc.h"
/**
* Internal macros
*/
#if CONFIG_IDF_TARGET_ESP32 // ESP32/PICO-D4
#define MAX_CHANNELS 8
#define MAX_DATA_PER_CHANNEL 64
#define MAX_DATA_PER_ITTERATION 62
#elif CONFIG_IDF_TARGET_ESP32S2
#define MAX_CHANNELS 4
#define MAX_DATA_PER_CHANNEL 64
#define MAX_DATA_PER_ITTERATION 62
#elif CONFIG_IDF_TARGET_ESP32C3
#define MAX_CHANNELS 4
#define MAX_DATA_PER_CHANNEL 48
#define MAX_DATA_PER_ITTERATION 46
#else
#error Target CONFIG_IDF_TARGET is not supported
#endif
#define _ABS(a) (a>0?a:-a)
#define _LIMIT(a,b) (a>b?b:a)
#if CONFIG_IDF_TARGET_ESP32C3
#define _INT_TX_END(channel) (1<<(channel))
#define _INT_RX_END(channel) (4<<(channel))
#define _INT_ERROR(channel) (16<<(channel))
#define _INT_THR_EVNT(channel) (256<<(channel))
#else
#define __INT_TX_END (1)
#define __INT_RX_END (2)
#define __INT_ERROR (4)
@ -44,6 +58,7 @@
#define _INT_RX_END(channel) (__INT_RX_END<<(channel*3))
#define _INT_ERROR(channel) (__INT_ERROR<<(channel*3))
#define _INT_THR_EVNT(channel) ((__INT_THR_EVNT)<<(channel))
#endif
#if CONFIG_DISABLE_HAL_LOCKS
# define RMT_MUTEX_LOCK(channel)
@ -53,7 +68,7 @@
# define RMT_MUTEX_UNLOCK(channel) xSemaphoreGive(g_rmt_objlocks[channel])
#endif /* CONFIG_DISABLE_HAL_LOCKS */
#define _RMT_INTERNAL_DEBUG
//#define _RMT_INTERNAL_DEBUG
#ifdef _RMT_INTERNAL_DEBUG
# define DEBUG_INTERRUPT_START(pin) digitalWrite(pin, 1);
# define DEBUG_INTERRUPT_END(pin) digitalWrite(pin, 0);
@ -94,24 +109,30 @@ struct rmt_obj_s
transaction_state_t tx_state;
rmt_rx_data_cb_t cb;
bool data_alloc;
void * arg;
};
/**
* Internal variables for channel descriptors
*/
static xSemaphoreHandle g_rmt_objlocks[MAX_CHANNELS] = {
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
NULL, NULL, NULL, NULL,
#if CONFIG_IDF_TARGET_ESP32
NULL, NULL, NULL, NULL
#endif
};
static rmt_obj_t g_rmt_objects[MAX_CHANNELS] = {
{ false, NULL, 0, 0, 0, 0, 0, NULL, E_NO_INTR, E_INACTIVE, NULL, false},
{ false, NULL, 0, 0, 0, 0, 0, NULL, E_NO_INTR, E_INACTIVE, NULL, false},
{ false, NULL, 0, 0, 0, 0, 0, NULL, E_NO_INTR, E_INACTIVE, NULL, false},
{ false, NULL, 0, 0, 0, 0, 0, NULL, E_NO_INTR, E_INACTIVE, NULL, false},
{ false, NULL, 0, 0, 0, 0, 0, NULL, E_NO_INTR, E_INACTIVE, NULL, false},
{ false, NULL, 0, 0, 0, 0, 0, NULL, E_NO_INTR, E_INACTIVE, NULL, false},
{ false, NULL, 0, 0, 0, 0, 0, NULL, E_NO_INTR, E_INACTIVE, NULL, false},
{ false, NULL, 0, 0, 0, 0, 0, NULL, E_NO_INTR, E_INACTIVE, NULL, false},
{ false, NULL, 0, 0, 0, 0, 0, NULL, E_NO_INTR, E_INACTIVE, NULL, false, NULL},
{ false, NULL, 0, 0, 0, 0, 0, NULL, E_NO_INTR, E_INACTIVE, NULL, false, NULL},
{ false, NULL, 0, 0, 0, 0, 0, NULL, E_NO_INTR, E_INACTIVE, NULL, false, NULL},
{ false, NULL, 0, 0, 0, 0, 0, NULL, E_NO_INTR, E_INACTIVE, NULL, false, NULL},
#if CONFIG_IDF_TARGET_ESP32
{ false, NULL, 0, 0, 0, 0, 0, NULL, E_NO_INTR, E_INACTIVE, NULL, false, NULL},
{ false, NULL, 0, 0, 0, 0, 0, NULL, E_NO_INTR, E_INACTIVE, NULL, false, NULL},
{ false, NULL, 0, 0, 0, 0, 0, NULL, E_NO_INTR, E_INACTIVE, NULL, false, NULL},
{ false, NULL, 0, 0, 0, 0, 0, NULL, E_NO_INTR, E_INACTIVE, NULL, false, NULL},
#endif
};
/**
@ -128,19 +149,19 @@ static xSemaphoreHandle g_rmt_block_lock = NULL;
*/
static void _initPin(int pin, int channel, bool tx_not_rx);
static bool _rmtSendOnce(rmt_obj_t* rmt, rmt_data_t* data, size_t size);
static bool _rmtSendOnce(rmt_obj_t* rmt, rmt_data_t* data, size_t size, bool continuous);
static void IRAM_ATTR _rmt_isr(void* arg);
static void ARDUINO_ISR_ATTR _rmt_isr(void* arg);
static rmt_obj_t* _rmtAllocate(int pin, int from, int size);
static void _initPin(int pin, int channel, bool tx_not_rx);
static int IRAM_ATTR _rmt_get_mem_len(uint8_t channel);
static int ARDUINO_ISR_ATTR _rmt_get_mem_len(uint8_t channel);
static void IRAM_ATTR _rmt_tx_mem_first(uint8_t ch);
static void ARDUINO_ISR_ATTR _rmt_tx_mem_first(uint8_t ch);
static void IRAM_ATTR _rmt_tx_mem_second(uint8_t ch);
static void ARDUINO_ISR_ATTR _rmt_tx_mem_second(uint8_t ch);
/**
@ -154,12 +175,17 @@ bool rmtSetCarrier(rmt_obj_t* rmt, bool carrier_en, bool carrier_level, uint32_t
size_t channel = rmt->channel;
RMT_MUTEX_LOCK(channel);
#if CONFIG_IDF_TARGET_ESP32C3
RMT.tx_carrier[channel].low = low;
RMT.tx_carrier[channel].high = high;
RMT.rx_conf[channel].conf0.carrier_en = carrier_en;
RMT.rx_conf[channel].conf0.carrier_out_lv = carrier_level;
#else
RMT.carrier_duty_ch[channel].low = low;
RMT.carrier_duty_ch[channel].high = high;
RMT.conf_ch[channel].conf0.carrier_en = carrier_en;
RMT.conf_ch[channel].conf0.carrier_out_lv = carrier_level;
#endif
RMT_MUTEX_UNLOCK(channel);
return true;
@ -175,8 +201,13 @@ bool rmtSetFilter(rmt_obj_t* rmt, bool filter_en, uint32_t filter_level)
RMT_MUTEX_LOCK(channel);
#if CONFIG_IDF_TARGET_ESP32C3
RMT.rx_conf[channel].conf1.rx_filter_thres = filter_level;
RMT.rx_conf[channel].conf1.rx_filter_en = filter_en;
#else
RMT.conf_ch[channel].conf1.rx_filter_thres = filter_level;
RMT.conf_ch[channel].conf1.rx_filter_en = filter_en;
#endif
RMT_MUTEX_UNLOCK(channel);
@ -192,7 +223,11 @@ bool rmtSetRxThreshold(rmt_obj_t* rmt, uint32_t value)
size_t channel = rmt->channel;
RMT_MUTEX_LOCK(channel);
#if CONFIG_IDF_TARGET_ESP32C3
RMT.rx_conf[channel].conf0.idle_thres = value;
#else
RMT.conf_ch[channel].conf0.idle_thres = value;
#endif
RMT_MUTEX_UNLOCK(channel);
return true;
@ -234,6 +269,20 @@ bool rmtDeinit(rmt_obj_t *rmt)
return true;
}
bool rmtLoop(rmt_obj_t* rmt, rmt_data_t* data, size_t size)
{
if (!rmt) {
return false;
}
int allocated_size = MAX_DATA_PER_CHANNEL * rmt->buffers;
if (size > allocated_size) {
return false;
}
return _rmtSendOnce(rmt, data, size, true);
}
bool rmtWrite(rmt_obj_t* rmt, rmt_data_t* data, size_t size)
{
if (!rmt) {
@ -243,13 +292,13 @@ bool rmtWrite(rmt_obj_t* rmt, rmt_data_t* data, size_t size)
int channel = rmt->channel;
int allocated_size = MAX_DATA_PER_CHANNEL * rmt->buffers;
if (size > allocated_size) {
if (size > (allocated_size - 1)) {
int half_tx_nr = MAX_DATA_PER_ITTERATION/2;
RMT_MUTEX_LOCK(channel);
// setup interrupt handler if not yet installed for half and full tx
if (!intr_handle) {
esp_intr_alloc(ETS_RMT_INTR_SOURCE, (int)ESP_INTR_FLAG_IRAM, _rmt_isr, NULL, &intr_handle);
esp_intr_alloc(ETS_RMT_INTR_SOURCE, (int)ARDUINO_ISR_FLAG, _rmt_isr, NULL, &intr_handle);
}
rmt->data_size = size - MAX_DATA_PER_ITTERATION;
@ -257,6 +306,18 @@ bool rmtWrite(rmt_obj_t* rmt, rmt_data_t* data, size_t size)
rmt->intr_mode = E_TX_INTR | E_TXTHR_INTR;
rmt->tx_state = E_SET_CONTI | E_FIRST_HALF;
#if CONFIG_IDF_TARGET_ESP32C3
//uint32_t val = RMT.tx_conf[channel].val;
// init the tx limit for interruption
RMT.tx_lim[channel].limit = half_tx_nr+2;
//RMT.tx_conf[channel].val = val;
//RMT.tx_conf[channel].conf_update = 1;
// reset memory pointer
RMT.tx_conf[channel].mem_rst = 1;
//RMT.tx_conf[channel].mem_rst = 0;
RMT.tx_conf[channel].mem_rd_rst = 1;
//RMT.tx_conf[channel].mem_rd_rst = 0;
#else
// init the tx limit for interruption
RMT.tx_lim_ch[channel].limit = half_tx_nr+2;
// reset memory pointer
@ -266,9 +327,9 @@ bool rmtWrite(rmt_obj_t* rmt, rmt_data_t* data, size_t size)
RMT.conf_ch[channel].conf1.mem_rd_rst = 0;
RMT.conf_ch[channel].conf1.mem_wr_rst = 1;
RMT.conf_ch[channel].conf1.mem_wr_rst = 0;
#endif
// set the tx end mark
RMTMEM.chan[channel].data32[MAX_DATA_PER_ITTERATION].val = 0;
//RMTMEM.chan[channel].data32[MAX_DATA_PER_ITTERATION].val = 0;
// clear and enable both Tx completed and half tx event
RMT.int_clr.val = _INT_TX_END(channel);
@ -282,10 +343,11 @@ bool rmtWrite(rmt_obj_t* rmt, rmt_data_t* data, size_t size)
RMT_MUTEX_UNLOCK(channel);
// start the transation
return _rmtSendOnce(rmt, data, MAX_DATA_PER_ITTERATION);
//return _rmtSendOnce(rmt, data, MAX_DATA_PER_ITTERATION, true);
return _rmtSendOnce(rmt, data, MAX_DATA_PER_ITTERATION, false);
} else {
// use one-go mode if data fits one buffer
return _rmtSendOnce(rmt, data, size);
return _rmtSendOnce(rmt, data, size, false);
}
}
@ -309,6 +371,7 @@ bool rmtReadData(rmt_obj_t* rmt, uint32_t* data, size_t size)
return true;
}
bool rmtBeginReceive(rmt_obj_t* rmt)
{
if (!rmt) {
@ -319,10 +382,15 @@ bool rmtBeginReceive(rmt_obj_t* rmt)
RMT.int_clr.val = _INT_ERROR(channel);
RMT.int_ena.val |= _INT_ERROR(channel);
#if CONFIG_IDF_TARGET_ESP32C3
RMT.rx_conf[channel].conf1.mem_owner = 1;
RMT.rx_conf[channel].conf1.mem_wr_rst = 1;
RMT.rx_conf[channel].conf1.rx_en = 1;
#else
RMT.conf_ch[channel].conf1.mem_owner = 1;
RMT.conf_ch[channel].conf1.mem_wr_rst = 1;
RMT.conf_ch[channel].conf1.rx_en = 1;
#endif
return true;
}
@ -342,7 +410,7 @@ bool rmtReceiveCompleted(rmt_obj_t* rmt)
}
}
bool rmtRead(rmt_obj_t* rmt, rmt_rx_data_cb_t cb)
bool rmtRead(rmt_obj_t* rmt, rmt_rx_data_cb_t cb, void * arg)
{
if (!rmt && !cb) {
return false;
@ -350,6 +418,7 @@ bool rmtRead(rmt_obj_t* rmt, rmt_rx_data_cb_t cb)
int channel = rmt->channel;
RMT_MUTEX_LOCK(channel);
rmt->arg = arg;
rmt->intr_mode = E_RX_INTR;
rmt->tx_state = E_FIRST_HALF;
rmt->cb = cb;
@ -360,17 +429,43 @@ bool rmtRead(rmt_obj_t* rmt, rmt_rx_data_cb_t cb)
rmt->data_alloc = true;
}
#if CONFIG_IDF_TARGET_ESP32C3
RMT.rx_conf[channel].conf1.mem_owner = 1;
#else
RMT.conf_ch[channel].conf1.mem_owner = 1;
#endif
RMT.int_clr.val = _INT_RX_END(channel);
RMT.int_clr.val = _INT_ERROR(channel);
RMT.int_ena.val |= _INT_RX_END(channel);
RMT.int_ena.val |= _INT_ERROR(channel);
#if CONFIG_IDF_TARGET_ESP32C3
RMT.rx_conf[channel].conf1.mem_wr_rst = 1;
RMT.rx_conf[channel].conf1.rx_en = 1;
#else
RMT.conf_ch[channel].conf1.mem_wr_rst = 1;
RMT.conf_ch[channel].conf1.rx_en = 1;
#endif
RMT_MUTEX_UNLOCK(channel);
return true;
}
bool rmtEnd(rmt_obj_t* rmt) {
if (!rmt) {
return false;
}
int channel = rmt->channel;
RMT_MUTEX_LOCK(channel);
#if CONFIG_IDF_TARGET_ESP32C3
RMT.rx_conf[channel].conf1.rx_en = 1;
#else
RMT.conf_ch[channel].conf1.rx_en = 1;
#endif
RMT_MUTEX_UNLOCK(channel);
return true;
@ -400,7 +495,11 @@ bool rmtReadAsync(rmt_obj_t* rmt, rmt_data_t* data, size_t size, void* eventFlag
RMT_MUTEX_LOCK(channel);
rmt->intr_mode = E_RX_INTR;
#if CONFIG_IDF_TARGET_ESP32C3
RMT.rx_conf[channel].conf1.mem_owner = 1;
#else
RMT.conf_ch[channel].conf1.mem_owner = 1;
#endif
RMT.int_clr.val = _INT_RX_END(channel);
RMT.int_clr.val = _INT_ERROR(channel);
@ -408,9 +507,15 @@ bool rmtReadAsync(rmt_obj_t* rmt, rmt_data_t* data, size_t size, void* eventFlag
RMT.int_ena.val |= _INT_RX_END(channel);
RMT.int_ena.val |= _INT_ERROR(channel);
#if CONFIG_IDF_TARGET_ESP32C3
RMT.rx_conf[channel].conf1.mem_wr_rst = 1;
RMT.rx_conf[channel].conf1.rx_en = 1;
#else
RMT.conf_ch[channel].conf1.mem_wr_rst = 1;
RMT.conf_ch[channel].conf1.rx_en = 1;
#endif
RMT_MUTEX_UNLOCK(channel);
// wait for data if requested so
@ -437,14 +542,20 @@ float rmtSetTick(rmt_obj_t* rmt, float tick)
* rmt tick for 1 MHz -> 1us (1x) div_cnt = 0x01
256us (256x) div_cnt = 0x00
*/
int apb_div = _LIMIT(tick/12.5, 256);
int ref_div = _LIMIT(tick/1000, 256);
float apb_tick = 12.5 * apb_div;
float ref_tick = 1000.0 * ref_div;
size_t channel = rmt->channel;
#if CONFIG_IDF_TARGET_ESP32C3
int apb_div = _LIMIT(tick/25.0, 256);
float apb_tick = 25.0 * apb_div;
RMT.tx_conf[channel].div_cnt = apb_div & 0xFF;
RMT.tx_conf[channel].conf_update = 1;
return apb_tick;
#else
int apb_div = _LIMIT(tick/12.5, 256);
int ref_div = _LIMIT(tick/1000, 256);
float apb_tick = 12.5 * apb_div;
float ref_tick = 1000.0 * ref_div;
if (_ABS(apb_tick - tick) < _ABS(ref_tick - tick)) {
RMT.conf_ch[channel].conf0.div_cnt = apb_div & 0xFF;
RMT.conf_ch[channel].conf1.ref_always_on = 1;
@ -454,6 +565,7 @@ float rmtSetTick(rmt_obj_t* rmt, float tick)
RMT.conf_ch[channel].conf1.ref_always_on = 0;
return ref_tick;
}
#endif
}
rmt_obj_t* rmtInit(int pin, bool tx_not_rx, rmt_reserve_memsize_t memsize)
@ -483,7 +595,7 @@ rmt_obj_t* rmtInit(int pin, bool tx_not_rx, rmt_reserve_memsize_t memsize)
break;
}
}
if (i == MAX_CHANNELS || i+j >= MAX_CHANNELS || j != buffers) {
if (i == MAX_CHANNELS || i+j > MAX_CHANNELS || j != buffers) {
xSemaphoreGive(g_rmt_block_lock);
return NULL;
}
@ -508,27 +620,76 @@ rmt_obj_t* rmtInit(int pin, bool tx_not_rx, rmt_reserve_memsize_t memsize)
rmt->tx_not_rx = tx_not_rx;
rmt->buffers =buffers;
rmt->channel = channel;
rmt->arg = NULL;
_initPin(pin, channel, tx_not_rx);
// Initialize the registers in default mode:
// - no carrier, filter
// - timebase tick of 1us
// - idle threshold set to 0x8000 (max pulse width + 1)
#if CONFIG_IDF_TARGET_ESP32C3
RMT.sys_conf.fifo_mask = 1;
if (tx_not_rx) {
RMT.tx_lim[channel].limit = MAX_DATA_PER_ITTERATION/2 + 2;
RMT.tx_conf[channel].val = 0;
// RMT.tx_conf[channel].carrier_en = 0;
// RMT.tx_conf[channel].carrier_out_lv = 0;
// RMT.tx_conf[channel].tx_conti_mode = 0;
// RMT.tx_conf[channel].idle_out_lv = 0; // signal level for idle
// RMT.tx_conf[channel].tx_start = 0;
// RMT.tx_conf[channel].tx_stop = 0;
// RMT.tx_conf[channel].carrier_eff_en = 0;
// RMT.tx_conf[channel].afifo_rst = 0;
// RMT.tx_conf[channel].conf_update = 0;
// RMT.tx_conf[channel].mem_tx_wrap_en = 0;
// RMT.tx_conf[channel].mem_rst = 1;
RMT.tx_conf[channel].idle_out_en = 1; // enable idle
RMT.tx_conf[channel].div_cnt = 1;
RMT.tx_conf[channel].mem_size = buffers;
RMT.tx_conf[channel].mem_rd_rst = 1;
RMT.tx_conf[channel].conf_update = 1;
} else {
RMT.rx_conf[channel].conf0.div_cnt = 1;
RMT.rx_conf[channel].conf0.mem_size = buffers;
RMT.rx_conf[channel].conf0.carrier_en = 0;
RMT.rx_conf[channel].conf0.carrier_out_lv = 0;
RMT.rx_conf[channel].conf0.idle_thres = 0x80;
RMT.rx_conf[channel].conf1.rx_filter_en = 0;
RMT.rx_conf[channel].conf1.rx_filter_thres = 0;
RMT.rx_conf[channel].conf1.mem_rst = 0;
RMT.rx_conf[channel].conf1.mem_rx_wrap_en = 0;
RMT.rx_conf[channel].conf1.afifo_rst = 0;
RMT.rx_conf[channel].conf1.conf_update = 0;
RMT.rx_conf[channel].conf1.rx_en = 1;
RMT.rx_conf[channel].conf1.mem_owner = 1;
RMT.rx_conf[channel].conf1.mem_wr_rst = 1;
}
#else
RMT.conf_ch[channel].conf0.div_cnt = 1;
RMT.conf_ch[channel].conf0.mem_size = buffers;
RMT.conf_ch[channel].conf0.carrier_en = 0;
RMT.conf_ch[channel].conf0.carrier_out_lv = 0;
#if CONFIG_IDF_TARGET_ESP32
RMT.conf_ch[channel].conf0.mem_pd = 0;
#endif
RMT.conf_ch[channel].conf0.idle_thres = 0x80;
RMT.conf_ch[channel].conf1.rx_en = 0;
RMT.conf_ch[channel].conf1.tx_conti_mode = 0;
#if CONFIG_IDF_TARGET_ESP32
RMT.conf_ch[channel].conf1.ref_cnt_rst = 0;
#else
RMT.conf_ch[channel].conf1.chk_rx_carrier_en = 0;
#endif
RMT.conf_ch[channel].conf1.rx_filter_en = 0;
RMT.conf_ch[channel].conf1.rx_filter_thres = 0;
RMT.conf_ch[channel].conf1.idle_out_lv = 0; // signal level for idle
RMT.conf_ch[channel].conf1.idle_out_en = 1; // enable idle
RMT.conf_ch[channel].conf1.ref_always_on = 0; // base clock
RMT.apb_conf.fifo_mask = 1;
if (tx_not_rx) {
@ -540,10 +701,10 @@ rmt_obj_t* rmtInit(int pin, bool tx_not_rx, rmt_reserve_memsize_t memsize)
RMT.conf_ch[channel].conf1.mem_owner = 1;
RMT.conf_ch[channel].conf1.mem_wr_rst = 1;
}
#endif
// install interrupt if at least one channel is active
if (!intr_handle) {
esp_intr_alloc(ETS_RMT_INTR_SOURCE, (int)ESP_INTR_FLAG_IRAM, _rmt_isr, NULL, &intr_handle);
esp_intr_alloc(ETS_RMT_INTR_SOURCE, (int)ARDUINO_ISR_FLAG, _rmt_isr, NULL, &intr_handle);
}
RMT_MUTEX_UNLOCK(channel);
@ -553,13 +714,17 @@ rmt_obj_t* rmtInit(int pin, bool tx_not_rx, rmt_reserve_memsize_t memsize)
/**
* Private methods definitions
*/
bool _rmtSendOnce(rmt_obj_t* rmt, rmt_data_t* data, size_t size)
bool _rmtSendOnce(rmt_obj_t* rmt, rmt_data_t* data, size_t size, bool continuous)
{
if (!rmt) {
return false;
}
int channel = rmt->channel;
#if CONFIG_IDF_TARGET_ESP32C3
RMT.sys_conf.fifo_mask = 1;
#else
RMT.apb_conf.fifo_mask = 1;
#endif
if (data && size>0) {
size_t i;
volatile uint32_t* rmt_mem_ptr = &(RMTMEM.chan[channel].data32[0].val);
@ -571,8 +736,15 @@ bool _rmtSendOnce(rmt_obj_t* rmt, rmt_data_t* data, size_t size)
}
RMT_MUTEX_LOCK(channel);
#if CONFIG_IDF_TARGET_ESP32C3
RMT.tx_conf[channel].tx_conti_mode = continuous;
RMT.tx_conf[channel].mem_rd_rst = 1;
RMT.tx_conf[channel].tx_start = 1;
#else
RMT.conf_ch[channel].conf1.tx_conti_mode = continuous;
RMT.conf_ch[channel].conf1.mem_rd_rst = 1;
RMT.conf_ch[channel].conf1.tx_start = 1;
#endif
RMT_MUTEX_UNLOCK(channel);
return true;
@ -597,6 +769,7 @@ static void _initPin(int pin, int channel, bool tx_not_rx)
{
if (!periph_enabled) {
periph_enabled = true;
periph_module_reset( PERIPH_RMT_MODULE );
periph_module_enable( PERIPH_RMT_MODULE );
}
if (tx_not_rx) {
@ -610,8 +783,9 @@ static void _initPin(int pin, int channel, bool tx_not_rx)
}
static void IRAM_ATTR _rmt_isr(void* arg)
static void ARDUINO_ISR_ATTR _rmt_isr(void* arg)
{
//DEBUG_INTERRUPT_START(4);
int intr_val = RMT.int_st.val;
size_t ch;
for (ch = 0; ch < MAX_CHANNELS; ch++) {
@ -643,12 +817,18 @@ static void IRAM_ATTR _rmt_isr(void* arg)
}
if (g_rmt_objects[ch].cb) {
// actually received data ptr
(g_rmt_objects[ch].cb)(data_received, _rmt_get_mem_len(ch));
(g_rmt_objects[ch].cb)(data_received, _rmt_get_mem_len(ch), g_rmt_objects[ch].arg);
// restart the reception
#if CONFIG_IDF_TARGET_ESP32C3
RMT.rx_conf[ch].conf1.mem_owner = 1;
RMT.rx_conf[ch].conf1.mem_wr_rst = 1;
RMT.rx_conf[ch].conf1.rx_en = 1;
#else
RMT.conf_ch[ch].conf1.mem_owner = 1;
RMT.conf_ch[ch].conf1.mem_wr_rst = 1;
RMT.conf_ch[ch].conf1.rx_en = 1;
#endif
RMT.int_ena.val |= _INT_RX_END(ch);
} else {
// if not callback provide, expect only one Rx
@ -674,10 +854,17 @@ static void IRAM_ATTR _rmt_isr(void* arg)
xEventGroupSetBits(g_rmt_objects[ch].events, RMT_FLAG_ERROR);
}
// reset memory
#if CONFIG_IDF_TARGET_ESP32C3
RMT.tx_conf[ch].mem_rd_rst = 1;
RMT.tx_conf[ch].mem_rd_rst = 0;
RMT.rx_conf[ch].conf1.mem_wr_rst = 1;
RMT.rx_conf[ch].conf1.mem_wr_rst = 0;
#else
RMT.conf_ch[ch].conf1.mem_rd_rst = 1;
RMT.conf_ch[ch].conf1.mem_rd_rst = 0;
RMT.conf_ch[ch].conf1.mem_wr_rst = 1;
RMT.conf_ch[ch].conf1.mem_wr_rst = 0;
#endif
}
if (intr_val & _INT_TX_END(ch)) {
@ -689,32 +876,50 @@ static void IRAM_ATTR _rmt_isr(void* arg)
if (intr_val & _INT_THR_EVNT(ch)) {
// clear the flag
RMT.int_clr.val = _INT_THR_EVNT(ch);
#if CONFIG_IDF_TARGET_ESP32C3
//RMT.int_clr.val = _INT_TX_END(ch);
//RMT.int_ena.val |= _INT_TX_END(ch);
#endif
// initial setup of continuous mode
if (g_rmt_objects[ch].tx_state & E_SET_CONTI) {
#if CONFIG_IDF_TARGET_ESP32C3
RMT.tx_conf[ch].tx_conti_mode = 1;
#else
RMT.conf_ch[ch].conf1.tx_conti_mode = 1;
#endif
g_rmt_objects[ch].intr_mode &= ~E_SET_CONTI;
}
_rmt_tx_mem_first(ch);
}
}
//DEBUG_INTERRUPT_END(4);
}
static void IRAM_ATTR _rmt_tx_mem_second(uint8_t ch)
static void ARDUINO_ISR_ATTR _rmt_tx_mem_second(uint8_t ch)
{
DEBUG_INTERRUPT_START(4)
uint32_t* data = g_rmt_objects[ch].data_ptr;
int half_tx_nr = MAX_DATA_PER_ITTERATION/2;
int i;
#if CONFIG_IDF_TARGET_ESP32C3
RMT.tx_lim[ch].limit = half_tx_nr+2;
#else
RMT.tx_lim_ch[ch].limit = half_tx_nr+2;
#endif
RMT.int_clr.val = _INT_THR_EVNT(ch);
RMT.int_ena.val |= _INT_THR_EVNT(ch);
#if CONFIG_IDF_TARGET_ESP32C3
//RMT.int_clr.val = _INT_TX_END(ch);
//RMT.int_ena.val &= ~_INT_TX_END(ch);
#endif
g_rmt_objects[ch].tx_state |= E_FIRST_HALF;
if (data) {
int remaining_size = g_rmt_objects[ch].data_size;
//ets_printf("RMT Tx[%d] %d\n", ch, remaining_size);
// will the remaining data occupy the entire halfbuffer
if (remaining_size > half_tx_nr) {
for (i = 0; i < half_tx_nr; i++) {
@ -733,17 +938,30 @@ static void IRAM_ATTR _rmt_tx_mem_second(uint8_t ch)
g_rmt_objects[ch].data_ptr = NULL;
}
#if CONFIG_IDF_TARGET_ESP32C3
RMTMEM.chan[ch].data32[half_tx_nr+i].val = 0;
RMT.tx_conf[ch].tx_start = 1;
#endif
} else if ((!(g_rmt_objects[ch].tx_state & E_LAST_DATA)) &&
(!(g_rmt_objects[ch].tx_state & E_END_TRANS))) {
//ets_printf("RMT Tx finishing %d!\n", ch);
for (i = 0; i < half_tx_nr; i++) {
RMTMEM.chan[ch].data32[half_tx_nr+i].val = 0x000F000F;
}
RMTMEM.chan[ch].data32[half_tx_nr+i].val = 0;
g_rmt_objects[ch].tx_state |= E_LAST_DATA;
#if CONFIG_IDF_TARGET_ESP32C3
RMT.tx_conf[ch].tx_conti_mode = 0;
#else
RMT.conf_ch[ch].conf1.tx_conti_mode = 0;
#endif
} else {
log_d("RMT Tx finished %d!\n", ch);
//ets_printf("RMT Tx finished %d!\n", ch);
#if CONFIG_IDF_TARGET_ESP32C3
RMT.tx_conf[ch].tx_conti_mode = 0;
#else
RMT.conf_ch[ch].conf1.tx_conti_mode = 0;
#endif
RMT.int_ena.val &= ~_INT_TX_END(ch);
RMT.int_ena.val &= ~_INT_THR_EVNT(ch);
g_rmt_objects[ch].intr_mode = E_NO_INTR;
@ -752,17 +970,22 @@ static void IRAM_ATTR _rmt_tx_mem_second(uint8_t ch)
DEBUG_INTERRUPT_END(4);
}
static void IRAM_ATTR _rmt_tx_mem_first(uint8_t ch)
static void ARDUINO_ISR_ATTR _rmt_tx_mem_first(uint8_t ch)
{
DEBUG_INTERRUPT_START(2);
uint32_t* data = g_rmt_objects[ch].data_ptr;
int half_tx_nr = MAX_DATA_PER_ITTERATION/2;
int i;
RMT.int_ena.val &= ~_INT_THR_EVNT(ch);
#if CONFIG_IDF_TARGET_ESP32C3
RMT.tx_lim[ch].limit = 0;
#else
RMT.tx_lim_ch[ch].limit = 0;
#endif
if (data) {
int remaining_size = g_rmt_objects[ch].data_size;
//ets_printf("RMT TxF[%d] %d\n", ch, remaining_size);
// will the remaining data occupy the entire halfbuffer
if (remaining_size > half_tx_nr) {
@ -773,7 +996,11 @@ static void IRAM_ATTR _rmt_tx_mem_first(uint8_t ch)
g_rmt_objects[ch].tx_state &= ~E_FIRST_HALF;
// turn off the treshold interrupt
RMT.int_ena.val &= ~_INT_THR_EVNT(ch);
#if CONFIG_IDF_TARGET_ESP32C3
RMT.tx_lim[ch].limit = 0;
#else
RMT.tx_lim_ch[ch].limit = 0;
#endif
g_rmt_objects[ch].data_size -= half_tx_nr;
g_rmt_objects[ch].data_ptr += half_tx_nr;
} else {
@ -790,23 +1017,37 @@ static void IRAM_ATTR _rmt_tx_mem_first(uint8_t ch)
g_rmt_objects[ch].data_ptr = NULL;
}
} else {
//ets_printf("RMT TxF finished %d!\n", ch);
for (i = 0; i < half_tx_nr; i++) {
RMTMEM.chan[ch].data32[i].val = 0x000F000F;
}
RMTMEM.chan[ch].data32[i].val = 0;
g_rmt_objects[ch].tx_state &= ~E_FIRST_HALF;
#if CONFIG_IDF_TARGET_ESP32C3
RMT.tx_lim[ch].limit = 0;
#else
RMT.tx_lim_ch[ch].limit = 0;
#endif
g_rmt_objects[ch].tx_state |= E_LAST_DATA;
#if CONFIG_IDF_TARGET_ESP32C3
RMT.tx_conf[ch].tx_conti_mode = 0;
#else
RMT.conf_ch[ch].conf1.tx_conti_mode = 0;
#endif
}
DEBUG_INTERRUPT_END(2);
}
static int IRAM_ATTR _rmt_get_mem_len(uint8_t channel)
static int ARDUINO_ISR_ATTR _rmt_get_mem_len(uint8_t channel)
{
#if CONFIG_IDF_TARGET_ESP32C3
int block_num = RMT.rx_conf[channel].conf0.mem_size;
int item_block_len = block_num * 48;
#else
int block_num = RMT.conf_ch[channel].conf0.mem_size;
int item_block_len = block_num * 64;
#endif
volatile rmt_item32_t* data = RMTMEM.chan[channel].data32;
int idx;
for(idx = 0; idx < item_block_len; idx++) {

View File

@ -40,7 +40,7 @@ typedef enum {
typedef struct rmt_obj_s rmt_obj_t;
typedef void (*rmt_rx_data_cb_t)(uint32_t *data, size_t len);
typedef void (*rmt_rx_data_cb_t)(uint32_t *data, size_t len, void *arg);
typedef struct {
union {
@ -73,6 +73,12 @@ float rmtSetTick(rmt_obj_t* rmt, float tick);
*/
bool rmtWrite(rmt_obj_t* rmt, rmt_data_t* data, size_t size);
/**
* Loop data up to the reserved memsize continuously
*
*/
bool rmtLoop(rmt_obj_t* rmt, rmt_data_t* data, size_t size);
/**
* Initiates async receive, event flag indicates data received
*
@ -84,8 +90,13 @@ bool rmtReadAsync(rmt_obj_t* rmt, rmt_data_t* data, size_t size, void* eventFlag
* and callback with data from ISR
*
*/
bool rmtRead(rmt_obj_t* rmt, rmt_rx_data_cb_t cb);
bool rmtRead(rmt_obj_t* rmt, rmt_rx_data_cb_t cb, void * arg);
/***
* Ends async receive started with rmtRead(); but does not
* rmtDeInit().
*/
bool rmtEnd(rmt_obj_t* rmt);
/* Additional interface */

View File

@ -16,11 +16,25 @@
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "rom/ets_sys.h"
#include "esp32-hal-matrix.h"
#include "soc/gpio_sd_reg.h"
#include "soc/gpio_sd_struct.h"
#include "esp_system.h"
#ifdef ESP_IDF_VERSION_MAJOR // IDF 4+
#if CONFIG_IDF_TARGET_ESP32 // ESP32/PICO-D4
#include "esp32/rom/ets_sys.h"
#elif CONFIG_IDF_TARGET_ESP32S2
#include "esp32s2/rom/ets_sys.h"
#elif CONFIG_IDF_TARGET_ESP32C3
#include "esp32c3/rom/ets_sys.h"
#else
#error Target CONFIG_IDF_TARGET is not supported
#endif
#else // ESP32 Before IDF 4.0
#include "rom/ets_sys.h"
#endif
#if CONFIG_DISABLE_HAL_LOCKS
#define SD_MUTEX_LOCK()
@ -69,6 +83,9 @@ uint32_t sigmaDeltaSetup(uint8_t channel, uint32_t freq) //chan 0-7 freq 1220-31
prescale = 0xFF;
}
SD_MUTEX_LOCK();
#ifndef CONFIG_IDF_TARGET_ESP32
SIGMADELTA.misc.function_clk_en = 1;
#endif
SIGMADELTA.channel[channel].prescale = prescale;
SIGMADELTA.cg.clk_en = 0;
SIGMADELTA.cg.clk_en = 1;

View File

@ -17,16 +17,78 @@
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "rom/ets_sys.h"
#include "esp_attr.h"
#include "esp_intr.h"
#include "rom/gpio.h"
#include "soc/spi_reg.h"
#include "soc/spi_struct.h"
#include "soc/io_mux_reg.h"
#include "soc/gpio_sig_map.h"
#include "soc/dport_reg.h"
#include "soc/rtc.h"
#include "driver/periph_ctrl.h"
#include "esp_system.h"
#ifdef ESP_IDF_VERSION_MAJOR // IDF 4+
#if CONFIG_IDF_TARGET_ESP32 // ESP32/PICO-D4
#include "soc/dport_reg.h"
#include "esp32/rom/ets_sys.h"
#include "esp32/rom/gpio.h"
#include "esp_intr_alloc.h"
#elif CONFIG_IDF_TARGET_ESP32S2
#include "soc/dport_reg.h"
#include "esp32s2/rom/ets_sys.h"
#include "esp32s2/rom/gpio.h"
#include "esp_intr_alloc.h"
#elif CONFIG_IDF_TARGET_ESP32C3
#include "esp32c3/rom/ets_sys.h"
#include "esp32c3/rom/gpio.h"
#include "esp_intr_alloc.h"
#else
#error Target CONFIG_IDF_TARGET is not supported
#endif
#else // ESP32 Before IDF 4.0
#include "rom/ets_sys.h"
#include "rom/gpio.h"
#include "esp_intr.h"
#endif
struct spi_struct_t {
spi_dev_t * dev;
#if !CONFIG_DISABLE_HAL_LOCKS
xSemaphoreHandle lock;
#endif
uint8_t num;
};
#if CONFIG_IDF_TARGET_ESP32S2
// ESP32S2
#define SPI_COUNT (3)
#define SPI_CLK_IDX(p) ((p==0)?SPICLK_OUT_MUX_IDX:((p==1)?FSPICLK_OUT_MUX_IDX:((p==2)?SPI3_CLK_OUT_MUX_IDX:0)))
#define SPI_MISO_IDX(p) ((p==0)?SPIQ_OUT_IDX:((p==1)?FSPIQ_OUT_IDX:((p==2)?SPI3_Q_OUT_IDX:0)))
#define SPI_MOSI_IDX(p) ((p==0)?SPID_IN_IDX:((p==1)?FSPID_IN_IDX:((p==2)?SPI3_D_IN_IDX:0)))
#define SPI_SPI_SS_IDX(n) ((n==0)?SPICS0_OUT_IDX:((n==1)?SPICS1_OUT_IDX:0))
#define SPI_HSPI_SS_IDX(n) ((n==0)?SPI3_CS0_OUT_IDX:((n==1)?SPI3_CS1_OUT_IDX:((n==2)?SPI3_CS2_OUT_IDX:SPI3_CS0_OUT_IDX)))
#define SPI_FSPI_SS_IDX(n) ((n==0)?FSPICS0_OUT_IDX:((n==1)?FSPICS1_OUT_IDX:((n==2)?FSPICS2_OUT_IDX:FSPICS0_OUT_IDX)))
#define SPI_SS_IDX(p, n) ((p==0)?SPI_SPI_SS_IDX(n):((p==1)?SPI_SPI_SS_IDX(n):((p==2)?SPI_HSPI_SS_IDX(n):0)))
#define SPI_INTR_SOURCE(u) ((u==0)?ETS_SPI1_INTR_SOURCE:((u==1)?ETS_SPI2_INTR_SOURCE:((u==2)?ETS_SPI3_INTR_SOURCE:0)))
#elif CONFIG_IDF_TARGET_ESP32C3
// ESP32S2
#define SPI_COUNT (1)
#define SPI_CLK_IDX(p) FSPICLK_OUT_IDX
#define SPI_MISO_IDX(p) FSPIQ_OUT_IDX
#define SPI_MOSI_IDX(p) FSPID_IN_IDX
#define SPI_SPI_SS_IDX(n) ((n==0)?FSPICS0_OUT_IDX:((n==1)?FSPICS1_OUT_IDX:((n==2)?FSPICS2_OUT_IDX:FSPICS0_OUT_IDX)))
#define SPI_SS_IDX(p, n) SPI_SPI_SS_IDX(n)
#define SPI_INTR_SOURCE(u) ETS_SPI2_INTR_SOURCE
#else
// ESP32
#define SPI_COUNT (4)
#define SPI_CLK_IDX(p) ((p==0)?SPICLK_OUT_IDX:((p==1)?SPICLK_OUT_IDX:((p==2)?HSPICLK_OUT_IDX:((p==3)?VSPICLK_OUT_IDX:0))))
#define SPI_MISO_IDX(p) ((p==0)?SPIQ_OUT_IDX:((p==1)?SPIQ_OUT_IDX:((p==2)?HSPIQ_OUT_IDX:((p==3)?VSPIQ_OUT_IDX:0))))
@ -37,36 +99,43 @@
#define SPI_VSPI_SS_IDX(n) ((n==0)?VSPICS0_OUT_IDX:((n==1)?VSPICS1_OUT_IDX:((n==2)?VSPICS2_OUT_IDX:VSPICS0_OUT_IDX)))
#define SPI_SS_IDX(p, n) ((p==0)?SPI_SPI_SS_IDX(n):((p==1)?SPI_SPI_SS_IDX(n):((p==2)?SPI_HSPI_SS_IDX(n):((p==3)?SPI_VSPI_SS_IDX(n):0))))
#define SPI_INUM(u) (2)
#define SPI_INTR_SOURCE(u) ((u==0)?ETS_SPI0_INTR_SOURCE:((u==1)?ETS_SPI1_INTR_SOURCE:((u==2)?ETS_SPI2_INTR_SOURCE:((p==3)?ETS_SPI3_INTR_SOURCE:0))))
struct spi_struct_t {
spi_dev_t * dev;
#if !CONFIG_DISABLE_HAL_LOCKS
xSemaphoreHandle lock;
#endif
uint8_t num;
};
#if CONFIG_DISABLE_HAL_LOCKS
#define SPI_MUTEX_LOCK()
#define SPI_MUTEX_UNLOCK()
static spi_t _spi_bus_array[4] = {
static spi_t _spi_bus_array[] = {
#if CONFIG_IDF_TARGET_ESP32S2
{(volatile spi_dev_t *)(DR_REG_SPI1_BASE), 0},
{(volatile spi_dev_t *)(DR_REG_SPI2_BASE), 1},
{(volatile spi_dev_t *)(DR_REG_SPI3_BASE), 2}
#else
{(volatile spi_dev_t *)(DR_REG_SPI0_BASE), 0},
{(volatile spi_dev_t *)(DR_REG_SPI1_BASE), 1},
{(volatile spi_dev_t *)(DR_REG_SPI2_BASE), 2},
{(volatile spi_dev_t *)(DR_REG_SPI3_BASE), 3}
#endif
};
#else
#define SPI_MUTEX_LOCK() do {} while (xSemaphoreTake(spi->lock, portMAX_DELAY) != pdPASS)
#define SPI_MUTEX_UNLOCK() xSemaphoreGive(spi->lock)
static spi_t _spi_bus_array[4] = {
static spi_t _spi_bus_array[] = {
#if CONFIG_IDF_TARGET_ESP32S2
{(volatile spi_dev_t *)(DR_REG_SPI1_BASE), NULL, 0},
{(volatile spi_dev_t *)(DR_REG_SPI2_BASE), NULL, 1},
{(volatile spi_dev_t *)(DR_REG_SPI3_BASE), NULL, 2}
#elif CONFIG_IDF_TARGET_ESP32C3
{(volatile spi_dev_t *)(&GPSPI2), NULL, FSPI}
#else
{(volatile spi_dev_t *)(DR_REG_SPI0_BASE), NULL, 0},
{(volatile spi_dev_t *)(DR_REG_SPI1_BASE), NULL, 1},
{(volatile spi_dev_t *)(DR_REG_SPI2_BASE), NULL, 2},
{(volatile spi_dev_t *)(DR_REG_SPI3_BASE), NULL, 3}
#endif
};
#endif
@ -76,6 +145,14 @@ void spiAttachSCK(spi_t * spi, int8_t sck)
return;
}
if(sck < 0) {
#if CONFIG_IDF_TARGET_ESP32S2
if(spi->num == FSPI) {
sck = 36;
} else {
log_e("HSPI Does not have default pins on ESP32S2!");
return;
}
#elif CONFIG_IDF_TARGET_ESP32
if(spi->num == HSPI) {
sck = 14;
} else if(spi->num == VSPI) {
@ -83,6 +160,10 @@ void spiAttachSCK(spi_t * spi, int8_t sck)
} else {
sck = 6;
}
#elif CONFIG_IDF_TARGET_ESP32C3
log_e("SPI Does not have default pins on ESP32C3!");
return;
#endif
}
pinMode(sck, OUTPUT);
pinMatrixOutAttach(sck, SPI_CLK_IDX(spi->num), false, false);
@ -94,6 +175,14 @@ void spiAttachMISO(spi_t * spi, int8_t miso)
return;
}
if(miso < 0) {
#if CONFIG_IDF_TARGET_ESP32S2
if(spi->num == FSPI) {
miso = 37;
} else {
log_e("HSPI Does not have default pins on ESP32S2!");
return;
}
#elif CONFIG_IDF_TARGET_ESP32
if(spi->num == HSPI) {
miso = 12;
} else if(spi->num == VSPI) {
@ -101,6 +190,10 @@ void spiAttachMISO(spi_t * spi, int8_t miso)
} else {
miso = 7;
}
#elif CONFIG_IDF_TARGET_ESP32C3
log_e("SPI Does not have default pins on ESP32C3!");
return;
#endif
}
SPI_MUTEX_LOCK();
pinMode(miso, INPUT);
@ -114,6 +207,14 @@ void spiAttachMOSI(spi_t * spi, int8_t mosi)
return;
}
if(mosi < 0) {
#if CONFIG_IDF_TARGET_ESP32S2
if(spi->num == FSPI) {
mosi = 35;
} else {
log_e("HSPI Does not have default pins on ESP32S2!");
return;
}
#elif CONFIG_IDF_TARGET_ESP32
if(spi->num == HSPI) {
mosi = 13;
} else if(spi->num == VSPI) {
@ -121,6 +222,10 @@ void spiAttachMOSI(spi_t * spi, int8_t mosi)
} else {
mosi = 8;
}
#elif CONFIG_IDF_TARGET_ESP32C3
log_e("SPI Does not have default pins on ESP32C3!");
return;
#endif
}
pinMode(mosi, OUTPUT);
pinMatrixOutAttach(mosi, SPI_MOSI_IDX(spi->num), false, false);
@ -132,6 +237,14 @@ void spiDetachSCK(spi_t * spi, int8_t sck)
return;
}
if(sck < 0) {
#if CONFIG_IDF_TARGET_ESP32S2
if(spi->num == FSPI) {
sck = 36;
} else {
log_e("HSPI Does not have default pins on ESP32S2!");
return;
}
#elif CONFIG_IDF_TARGET_ESP32
if(spi->num == HSPI) {
sck = 14;
} else if(spi->num == VSPI) {
@ -139,6 +252,10 @@ void spiDetachSCK(spi_t * spi, int8_t sck)
} else {
sck = 6;
}
#elif CONFIG_IDF_TARGET_ESP32C3
log_e("SPI Does not have default pins on ESP32C3!");
return;
#endif
}
pinMatrixOutDetach(sck, false, false);
pinMode(sck, INPUT);
@ -150,6 +267,14 @@ void spiDetachMISO(spi_t * spi, int8_t miso)
return;
}
if(miso < 0) {
#if CONFIG_IDF_TARGET_ESP32S2
if(spi->num == FSPI) {
miso = 37;
} else {
log_e("HSPI Does not have default pins on ESP32S2!");
return;
}
#elif CONFIG_IDF_TARGET_ESP32
if(spi->num == HSPI) {
miso = 12;
} else if(spi->num == VSPI) {
@ -157,6 +282,10 @@ void spiDetachMISO(spi_t * spi, int8_t miso)
} else {
miso = 7;
}
#elif CONFIG_IDF_TARGET_ESP32C3
log_e("SPI Does not have default pins on ESP32C3!");
return;
#endif
}
pinMatrixInDetach(SPI_MISO_IDX(spi->num), false, false);
pinMode(miso, INPUT);
@ -168,6 +297,14 @@ void spiDetachMOSI(spi_t * spi, int8_t mosi)
return;
}
if(mosi < 0) {
#if CONFIG_IDF_TARGET_ESP32S2
if(spi->num == FSPI) {
mosi = 35;
} else {
log_e("HSPI Does not have default pins on ESP32S2!");
return;
}
#elif CONFIG_IDF_TARGET_ESP32
if(spi->num == HSPI) {
mosi = 13;
} else if(spi->num == VSPI) {
@ -175,6 +312,10 @@ void spiDetachMOSI(spi_t * spi, int8_t mosi)
} else {
mosi = 8;
}
#elif CONFIG_IDF_TARGET_ESP32C3
log_e("SPI Does not have default pins on ESP32C3!");
return;
#endif
}
pinMatrixOutDetach(mosi, false, false);
pinMode(mosi, INPUT);
@ -190,6 +331,14 @@ void spiAttachSS(spi_t * spi, uint8_t cs_num, int8_t ss)
}
if(ss < 0) {
cs_num = 0;
#if CONFIG_IDF_TARGET_ESP32S2
if(spi->num == FSPI) {
ss = 34;
} else {
log_e("HSPI Does not have default pins on ESP32S2!");
return;
}
#elif CONFIG_IDF_TARGET_ESP32
if(spi->num == HSPI) {
ss = 15;
} else if(spi->num == VSPI) {
@ -197,6 +346,10 @@ void spiAttachSS(spi_t * spi, uint8_t cs_num, int8_t ss)
} else {
ss = 11;
}
#elif CONFIG_IDF_TARGET_ESP32C3
log_e("SPI Does not have default pins on ESP32C3!");
return;
#endif
}
pinMode(ss, OUTPUT);
pinMatrixOutAttach(ss, SPI_SS_IDX(spi->num, cs_num), false, false);
@ -209,6 +362,14 @@ void spiDetachSS(spi_t * spi, int8_t ss)
return;
}
if(ss < 0) {
#if CONFIG_IDF_TARGET_ESP32S2
if(spi->num == FSPI) {
ss = 34;
} else {
log_e("HSPI Does not have default pins on ESP32S2!");
return;
}
#elif CONFIG_IDF_TARGET_ESP32
if(spi->num == HSPI) {
ss = 15;
} else if(spi->num == VSPI) {
@ -216,6 +377,10 @@ void spiDetachSS(spi_t * spi, int8_t ss)
} else {
ss = 11;
}
#elif CONFIG_IDF_TARGET_ESP32C3
log_e("SPI Does not have default pins on ESP32C3!");
return;
#endif
}
pinMatrixOutDetach(ss, false, false);
pinMode(ss, INPUT);
@ -227,7 +392,11 @@ void spiEnableSSPins(spi_t * spi, uint8_t cs_mask)
return;
}
SPI_MUTEX_LOCK();
#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3
spi->dev->misc.val &= ~(cs_mask & SPI_CS_MASK_ALL);
#else
spi->dev->pin.val &= ~(cs_mask & SPI_CS_MASK_ALL);
#endif
SPI_MUTEX_UNLOCK();
}
@ -237,7 +406,11 @@ void spiDisableSSPins(spi_t * spi, uint8_t cs_mask)
return;
}
SPI_MUTEX_LOCK();
#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3
spi->dev->misc.val |= (cs_mask & SPI_CS_MASK_ALL);
#else
spi->dev->pin.val |= (cs_mask & SPI_CS_MASK_ALL);
#endif
SPI_MUTEX_UNLOCK();
}
@ -269,7 +442,11 @@ void spiSSSet(spi_t * spi)
return;
}
SPI_MUTEX_LOCK();
#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3
spi->dev->misc.cs_keep_active = 1;
#else
spi->dev->pin.cs_keep_active = 1;
#endif
SPI_MUTEX_UNLOCK();
}
@ -279,7 +456,11 @@ void spiSSClear(spi_t * spi)
return;
}
SPI_MUTEX_LOCK();
#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3
spi->dev->misc.cs_keep_active = 0;
#else
spi->dev->pin.cs_keep_active = 0;
#endif
SPI_MUTEX_UNLOCK();
}
@ -306,7 +487,11 @@ uint8_t spiGetDataMode(spi_t * spi)
if(!spi) {
return 0;
}
#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3
bool idleEdge = spi->dev->misc.ck_idle_edge;
#else
bool idleEdge = spi->dev->pin.ck_idle_edge;
#endif
bool outEdge = spi->dev->user.ck_out_edge;
if(idleEdge) {
if(outEdge) {
@ -328,20 +513,36 @@ void spiSetDataMode(spi_t * spi, uint8_t dataMode)
SPI_MUTEX_LOCK();
switch (dataMode) {
case SPI_MODE1:
#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3
spi->dev->misc.ck_idle_edge = 0;
#else
spi->dev->pin.ck_idle_edge = 0;
#endif
spi->dev->user.ck_out_edge = 1;
break;
case SPI_MODE2:
#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3
spi->dev->misc.ck_idle_edge = 1;
#else
spi->dev->pin.ck_idle_edge = 1;
#endif
spi->dev->user.ck_out_edge = 1;
break;
case SPI_MODE3:
#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3
spi->dev->misc.ck_idle_edge = 1;
#else
spi->dev->pin.ck_idle_edge = 1;
#endif
spi->dev->user.ck_out_edge = 0;
break;
case SPI_MODE0:
default:
#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3
spi->dev->misc.ck_idle_edge = 0;
#else
spi->dev->pin.ck_idle_edge = 0;
#endif
spi->dev->user.ck_out_edge = 0;
break;
}
@ -384,28 +585,48 @@ static void _on_apb_change(void * arg, apb_change_ev_t ev_type, uint32_t old_apb
}
}
static void spiInitBus(spi_t * spi)
{
#ifndef CONFIG_IDF_TARGET_ESP32C3
spi->dev->slave.trans_done = 0;
#endif
spi->dev->slave.val = 0;
#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3
spi->dev->misc.val = 0;
#else
spi->dev->pin.val = 0;
#endif
spi->dev->user.val = 0;
spi->dev->user1.val = 0;
spi->dev->ctrl.val = 0;
#ifndef CONFIG_IDF_TARGET_ESP32C3
spi->dev->ctrl1.val = 0;
spi->dev->ctrl2.val = 0;
#else
spi->dev->clk_gate.val = 0;
spi->dev->dma_conf.val = 0;
spi->dev->dma_conf.rx_afifo_rst = 1;
spi->dev->dma_conf.buf_afifo_rst = 1;
#endif
spi->dev->clock.val = 0;
}
void spiStopBus(spi_t * spi)
{
if(!spi) {
return;
}
SPI_MUTEX_LOCK();
spi->dev->slave.trans_done = 0;
spi->dev->slave.slave_mode = 0;
spi->dev->pin.val = 0;
spi->dev->user.val = 0;
spi->dev->user1.val = 0;
spi->dev->ctrl.val = 0;
spi->dev->ctrl1.val = 0;
spi->dev->ctrl2.val = 0;
spi->dev->clock.val = 0;
SPI_MUTEX_UNLOCK();
removeApbChangeCallback(spi, _on_apb_change);
SPI_MUTEX_LOCK();
spiInitBus(spi);
SPI_MUTEX_UNLOCK();
}
spi_t * spiStartBus(uint8_t spi_num, uint32_t clockDiv, uint8_t dataMode, uint8_t bitOrder)
{
if(spi_num > 3){
if(spi_num >= SPI_COUNT){
return NULL;
}
@ -420,34 +641,58 @@ spi_t * spiStartBus(uint8_t spi_num, uint32_t clockDiv, uint8_t dataMode, uint8_
}
#endif
if(spi_num == HSPI) {
DPORT_SET_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG, DPORT_SPI_CLK_EN);
DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, DPORT_SPI_RST);
} else if(spi_num == VSPI) {
DPORT_SET_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG, DPORT_SPI_CLK_EN_2);
DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, DPORT_SPI_RST_2);
#if CONFIG_IDF_TARGET_ESP32S2
if(spi_num == FSPI) {
DPORT_SET_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG, DPORT_SPI2_CLK_EN);
DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, DPORT_SPI2_RST);
} else if(spi_num == HSPI) {
DPORT_SET_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG, DPORT_SPI3_CLK_EN);
DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, DPORT_SPI3_RST);
} else {
DPORT_SET_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG, DPORT_SPI_CLK_EN_1);
DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, DPORT_SPI_RST_1);
DPORT_SET_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG, DPORT_SPI01_CLK_EN);
DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, DPORT_SPI01_RST);
}
spiStopBus(spi);
spiSetDataMode(spi, dataMode);
spiSetBitOrder(spi, bitOrder);
spiSetClockDiv(spi, clockDiv);
#elif CONFIG_IDF_TARGET_ESP32
if(spi_num == HSPI) {
DPORT_SET_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG, DPORT_SPI2_CLK_EN);
DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, DPORT_SPI2_RST);
} else if(spi_num == VSPI) {
DPORT_SET_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG, DPORT_SPI3_CLK_EN);
DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, DPORT_SPI3_RST);
} else {
DPORT_SET_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG, DPORT_SPI01_CLK_EN);
DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, DPORT_SPI01_RST);
}
#elif CONFIG_IDF_TARGET_ESP32C3
periph_module_reset( PERIPH_SPI2_MODULE );
periph_module_enable( PERIPH_SPI2_MODULE );
#endif
SPI_MUTEX_LOCK();
spiInitBus(spi);
#if CONFIG_IDF_TARGET_ESP32C3
spi->dev->clk_gate.clk_en = 1;
spi->dev->clk_gate.mst_clk_sel = 1;
spi->dev->clk_gate.mst_clk_active = 1;
spi->dev->dma_conf.tx_seg_trans_clr_en = 1;
spi->dev->dma_conf.rx_seg_trans_clr_en = 1;
spi->dev->dma_conf.dma_seg_trans_en = 0;
#endif
spi->dev->user.usr_mosi = 1;
spi->dev->user.usr_miso = 1;
spi->dev->user.doutdin = 1;
int i;
for(i=0; i<16; i++) {
spi->dev->data_buf[i] = 0x00000000;
}
SPI_MUTEX_UNLOCK();
spiSetDataMode(spi, dataMode);
spiSetBitOrder(spi, bitOrder);
spiSetClockDiv(spi, clockDiv);
addApbChangeCallback(spi, _on_apb_change);
return spi;
}
@ -459,7 +704,17 @@ void spiWaitReady(spi_t * spi)
while(spi->dev->cmd.usr);
}
void spiWrite(spi_t * spi, uint32_t *data, uint8_t len)
#if CONFIG_IDF_TARGET_ESP32S2
#define usr_mosi_dbitlen usr_mosi_bit_len
#define usr_miso_dbitlen usr_miso_bit_len
#elif CONFIG_IDF_TARGET_ESP32C3
#define usr_mosi_dbitlen ms_data_bitlen
#define usr_miso_dbitlen ms_data_bitlen
#define mosi_dlen ms_dlen
#define miso_dlen ms_dlen
#endif
void spiWrite(spi_t * spi, const uint32_t *data, uint8_t len)
{
if(!spi) {
return;
@ -470,10 +725,16 @@ void spiWrite(spi_t * spi, uint32_t *data, uint8_t len)
}
SPI_MUTEX_LOCK();
spi->dev->mosi_dlen.usr_mosi_dbitlen = (len * 32) - 1;
#ifndef CONFIG_IDF_TARGET_ESP32C3
spi->dev->miso_dlen.usr_miso_dbitlen = 0;
#endif
for(i=0; i<len; i++) {
spi->dev->data_buf[i] = data[i];
}
#if CONFIG_IDF_TARGET_ESP32C3
spi->dev->cmd.update = 1;
while (spi->dev->cmd.update);
#endif
spi->dev->cmd.usr = 1;
while(spi->dev->cmd.usr);
SPI_MUTEX_UNLOCK();
@ -494,6 +755,10 @@ void spiTransfer(spi_t * spi, uint32_t *data, uint8_t len)
for(i=0; i<len; i++) {
spi->dev->data_buf[i] = data[i];
}
#if CONFIG_IDF_TARGET_ESP32C3
spi->dev->cmd.update = 1;
while (spi->dev->cmd.update);
#endif
spi->dev->cmd.usr = 1;
while(spi->dev->cmd.usr);
for(i=0; i<len; i++) {
@ -509,8 +774,14 @@ void spiWriteByte(spi_t * spi, uint8_t data)
}
SPI_MUTEX_LOCK();
spi->dev->mosi_dlen.usr_mosi_dbitlen = 7;
#ifndef CONFIG_IDF_TARGET_ESP32C3
spi->dev->miso_dlen.usr_miso_dbitlen = 0;
#endif
spi->dev->data_buf[0] = data;
#if CONFIG_IDF_TARGET_ESP32C3
spi->dev->cmd.update = 1;
while (spi->dev->cmd.update);
#endif
spi->dev->cmd.usr = 1;
while(spi->dev->cmd.usr);
SPI_MUTEX_UNLOCK();
@ -525,6 +796,10 @@ uint8_t spiTransferByte(spi_t * spi, uint8_t data)
spi->dev->mosi_dlen.usr_mosi_dbitlen = 7;
spi->dev->miso_dlen.usr_miso_dbitlen = 7;
spi->dev->data_buf[0] = data;
#if CONFIG_IDF_TARGET_ESP32C3
spi->dev->cmd.update = 1;
while (spi->dev->cmd.update);
#endif
spi->dev->cmd.usr = 1;
while(spi->dev->cmd.usr);
data = spi->dev->data_buf[0] & 0xFF;
@ -532,17 +807,7 @@ uint8_t spiTransferByte(spi_t * spi, uint8_t data)
return data;
}
uint32_t __spiTranslate24(uint32_t data)
{
union {
uint32_t l;
uint8_t b[4];
} out;
out.l = data;
return out.b[2] | (out.b[1] << 8) | (out.b[0] << 16);
}
uint32_t __spiTranslate32(uint32_t data)
static uint32_t __spiTranslate32(uint32_t data)
{
union {
uint32_t l;
@ -562,8 +827,14 @@ void spiWriteWord(spi_t * spi, uint16_t data)
}
SPI_MUTEX_LOCK();
spi->dev->mosi_dlen.usr_mosi_dbitlen = 15;
#ifndef CONFIG_IDF_TARGET_ESP32C3
spi->dev->miso_dlen.usr_miso_dbitlen = 0;
#endif
spi->dev->data_buf[0] = data;
#if CONFIG_IDF_TARGET_ESP32C3
spi->dev->cmd.update = 1;
while (spi->dev->cmd.update);
#endif
spi->dev->cmd.usr = 1;
while(spi->dev->cmd.usr);
SPI_MUTEX_UNLOCK();
@ -581,6 +852,10 @@ uint16_t spiTransferWord(spi_t * spi, uint16_t data)
spi->dev->mosi_dlen.usr_mosi_dbitlen = 15;
spi->dev->miso_dlen.usr_miso_dbitlen = 15;
spi->dev->data_buf[0] = data;
#if CONFIG_IDF_TARGET_ESP32C3
spi->dev->cmd.update = 1;
while (spi->dev->cmd.update);
#endif
spi->dev->cmd.usr = 1;
while(spi->dev->cmd.usr);
data = spi->dev->data_buf[0];
@ -601,8 +876,14 @@ void spiWriteLong(spi_t * spi, uint32_t data)
}
SPI_MUTEX_LOCK();
spi->dev->mosi_dlen.usr_mosi_dbitlen = 31;
#ifndef CONFIG_IDF_TARGET_ESP32C3
spi->dev->miso_dlen.usr_miso_dbitlen = 0;
#endif
spi->dev->data_buf[0] = data;
#if CONFIG_IDF_TARGET_ESP32C3
spi->dev->cmd.update = 1;
while (spi->dev->cmd.update);
#endif
spi->dev->cmd.usr = 1;
while(spi->dev->cmd.usr);
SPI_MUTEX_UNLOCK();
@ -620,6 +901,10 @@ uint32_t spiTransferLong(spi_t * spi, uint32_t data)
spi->dev->mosi_dlen.usr_mosi_dbitlen = 31;
spi->dev->miso_dlen.usr_miso_dbitlen = 31;
spi->dev->data_buf[0] = data;
#if CONFIG_IDF_TARGET_ESP32C3
spi->dev->cmd.update = 1;
while (spi->dev->cmd.update);
#endif
spi->dev->cmd.usr = 1;
while(spi->dev->cmd.usr);
data = spi->dev->data_buf[0];
@ -630,7 +915,7 @@ uint32_t spiTransferLong(spi_t * spi, uint32_t data)
return data;
}
void __spiTransferBytes(spi_t * spi, uint8_t * data, uint8_t * out, uint32_t bytes)
static void __spiTransferBytes(spi_t * spi, const uint8_t * data, uint8_t * out, uint32_t bytes)
{
if(!spi) {
return;
@ -659,6 +944,10 @@ void __spiTransferBytes(spi_t * spi, uint8_t * data, uint8_t * out, uint32_t byt
spi->dev->data_buf[i] = wordsBuf[i]; //copy buffer to spi fifo
}
#if CONFIG_IDF_TARGET_ESP32C3
spi->dev->cmd.update = 1;
while (spi->dev->cmd.update);
#endif
spi->dev->cmd.usr = 1;
while(spi->dev->cmd.usr);
@ -671,7 +960,7 @@ void __spiTransferBytes(spi_t * spi, uint8_t * data, uint8_t * out, uint32_t byt
}
}
void spiTransferBytes(spi_t * spi, uint8_t * data, uint8_t * out, uint32_t size)
void spiTransferBytes(spi_t * spi, const uint8_t * data, uint8_t * out, uint32_t size)
{
if(!spi) {
return;
@ -723,20 +1012,36 @@ void spiTransaction(spi_t * spi, uint32_t clockDiv, uint8_t dataMode, uint8_t bi
spi->dev->clock.val = clockDiv;
switch (dataMode) {
case SPI_MODE1:
#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3
spi->dev->misc.ck_idle_edge = 0;
#else
spi->dev->pin.ck_idle_edge = 0;
#endif
spi->dev->user.ck_out_edge = 1;
break;
case SPI_MODE2:
#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3
spi->dev->misc.ck_idle_edge = 1;
#else
spi->dev->pin.ck_idle_edge = 1;
#endif
spi->dev->user.ck_out_edge = 1;
break;
case SPI_MODE3:
#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3
spi->dev->misc.ck_idle_edge = 1;
#else
spi->dev->pin.ck_idle_edge = 1;
#endif
spi->dev->user.ck_out_edge = 0;
break;
case SPI_MODE0:
default:
#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3
spi->dev->misc.ck_idle_edge = 0;
#else
spi->dev->pin.ck_idle_edge = 0;
#endif
spi->dev->user.ck_out_edge = 0;
break;
}
@ -765,14 +1070,20 @@ void spiEndTransaction(spi_t * spi)
SPI_MUTEX_UNLOCK();
}
void IRAM_ATTR spiWriteByteNL(spi_t * spi, uint8_t data)
void ARDUINO_ISR_ATTR spiWriteByteNL(spi_t * spi, uint8_t data)
{
if(!spi) {
return;
}
spi->dev->mosi_dlen.usr_mosi_dbitlen = 7;
#ifndef CONFIG_IDF_TARGET_ESP32C3
spi->dev->miso_dlen.usr_miso_dbitlen = 0;
#endif
spi->dev->data_buf[0] = data;
#if CONFIG_IDF_TARGET_ESP32C3
spi->dev->cmd.update = 1;
while (spi->dev->cmd.update);
#endif
spi->dev->cmd.usr = 1;
while(spi->dev->cmd.usr);
}
@ -785,13 +1096,17 @@ uint8_t spiTransferByteNL(spi_t * spi, uint8_t data)
spi->dev->mosi_dlen.usr_mosi_dbitlen = 7;
spi->dev->miso_dlen.usr_miso_dbitlen = 7;
spi->dev->data_buf[0] = data;
#if CONFIG_IDF_TARGET_ESP32C3
spi->dev->cmd.update = 1;
while (spi->dev->cmd.update);
#endif
spi->dev->cmd.usr = 1;
while(spi->dev->cmd.usr);
data = spi->dev->data_buf[0] & 0xFF;
return data;
}
void IRAM_ATTR spiWriteShortNL(spi_t * spi, uint16_t data)
void ARDUINO_ISR_ATTR spiWriteShortNL(spi_t * spi, uint16_t data)
{
if(!spi) {
return;
@ -800,8 +1115,14 @@ void IRAM_ATTR spiWriteShortNL(spi_t * spi, uint16_t data)
MSB_16_SET(data, data);
}
spi->dev->mosi_dlen.usr_mosi_dbitlen = 15;
#ifndef CONFIG_IDF_TARGET_ESP32C3
spi->dev->miso_dlen.usr_miso_dbitlen = 0;
#endif
spi->dev->data_buf[0] = data;
#if CONFIG_IDF_TARGET_ESP32C3
spi->dev->cmd.update = 1;
while (spi->dev->cmd.update);
#endif
spi->dev->cmd.usr = 1;
while(spi->dev->cmd.usr);
}
@ -817,6 +1138,10 @@ uint16_t spiTransferShortNL(spi_t * spi, uint16_t data)
spi->dev->mosi_dlen.usr_mosi_dbitlen = 15;
spi->dev->miso_dlen.usr_miso_dbitlen = 15;
spi->dev->data_buf[0] = data;
#if CONFIG_IDF_TARGET_ESP32C3
spi->dev->cmd.update = 1;
while (spi->dev->cmd.update);
#endif
spi->dev->cmd.usr = 1;
while(spi->dev->cmd.usr);
data = spi->dev->data_buf[0] & 0xFFFF;
@ -826,7 +1151,7 @@ uint16_t spiTransferShortNL(spi_t * spi, uint16_t data)
return data;
}
void IRAM_ATTR spiWriteLongNL(spi_t * spi, uint32_t data)
void ARDUINO_ISR_ATTR spiWriteLongNL(spi_t * spi, uint32_t data)
{
if(!spi) {
return;
@ -835,8 +1160,14 @@ void IRAM_ATTR spiWriteLongNL(spi_t * spi, uint32_t data)
MSB_32_SET(data, data);
}
spi->dev->mosi_dlen.usr_mosi_dbitlen = 31;
#ifndef CONFIG_IDF_TARGET_ESP32C3
spi->dev->miso_dlen.usr_miso_dbitlen = 0;
#endif
spi->dev->data_buf[0] = data;
#if CONFIG_IDF_TARGET_ESP32C3
spi->dev->cmd.update = 1;
while (spi->dev->cmd.update);
#endif
spi->dev->cmd.usr = 1;
while(spi->dev->cmd.usr);
}
@ -852,6 +1183,10 @@ uint32_t spiTransferLongNL(spi_t * spi, uint32_t data)
spi->dev->mosi_dlen.usr_mosi_dbitlen = 31;
spi->dev->miso_dlen.usr_miso_dbitlen = 31;
spi->dev->data_buf[0] = data;
#if CONFIG_IDF_TARGET_ESP32C3
spi->dev->cmd.update = 1;
while (spi->dev->cmd.update);
#endif
spi->dev->cmd.usr = 1;
while(spi->dev->cmd.usr);
data = spi->dev->data_buf[0];
@ -861,7 +1196,10 @@ uint32_t spiTransferLongNL(spi_t * spi, uint32_t data)
return data;
}
void spiWriteNL(spi_t * spi, const void * data_in, size_t len){
void spiWriteNL(spi_t * spi, const void * data_in, uint32_t len){
if(!spi) {
return;
}
size_t longs = len >> 2;
if(len & 3){
longs++;
@ -874,10 +1212,16 @@ void spiWriteNL(spi_t * spi, const void * data_in, size_t len){
c_longs = (longs > 16)?16:longs;
spi->dev->mosi_dlen.usr_mosi_dbitlen = (c_len*8)-1;
#ifndef CONFIG_IDF_TARGET_ESP32C3
spi->dev->miso_dlen.usr_miso_dbitlen = 0;
#endif
for (int i=0; i<c_longs; i++) {
spi->dev->data_buf[i] = data[i];
}
#if CONFIG_IDF_TARGET_ESP32C3
spi->dev->cmd.update = 1;
while (spi->dev->cmd.update);
#endif
spi->dev->cmd.usr = 1;
while(spi->dev->cmd.usr);
@ -887,7 +1231,7 @@ void spiWriteNL(spi_t * spi, const void * data_in, size_t len){
}
}
void spiTransferBytesNL(spi_t * spi, const void * data_in, uint8_t * data_out, size_t len){
void spiTransferBytesNL(spi_t * spi, const void * data_in, uint8_t * data_out, uint32_t len){
if(!spi) {
return;
}
@ -914,13 +1258,29 @@ void spiTransferBytesNL(spi_t * spi, const void * data_in, uint8_t * data_out, s
spi->dev->data_buf[i] = 0xFFFFFFFF;
}
}
#if CONFIG_IDF_TARGET_ESP32C3
spi->dev->cmd.update = 1;
while (spi->dev->cmd.update);
#endif
spi->dev->cmd.usr = 1;
while(spi->dev->cmd.usr);
if(result){
if(c_len & 3){
for (int i=0; i<(c_longs-1); i++) {
result[i] = spi->dev->data_buf[i];
}
uint32_t last_data = spi->dev->data_buf[c_longs-1];
uint8_t * last_out8 = (uint8_t *)&result[c_longs-1];
uint8_t * last_data8 = (uint8_t *)&last_data;
for (int i=0; i<(c_len & 3); i++) {
last_out8[i] = last_data8[i];
}
} else {
for (int i=0; i<c_longs; i++) {
result[i] = spi->dev->data_buf[i];
}
}
}
if(data){
data += c_longs;
}
@ -957,6 +1317,10 @@ void spiTransferBitsNL(spi_t * spi, uint32_t data, uint32_t * out, uint8_t bits)
spi->dev->mosi_dlen.usr_mosi_dbitlen = (bits - 1);
spi->dev->miso_dlen.usr_miso_dbitlen = (bits - 1);
spi->dev->data_buf[0] = data;
#if CONFIG_IDF_TARGET_ESP32C3
spi->dev->cmd.update = 1;
while (spi->dev->cmd.update);
#endif
spi->dev->cmd.usr = 1;
while(spi->dev->cmd.usr);
data = spi->dev->data_buf[0];
@ -974,7 +1338,7 @@ void spiTransferBitsNL(spi_t * spi, uint32_t data, uint32_t * out, uint8_t bits)
}
}
void IRAM_ATTR spiWritePixelsNL(spi_t * spi, const void * data_in, size_t len){
void ARDUINO_ISR_ATTR spiWritePixelsNL(spi_t * spi, const void * data_in, uint32_t len){
size_t longs = len >> 2;
if(len & 3){
longs++;
@ -989,7 +1353,9 @@ void IRAM_ATTR spiWritePixelsNL(spi_t * spi, const void * data_in, size_t len){
l_bytes = (c_len & 3);
spi->dev->mosi_dlen.usr_mosi_dbitlen = (c_len*8)-1;
#ifndef CONFIG_IDF_TARGET_ESP32C3
spi->dev->miso_dlen.usr_miso_dbitlen = 0;
#endif
for (int i=0; i<c_longs; i++) {
if(msb){
if(l_bytes && i == (c_longs - 1)){
@ -1005,6 +1371,10 @@ void IRAM_ATTR spiWritePixelsNL(spi_t * spi, const void * data_in, size_t len){
spi->dev->data_buf[i] = data[i];
}
}
#if CONFIG_IDF_TARGET_ESP32C3
spi->dev->cmd.update = 1;
while (spi->dev->cmd.update);
#endif
spi->dev->cmd.usr = 1;
while(spi->dev->cmd.usr);
@ -1027,7 +1397,12 @@ typedef union {
uint32_t clkcnt_l: 6; /*it must be equal to spi_clkcnt_N.*/
uint32_t clkcnt_h: 6; /*it must be floor((spi_clkcnt_N+1)/2-1).*/
uint32_t clkcnt_n: 6; /*it is the divider of spi_clk. So spi_clk frequency is system/(spi_clkdiv_pre+1)/(spi_clkcnt_N+1)*/
#if CONFIG_IDF_TARGET_ESP32C3
uint32_t clkdiv_pre: 4; /*it is pre-divider of spi_clk.*/
uint32_t reserved: 9; /*reserved*/
#else
uint32_t clkdiv_pre: 13; /*it is pre-divider of spi_clk.*/
#endif
uint32_t clk_equ_sysclk: 1; /*1: spi_clk is eqaul to system 0: spi_clk is divided from system clock.*/
};
} spiClk_t;
@ -1069,8 +1444,13 @@ uint32_t spiFrequencyToClockDiv(uint32_t freq)
while(calPreVari++ <= 1) {
calPre = (((apb_freq / (reg.clkcnt_n + 1)) / freq) - 1) + calPreVari;
#if CONFIG_IDF_TARGET_ESP32C3
if(calPre > 0xF) {
reg.clkdiv_pre = 0xF;
#else
if(calPre > 0x1FFF) {
reg.clkdiv_pre = 0x1FFF;
#endif
} else if(calPre <= 0) {
reg.clkdiv_pre = 0;
} else {

View File

@ -19,14 +19,22 @@
extern "C" {
#endif
#include "sdkconfig.h"
#include <stdint.h>
#include <stdbool.h>
#define SPI_HAS_TRANSACTION
#if CONFIG_IDF_TARGET_ESP32C3
#define FSPI 0
#define HSPI 1
#else
#define FSPI 1 //SPI bus attached to the flash (can use the same data lines but different SS)
#define HSPI 2 //SPI bus normally mapped to pins 12 - 15, but can be matrixed to any pins
#if CONFIG_IDF_TARGET_ESP32
#define VSPI 3 //SPI bus normally attached to pins 5, 18, 19 and 23, but can be matrixed to any pins
#endif
#endif
// This defines are not representing the real Divider of the ESP32
// the Defines match to an AVR Arduino on 16MHz for better compatibility
@ -54,7 +62,7 @@ extern "C" {
struct spi_struct_t;
typedef struct spi_struct_t spi_t;
spi_t * spiStartBus(uint8_t spi_num, uint32_t freq, uint8_t dataMode, uint8_t bitOrder);
spi_t * spiStartBus(uint8_t spi_num, uint32_t clockDiv, uint8_t dataMode, uint8_t bitOrder);
void spiStopBus(spi_t * spi);
//Attach/Detach Signal Pins
@ -96,7 +104,7 @@ void spiSetClockDiv(spi_t * spi, uint32_t clockDiv);
void spiSetDataMode(spi_t * spi, uint8_t dataMode);
void spiSetBitOrder(spi_t * spi, uint8_t bitOrder);
void spiWrite(spi_t * spi, uint32_t *data, uint8_t len);
void spiWrite(spi_t * spi, const uint32_t *data, uint8_t len);
void spiWriteByte(spi_t * spi, uint8_t data);
void spiWriteWord(spi_t * spi, uint16_t data);
void spiWriteLong(spi_t * spi, uint32_t data);
@ -105,7 +113,7 @@ void spiTransfer(spi_t * spi, uint32_t *out, uint8_t len);
uint8_t spiTransferByte(spi_t * spi, uint8_t data);
uint16_t spiTransferWord(spi_t * spi, uint16_t data);
uint32_t spiTransferLong(spi_t * spi, uint32_t data);
void spiTransferBytes(spi_t * spi, uint8_t * data, uint8_t * out, uint32_t size);
void spiTransferBytes(spi_t * spi, const uint8_t * data, uint8_t * out, uint32_t size);
void spiTransferBits(spi_t * spi, uint32_t data, uint32_t * out, uint8_t bits);
/*
@ -115,11 +123,11 @@ void spiTransaction(spi_t * spi, uint32_t clockDiv, uint8_t dataMode, uint8_t bi
void spiSimpleTransaction(spi_t * spi);
void spiEndTransaction(spi_t * spi);
void spiWriteNL(spi_t * spi, const void * data, uint32_t len);
void spiWriteNL(spi_t * spi, const void * data_in, uint32_t len);
void spiWriteByteNL(spi_t * spi, uint8_t data);
void spiWriteShortNL(spi_t * spi, uint16_t data);
void spiWriteLongNL(spi_t * spi, uint32_t data);
void spiWritePixelsNL(spi_t * spi, const void * data, uint32_t len);
void spiWritePixelsNL(spi_t * spi, const void * data_in, uint32_t len);
#define spiTransferNL(spi, data, len) spiTransferBytesNL(spi, data, data, len)
uint8_t spiTransferByteNL(spi_t * spi, uint8_t data);

View File

@ -14,6 +14,8 @@
#include "esp32-hal.h"
#include "lwip/apps/sntp.h"
//#include "tcpip_adapter.h"
#include "esp_netif.h"
static void setTimeZone(long offset, int daylight)
{
@ -45,6 +47,8 @@ static void setTimeZone(long offset, int daylight)
* */
void configTime(long gmtOffset_sec, int daylightOffset_sec, const char* server1, const char* server2, const char* server3)
{
//tcpip_adapter_init(); // Should not hurt anything if already inited
esp_netif_init();
if(sntp_enabled()){
sntp_stop();
}
@ -62,6 +66,8 @@ void configTime(long gmtOffset_sec, int daylightOffset_sec, const char* server1,
* */
void configTzTime(const char* tz, const char* server1, const char* server2, const char* server3)
{
//tcpip_adapter_init(); // Should not hurt anything if already inited
esp_netif_init();
if(sntp_enabled()){
sntp_stop();
}

View File

@ -14,18 +14,40 @@
#include "esp32-hal-timer.h"
#include "freertos/FreeRTOS.h"
#ifndef CONFIG_IDF_TARGET_ESP32C3
#include "freertos/xtensa_api.h"
#include "freertos/task.h"
#include "rom/ets_sys.h"
#include "soc/timer_group_struct.h"
#include "soc/dport_reg.h"
#endif
#include "freertos/task.h"
#include "soc/timer_group_struct.h"
#include "esp_attr.h"
#include "driver/periph_ctrl.h"
#include "esp_system.h"
#ifdef ESP_IDF_VERSION_MAJOR // IDF 4+
#if CONFIG_IDF_TARGET_ESP32 // ESP32/PICO-D4
#include "esp32/rom/ets_sys.h"
#include "esp_intr_alloc.h"
#elif CONFIG_IDF_TARGET_ESP32S2
#include "esp32s2/rom/ets_sys.h"
#include "esp_intr_alloc.h"
#include "soc/periph_defs.h"
#elif CONFIG_IDF_TARGET_ESP32C3
#include "esp32c3/rom/ets_sys.h"
#include "esp_intr_alloc.h"
#include "soc/periph_defs.h"
#else
#error Target CONFIG_IDF_TARGET is not supported
#endif
#else // ESP32 Before IDF 4.0
#include "rom/ets_sys.h"
#include "esp_intr.h"
#endif
#define HWTIMER_LOCK() portENTER_CRITICAL(timer->lock)
#define HWTIMER_UNLOCK() portEXIT_CRITICAL(timer->lock)
typedef struct {
typedef volatile struct {
union {
struct {
uint32_t reserved0: 10;
@ -67,11 +89,18 @@ static hw_timer_t hw_timer[4] = {
typedef void (*voidFuncPtr)(void);
static voidFuncPtr __timerInterruptHandlers[4] = {0,0,0,0};
void IRAM_ATTR __timerISR(void * arg){
void ARDUINO_ISR_ATTR __timerISR(void * arg){
#if CONFIG_IDF_TARGET_ESP32
uint32_t s0 = TIMERG0.int_st_timers.val;
uint32_t s1 = TIMERG1.int_st_timers.val;
TIMERG0.int_clr_timers.val = s0;
TIMERG1.int_clr_timers.val = s1;
#else
uint32_t s0 = TIMERG0.int_st.val;
uint32_t s1 = TIMERG1.int_st.val;
TIMERG0.int_clr.val = s0;
TIMERG1.int_clr.val = s1;
#endif
uint8_t status = (s1 & 3) << 2 | (s0 & 3);
uint8_t i = 4;
//restart the timers that should autoreload
@ -165,6 +194,7 @@ void timerStop(hw_timer_t *timer){
void timerRestart(hw_timer_t *timer){
timer->dev->config.enable = 0;
timer->dev->reload = 1;
timer->dev->config.enable = 1;
}
@ -202,15 +232,29 @@ hw_timer_t * timerBegin(uint8_t num, uint16_t divider, bool countUp){
}
hw_timer_t * timer = &hw_timer[num];
if(timer->group) {
DPORT_SET_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG, DPORT_TIMERGROUP1_CLK_EN);
DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, DPORT_TIMERGROUP1_RST);
TIMERG1.int_ena.val &= ~BIT(timer->timer);
periph_module_enable(PERIPH_TIMG1_MODULE);
} else {
DPORT_SET_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG, DPORT_TIMERGROUP_CLK_EN);
DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, DPORT_TIMERGROUP_RST);
TIMERG0.int_ena.val &= ~BIT(timer->timer);
periph_module_enable(PERIPH_TIMG0_MODULE);
}
timer->dev->config.enable = 0;
if(timer->group) {
TIMERG1.int_ena.val &= ~BIT(timer->timer);
#if CONFIG_IDF_TARGET_ESP32
TIMERG1.int_clr_timers.val |= BIT(timer->timer);
#else
TIMERG1.int_clr.val = BIT(timer->timer);
#endif
} else {
TIMERG0.int_ena.val &= ~BIT(timer->timer);
#if CONFIG_IDF_TARGET_ESP32
TIMERG0.int_clr_timers.val |= BIT(timer->timer);
#else
TIMERG0.int_clr.val = BIT(timer->timer);
#endif
}
#ifdef TIMER_GROUP_SUPPORTS_XTAL_CLOCK
timer->dev->config.use_xtal = 0;
#endif
timerSetDivider(timer, divider);
timerSetCountUp(timer, countUp);
timerSetAutoReload(timer, false);
@ -228,6 +272,12 @@ void timerEnd(hw_timer_t *timer){
}
void timerAttachInterrupt(hw_timer_t *timer, void (*fn)(void), bool edge){
#if CONFIG_IDF_TARGET_ESP32
if(edge){
log_w("EDGE timer interrupt does not work properly on ESP32! Setting to LEVEL...");
edge = false;
}
#endif
static bool initialized = false;
static intr_handle_t intr_handle = NULL;
if(intr_handle){
@ -239,8 +289,18 @@ void timerAttachInterrupt(hw_timer_t *timer, void (*fn)(void), bool edge){
timer->dev->config.alarm_en = 0;
if(timer->num & 2){
TIMERG1.int_ena.val &= ~BIT(timer->timer);
#if CONFIG_IDF_TARGET_ESP32
TIMERG1.int_clr_timers.val |= BIT(timer->timer);
#else
TIMERG1.int_clr.val = BIT(timer->timer);
#endif
} else {
TIMERG0.int_ena.val &= ~BIT(timer->timer);
#if CONFIG_IDF_TARGET_ESP32
TIMERG0.int_clr_timers.val |= BIT(timer->timer);
#else
TIMERG0.int_clr.val = BIT(timer->timer);
#endif
}
__timerInterruptHandlers[timer->num] = NULL;
} else {
@ -248,12 +308,15 @@ void timerAttachInterrupt(hw_timer_t *timer, void (*fn)(void), bool edge){
timer->dev->config.level_int_en = edge?0:1;//When set, an alarm will generate a level type interrupt.
timer->dev->config.edge_int_en = edge?1:0;//When set, an alarm will generate an edge type interrupt.
int intr_source = 0;
#ifndef CONFIG_IDF_TARGET_ESP32C3
if(!edge){
#endif
if(timer->group){
intr_source = ETS_TG1_T0_LEVEL_INTR_SOURCE + timer->timer;
} else {
intr_source = ETS_TG0_T0_LEVEL_INTR_SOURCE + timer->timer;
}
#ifndef CONFIG_IDF_TARGET_ESP32C3
} else {
if(timer->group){
intr_source = ETS_TG1_T0_EDGE_INTR_SOURCE + timer->timer;
@ -261,9 +324,10 @@ void timerAttachInterrupt(hw_timer_t *timer, void (*fn)(void), bool edge){
intr_source = ETS_TG0_T0_EDGE_INTR_SOURCE + timer->timer;
}
}
#endif
if(!initialized){
initialized = true;
esp_intr_alloc(intr_source, (int)(ESP_INTR_FLAG_IRAM|ESP_INTR_FLAG_LOWMED|ESP_INTR_FLAG_EDGE), __timerISR, NULL, &intr_handle);
esp_intr_alloc(intr_source, (int)(ARDUINO_ISR_FLAG|ESP_INTR_FLAG_LOWMED), __timerISR, NULL, &intr_handle);
} else {
intr_matrix_set(esp_intr_get_cpu(intr_handle), intr_source, esp_intr_get_intno(intr_handle));
}

View File

@ -0,0 +1,773 @@
#include "sdkconfig.h"
#if CONFIG_TINYUSB_ENABLED
#include <stdlib.h>
#include <stdbool.h>
#include "esp_log.h"
#include "soc/soc.h"
#include "soc/efuse_reg.h"
#include "soc/rtc_cntl_reg.h"
#include "soc/usb_struct.h"
#include "soc/usb_reg.h"
#include "soc/usb_wrap_reg.h"
#include "soc/usb_wrap_struct.h"
#include "soc/usb_periph.h"
#include "soc/periph_defs.h"
#include "soc/timer_group_struct.h"
#include "soc/system_reg.h"
#include "hal/usb_hal.h"
#include "hal/gpio_ll.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "driver/periph_ctrl.h"
#include "esp_efuse.h"
#include "esp_efuse_table.h"
#include "esp_rom_gpio.h"
#include "esp32-hal.h"
#include "esp32-hal-tinyusb.h"
#include "esp32s2/rom/usb/usb_persist.h"
#include "esp32s2/rom/usb/usb_dc.h"
#include "esp32s2/rom/usb/chip_usb_dw_wrapper.h"
typedef enum{
TINYUSB_USBDEV_0,
} tinyusb_usbdev_t;
typedef char *tusb_desc_strarray_device_t[USB_STRING_DESCRIPTOR_ARRAY_SIZE];
typedef struct {
bool external_phy;
} tinyusb_config_t;
static void configure_pins(usb_hal_context_t *usb)
{
for (const usb_iopin_dsc_t *iopin = usb_periph_iopins; iopin->pin != -1; ++iopin) {
if ((usb->use_external_phy) || (iopin->ext_phy_only == 0)) {
esp_rom_gpio_pad_select_gpio(iopin->pin);
if (iopin->is_output) {
esp_rom_gpio_connect_out_signal(iopin->pin, iopin->func, false, false);
} else {
esp_rom_gpio_connect_in_signal(iopin->pin, iopin->func, false);
if ((iopin->pin != GPIO_FUNC_IN_LOW) && (iopin->pin != GPIO_FUNC_IN_HIGH)) {
gpio_ll_input_enable(&GPIO, iopin->pin);
}
}
esp_rom_gpio_pad_unhold(iopin->pin);
}
}
if (!usb->use_external_phy) {
gpio_set_drive_capability(USBPHY_DM_NUM, GPIO_DRIVE_CAP_3);
gpio_set_drive_capability(USBPHY_DP_NUM, GPIO_DRIVE_CAP_3);
}
}
esp_err_t tinyusb_driver_install(const tinyusb_config_t *config)
{
log_i("Driver installation...");
// Hal init
usb_hal_context_t hal = {
.use_external_phy = config->external_phy
};
usb_hal_init(&hal);
configure_pins(&hal);
if (!tusb_init()) {
log_e("Can't initialize the TinyUSB stack.");
return ESP_FAIL;
}
log_i("Driver installed");
return ESP_OK;
}
typedef char tusb_str_t[127];
static bool WEBUSB_ENABLED = false;
static tusb_str_t WEBUSB_URL = "";
static tusb_str_t USB_DEVICE_PRODUCT = "";
static tusb_str_t USB_DEVICE_MANUFACTURER = "";
static tusb_str_t USB_DEVICE_SERIAL = "";
static uint8_t USB_DEVICE_ATTRIBUTES = 0;
static uint16_t USB_DEVICE_POWER = 0;
/*
* Device Descriptor
* */
static tusb_desc_device_t tinyusb_device_descriptor = {
.bLength = sizeof(tusb_desc_device_t),
.bDescriptorType = TUSB_DESC_DEVICE,
.bcdUSB = 0,
.bDeviceClass = 0,
.bDeviceSubClass = 0,
.bDeviceProtocol = 0,
.bMaxPacketSize0 = CFG_TUD_ENDOINT0_SIZE,
.idVendor = 0,
.idProduct = 0,
.bcdDevice = 0,
.iManufacturer = 0x01,
.iProduct = 0x02,
.iSerialNumber = 0x03,
.bNumConfigurations = 0x01
};
/*
* String Descriptors
* */
#define MAX_STRING_DESCRIPTORS 20
static uint32_t tinyusb_string_descriptor_len = 4;
static char * tinyusb_string_descriptor[MAX_STRING_DESCRIPTORS] = {
// array of pointer to string descriptors
"\x09\x04", // 0: is supported language is English (0x0409)
USB_DEVICE_MANUFACTURER,// 1: Manufacturer
USB_DEVICE_PRODUCT, // 2: Product
USB_DEVICE_SERIAL, // 3: Serials, should use chip ID
};
/* Microsoft OS 2.0 registry property descriptor
Per MS requirements https://msdn.microsoft.com/en-us/library/windows/hardware/hh450799(v=vs.85).aspx
device should create DeviceInterfaceGUIDs. It can be done by driver and
in case of real PnP solution device should expose MS "Microsoft OS 2.0
registry property descriptor". Such descriptor can insert any record
into Windows registry per device/configuration/interface. In our case it
will insert "DeviceInterfaceGUIDs" multistring property.
GUID is freshly generated and should be OK to use.
https://developers.google.com/web/fundamentals/native-hardware/build-for-webusb/
(Section Microsoft OS compatibility descriptors)
*/
#define MS_OS_20_DESC_LEN 0xB2
static uint8_t const tinyusb_ms_os_20_descriptor[] =
{
// Set header: length, type, windows version, total length
U16_TO_U8S_LE(0x000A), U16_TO_U8S_LE(MS_OS_20_SET_HEADER_DESCRIPTOR), U32_TO_U8S_LE(0x06030000), U16_TO_U8S_LE(MS_OS_20_DESC_LEN),
// Configuration subset header: length, type, configuration index, reserved, configuration total length
U16_TO_U8S_LE(0x0008), U16_TO_U8S_LE(MS_OS_20_SUBSET_HEADER_CONFIGURATION), 0, 0, U16_TO_U8S_LE(MS_OS_20_DESC_LEN-0x0A),
// Function Subset header: length, type, first interface, reserved, subset length
U16_TO_U8S_LE(0x0008), U16_TO_U8S_LE(MS_OS_20_SUBSET_HEADER_FUNCTION), 0, 0, U16_TO_U8S_LE(MS_OS_20_DESC_LEN-0x0A-0x08),
// MS OS 2.0 Compatible ID descriptor: length, type, compatible ID, sub compatible ID
U16_TO_U8S_LE(0x0014), U16_TO_U8S_LE(MS_OS_20_FEATURE_COMPATBLE_ID), 'W', 'I', 'N', 'U', 'S', 'B', 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // sub-compatible
// MS OS 2.0 Registry property descriptor: length, type
U16_TO_U8S_LE(MS_OS_20_DESC_LEN-0x0A-0x08-0x08-0x14), U16_TO_U8S_LE(MS_OS_20_FEATURE_REG_PROPERTY),
U16_TO_U8S_LE(0x0007), U16_TO_U8S_LE(0x002A), // wPropertyDataType, wPropertyNameLength and PropertyName "DeviceInterfaceGUIDs\0" in UTF-16
'D', 0x00, 'e', 0x00, 'v', 0x00, 'i', 0x00, 'c', 0x00, 'e', 0x00, 'I', 0x00, 'n', 0x00, 't', 0x00, 'e', 0x00,
'r', 0x00, 'f', 0x00, 'a', 0x00, 'c', 0x00, 'e', 0x00, 'G', 0x00, 'U', 0x00, 'I', 0x00, 'D', 0x00, 's', 0x00, 0x00, 0x00,
U16_TO_U8S_LE(0x0050), // wPropertyDataLength
//bPropertyData: “{975F44D9-0D08-43FD-8B3E-127CA8AFFF9D}”.
'{', 0x00, '9', 0x00, '7', 0x00, '5', 0x00, 'F', 0x00, '4', 0x00, '4', 0x00, 'D', 0x00, '9', 0x00, '-', 0x00,
'0', 0x00, 'D', 0x00, '0', 0x00, '8', 0x00, '-', 0x00, '4', 0x00, '3', 0x00, 'F', 0x00, 'D', 0x00, '-', 0x00,
'8', 0x00, 'B', 0x00, '3', 0x00, 'E', 0x00, '-', 0x00, '1', 0x00, '2', 0x00, '7', 0x00, 'C', 0x00, 'A', 0x00,
'8', 0x00, 'A', 0x00, 'F', 0x00, 'F', 0x00, 'F', 0x00, '9', 0x00, 'D', 0x00, '}', 0x00, 0x00, 0x00, 0x00, 0x00
};
TU_VERIFY_STATIC(sizeof(tinyusb_ms_os_20_descriptor) == MS_OS_20_DESC_LEN, "Incorrect size");
/*
* BOS Descriptor (required for webUSB)
* */
#define BOS_TOTAL_LEN (TUD_BOS_DESC_LEN + TUD_BOS_WEBUSB_DESC_LEN + TUD_BOS_MICROSOFT_OS_DESC_LEN)
enum {
VENDOR_REQUEST_WEBUSB = 1,
VENDOR_REQUEST_MICROSOFT = 2
};
static uint8_t const tinyusb_bos_descriptor[] = {
// total length, number of device caps
TUD_BOS_DESCRIPTOR(BOS_TOTAL_LEN, 2),
// Vendor Code, iLandingPage
TUD_BOS_WEBUSB_DESCRIPTOR(VENDOR_REQUEST_WEBUSB, 1),
// Microsoft OS 2.0 descriptor
TUD_BOS_MS_OS_20_DESCRIPTOR(MS_OS_20_DESC_LEN, VENDOR_REQUEST_MICROSOFT)
};
/*
* URL Descriptor (required for webUSB)
* */
typedef struct TU_ATTR_PACKED {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bScheme;
char url[127];
} tinyusb_desc_webusb_url_t;
static tinyusb_desc_webusb_url_t tinyusb_url_descriptor = {
.bLength = 3,
.bDescriptorType = 3, // WEBUSB URL type
.bScheme = 255, // URL Scheme Prefix: 0: "http://", 1: "https://", 255: ""
.url = ""
};
/*
* Configuration Descriptor
* */
static tinyusb_descriptor_cb_t tinyusb_loaded_interfaces_callbacks[USB_INTERFACE_MAX];
static uint32_t tinyusb_loaded_interfaces_mask = 0;
static uint8_t tinyusb_loaded_interfaces_num = 0;
static uint16_t tinyusb_config_descriptor_len = 0;
static uint8_t * tinyusb_config_descriptor = NULL;
/*
* Endpoint Usage Tracking
* */
typedef union {
struct {
uint32_t in:16;
uint32_t out:16;
};
uint32_t val;
} tinyusb_endpoints_usage_t;
static tinyusb_endpoints_usage_t tinyusb_endpoints;
/*
* TinyUSB Callbacks
* */
/**
* @brief Invoked when received GET CONFIGURATION DESCRIPTOR.
*/
uint8_t const *tud_descriptor_configuration_cb(uint8_t index)
{
//log_d("%u", index);
return tinyusb_config_descriptor;
}
/**
* @brief Invoked when received GET DEVICE DESCRIPTOR.
*/
uint8_t const *tud_descriptor_device_cb(void)
{
//log_d("");
return (uint8_t const *)&tinyusb_device_descriptor;
}
/**
* @brief Invoked when received GET STRING DESCRIPTOR request.
*/
uint16_t const *tud_descriptor_string_cb(uint8_t index, uint16_t langid)
{
//log_d("%u (0x%x)", index, langid);
static uint16_t _desc_str[127];
uint8_t chr_count;
if (index == 0) {
memcpy(&_desc_str[1], tinyusb_string_descriptor[0], 2);
chr_count = 1;
} else {
// Convert ASCII string into UTF-16
if (index >= tinyusb_string_descriptor_len) {
return NULL;
}
const char *str = tinyusb_string_descriptor[index];
// Cap at max char
chr_count = strlen(str);
if (chr_count > 126) {
chr_count = 126;
}
for (uint8_t i = 0; i < chr_count; i++) {
_desc_str[1 + i] = str[i];
}
}
// first byte is len, second byte is string type
_desc_str[0] = (TUSB_DESC_STRING << 8 ) | (2*chr_count + 2);
return _desc_str;
}
/**
* @brief Invoked when received GET BOS DESCRIPTOR request.
*/
uint8_t const * tud_descriptor_bos_cb(void)
{
//log_v("");
return tinyusb_bos_descriptor;
}
__attribute__ ((weak)) bool tinyusb_vendor_control_request_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t const * request){ return false; }
/**
* @brief Handle WebUSB and Vendor requests.
*/
bool tud_vendor_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t const * request)
{
if(WEBUSB_ENABLED && (request->bRequest == VENDOR_REQUEST_WEBUSB
|| (request->bRequest == VENDOR_REQUEST_MICROSOFT && request->wIndex == 7))){
// we only care for SETUP stage
if (stage == CONTROL_STAGE_SETUP) {
if(request->bRequest == VENDOR_REQUEST_WEBUSB){
// match vendor request in BOS descriptor
// Get landing page url
tinyusb_url_descriptor.bLength = 3 + strlen(WEBUSB_URL);
snprintf(tinyusb_url_descriptor.url, 127, "%s", WEBUSB_URL);
return tud_control_xfer(rhport, request, (void*) &tinyusb_url_descriptor, tinyusb_url_descriptor.bLength);
}
// Get Microsoft OS 2.0 compatible descriptor
uint16_t total_len;
memcpy(&total_len, tinyusb_ms_os_20_descriptor + 8, 2);
return tud_control_xfer(rhport, request, (void*) tinyusb_ms_os_20_descriptor, total_len);
}
return true;
}
log_v("rhport: %u, stage: %u, type: 0x%x, request: 0x%x", rhport, stage, request->bmRequestType_bit.type, request->bRequest);
return tinyusb_vendor_control_request_cb(rhport, stage, request);
}
/*
* Required Callbacks
* */
#if CFG_TUD_HID
__attribute__ ((weak)) const uint8_t * tud_hid_descriptor_report_cb(uint8_t itf){return NULL;}
__attribute__ ((weak)) uint16_t tud_hid_get_report_cb(uint8_t itf, uint8_t report_id, hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen){return 0;}
__attribute__ ((weak)) void tud_hid_set_report_cb(uint8_t itf, uint8_t report_id, hid_report_type_t report_type, const uint8_t * buffer, uint16_t bufsize){}
#endif
#if CFG_TUD_MSC
__attribute__ ((weak)) bool tud_msc_test_unit_ready_cb(uint8_t lun){return false;}
__attribute__ ((weak)) void tud_msc_inquiry_cb(uint8_t lun, uint8_t vendor_id[8], uint8_t product_id[16], uint8_t product_rev[4]){}
__attribute__ ((weak)) void tud_msc_capacity_cb(uint8_t lun, uint32_t* block_count, uint16_t* block_size){}
__attribute__ ((weak)) int32_t tud_msc_read10_cb(uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize){return -1;}
__attribute__ ((weak)) int32_t tud_msc_write10_cb(uint8_t lun, uint32_t lba, uint32_t offset, uint8_t* buffer, uint32_t bufsize){return -1;}
__attribute__ ((weak)) int32_t tud_msc_scsi_cb (uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, uint16_t bufsize){return -1;}
#endif
/*
* Private API
* */
static bool usb_persist_enabled = false;
static restart_type_t usb_persist_mode = RESTART_NO_PERSIST;
static bool tinyusb_reserve_in_endpoint(uint8_t endpoint){
if(endpoint > 6 || (tinyusb_endpoints.in & BIT(endpoint)) != 0){
return false;
}
tinyusb_endpoints.in |= BIT(endpoint);
return true;
}
static bool tinyusb_reserve_out_endpoint(uint8_t endpoint){
if(endpoint > 6 || (tinyusb_endpoints.out & BIT(endpoint)) != 0){
return false;
}
tinyusb_endpoints.out |= BIT(endpoint);
return true;
}
static bool tinyusb_has_available_fifos(void){
uint8_t max_endpoints = 4, active_endpoints = 0;
if (tinyusb_loaded_interfaces_mask & BIT(USB_INTERFACE_CDC)) {
max_endpoints = 5; //CDC endpoint 0x85 is actually not linked to FIFO and not used
}
for(uint8_t i=1; i<7; i++){
if((tinyusb_endpoints.in & BIT(i)) != 0){
active_endpoints++;
}
}
return active_endpoints < max_endpoints;
}
static uint16_t tinyusb_load_descriptor(tinyusb_interface_t interface, uint8_t * dst, uint8_t * itf)
{
if(tinyusb_loaded_interfaces_callbacks[interface]){
return tinyusb_loaded_interfaces_callbacks[interface](dst, itf);
}
return 0;
}
static bool tinyusb_load_enabled_interfaces(){
tinyusb_config_descriptor_len += TUD_CONFIG_DESC_LEN;
tinyusb_config_descriptor = (uint8_t *)malloc(tinyusb_config_descriptor_len);
if (tinyusb_config_descriptor == NULL) {
log_e("Descriptor Malloc Failed");
return false;
}
uint8_t * dst = tinyusb_config_descriptor + TUD_CONFIG_DESC_LEN;
for(int i=0; i<USB_INTERFACE_MAX; i++){
if (tinyusb_loaded_interfaces_mask & (1U << i)) {
uint16_t len = tinyusb_load_descriptor((tinyusb_interface_t)i, dst, &tinyusb_loaded_interfaces_num);
if (!len) {
log_e("Descriptor Load Failed");
return false;
} else {
if(i == USB_INTERFACE_CDC){
if(!tinyusb_reserve_out_endpoint(3) ||!tinyusb_reserve_in_endpoint(4) || !tinyusb_reserve_in_endpoint(5)){
log_e("CDC Reserve Endpoints Failed");
return false;
}
}
dst += len;
}
}
}
uint8_t str_index = tinyusb_add_string_descriptor("TinyUSB Device");
uint8_t descriptor[TUD_CONFIG_DESC_LEN] = {
//num configs, interface count, string index, total length, attribute, power in mA
TUD_CONFIG_DESCRIPTOR(1, tinyusb_loaded_interfaces_num, str_index, tinyusb_config_descriptor_len, USB_DEVICE_ATTRIBUTES, USB_DEVICE_POWER)
};
memcpy(tinyusb_config_descriptor, descriptor, TUD_CONFIG_DESC_LEN);
if ((tinyusb_loaded_interfaces_mask == (BIT(USB_INTERFACE_CDC) | BIT(USB_INTERFACE_DFU))) || (tinyusb_loaded_interfaces_mask == BIT(USB_INTERFACE_CDC))) {
//usb_persist_enabled = true;
//log_d("USB Persist enabled");
}
log_d("Load Done: if_num: %u, descr_len: %u, if_mask: 0x%x", tinyusb_loaded_interfaces_num, tinyusb_config_descriptor_len, tinyusb_loaded_interfaces_mask);
return true;
}
static inline char nibble_to_hex_char(uint8_t b)
{
if (b < 0xa) {
return '0' + b;
} else {
return 'a' + b - 0xa;
}
}
static void set_usb_serial_num(void)
{
/* Get the MAC address */
const uint32_t mac0 = REG_GET_FIELD(EFUSE_RD_MAC_SPI_SYS_0_REG, EFUSE_MAC_0);
const uint32_t mac1 = REG_GET_FIELD(EFUSE_RD_MAC_SPI_SYS_1_REG, EFUSE_MAC_1);
uint8_t mac_bytes[6];
memcpy(mac_bytes, &mac0, 4);
memcpy(mac_bytes + 4, &mac1, 2);
/* Convert to UTF16 string */
uint8_t* srl = (uint8_t*)USB_DEVICE_SERIAL;
for (int i = 0; i < 6; ++i) {
uint8_t b = mac_bytes[5 - i]; /* printing from the MSB */
if (i) {
*srl++ = ':';
}
*srl++ = nibble_to_hex_char(b >> 4);
*srl++ = nibble_to_hex_char(b & 0xf);
}
*srl++ = '\0';
}
static void tinyusb_apply_device_config(tinyusb_device_config_t *config){
if(config->product_name){
snprintf(USB_DEVICE_PRODUCT, 126, "%s", config->product_name);
}
if(config->manufacturer_name){
snprintf(USB_DEVICE_MANUFACTURER, 126, "%s", config->manufacturer_name);
}
if(config->serial_number && config->serial_number[0]){
snprintf(USB_DEVICE_SERIAL, 126, "%s", config->serial_number);
} else {
set_usb_serial_num();
}
if(config->webusb_url){
snprintf(WEBUSB_URL, 126, "%s", config->webusb_url);
}
// Windows 10 will not recognize the CDC device if WebUSB is enabled and USB Class is not 2 (CDC)
if(
(tinyusb_loaded_interfaces_mask & BIT(USB_INTERFACE_CDC))
&& config->webusb_enabled
&& (config->usb_class != TUSB_CLASS_CDC)
){
config->usb_class = TUSB_CLASS_CDC;
}
WEBUSB_ENABLED = config->webusb_enabled;
USB_DEVICE_ATTRIBUTES = config->usb_attributes;
USB_DEVICE_POWER = config->usb_power_ma;
tinyusb_device_descriptor.bcdUSB = config->usb_version;
tinyusb_device_descriptor.idVendor = config->vid;
tinyusb_device_descriptor.idProduct = config->pid;
tinyusb_device_descriptor.bcdDevice = config->fw_version;
tinyusb_device_descriptor.bDeviceClass = config->usb_class;
tinyusb_device_descriptor.bDeviceSubClass = config->usb_subclass;
tinyusb_device_descriptor.bDeviceProtocol = config->usb_protocol;
}
static void IRAM_ATTR usb_persist_shutdown_handler(void)
{
if(usb_persist_mode != RESTART_NO_PERSIST){
if (usb_persist_enabled) {
usb_dc_prepare_persist();
}
if (usb_persist_mode == RESTART_BOOTLOADER) {
//USB CDC Download
if (usb_persist_enabled) {
chip_usb_set_persist_flags(USBDC_PERSIST_ENA);
} else {
periph_module_reset(PERIPH_USB_MODULE);
periph_module_enable(PERIPH_USB_MODULE);
}
REG_WRITE(RTC_CNTL_OPTION1_REG, RTC_CNTL_FORCE_DOWNLOAD_BOOT);
} else if (usb_persist_mode == RESTART_BOOTLOADER_DFU) {
//DFU Download
// Reset USB Core
USB0.grstctl |= USB_CSFTRST;
while ((USB0.grstctl & USB_CSFTRST) == USB_CSFTRST){}
chip_usb_set_persist_flags(USBDC_BOOT_DFU);
REG_WRITE(RTC_CNTL_OPTION1_REG, RTC_CNTL_FORCE_DOWNLOAD_BOOT);
} else if (usb_persist_enabled) {
//USB Persist reboot
chip_usb_set_persist_flags(USBDC_PERSIST_ENA);
}
}
}
// USB Device Driver task
// This top level thread processes all usb events and invokes callbacks
static void usb_device_task(void *param) {
(void)param;
while(1) tud_task(); // RTOS forever loop
}
/*
* PUBLIC API
* */
esp_err_t tinyusb_enable_interface(tinyusb_interface_t interface, uint16_t descriptor_len, tinyusb_descriptor_cb_t cb)
{
if((interface >= USB_INTERFACE_MAX) || (tinyusb_loaded_interfaces_mask & (1U << interface))){
log_e("Interface %u not enabled", interface);
return ESP_FAIL;
}
tinyusb_loaded_interfaces_mask |= (1U << interface);
tinyusb_config_descriptor_len += descriptor_len;
tinyusb_loaded_interfaces_callbacks[interface] = cb;
log_d("Interface %u enabled", interface);
return ESP_OK;
}
esp_err_t tinyusb_init(tinyusb_device_config_t *config) {
static bool initialized = false;
if(initialized){
return ESP_OK;
}
initialized = true;
tinyusb_endpoints.val = 0;
tinyusb_apply_device_config(config);
if (!tinyusb_load_enabled_interfaces()) {
initialized = false;
return ESP_FAIL;
}
bool usb_did_persist = (USB_WRAP.date.val == USBDC_PERSIST_ENA);
//if(usb_did_persist && usb_persist_enabled){
// Enable USB/IO_MUX peripheral reset, if coming from persistent reboot
REG_CLR_BIT(RTC_CNTL_USB_CONF_REG, RTC_CNTL_IO_MUX_RESET_DISABLE);
REG_CLR_BIT(RTC_CNTL_USB_CONF_REG, RTC_CNTL_USB_RESET_DISABLE);
//} else
if(!usb_did_persist || !usb_persist_enabled){
// Reset USB module
periph_module_reset(PERIPH_USB_MODULE);
periph_module_enable(PERIPH_USB_MODULE);
}
if (esp_register_shutdown_handler(usb_persist_shutdown_handler) != ESP_OK) {
initialized = false;
return ESP_FAIL;
}
tinyusb_config_t tusb_cfg = {
.external_phy = false // In the most cases you need to use a `false` value
};
esp_err_t err = tinyusb_driver_install(&tusb_cfg);
if (err != ESP_OK) {
initialized = false;
return err;
}
xTaskCreate(usb_device_task, "usbd", 4096, NULL, configMAX_PRIORITIES - 1, NULL);
return err;
}
void usb_persist_restart(restart_type_t mode)
{
if (mode < RESTART_TYPE_MAX) {
usb_persist_mode = mode;
esp_restart();
}
}
uint8_t tinyusb_add_string_descriptor(const char * str){
if(str == NULL || tinyusb_string_descriptor_len >= MAX_STRING_DESCRIPTORS){
return 0;
}
uint8_t index = tinyusb_string_descriptor_len;
tinyusb_string_descriptor[tinyusb_string_descriptor_len++] = (char*)str;
return index;
}
uint8_t tinyusb_get_free_duplex_endpoint(void){
if(!tinyusb_has_available_fifos()){
log_e("No available IN endpoints");
return 0;
}
for(uint8_t i=1; i<7; i++){
if((tinyusb_endpoints.in & BIT(i)) == 0 && (tinyusb_endpoints.out & BIT(i)) == 0){
tinyusb_endpoints.in |= BIT(i);
tinyusb_endpoints.out |= BIT(i);
return i;
}
}
log_e("No available duplex endpoints");
return 0;
}
uint8_t tinyusb_get_free_in_endpoint(void){
if(!tinyusb_has_available_fifos()){
log_e("No available IN endpoints");
return 0;
}
for(uint8_t i=1; i<7; i++){
if((tinyusb_endpoints.in & BIT(i)) == 0 && (tinyusb_endpoints.out & BIT(i)) != 0){
tinyusb_endpoints.in |= BIT(i);
return i;
}
}
for(uint8_t i=1; i<7; i++){
if((tinyusb_endpoints.in & BIT(i)) == 0){
tinyusb_endpoints.in |= BIT(i);
return i;
}
}
return 0;
}
uint8_t tinyusb_get_free_out_endpoint(void){
for(uint8_t i=1; i<7; i++){
if((tinyusb_endpoints.out & BIT(i)) == 0 && (tinyusb_endpoints.in & BIT(i)) != 0){
tinyusb_endpoints.out |= BIT(i);
return i;
}
}
for(uint8_t i=1; i<7; i++){
if((tinyusb_endpoints.out & BIT(i)) == 0){
tinyusb_endpoints.out |= BIT(i);
return i;
}
}
return 0;
}
/*
void usb_dw_reg_dump(void)
{
#define USB_PRINT_REG(r) printf("USB0." #r " = 0x%x;\n", USB0.r)
#define USB_PRINT_IREG(i, r) printf("USB0.in_ep_reg[%u]." #r " = 0x%x;\n", i, USB0.in_ep_reg[i].r)
#define USB_PRINT_OREG(i, r) printf("USB0.out_ep_reg[%u]." #r " = 0x%x;\n", i, USB0.out_ep_reg[i].r)
uint8_t i;
USB_PRINT_REG(gotgctl);
USB_PRINT_REG(gotgint);
USB_PRINT_REG(gahbcfg);
USB_PRINT_REG(gusbcfg);
USB_PRINT_REG(grstctl);
USB_PRINT_REG(gintsts);
USB_PRINT_REG(gintmsk);
USB_PRINT_REG(grxstsr);
USB_PRINT_REG(grxstsp);
USB_PRINT_REG(grxfsiz);
USB_PRINT_REG(gnptxsts);
USB_PRINT_REG(gpvndctl);
USB_PRINT_REG(ggpio);
USB_PRINT_REG(guid);
USB_PRINT_REG(gsnpsid);
USB_PRINT_REG(ghwcfg1);
USB_PRINT_REG(ghwcfg2);
USB_PRINT_REG(ghwcfg3);
USB_PRINT_REG(ghwcfg4);
USB_PRINT_REG(glpmcfg);
USB_PRINT_REG(gpwrdn);
USB_PRINT_REG(gdfifocfg);
USB_PRINT_REG(gadpctl);
USB_PRINT_REG(hptxfsiz);
USB_PRINT_REG(hcfg);
USB_PRINT_REG(hfir);
USB_PRINT_REG(hfnum);
USB_PRINT_REG(hptxsts);
USB_PRINT_REG(haint);
USB_PRINT_REG(haintmsk);
USB_PRINT_REG(hflbaddr);
USB_PRINT_REG(hprt);
USB_PRINT_REG(dcfg);
USB_PRINT_REG(dctl);
USB_PRINT_REG(dsts);
USB_PRINT_REG(diepmsk);
USB_PRINT_REG(doepmsk);
USB_PRINT_REG(daint);
USB_PRINT_REG(daintmsk);
USB_PRINT_REG(dtknqr1);
USB_PRINT_REG(dtknqr2);
USB_PRINT_REG(dvbusdis);
USB_PRINT_REG(dvbuspulse);
USB_PRINT_REG(dtknqr3_dthrctl);
USB_PRINT_REG(dtknqr4_fifoemptymsk);
USB_PRINT_REG(deachint);
USB_PRINT_REG(deachintmsk);
USB_PRINT_REG(pcgctrl);
USB_PRINT_REG(pcgctrl1);
USB_PRINT_REG(gnptxfsiz);
for (i = 0; i < 4; i++) {
printf("USB0.dieptxf[%u] = 0x%x;\n", i, USB0.dieptxf[i]);
}
// for (i = 0; i < 16; i++) {
// printf("USB0.diepeachintmsk[%u] = 0x%x;\n", i, USB0.diepeachintmsk[i]);
// }
// for (i = 0; i < 16; i++) {
// printf("USB0.doepeachintmsk[%u] = 0x%x;\n", i, USB0.doepeachintmsk[i]);
// }
for (i = 0; i < 7; i++) {
printf("// EP %u:\n", i);
USB_PRINT_IREG(i, diepctl);
USB_PRINT_IREG(i, diepint);
USB_PRINT_IREG(i, dieptsiz);
USB_PRINT_IREG(i, diepdma);
USB_PRINT_IREG(i, dtxfsts);
USB_PRINT_OREG(i, doepctl);
USB_PRINT_OREG(i, doepint);
USB_PRINT_OREG(i, doeptsiz);
USB_PRINT_OREG(i, doepdma);
}
}
*/
#endif /* CONFIG_TINYUSB_ENABLED */

View File

@ -0,0 +1,108 @@
// Copyright 2015-2020 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "esp32-hal.h"
#if CONFIG_IDF_TARGET_ESP32S2
#if CONFIG_TINYUSB_ENABLED
#ifdef __cplusplus
extern "C" {
#endif
#include "tusb.h"
#include "tusb_option.h"
#include "tusb_config.h"
#define USB_ESPRESSIF_VID 0x303A
#define USB_STRING_DESCRIPTOR_ARRAY_SIZE 10
typedef struct {
uint16_t vid;
uint16_t pid;
const char * product_name;
const char * manufacturer_name;
const char * serial_number;
uint16_t fw_version;
uint16_t usb_version;
uint8_t usb_class;
uint8_t usb_subclass;
uint8_t usb_protocol;
uint8_t usb_attributes;
uint16_t usb_power_ma;
bool webusb_enabled;
const char * webusb_url;
} tinyusb_device_config_t;
#define TINYUSB_CONFIG_DEFAULT() { \
.vid = USB_ESPRESSIF_VID, \
.pid = 0x0002, \
.product_name = CONFIG_TINYUSB_DESC_PRODUCT_STRING, \
.manufacturer_name = CONFIG_TINYUSB_DESC_MANUFACTURER_STRING, \
.serial_number = CONFIG_TINYUSB_DESC_SERIAL_STRING, \
.fw_version = CONFIG_TINYUSB_DESC_BCDDEVICE, \
.usb_version = 0x0200, \
.usb_class = TUSB_CLASS_MISC, \
.usb_subclass = MISC_SUBCLASS_COMMON, \
.usb_protocol = MISC_PROTOCOL_IAD, \
.usb_attributes = TUSB_DESC_CONFIG_ATT_SELF_POWERED, \
.usb_power_ma = 500, \
.webusb_enabled = false, \
.webusb_url = "espressif.github.io/arduino-esp32/webusb.html" \
}
esp_err_t tinyusb_init(tinyusb_device_config_t *config);
/*
* USB Persistence API
* */
typedef enum {
RESTART_NO_PERSIST,
RESTART_PERSIST,
RESTART_BOOTLOADER,
RESTART_BOOTLOADER_DFU,
RESTART_TYPE_MAX
} restart_type_t;
void usb_persist_restart(restart_type_t mode);
// The following definitions and functions are to be used only by the drivers
typedef enum {
USB_INTERFACE_CDC,
USB_INTERFACE_DFU,
USB_INTERFACE_HID,
USB_INTERFACE_VENDOR,
USB_INTERFACE_MSC,
USB_INTERFACE_MIDI,
USB_INTERFACE_CUSTOM,
USB_INTERFACE_MAX
} tinyusb_interface_t;
typedef uint16_t (*tinyusb_descriptor_cb_t)(uint8_t * dst, uint8_t * itf);
esp_err_t tinyusb_enable_interface(tinyusb_interface_t interface, uint16_t descriptor_len, tinyusb_descriptor_cb_t cb);
uint8_t tinyusb_add_string_descriptor(const char * str);
uint8_t tinyusb_get_free_duplex_endpoint(void);
uint8_t tinyusb_get_free_in_endpoint(void);
uint8_t tinyusb_get_free_out_endpoint(void);
#ifdef __cplusplus
}
#endif
#endif /* CONFIG_TINYUSB_ENABLED */
#endif /* CONFIG_IDF_TARGET_ESP32S2 */

View File

@ -13,14 +13,32 @@
// limitations under the License.
#include "esp32-hal-touch.h"
#ifndef CONFIG_IDF_TARGET_ESP32C3
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "rom/ets_sys.h"
#include "esp_attr.h"
#include "esp_intr.h"
#include "soc/rtc_io_reg.h"
#include "soc/rtc_cntl_reg.h"
#include "soc/sens_reg.h"
#include "soc/sens_struct.h"
#include "soc/rtc_cntl_reg.h"
#include "driver/touch_sensor.h"
#include "esp_system.h"
#ifdef ESP_IDF_VERSION_MAJOR // IDF 4+
#if CONFIG_IDF_TARGET_ESP32 // ESP32/PICO-D4
#include "esp32/rom/ets_sys.h"
#include "esp_intr_alloc.h"
#elif CONFIG_IDF_TARGET_ESP32S2
#include "esp32s2/rom/ets_sys.h"
#include "esp_intr_alloc.h"
#include "soc/periph_defs.h"
#else
#error Target CONFIG_IDF_TARGET is not supported
#endif
#else // ESP32 Before IDF 4.0
#include "rom/ets_sys.h"
#include "esp_intr.h"
#endif
static uint16_t __touchSleepCycles = 0x1000;
static uint16_t __touchMeasureCycles = 0x1000;
@ -29,8 +47,9 @@ typedef void (*voidFuncPtr)(void);
static voidFuncPtr __touchInterruptHandlers[10] = {0,};
static intr_handle_t touch_intr_handle = NULL;
void IRAM_ATTR __touchISR(void * arg)
void ARDUINO_ISR_ATTR __touchISR(void * arg)
{
#if CONFIG_IDF_TARGET_ESP32
uint32_t pad_intr = READ_PERI_REG(SENS_SAR_TOUCH_CTRL2_REG) & 0x3ff;
uint32_t rtc_intr = READ_PERI_REG(RTC_CNTL_INT_ST_REG);
uint8_t i = 0;
@ -47,16 +66,21 @@ void IRAM_ATTR __touchISR(void * arg)
}
}
}
#endif
}
void __touchSetCycles(uint16_t measure, uint16_t sleep)
{
__touchSleepCycles = sleep;
__touchMeasureCycles = measure;
#if CONFIG_IDF_TARGET_ESP32
//Touch pad SleepCycle Time
SET_PERI_REG_BITS(SENS_SAR_TOUCH_CTRL2_REG, SENS_TOUCH_SLEEP_CYCLES, __touchSleepCycles, SENS_TOUCH_SLEEP_CYCLES_S);
//Touch Pad Measure Time
SET_PERI_REG_BITS(SENS_SAR_TOUCH_CTRL1_REG, SENS_TOUCH_MEAS_DELAY, __touchMeasureCycles, SENS_TOUCH_MEAS_DELAY_S);
#else
touch_pad_set_meas_time(sleep, measure);
#endif
}
void __touchInit()
@ -66,15 +90,27 @@ void __touchInit()
return;
}
initialized = true;
#if CONFIG_IDF_TARGET_ESP32
SET_PERI_REG_BITS(RTC_IO_TOUCH_CFG_REG, RTC_IO_TOUCH_XPD_BIAS, 1, RTC_IO_TOUCH_XPD_BIAS_S);
SET_PERI_REG_MASK(SENS_SAR_TOUCH_CTRL2_REG, SENS_TOUCH_MEAS_EN_CLR);
//clear touch enable
WRITE_PERI_REG(SENS_SAR_TOUCH_ENABLE_REG, 0x0);
SET_PERI_REG_MASK(RTC_CNTL_STATE0_REG, RTC_CNTL_TOUCH_SLP_TIMER_EN);
__touchSetCycles(__touchMeasureCycles, __touchSleepCycles);
esp_intr_alloc(ETS_RTC_CORE_INTR_SOURCE, (int)ESP_INTR_FLAG_IRAM, __touchISR, NULL, &touch_intr_handle);
esp_intr_alloc(ETS_RTC_CORE_INTR_SOURCE, (int)ARDUINO_ISR_FLAG, __touchISR, NULL, &touch_intr_handle);
#else
touch_pad_init();
touch_pad_set_voltage(TOUCH_HVOLT_2V7, TOUCH_LVOLT_0V5, TOUCH_HVOLT_ATTEN_0V5);
touch_pad_set_idle_channel_connect(TOUCH_PAD_CONN_GND);
__touchSetCycles(__touchMeasureCycles, __touchSleepCycles);
touch_pad_denoise_t denoise = {
.grade = TOUCH_PAD_DENOISE_BIT4,
.cap_level = TOUCH_PAD_DENOISE_CAP_L4,
};
touch_pad_denoise_set_config(&denoise);
touch_pad_denoise_enable();
touch_pad_set_fsm_mode(TOUCH_FSM_MODE_TIMER);
touch_pad_fsm_start();
#endif
}
uint16_t __touchRead(uint8_t pin)
@ -88,6 +124,7 @@ uint16_t __touchRead(uint8_t pin)
__touchInit();
#if CONFIG_IDF_TARGET_ESP32
uint32_t v0 = READ_PERI_REG(SENS_SAR_TOUCH_ENABLE_REG);
//Disable Intr & enable touch pad
WRITE_PERI_REG(SENS_SAR_TOUCH_ENABLE_REG,
@ -119,6 +156,25 @@ uint16_t __touchRead(uint8_t pin)
//restore previous value
WRITE_PERI_REG(SENS_SAR_TOUCH_ENABLE_REG, v0);
return touch_value;
#else
static uint32_t chan_mask = 0;
uint32_t value = 0;
if((chan_mask & (1 << pad)) == 0){
if(touch_pad_set_thresh((touch_pad_t)pad, TOUCH_PAD_THRESHOLD_MAX) != ESP_OK){
log_e("touch_pad_set_thresh failed");
} else if(touch_pad_config((touch_pad_t)pad) != ESP_OK){
log_e("touch_pad_config failed");
} else {
chan_mask |= (1 << pad);
}
}
if((chan_mask & (1 << pad)) != 0) {
if(touch_pad_read_raw_data((touch_pad_t)pad, &value) != ESP_OK){
log_e("touch_pad_read_raw_data failed");
}
}
return value;
#endif
}
void __touchAttachInterrupt(uint8_t pin, void (*userFunc)(void), uint16_t threshold)
@ -134,6 +190,7 @@ void __touchAttachInterrupt(uint8_t pin, void (*userFunc)(void), uint16_t thresh
__touchInterruptHandlers[pad] = userFunc;
#if CONFIG_IDF_TARGET_ESP32
//clear touch force ,select the Touch mode is Timer
CLEAR_PERI_REG_MASK(SENS_SAR_TOUCH_CTRL2_REG, SENS_TOUCH_START_EN_M|SENS_TOUCH_START_FORCE_M);
@ -161,8 +218,12 @@ void __touchAttachInterrupt(uint8_t pin, void (*userFunc)(void), uint16_t thresh
(1 << (pad + SENS_TOUCH_PAD_WORKEN_S)) | \
(1 << (pad + SENS_TOUCH_PAD_OUTEN2_S)) | \
(1 << (pad + SENS_TOUCH_PAD_OUTEN1_S)));
#else
#endif
}
extern uint16_t touchRead(uint8_t pin) __attribute__ ((weak, alias("__touchRead")));
extern void touchAttachInterrupt(uint8_t pin, void (*userFunc)(void), uint16_t threshold) __attribute__ ((weak, alias("__touchAttachInterrupt")));
extern void touchSetCycles(uint16_t measure, uint16_t sleep) __attribute__ ((weak, alias("__touchSetCycles")));
#endif

View File

@ -18,22 +18,58 @@
#include "freertos/task.h"
#include "freertos/queue.h"
#include "freertos/semphr.h"
#include "rom/ets_sys.h"
#include "esp_attr.h"
#include "esp_intr.h"
#include "rom/uart.h"
#include "soc/uart_reg.h"
#include "soc/uart_struct.h"
#include "soc/io_mux_reg.h"
#include "soc/gpio_sig_map.h"
#include "soc/dport_reg.h"
#include "soc/rtc.h"
#include "hal/uart_ll.h"
#include "esp_intr_alloc.h"
#include "esp_system.h"
#ifdef ESP_IDF_VERSION_MAJOR // IDF 4+
#if CONFIG_IDF_TARGET_ESP32 // ESP32/PICO-D4
#include "soc/dport_reg.h"
#include "esp32/rom/ets_sys.h"
#include "esp32/rom/uart.h"
#elif CONFIG_IDF_TARGET_ESP32S2
#include "soc/dport_reg.h"
#include "esp32s2/rom/ets_sys.h"
#include "esp32s2/rom/uart.h"
#include "soc/periph_defs.h"
#elif CONFIG_IDF_TARGET_ESP32C3
#include "esp32c3/rom/ets_sys.h"
#include "esp32c3/rom/uart.h"
#include "soc/periph_defs.h"
#else
#error Target CONFIG_IDF_TARGET is not supported
#endif
#else // ESP32 Before IDF 4.0
#include "rom/ets_sys.h"
#include "rom/uart.h"
#include "esp_intr.h"
#endif
#if CONFIG_IDF_TARGET_ESP32
#define UART_PORTS_NUM 3
#define UART_REG_BASE(u) ((u==0)?DR_REG_UART_BASE:( (u==1)?DR_REG_UART1_BASE:( (u==2)?DR_REG_UART2_BASE:0)))
#define UART_RXD_IDX(u) ((u==0)?U0RXD_IN_IDX:( (u==1)?U1RXD_IN_IDX:( (u==2)?U2RXD_IN_IDX:0)))
#define UART_TXD_IDX(u) ((u==0)?U0TXD_OUT_IDX:( (u==1)?U1TXD_OUT_IDX:( (u==2)?U2TXD_OUT_IDX:0)))
#define UART_INTR_SOURCE(u) ((u==0)?ETS_UART0_INTR_SOURCE:( (u==1)?ETS_UART1_INTR_SOURCE:((u==2)?ETS_UART2_INTR_SOURCE:0)))
#elif CONFIG_IDF_TARGET_ESP32S2
#define UART_PORTS_NUM 2
#define UART_REG_BASE(u) ((u==0)?DR_REG_UART_BASE:( (u==1)?DR_REG_UART1_BASE:0))
#define UART_RXD_IDX(u) ((u==0)?U0RXD_IN_IDX:( (u==1)?U1RXD_IN_IDX:0))
#define UART_TXD_IDX(u) ((u==0)?U0TXD_OUT_IDX:( (u==1)?U1TXD_OUT_IDX:0))
#define UART_INTR_SOURCE(u) ((u==0)?ETS_UART0_INTR_SOURCE:( (u==1)?ETS_UART1_INTR_SOURCE:0))
#else
#define UART_PORTS_NUM 2
#define UART_REG_BASE(u) ((u==0)?DR_REG_UART_BASE:( (u==1)?DR_REG_UART1_BASE:0))
#define UART_RXD_IDX(u) ((u==0)?U0RXD_IN_IDX:( (u==1)?U1RXD_IN_IDX:0))
#define UART_TXD_IDX(u) ((u==0)?U0TXD_OUT_IDX:( (u==1)?U1TXD_OUT_IDX:0))
#define UART_INTR_SOURCE(u) ((u==0)?ETS_UART0_INTR_SOURCE:( (u==1)?ETS_UART1_INTR_SOURCE:0))
#endif
static int s_uart_debug_nr = 0;
@ -51,31 +87,35 @@ struct uart_struct_t {
#define UART_MUTEX_LOCK()
#define UART_MUTEX_UNLOCK()
static uart_t _uart_bus_array[3] = {
{(volatile uart_dev_t *)(DR_REG_UART_BASE), 0, NULL, NULL},
{(volatile uart_dev_t *)(DR_REG_UART1_BASE), 1, NULL, NULL},
{(volatile uart_dev_t *)(DR_REG_UART2_BASE), 2, NULL, NULL}
static uart_t _uart_bus_array[] = {
{&UART0, 0, NULL, NULL},
{&UART1, 1, NULL, NULL},
#if CONFIG_IDF_TARGET_ESP32
{&UART2, 2, NULL, NULL}
#endif
};
#else
#define UART_MUTEX_LOCK() do {} while (xSemaphoreTake(uart->lock, portMAX_DELAY) != pdPASS)
#define UART_MUTEX_UNLOCK() xSemaphoreGive(uart->lock)
static uart_t _uart_bus_array[3] = {
{(volatile uart_dev_t *)(DR_REG_UART_BASE), NULL, 0, NULL, NULL},
{(volatile uart_dev_t *)(DR_REG_UART1_BASE), NULL, 1, NULL, NULL},
{(volatile uart_dev_t *)(DR_REG_UART2_BASE), NULL, 2, NULL, NULL}
static uart_t _uart_bus_array[] = {
{&UART0, NULL, 0, NULL, NULL},
{&UART1, NULL, 1, NULL, NULL},
#if CONFIG_IDF_TARGET_ESP32
{&UART2, NULL, 2, NULL, NULL}
#endif
};
#endif
static void uart_on_apb_change(void * arg, apb_change_ev_t ev_type, uint32_t old_apb, uint32_t new_apb);
static void IRAM_ATTR _uart_isr(void *arg)
static void ARDUINO_ISR_ATTR _uart_isr(void *arg)
{
uint8_t i, c;
BaseType_t xHigherPriorityTaskWoken;
uart_t* uart;
for(i=0;i<3;i++){
for(i=0;i<UART_PORTS_NUM;i++){
uart = &_uart_bus_array[i];
if(uart->intr_handle == NULL){
continue;
@ -83,9 +123,15 @@ static void IRAM_ATTR _uart_isr(void *arg)
uart->dev->int_clr.rxfifo_full = 1;
uart->dev->int_clr.frm_err = 1;
uart->dev->int_clr.rxfifo_tout = 1;
#if CONFIG_IDF_TARGET_ESP32
while(uart->dev->status.rxfifo_cnt || (uart->dev->mem_rx_status.wr_addr != uart->dev->mem_rx_status.rd_addr)) {
c = uart->dev->fifo.rw_byte;
if(uart->queue != NULL && !xQueueIsQueueFullFromISR(uart->queue)) {
#else
uint32_t fifo_reg = UART_FIFO_AHB_REG(i);
while(uart->dev->status.rxfifo_cnt) {
c = ESP_REG(fifo_reg);
#endif
if(uart->queue != NULL) {
xQueueSendFromISR(uart->queue, &c, &xHigherPriorityTaskWoken);
}
}
@ -96,22 +142,26 @@ static void IRAM_ATTR _uart_isr(void *arg)
}
}
void uartEnableInterrupt(uart_t* uart)
static void uartEnableInterrupt(uart_t* uart, uint8_t rxfifo_full_thrhd)
{
UART_MUTEX_LOCK();
uart->dev->conf1.rxfifo_full_thrhd = 112;
uart->dev->conf1.rxfifo_full_thrhd = rxfifo_full_thrhd;
#if CONFIG_IDF_TARGET_ESP32
uart->dev->conf1.rx_tout_thrhd = 2;
#else
uart->dev->mem_conf.rx_tout_thrhd = 2;
#endif
uart->dev->conf1.rx_tout_en = 1;
uart->dev->int_ena.rxfifo_full = 1;
uart->dev->int_ena.frm_err = 1;
uart->dev->int_ena.rxfifo_tout = 1;
uart->dev->int_clr.val = 0xffffffff;
esp_intr_alloc(UART_INTR_SOURCE(uart->num), (int)ESP_INTR_FLAG_IRAM, _uart_isr, NULL, &uart->intr_handle);
esp_intr_alloc(UART_INTR_SOURCE(uart->num), (int)ARDUINO_ISR_FLAG, _uart_isr, NULL, &uart->intr_handle);
UART_MUTEX_UNLOCK();
}
void uartDisableInterrupt(uart_t* uart)
static void uartDisableInterrupt(uart_t* uart)
{
UART_MUTEX_LOCK();
uart->dev->conf1.val = 0;
@ -124,7 +174,7 @@ void uartDisableInterrupt(uart_t* uart)
UART_MUTEX_UNLOCK();
}
void uartDetachRx(uart_t* uart)
static void uartDetachRx(uart_t* uart, uint8_t rxPin)
{
if(uart == NULL) {
return;
@ -133,36 +183,36 @@ void uartDetachRx(uart_t* uart)
uartDisableInterrupt(uart);
}
void uartDetachTx(uart_t* uart)
static void uartDetachTx(uart_t* uart, uint8_t txPin)
{
if(uart == NULL) {
return;
}
pinMatrixOutDetach(UART_TXD_IDX(uart->num), false, false);
pinMatrixOutDetach(txPin, false, false);
}
void uartAttachRx(uart_t* uart, uint8_t rxPin, bool inverted)
static void uartAttachRx(uart_t* uart, uint8_t rxPin, bool inverted, uint8_t rxfifo_full_thrhd)
{
if(uart == NULL || rxPin > 39) {
if(uart == NULL || rxPin >= GPIO_PIN_COUNT) {
return;
}
pinMode(rxPin, INPUT);
uartEnableInterrupt(uart, rxfifo_full_thrhd);
pinMatrixInAttach(rxPin, UART_RXD_IDX(uart->num), inverted);
uartEnableInterrupt(uart);
}
void uartAttachTx(uart_t* uart, uint8_t txPin, bool inverted)
static void uartAttachTx(uart_t* uart, uint8_t txPin, bool inverted)
{
if(uart == NULL || txPin > 39) {
if(uart == NULL || txPin >= GPIO_PIN_COUNT) {
return;
}
pinMode(txPin, OUTPUT);
pinMatrixOutAttach(txPin, UART_TXD_IDX(uart->num), inverted, false);
}
uart_t* uartBegin(uint8_t uart_nr, uint32_t baudrate, uint32_t config, int8_t rxPin, int8_t txPin, uint16_t queueLen, bool inverted)
uart_t* uartBegin(uint8_t uart_nr, uint32_t baudrate, uint32_t config, int8_t rxPin, int8_t txPin, uint16_t queueLen, bool inverted, uint8_t rxfifo_full_thrhd)
{
if(uart_nr > 2) {
if(uart_nr >= UART_PORTS_NUM) {
return NULL;
}
@ -187,16 +237,22 @@ uart_t* uartBegin(uint8_t uart_nr, uint32_t baudrate, uint32_t config, int8_t rx
return NULL;
}
}
#if CONFIG_IDF_TARGET_ESP32C3
#else
if(uart_nr == 1){
DPORT_SET_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG, DPORT_UART1_CLK_EN);
DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, DPORT_UART1_RST);
#if CONFIG_IDF_TARGET_ESP32
} else if(uart_nr == 2){
DPORT_SET_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG, DPORT_UART2_CLK_EN);
DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, DPORT_UART2_RST);
#endif
} else {
DPORT_SET_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG, DPORT_UART_CLK_EN);
DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, DPORT_UART_RST);
}
#endif
uartFlush(uart);
uartSetBaudRate(uart, baudrate);
UART_MUTEX_LOCK();
@ -208,21 +264,25 @@ uart_t* uartBegin(uint8_t uart_nr, uint32_t baudrate, uint32_t config, int8_t rx
uart->dev->conf0.stop_bit_num = ONE_STOP_BITS_CONF;
uart->dev->rs485_conf.dl1_en = 1;
}
// tx_idle_num : idle interval after tx FIFO is empty(unit: the time it takes to send one bit under current baudrate)
// Setting it to 0 prevents line idle time/delays when sending messages with small intervals
uart->dev->idle_conf.tx_idle_num = 0; //
UART_MUTEX_UNLOCK();
if(rxPin != -1) {
uartAttachRx(uart, rxPin, inverted);
uartAttachRx(uart, rxPin, inverted, rxfifo_full_thrhd);
}
if(txPin != -1) {
uartAttachTx(uart, txPin, inverted);
}
addApbChangeCallback(uart, uart_on_apb_change);
return uart;
}
void uartEnd(uart_t* uart)
void uartEnd(uart_t* uart, uint8_t txPin, uint8_t rxPin)
{
if(uart == NULL) {
return;
@ -239,8 +299,8 @@ void uartEnd(uart_t* uart)
UART_MUTEX_UNLOCK();
uartDetachRx(uart);
uartDetachTx(uart);
uartDetachRx(uart, rxPin);
uartDetachTx(uart, txPin);
}
size_t uartResizeRxBuffer(uart_t * uart, size_t new_size) {
@ -253,7 +313,8 @@ size_t uartResizeRxBuffer(uart_t * uart, size_t new_size) {
vQueueDelete(uart->queue);
uart->queue = xQueueCreate(new_size, sizeof(uint8_t));
if(uart->queue == NULL) {
return NULL;
UART_MUTEX_UNLOCK();
return 0;
}
}
UART_MUTEX_UNLOCK();
@ -261,12 +322,27 @@ size_t uartResizeRxBuffer(uart_t * uart, size_t new_size) {
return new_size;
}
void uartSetRxInvert(uart_t* uart, bool invert)
{
if (uart == NULL)
return;
if (invert)
uart->dev->conf0.rxd_inv = 1;
else
uart->dev->conf0.rxd_inv = 0;
}
uint32_t uartAvailable(uart_t* uart)
{
if(uart == NULL || uart->queue == NULL) {
return 0;
}
#ifdef UART_READ_RX_FIFO
return (uxQueueMessagesWaiting(uart->queue) + uart->dev->status.rxfifo_cnt) ;
#else
return uxQueueMessagesWaiting(uart->queue);
#endif
}
uint32_t uartAvailableForWrite(uart_t* uart)
@ -277,12 +353,45 @@ uint32_t uartAvailableForWrite(uart_t* uart)
return 0x7f - uart->dev->status.txfifo_cnt;
}
#ifdef UART_READ_RX_FIFO
void uartRxFifoToQueue(uart_t* uart)
{
uint8_t c;
UART_MUTEX_LOCK();
//disable interrupts
uart->dev->int_ena.val = 0;
uart->dev->int_clr.val = 0xffffffff;
#if CONFIG_IDF_TARGET_ESP32
while (uart->dev->status.rxfifo_cnt || (uart->dev->mem_rx_status.wr_addr != uart->dev->mem_rx_status.rd_addr)) {
c = uart->dev->fifo.rw_byte;
#else
uint32_t fifo_reg = UART_FIFO_AHB_REG(uart->num);
while (uart->dev->status.rxfifo_cnt) {
c = ESP_REG(fifo_reg);
#endif
xQueueSend(uart->queue, &c, 0);
}
//enable interrupts
uart->dev->int_ena.rxfifo_full = 1;
uart->dev->int_ena.frm_err = 1;
uart->dev->int_ena.rxfifo_tout = 1;
uart->dev->int_clr.val = 0xffffffff;
UART_MUTEX_UNLOCK();
}
#endif
uint8_t uartRead(uart_t* uart)
{
if(uart == NULL || uart->queue == NULL) {
return 0;
}
uint8_t c;
#ifdef UART_READ_RX_FIFO
if ((uxQueueMessagesWaiting(uart->queue) == 0) && (uart->dev->status.rxfifo_cnt > 0))
{
uartRxFifoToQueue(uart);
}
#endif
if(xQueueReceive(uart->queue, &c, 0)) {
return c;
}
@ -295,6 +404,12 @@ uint8_t uartPeek(uart_t* uart)
return 0;
}
uint8_t c;
#ifdef UART_READ_RX_FIFO
if ((uxQueueMessagesWaiting(uart->queue) == 0) && (uart->dev->status.rxfifo_cnt > 0))
{
uartRxFifoToQueue(uart);
}
#endif
if(xQueuePeek(uart->queue, &c, 0)) {
return c;
}
@ -307,8 +422,12 @@ void uartWrite(uart_t* uart, uint8_t c)
return;
}
UART_MUTEX_LOCK();
while(uart->dev->status.txfifo_cnt == 0x7F);
while(uart->dev->status.txfifo_cnt >= 0x7E);
#if CONFIG_IDF_TARGET_ESP32
uart->dev->fifo.rw_byte = c;
#else
ESP_REG(UART_FIFO_AHB_REG(uart->num)) = c;
#endif
UART_MUTEX_UNLOCK();
}
@ -318,23 +437,37 @@ void uartWriteBuf(uart_t* uart, const uint8_t * data, size_t len)
return;
}
UART_MUTEX_LOCK();
#ifndef CONFIG_IDF_TARGET_ESP32
uint32_t fifo_reg = UART_FIFO_AHB_REG(uart->num);
#endif
while(len) {
while(uart->dev->status.txfifo_cnt == 0x7F);
while(uart->dev->status.txfifo_cnt >= 0x7E);
#if CONFIG_IDF_TARGET_ESP32
uart->dev->fifo.rw_byte = *data++;
#else
ESP_REG(fifo_reg) = *data++;
#endif
len--;
}
UART_MUTEX_UNLOCK();
}
void uartFlush(uart_t* uart)
{
uartFlushTxOnly(uart,true);
}
void uartFlushTxOnly(uart_t* uart, bool txOnly)
{
if(uart == NULL) {
return;
}
UART_MUTEX_LOCK();
#if CONFIG_IDF_TARGET_ESP32
while(uart->dev->status.txfifo_cnt || uart->dev->status.st_utx_out);
if( !txOnly ){
//Due to hardware issue, we can not use fifo_rst to reset uart fifo.
//See description about UART_TXFIFO_RST and UART_RXFIFO_RST in <<esp32_technical_reference_manual>> v2.6 or later.
@ -344,6 +477,12 @@ void uartFlush(uart_t* uart)
}
xQueueReset(uart->queue);
}
#else
while(uart->dev->status.txfifo_cnt);
uart->dev->conf0.txfifo_rst = 1;
uart->dev->conf0.txfifo_rst = 0;
#endif
UART_MUTEX_UNLOCK();
}
@ -354,9 +493,7 @@ void uartSetBaudRate(uart_t* uart, uint32_t baud_rate)
return;
}
UART_MUTEX_LOCK();
uint32_t clk_div = ((getApbFrequency()<<4)/baud_rate);
uart->dev->clk_div.div_int = clk_div>>4 ;
uart->dev->clk_div.div_frag = clk_div & 0xf;
uart_ll_set_baudrate(uart->dev, baud_rate);
UART_MUTEX_UNLOCK();
}
@ -370,18 +507,31 @@ static void uart_on_apb_change(void * arg, apb_change_ev_t ev_type, uint32_t old
uart->dev->int_clr.val = 0xffffffff;
// read RX fifo
uint8_t c;
BaseType_t xHigherPriorityTaskWoken;
// BaseType_t xHigherPriorityTaskWoken;
#if CONFIG_IDF_TARGET_ESP32
while(uart->dev->status.rxfifo_cnt != 0 || (uart->dev->mem_rx_status.wr_addr != uart->dev->mem_rx_status.rd_addr)) {
c = uart->dev->fifo.rw_byte;
if(uart->queue != NULL && !xQueueIsQueueFullFromISR(uart->queue)) {
xQueueSendFromISR(uart->queue, &c, &xHigherPriorityTaskWoken);
#else
uint32_t fifo_reg = UART_FIFO_AHB_REG(uart->num);
while(uart->dev->status.rxfifo_cnt != 0) {
c = ESP_REG(fifo_reg);
#endif
if(uart->queue != NULL ) {
xQueueSend(uart->queue, &c, 1); //&xHigherPriorityTaskWoken);
}
}
UART_MUTEX_UNLOCK();
// wait TX empty
#if CONFIG_IDF_TARGET_ESP32
while(uart->dev->status.txfifo_cnt || uart->dev->status.st_utx_out);
#else
while(uart->dev->status.txfifo_cnt);
#endif
} else {
//todo:
// set baudrate
UART_MUTEX_LOCK();
uint32_t clk_div = (uart->dev->clk_div.div_int << 4) | (uart->dev->clk_div.div_frag & 0x0F);
uint32_t baud_rate = ((old_apb<<4)/clk_div);
clk_div = ((new_apb<<4)/baud_rate);
@ -410,23 +560,35 @@ uint32_t uartGetBaudRate(uart_t* uart)
return ((getApbFrequency()<<4)/clk_div);
}
static void IRAM_ATTR uart0_write_char(char c)
static void ARDUINO_ISR_ATTR uart0_write_char(char c)
{
while(((ESP_REG(0x01C+DR_REG_UART_BASE) >> UART_TXFIFO_CNT_S) & 0x7F) == 0x7F);
#if CONFIG_IDF_TARGET_ESP32
while(((ESP_REG(0x01C+DR_REG_UART_BASE) >> UART_TXFIFO_CNT_S) & 0x7F) >= 0x7E);
ESP_REG(DR_REG_UART_BASE) = c;
#else
while(UART0.status.txfifo_cnt == 0x7F);
WRITE_PERI_REG(UART_FIFO_AHB_REG(0), c);
#endif
}
static void IRAM_ATTR uart1_write_char(char c)
static void ARDUINO_ISR_ATTR uart1_write_char(char c)
{
while(((ESP_REG(0x01C+DR_REG_UART1_BASE) >> UART_TXFIFO_CNT_S) & 0x7F) == 0x7F);
#if CONFIG_IDF_TARGET_ESP32
while(((ESP_REG(0x01C+DR_REG_UART1_BASE) >> UART_TXFIFO_CNT_S) & 0x7F) >= 0x7E);
ESP_REG(DR_REG_UART1_BASE) = c;
#else
while(UART1.status.txfifo_cnt == 0x7F);
WRITE_PERI_REG(UART_FIFO_AHB_REG(1), c);
#endif
}
static void IRAM_ATTR uart2_write_char(char c)
#if CONFIG_IDF_TARGET_ESP32
static void ARDUINO_ISR_ATTR uart2_write_char(char c)
{
while(((ESP_REG(0x01C+DR_REG_UART2_BASE) >> UART_TXFIFO_CNT_S) & 0x7F) == 0x7F);
while(((ESP_REG(0x01C+DR_REG_UART2_BASE) >> UART_TXFIFO_CNT_S) & 0x7F) >= 0x7E);
ESP_REG(DR_REG_UART2_BASE) = c;
}
#endif
void uart_install_putc()
{
@ -437,9 +599,11 @@ void uart_install_putc()
case 1:
ets_install_putc1((void (*)(char)) &uart1_write_char);
break;
#if CONFIG_IDF_TARGET_ESP32
case 2:
ets_install_putc1((void (*)(char)) &uart2_write_char);
break;
#endif
default:
ets_install_putc1(NULL);
break;
@ -448,7 +612,7 @@ void uart_install_putc()
void uartSetDebug(uart_t* uart)
{
if(uart == NULL || uart->num > 2) {
if(uart == NULL || uart->num >= UART_PORTS_NUM) {
s_uart_debug_nr = -1;
//ets_install_putc1(NULL);
//return;
@ -467,9 +631,6 @@ int uartGetDebug()
int log_printf(const char *format, ...)
{
if(s_uart_debug_nr < 0){
return 0;
}
static char loc_buf[64];
char * temp = loc_buf;
int len;
@ -487,7 +648,7 @@ int log_printf(const char *format, ...)
}
vsnprintf(temp, len+1, format, arg);
#if !CONFIG_DISABLE_HAL_LOCKS
if(_uart_bus_array[s_uart_debug_nr].lock){
if(s_uart_debug_nr != -1 && _uart_bus_array[s_uart_debug_nr].lock){
xSemaphoreTake(_uart_bus_array[s_uart_debug_nr].lock, portMAX_DELAY);
ets_printf("%s", temp);
xSemaphoreGive(_uart_bus_array[s_uart_debug_nr].lock);
@ -529,15 +690,17 @@ unsigned long uartBaudrateDetect(uart_t *uart, bool flg)
*/
void uartStartDetectBaudrate(uart_t *uart) {
if(!uart) return;
#ifndef CONFIG_IDF_TARGET_ESP32C3
uart->dev->auto_baud.glitch_filt = 0x08;
uart->dev->auto_baud.en = 0;
uart->dev->auto_baud.en = 1;
#endif
}
unsigned long
uartDetectBaudrate(uart_t *uart)
{
#ifndef CONFIG_IDF_TARGET_ESP32C3
static bool uartStateDetectingBaudrate = false;
if(!uartStateDetectingBaudrate) {
@ -572,11 +735,18 @@ uartDetectBaudrate(uart_t *uart)
}
return default_rates[i];
#else
return 0;
#endif
}
/*
* Returns the status of the RX state machine, if the value is non-zero the state machine is active.
*/
bool uartRxActive(uart_t* uart) {
#if CONFIG_IDF_TARGET_ESP32
return uart->dev->status.st_urx_out != 0;
#else
return 0;
#endif
}

View File

@ -51,8 +51,8 @@ extern "C" {
struct uart_struct_t;
typedef struct uart_struct_t uart_t;
uart_t* uartBegin(uint8_t uart_nr, uint32_t baudrate, uint32_t config, int8_t rxPin, int8_t txPin, uint16_t queueLen, bool inverted);
void uartEnd(uart_t* uart);
uart_t* uartBegin(uint8_t uart_nr, uint32_t baudrate, uint32_t config, int8_t rxPin, int8_t txPin, uint16_t queueLen, bool inverted, uint8_t rxfifo_full_thrhd);
void uartEnd(uart_t* uart, uint8_t rxPin, uint8_t txPin);
uint32_t uartAvailable(uart_t* uart);
uint32_t uartAvailableForWrite(uart_t* uart);
@ -63,12 +63,15 @@ void uartWrite(uart_t* uart, uint8_t c);
void uartWriteBuf(uart_t* uart, const uint8_t * data, size_t len);
void uartFlush(uart_t* uart);
void uartFlushTxOnly(uart_t* uart, bool txOnly );
void uartSetBaudRate(uart_t* uart, uint32_t baud_rate);
uint32_t uartGetBaudRate(uart_t* uart);
size_t uartResizeRxBuffer(uart_t* uart, size_t new_size);
void uartSetRxInvert(uart_t* uart, bool invert);
void uartSetDebug(uart_t* uart);
int uartGetDebug();

View File

@ -20,10 +20,6 @@
#ifndef HAL_ESP32_HAL_H_
#define HAL_ESP32_HAL_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
@ -34,9 +30,34 @@ extern "C" {
#include <math.h>
#include "sdkconfig.h"
#include "esp_system.h"
#include "esp_sleep.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifndef F_CPU
#if CONFIG_IDF_TARGET_ESP32 // ESP32/PICO-D4
#define F_CPU (CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ * 1000000U)
#elif CONFIG_IDF_TARGET_ESP32S2
#define F_CPU (CONFIG_ESP32S2_DEFAULT_CPU_FREQ_MHZ * 1000000U)
#endif
#endif
#if CONFIG_ARDUINO_ISR_IRAM
#define ARDUINO_ISR_ATTR IRAM_ATTR
#define ARDUINO_ISR_FLAG ESP_INTR_FLAG_IRAM
#else
#define ARDUINO_ISR_ATTR
#define ARDUINO_ISR_FLAG (0)
#endif
#ifndef ARDUINO_RUNNING_CORE
#define ARDUINO_RUNNING_CORE CONFIG_ARDUINO_RUNNING_CORE
#endif
#ifndef ARDUINO_EVENT_RUNNING_CORE
#define ARDUINO_EVENT_RUNNING_CORE CONFIG_ARDUINO_EVENT_RUNNING_CORE
#endif
//forward declaration from freertos/portmacro.h
@ -64,12 +85,6 @@ void yield(void);
#include "esp32-hal-psram.h"
#include "esp32-hal-cpu.h"
#ifndef BOARD_HAS_PSRAM
#ifdef CONFIG_SPIRAM_SUPPORT
#undef CONFIG_SPIRAM_SUPPORT
#endif
#endif
//returns chip temperature in Celsius
float temperatureRead();

View File

@ -18,7 +18,7 @@
#define _ESP8266_COMPAT_H_
#define ICACHE_FLASH_ATTR
#define ICACHE_RAM_ATTR IRAM_ATTR
#define ICACHE_RAM_ATTR ARDUINO_ISR_ATTR
#endif /* _ESP8266_COMPAT_H_ */

View File

@ -0,0 +1,46 @@
// Copyright 2019 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
/** Major version number (X.x.x) */
#define ESP_ARDUINO_VERSION_MAJOR 2
/** Minor version number (x.X.x) */
#define ESP_ARDUINO_VERSION_MINOR 0
/** Patch version number (x.x.X) */
#define ESP_ARDUINO_VERSION_PATCH 0
/**
* Macro to convert ARDUINO version number into an integer
*
* To be used in comparisons, such as ESP_ARDUINO_VERSION >= ESP_ARDUINO_VERSION_VAL(2, 0, 0)
*/
#define ESP_ARDUINO_VERSION_VAL(major, minor, patch) ((major << 16) | (minor << 8) | (patch))
/**
* Current ARDUINO version, as an integer
*
* To be used in comparisons, such as ESP_ARDUINO_VERSION >= ESP_ARDUINO_VERSION_VAL(2, 0, 0)
*/
#define ESP_ARDUINO_VERSION ESP_ARDUINO_VERSION_VAL(ESP_ARDUINO_VERSION_MAJOR, \
ESP_ARDUINO_VERSION_MINOR, \
ESP_ARDUINO_VERSION_PATCH)
#ifdef __cplusplus
}
#endif

View File

@ -2,10 +2,31 @@
#include "freertos/task.h"
#include "esp_task_wdt.h"
#include "Arduino.h"
#if ARDUINO_SERIAL_PORT //Serial used for USB CDC
#include "USB.h"
#endif
#ifndef ARDUINO_LOOP_STACK_SIZE
#ifndef CONFIG_ARDUINO_LOOP_STACK_SIZE
#define ARDUINO_LOOP_STACK_SIZE 8192
#else
#define ARDUINO_LOOP_STACK_SIZE CONFIG_ARDUINO_LOOP_STACK_SIZE
#endif
#endif
TaskHandle_t loopTaskHandle = NULL;
#if CONFIG_AUTOSTART_ARDUINO
#if CONFIG_FREERTOS_UNICORE
void yieldIfNecessary(void){
static uint64_t lastYield = 0;
uint64_t now = millis();
if((now - lastYield) > 2000) {
lastYield = now;
vTaskDelay(5); //delay 1 RTOS tick
}
}
#endif
bool loopTaskWDTEnabled;
@ -13,18 +34,26 @@ void loopTask(void *pvParameters)
{
setup();
for(;;) {
#if CONFIG_FREERTOS_UNICORE
yieldIfNecessary();
#endif
if(loopTaskWDTEnabled){
esp_task_wdt_reset();
}
loop();
if (serialEventRun) serialEventRun();
}
}
extern "C" void app_main()
{
#if ARDUINO_SERIAL_PORT //Serial used for USB CDC
USB.begin();
Serial.begin();
#endif
loopTaskWDTEnabled = false;
initArduino();
xTaskCreateUniversal(loopTask, "loopTask", 8192, NULL, 1, &loopTaskHandle, CONFIG_ARDUINO_RUNNING_CORE);
xTaskCreateUniversal(loopTask, "loopTask", ARDUINO_LOOP_STACK_SIZE, NULL, 1, &loopTaskHandle, ARDUINO_RUNNING_CORE);
}
#endif

View File

@ -53,6 +53,8 @@ typedef unsigned long prog_uint32_t;
*(void * const *)(_addr); \
})
#define pgm_get_far_address(x) ((uint32_t)(&(x)))
#define pgm_read_byte_near(addr) pgm_read_byte(addr)
#define pgm_read_word_near(addr) pgm_read_word(addr)
#define pgm_read_dword_near(addr) pgm_read_dword(addr)

View File

@ -28,7 +28,9 @@
#include <stdint.h>
#include <math.h>
#include "stdlib_noniso.h"
#include "esp_system.h"
#if !CONFIG_DSP_ANSI && !CONFIG_DSP_OPTIMIZED
void reverse(char* begin, char* end) {
char *is = begin;
char *ie = end - 1;
@ -40,6 +42,9 @@ void reverse(char* begin, char* end) {
--ie;
}
}
#else
void reverse(char* begin, char* end);
#endif
char* ltoa(long value, char* result, int base) {
if(base < 2 || base > 16) {

View File

@ -0,0 +1,122 @@
# Arduino-ESP32 Example/Library Name ==(REQUIRED)==
==*Add a brief description about this example/library here!*==
This example/library demonstrates how to create a new example README file.
# Supported Targets ==(REQUIRED)==
==*Add the supported devices here!*==
Currently, this example supports the following targets.
| Supported Targets | ESP32 | ESP32-S2 | ESP32-C3 |
| ----------------- | ----- | -------- | -------- |
## How to Use Example/Library ==(OPTIONAL)==
==*Add a brief description on how to use this example.*==
* How to install the Arduino IDE: [Install Arduino IDE](https://github.com/espressif/arduino-esp32/tree/master/docs/arduino-ide).
### Hardware Connection ==(OPTIONAL)==
==*Add a brief description about wiring or any other hardware specific connection.*==
To use this example, you need to connect the LED to the `GPIOx`.
SDCard GPIO connection scheme:
| SDCard Pin | Function | GPIO |
| ----------- | -------- | ------ |
| 1 | CS | GPIO5 |
| 2 | DI/MOSI | GPIO23 |
| 3 | VSS/GND | GND |
| 4 | VDD/3V3 | 3V3 |
| 5 | SCLK | GPIO18 |
| 6 | VSS/GND | GND |
| 7 | DO/MISO | GPIO19 |
To add images, please create a folder `_asset` inside the example folder to add the relevant images.
### Configure the Project ==(OPTIONAL)==
==*Add a brief description about this example here!*==
Set the LED GPIO by changing the `LED_BUILTIN` value in the function `pinMode(LED_BUILTIN, OUTPUT);`. By default, the GPIO is: `GPIOx`.
#### Example for the GPIO4:
==*Add some code explanation if relevant to the example.*==
```cpp
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin 4 as an output.
pinMode(4, OUTPUT);
}
```
#### Using Arduino IDE
To get more information about the Espressif boards see [Espressif Development Kits](https://www.espressif.com/en/products/devkits).
* Before Compile/Verify, select the correct board: `Tools -> Board`.
* Select the COM port: `Tools -> Port: xxx` where the `xxx` is the detected COM port.
#### Using Platform IO
* Select the COM port: `Devices` or setting the `upload_port` option on the `platformio.ini` file.
## Example/Log Output ==(OPTIONAL)==
==*Add the log/serial output here!*==
```
ets Jul 29 2019 12:21:46
rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0030,len:1412
load:0x40078000,len:13400
load:0x40080400,len:3672
entry 0x400805f8
ESP32 Chip model = ESP32-D0WDQ5 Rev 3
This chip has 2 cores
Chip ID: 3957392
```
## Troubleshooting ==(REQUIRED)==
==*Add specific issues you may find by using this example here!*==
***Important: Make sure you are using a good quality USB cable and that you have a reliable power source***
* **LED not blinking:** Check the wiring connection and the IO selection.
* **Programming Fail:** If the programming/flash procedure fails, try reducing the serial connection speed.
* **COM port not detected:** Check the USB cable and the USB to Serial driver installation.
If the error persist, you can ask for help at the official [ESP32 forum](https://esp32.com) or see [Contribute](#contribute).
## Contribute ==(REQUIRED)==
==*Do not change! Keep as is.*==
To know how to contribute to this project, see [How to contribute.](https://github.com/espressif/arduino-esp32/blob/master/CONTRIBUTING.rst)
If you have any **feedback** or **issue** to report on this example/library, please open an issue or fix it by creating a new PR. Contributions are more than welcome!
Before creating a new issue, be sure to try the Troubleshooting and to check if the same issue was already created by someone else.
## Resources ==(REQUIRED)==
==*Do not change here! Keep as is or add only relevant documents/info for this example. Do not add any purchase link/marketing stuff*==
* Official ESP32 Forum: [Link](https://esp32.com)
* Arduino-ESP32 Official Repository: [espressif/arduino-esp32](https://github.com/espressif/arduino-esp32)
* ESP32 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32_datasheet_en.pdf)
* ESP32-S2 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-s2_datasheet_en.pdf)
* ESP32-C3 Datasheet: [Link to datasheet](https://www.espressif.com/sites/default/files/documentation/esp32-c3_datasheet_en.pdf)
* Official ESP-IDF documentation: [ESP-IDF](https://idf.espressif.com)

View File

@ -1,26 +1,28 @@
Make your question, not a Statement, inclusive. Include all pertinent information:
What you are trying to do.
Describe your system( Hardware, computer, O/S, core version, environment)
What you are trying to do
Describe your system (Hardware, computer, O/S, core version, environment)
Describe what is failing
Show the shortest possible code that will duplicate the error
Show the EXACT error message(it doesn't work is not enough)
Show the EXACT error message (it doesn't work is not enough)
Then if someone is interested and knowledgeable you might get a answer. All of this work on your part shows us that you have worked to solve YOUR problem. The more complete your issue posting is, the more likely someone will volunteer their time to help you.
If you have a Guru Meditation Error or Backtrace, ***please decode it***:
https://github.com/me-no-dev/EspExceptionDecoder
[ExceptionDecoder](https://github.com/me-no-dev/EspExceptionDecoder)
----------------------------- Remove above -----------------------------
### Hardware:
Board: ?ESP32 Dev Module? ?node32? ?ttgo_lora?
Core Installation/update date: ?11/jul/2017?
IDE name: ?Arduino IDE? ?Platform.io? ?IDF component?
Flash Frequency: ?40Mhz?
PSRAM enabled: ?no?
Upload Speed: ?115200?
Computer OS: ?Windows 10? ?Mac OSX? ?Ubuntu?
|||||||
|:---|---|---|---|---|---|
|<B>Board</B>|ESP32 Dev Module|node32|ttgo_lora|ESP32-S2-Saola|Custom w/ ESP32-S2-WROVER 16MB|
|<B>Version/Date</B>|1.0.4|2.0.0|0badbeef|11/jul/2017|today's master|
|<B>IDE name</B>|Arduino IDE|Atom + Platform.io|IDF component|VSCode|
|<B>Flash Frequency</B>|40Mhz|80Mhz|
|<B>PSRAM enabled</B>|yes|no|
|<B>Upload Speed</B>|115200|
|<B>Computer OS</B>|Windows 10|Mac OSX|Ubuntu|
### Description:
Describe your problem here

28
docs/Makefile Normal file
View File

@ -0,0 +1,28 @@
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = source
BUILDDIR = build
LINKCHECKDIR = build/linkcheck
.PHONY: checklinks
checklinks:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(LINKCHECKDIR)
@echo
@echo "Check finished. Report is in $(LINKCHECKDIR)."
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

View File

@ -1,59 +0,0 @@
# Over the Air through Web browser
OTAWebUpdate is done with a web browser that can be useful in the following typical scenarios:
- Once the application developed and loading directly from Arduino IDE is inconvenient or not possible
- after deployment if user is unable to expose Firmware for OTA from external update server
- provide updates after deployment to small quantity of modules when setting an update server is not practicable
## Requirements
- The ESP and the computer must be connected to the same network
## Implementation
The sample implementation has been done using:
- example sketch OTAWebUpdater.ino
- ESP32 (Dev Module)
You can use another module also if it meets Flash chip size of the sketch
1-Before you begin, please make sure that you have the following software installed:
- Arduino IDE
- Host software depending on O/S you use:
- Avahi http://avahi.org/ for Linux
- Bonjour http://www.apple.com/support/bonjour/ for Windows
- Mac OSX and iOS - support is already built in / no any extra s/w is required
Prepare the sketch and configuration for initial upload with a serial port
- Start Arduino IDE and load sketch OTAWebUpdater.ino available under File > Examples > OTAWebUpdater.ino
- Update ssid and pass in the sketch so the module can join your Wi-Fi network
- Open File > Preferences, look for “Show verbose output during:” and check out “compilation” option
![verbrose](esp32verbose.PNG)
- Upload sketch (Ctrl+U)
- Now open web browser and enter the url, i.e. http://esp32.local. Once entered, browser should display a form
![login](esp32login.PNG)
> username= admin
> password= admin
**Note**-*If entering “http://ESP32.local” does not work, try replacing “ESP32” with modules IP address.This workaround is useful in case the host software installed does not work*.
Now click on Login button and browser will display a upload form
![upload](esp32upload.PNG)
For Uploading the New Firmware you need to provide the Binary File of your Code.
Exporting Binary file of the Firmware (Code)
- Open up the Arduino IDE
- Open up the Code, for Exporting up Binary file
- Now go to Sketch > export compiled Binary
![export](exportTobinary.PNG)
- Binary file is exported to the same Directory where your code is present
Once you are comfortable with this procedure go ahead and modify OTAWebUpdater.ino sketch to print some additional messages, compile it, Export new binary file and upload it using web browser to see entered changes on a Serial Monitor

View File

@ -1,13 +0,0 @@
Installation instructions using Arduino IDE Boards Manager
==========================================================
Starting with 1.6.4, Arduino allows installation of third-party platform packages using Boards Manager. We have packages available for Windows, Mac OS, and Linux (32 and 64 bit).
- Install the current upstream Arduino IDE at the 1.8 level or later. The current version is at the [Arduino website](http://www.arduino.cc/en/main/software).
- Start Arduino and open Preferences window.
- Enter ```https://dl.espressif.com/dl/package_esp32_index.json``` into *Additional Board Manager URLs* field. You can add multiple URLs, separating them with commas.
- Open Boards Manager from Tools > Board menu and install *esp32* platform (and don't forget to select your ESP32 board from Tools > Board menu after installation).
Stable release link: `https://dl.espressif.com/dl/package_esp32_index.json`
Development release link: `https://dl.espressif.com/dl/package_esp32_dev_index.json`

View File

@ -1,36 +0,0 @@
Installation instructions for Debian / Ubuntu OS
=================================================
- Install latest Arduino IDE from [arduino.cc](https://www.arduino.cc/en/Main/Software)
- Open Terminal and execute the following command (copy->paste and hit enter):
```bash
sudo usermod -a -G dialout $USER && \
sudo apt-get install git && \
wget https://bootstrap.pypa.io/get-pip.py && \
sudo python get-pip.py && \
sudo pip install pyserial && \
mkdir -p ~/Arduino/hardware/espressif && \
cd ~/Arduino/hardware/espressif && \
git clone https://github.com/espressif/arduino-esp32.git esp32 && \
cd esp32 && \
git submodule update --init --recursive && \
cd tools && \
python3 get.py
```
- Restart Arduino IDE
- If you have Arduino installed to ~/, modify the installation as follows, beginning at `mkdir -p ~/Arduino/hardware`:
```bash
cd ~/Arduino/hardware
mkdir -p espressif && \
cd espressif && \
git clone https://github.com/espressif/arduino-esp32.git esp32 && \
cd esp32 && \
git submodule update --init --recursive && \
cd tools && \
python3 get.py
```

View File

@ -1,18 +0,0 @@
Installation instructions for Fedora
=====================================
- Install the latest Arduino IDE from [arduino.cc](https://www.arduino.cc/en/Main/Software). `$ sudo dnf -y install arduino` will most likely install an older release.
- Open Terminal and execute the following command (copy->paste and hit enter):
```bash
sudo usermod -a -G dialout $USER && \
sudo dnf install git python3-pip python3-pyserial && \
mkdir -p ~/Arduino/hardware/espressif && \
cd ~/Arduino/hardware/espressif && \
git clone https://github.com/espressif/arduino-esp32.git esp32 && \
cd esp32 && \
git submodule update --init --recursive && \
cd tools && \
python get.py
```
- Restart Arduino IDE

View File

@ -1,29 +0,0 @@
Installation instructions for Mac OS
=====================================
- Install latest Arduino IDE from [arduino.cc](https://www.arduino.cc/en/Main/Software)
- Open Terminal and execute the following command (copy->paste and hit enter):
```bash
mkdir -p ~/Documents/Arduino/hardware/espressif && \
cd ~/Documents/Arduino/hardware/espressif && \
git clone https://github.com/espressif/arduino-esp32.git esp32 && \
cd esp32 && \
git submodule update --init --recursive && \
cd tools && \
python get.py
```
Where `~/Documents/Arduino` represents your sketch book location as per "Arduino" > "Preferences" > "Sketchbook location" (in the IDE once started). Adjust the command above accordingly if necessary!
 
- If you get the error below. Install the command line dev tools with xcode-select --install and try the command above again:
```xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun```
```xcode-select --install```
- Try `python3` instead of `python` if you get the error: `IOError: [Errno socket error] [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590)` when running `python get.py`
- If you get the following error when running `python get.py` urllib.error.URLError: <urlopen error SSL: CERTIFICATE_VERIFY_FAILED, go to Macintosh HD > Applications > Python3.6 folder (or any other python version), and run the following scripts: Install Certificates.command and Update Shell Profile.command
- Restart Arduino IDE

View File

@ -1,22 +0,0 @@
Installation instructions for openSUSE
======================================
- Install the latest Arduino IDE from [arduino.cc](https://www.arduino.cc/en/Main/Software).
- Open Terminal and execute the following command (copy->paste and hit enter):
```bash
sudo usermod -a -G dialout $USER && \
if [ `python --version 2>&1 | grep '2.7' | wc -l` = "1" ]; then \
sudo zypper install git python-pip python-pyserial; \
else \
sudo zypper install git python3-pip python3-pyserial; \
fi && \
mkdir -p ~/Arduino/hardware/espressif && \
cd ~/Arduino/hardware/espressif && \
git clone https://github.com/espressif/arduino-esp32.git esp32 && \
cd esp32 && \
git submodule update --init --recursive && \
cd tools && \
python get.py
```
- Restart Arduino IDE

View File

@ -1,49 +0,0 @@
## Steps to install Arduino ESP32 support on Windows
### Tested on 32 and 64 bit Windows 10 machines
1. Download and install the latest Arduino IDE ```Windows Installer``` from [arduino.cc](https://www.arduino.cc/en/Main/Software)
2. Download and install Git from [git-scm.com](https://git-scm.com/download/win)
3. Start ```Git GUI``` and run through the following steps:
- Select ```Clone Existing Repository```
![Step 1](win-screenshots/win-gui-1.png)
- Select source and destination
- Sketchbook Directory: Usually ```C:/Users/[YOUR_USER_NAME]/Documents/Arduino``` and is listed underneath the "Sketchbook location" in Arduino preferences.
- Source Location: ```https://github.com/espressif/arduino-esp32.git```
- Target Directory: ```[ARDUINO_SKETCHBOOK_DIR]/hardware/espressif/esp32```
- Click ```Clone``` to start cloning the repository
![Step 2](win-screenshots/win-gui-2.png)
![Step 3](win-screenshots/win-gui-3.png)
- open a `Git Bash` session pointing to ```[ARDUINO_SKETCHBOOK_DIR]/hardware/espressif/esp32``` and execute ```git submodule update --init --recursive```
- Open ```[ARDUINO_SKETCHBOOK_DIR]/hardware/espressif/esp32/tools``` and double-click ```get.exe```
![Step 4](win-screenshots/win-gui-4.png)
- When ```get.exe``` finishes, you should see the following files in the directory
![Step 5](win-screenshots/win-gui-5.png)
4. Plug your ESP32 board and wait for the drivers to install (or install manually any that might be required)
5. Start Arduino IDE
6. Select your board in ```Tools > Board``` menu
7. Select the COM port that the board is attached to
8. Compile and upload (You might need to hold the boot button while uploading)
![Arduino IDE Example](win-screenshots/arduino-ide.png)
### How to update to the latest code
1. Start ```Git GUI``` and you should see the repository under ```Open Recent Repository```. Click on it!
![Update Step 1](win-screenshots/win-gui-update-1.png)
2. From menu ```Remote``` select ```Fetch from``` > ```origin```
![Update Step 2](win-screenshots/win-gui-update-2.png)
3. Wait for git to pull any changes and close ```Git GUI```
4. Open ```[ARDUINO_SKETCHBOOK_DIR]/hardware/espressif/esp32/tools``` and double-click ```get.exe```
![Step 4](win-screenshots/win-gui-4.png)

View File

@ -1,73 +0,0 @@
To use as a component of ESP-IDF
=================================================
## Installation
- Download and install [esp-idf](https://github.com/espressif/esp-idf)
- Create blank idf project (from one of the examples)
- in the project folder, create a folder called components and clone this repository inside
```bash
mkdir -p components && \
cd components && \
git clone https://github.com/espressif/arduino-esp32.git arduino && \
cd arduino && \
git submodule update --init --recursive && \
cd ../.. && \
make menuconfig
```
- ```make menuconfig``` has some Arduino options
- "Autostart Arduino setup and loop on boot"
- If you enable this options, your main.cpp should be formated like any other sketch
```arduino
//file: main.cpp
#include "Arduino.h"
void setup(){
Serial.begin(115200);
}
void loop(){
Serial.println("loop");
delay(1000);
}
```
- Else you need to implement ```app_main()``` and call ```initArduino();``` in it.
Keep in mind that setup() and loop() will not be called in this case.
If you plan to base your code on examples provided in [esp-idf](https://github.com/espressif/esp-idf/tree/master/examples), please make sure move the app_main() function in main.cpp from the files in the example.
```arduino
//file: main.cpp
#include "Arduino.h"
extern "C" void app_main()
{
initArduino();
pinMode(4, OUTPUT);
digitalWrite(4, HIGH);
//do your own thing
}
```
- "Disable mutex locks for HAL"
- If enabled, there will be no protection on the drivers from concurently accessing them from another thread/interrupt/core
- "Autoconnect WiFi on boot"
- If enabled, WiFi will start with the last known configuration
- Else it will wait for WiFi.begin
- ```make flash monitor``` will build, upload and open serial monitor to your board
## Logging To Serial
If you are writing code that does not require Arduino to compile and you want your `ESP_LOGx` macros to work in Arduino IDE, you can enable the compatibility by adding the following lines after your includes:
```cpp
#ifdef ARDUINO_ARCH_ESP32
#include "esp32-hal-log.h"
#endif
```
## Compilation Errors
As commits are made to esp-idf and submodules, the codebases can develop incompatibilities which cause compilation errors. If you have problems compiling, follow the instructions in [Issue #1142](https://github.com/espressif/arduino-esp32/issues/1142) to roll esp-idf back to a known good version.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 510 KiB

35
docs/make.bat Normal file
View File

@ -0,0 +1,35 @@
@ECHO OFF
pushd %~dp0
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=source
set BUILDDIR=build
if "%1" == "" goto help
%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.http://sphinx-doc.org/
exit /b 1
)
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
goto end
:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
:end
popd

View File

@ -1,4 +0,0 @@
To use make
============
[makeEspArduino](https://github.com/plerup/makeEspArduino) is a generic makefile for any ESP8266/ESP32 Arduino project.Using make instead of the Arduino IDE makes it easier to do automated and production builds.

View File

@ -1,11 +0,0 @@
Installation instructions for using PlatformIO
=================================================
- [What is PlatformIO?](https://docs.platformio.org/en/latest/what-is-platformio.html?utm_source=github&utm_medium=arduino-esp32)
- [PlatformIO IDE](https://platformio.org/platformio-ide?utm_source=github&utm_medium=arduino-esp32)
- [PlatformIO Core](https://docs.platformio.org/en/latest/core.html?utm_source=github&utm_medium=arduino-esp32) (command line tool)
- [Advanced usage](https://docs.platformio.org/en/latest/platforms/espressif32.html?utm_source=github&utm_medium=arduino-esp32) -
custom settings, uploading to SPIFFS, Over-the-Air (OTA), staging version
- [Integration with Cloud and Standalone IDEs](https://docs.platformio.org/en/latest/ide.html?utm_source=github&utm_medium=arduino-esp32) -
Cloud9, Codeanywhere, Eclipse Che (Codenvy), Atom, CLion, Eclipse, Emacs, NetBeans, Qt Creator, Sublime Text, VIM, Visual Studio, and VSCode
- [Project Examples](https://docs.platformio.org/en/latest/platforms/espressif32.html?utm_source=github&utm_medium=arduino-esp32#examples)

5
docs/requirements.txt Normal file
View File

@ -0,0 +1,5 @@
# This is a list of python packages used to generate documentation. This file is used with pip:
# pip install --user -r requirements.txt
#
# matplotlib is currently required only by the script generate_chart.py
sphinx-copybutton==0.3.0

View File

Before

Width:  |  Height:  |  Size: 186 KiB

After

Width:  |  Height:  |  Size: 186 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Some files were not shown because too many files have changed in this diff Show More