Compare commits

...
59 Commits
Author SHA1 Message Date
Earle F. Philhower, III e60858c327 Update version 2025-03-11 13:35:52 -07:00
Earle F. Philhower, III bebd1dff50 Update README.md (#2848) 2025-03-11 13:34:08 -07:00
Earle F. Philhower, III 14145e4469 Update to SDK 2.1.2-develop (#2844)
Supercedes #2815

Move to pico-sdk official develop branch which includes a necessary
IRQ header fix.

200MHz is now default for the Pico, but 133 is still available from
the menus.
2025-03-11 13:30:17 -07:00
Dryw Wade d9d556bcd0 Add SparkFun XRP Controller (#2847) 2025-03-11 13:00:55 -07:00
InfiniteCoder 5bd1a3a0f6 A2DP: scanAsyncDone & scanAsyncResults; fix write and availableForWrite (#2839) 2025-03-06 10:55:56 -08:00
Earle F. Philhower, III 5bfc35caf5 Enable add'l UART_AUX pinouts for RP2350 (#2837)
Fixes #2835.  Thanks @deltaford!
2025-03-05 07:02:32 -08:00
Alex Brudner 8e1e709ab1 Add SparkFun IoT RedBoard RP2350 (#2836) 2025-03-03 16:30:42 -08:00
Jeff Epler 46a58fb4b5 Early out of (un)maskInterrupts() if no GPIO interrupts need to be masked (#2831)
My application is designed to generate HSTX data on core0 in interrupts,
but also uses hardware SPI for SD card access.

It turns out that the amount of time spent in maskInterrupts/
unmaskInterrupts, even with an empty _usingIRQs, is too long.

Add a quick check and avoid touching the interrupt disable flag if
there's not actually any GPIO interrupt to (un)mask.
2025-02-28 12:44:47 -08:00
Earle F. Philhower, III 8deb6b9724 Adjust the PSRAM clock when over/underclock F_SYS (#2824)
* Adjust the PSRAM clock when over/underclock F_SYS

Fixes #2818

* Need to increase PSRAM divider before sysclk increase

Per datasheet, when increasing sysclk speed we need to set the qmi
clocks first and do a dummy transfer to ensure no invalid speed
operations happen on the bus.  Handle the logic for this while setting
up the overclock.
2025-02-26 16:38:52 -08:00
Jeff Epler 6236d1f7c5 Define HSTX pins on Adafruit boards with HSTX or DVI connectors (#2825) 2025-02-25 08:36:58 -08:00
Dryw Wade 91ce323a68 Add SparkFun XRP Controller (Beta) (#2823) 2025-02-24 12:03:55 -08:00
Earle F. Philhower, III 2f82bfd22a Update README.md 2025-02-23 11:36:36 -08:00
Michael Ring 1689c75ef1 Support Makerbase MKSTHR36 and MKSTHR42 Boards (#2819)
* Support Makerbase MKSTHR36 and MKSTHR42 Boards

* Added missing define for PIN_SERIAL1_* for MKSTHR42 Board
2025-02-23 11:35:53 -08:00
brabl2 935eb64a8e Added WizNet W6100 to the AdvancedWebServer example (#2812) 2025-02-19 07:25:09 -08:00
Earle F. Philhower, III 31786cdc24 Update version 2025-02-18 12:55:03 -08:00
Earle F. Philhower, III 3d17a56ecf Fix Wire/Wire1 definitions for Xaio RP2350 (#2811)
Fixes #2808
2025-02-18 10:28:12 -08:00
Earle F. Philhower, III 3cb5c315f3 Correct Seeed XAIO RP2350 config (#2803)
Fixes #2801
2025-02-15 16:15:29 -08:00
Earle F. Philhower, III 0148b1469c Update README.md 2025-02-09 09:53:46 -08:00
Stefan NürnbergerandStefan Nuernberger 96a4059f09 added I2C TwoWire::busIdle to be checked by writeReadAsync (#2798)
---------
Co-authored-by: Stefan Nuernberger <stefan@elexir.eu>
2025-02-09 09:52:45 -08:00
Limor "Ladyada" Fried c3d15931a4 Add new RP2350 Metro! (#2795) 2025-02-09 09:16:45 -08:00
Earle F. Philhower, III c79e543c41 Move to Arduino API 10501 (#2797)
* Move to Arduino API 10501

Track upstream Arduino API headers

* IPAddress V4/V6 compatiblity restored

* Fix WiFiUDP includes

* String differences in example

* HardwareSerial using exported
2025-02-08 22:45:10 -08:00
Stefan NürnbergerandStefan Nuernberger 3c556e6729 fixed: Wire::writeReadAsync not setting _dmaSendBufferLen, therefore allocating the DMA buffer anew on every call (#2796)
Co-authored-by: Stefan Nuernberger <stefan@elexir.eu>
2025-02-08 14:15:18 -08:00
Earle F. Philhower, III 5e2fbf324b Update version 2025-02-04 14:34:53 -08:00
Maximilian Gerhardt fb82f16704 Document PSRAM and Boot2 better (#2792) 2025-02-04 12:01:54 -08:00
Earle F. Philhower, III 79568a3e63 OTA Updater better error codes on OOS (#2793)
Fixes #2785.  Thanks @donmsmall!
2025-02-04 11:54:12 -08:00
Earle F. Philhower, III b506c010f7 Fix I2C on Adafruit Feather RP2350 HSTX (#2784)
Fixes #2783
2025-01-30 12:08:24 -08:00
Earle F. Philhower, III 8c3170596f Deduplicate SPI and SoftwareSPI routines (#2779) 2025-01-28 12:47:13 -08:00
Earle F. Philhower, III acf81f426c Add PIO-based SoftwareSPI enabling SPI on any pins (#2778)
* Add PIO-based SoftwareSPI enabling SPI on any pins

The Raspberry Pi team has a working PIO-based SPI interface.  Wrap it
to work like a hardware SPI interface, allowing SPI on any pin
combination.

Tested reading and writing an SD card using unmodified SD library.

* Add W5500 example

Good for testing, shows non-contiguous pin outs.
2025-01-27 13:59:52 -08:00
Cooper Dalrymple a426fbf51d Add buffer read to AudioBufferManager and I2S (#2777)
* Added buffer read to `AudioBufferManager` and `I2S`. Example and documentation included.
* Update type of words to unsigned in example.
* Improve buffered loopback example.
* Remove const from read buffer.
2025-01-26 10:03:44 -08:00
Cooper Dalrymple e133147192 Bi-directional I2S support (#2775)
* Initial bi-directional I2S support.

* Formatting update on pioasm file.

* Added loopback example.

* Updated documentation.

* Fix `getOverUnderflow` naming.

* Revert `getOverUnderflow` naming changes.

* Remove python cache file.

* Remove `availableForRead`.

* Updated naming convention of OverUnderflow methods.

* Update constructor to prevent conflicts with existing code.

* Avoid ambiguous `setDATA` in bi-directional mode.

* Use only input buffer manager in `available`.

* Fix input checks in `read` and `peek`.

* Fix erroneous comment.

* Update pio_i2s.pio to pio v1.

* Change pio_i2s.pio back to pio v0.
2025-01-23 16:30:53 -08:00
Earle F. Philhower, III 84826935a9 Don't set SDFAT_FILE_TYPE, default is OK (#2773)
* Don't set SDFAT_FILE_TYPE, default is OK

Fixes #2772

No need to set SDFAT_FILE_TYPE=3 as that is the defaulr value with upstream
SdFat.  Remove it from platform.txt and platform.io build.

* Codespell got all techy
2025-01-22 10:08:28 -08:00
Earle F. Philhower, III 9480c2a55d Update version 2025-01-21 10:15:08 -08:00
Markus Gyger b3d0ccc7e3 Change duty cycle of PIO Tone to 50% (#2770) 2025-01-21 10:03:31 -08:00
Dryw Wade 5a34395f46 PIOProgram: Replace __pioHighGPIO with pio_get_gpio_base() (#2769)
Fixes #2768
2025-01-21 09:33:04 -08:00
Earle F. Philhower, III e20c973bf5 SDIO doesn't take a clock speed parameter (#2766)
It's fixed by the PIO program and GPIO slew rates encoded in the SdFAT
driver.  Remove the parameter from the SD/SDFS begins.
2025-01-18 09:19:39 -08:00
Earle F. Philhower, III 452ef17174 Replace ESP8266SdFat w/SdFat 2.3.0, SDIO, ExFAT (#2764)
* Replace ESP8266SdFat w/SdFat 2.3.0, add SDIO and ExFAT support

Remove ESP8266SdFat fork and replaces with upstream SdFat to simplify
maintenance.

This 2.3.0 version adds SDIO support and enables exFAT support.
Also upgraded FAT filename support to 256 chars, identical to  LittleFS.

* Add SDIO support to SD and SDFS, documentation, and examples

* Update SD examples to all support SPI0, SPI1, or SDIO
2025-01-17 15:22:39 -08:00
Earle F. Philhower, III 4785c16243 Update to LittleFS v2.10.1 (#2762)
Minor behavior changes WRT path handling with trailing slashes, but
should not affect anything on the Arduino side.
2025-01-17 10:18:32 -08:00
Earle F. Philhower, III 2506b8e1d1 Update to Adafruit TinyUSB 3.4.2 (#2761)
Should be no change, just keeping in pace with upstream.
2025-01-17 10:03:22 -08:00
Earle F. Philhower, III 7bfe25b8aa Remove SDK C++ new/delete, duplicated objects (#2760)
* Remove Pico-SDK C++ exception-override new/delete

We support exceptions on and off, but the cxx_options file in the
SDK implemented a single override to new/delete.

Remove it so we will use GCC's build-in operator new/delete
which will be correct for either option (2 different libstdc++
versions are shipped as part of the toolchain).

* Remove duplicated SDK files

The SDK will link in the same compilation unit in the LWIP builds.
Remove them to shrink the repo size by ~28MB.
2025-01-16 15:02:01 -08:00
SomebodyOdd 2348051026 A2DPSink: Remove stubs, fix volume and connect callbacks (#2757)
* A2DPSink: Remove Stream implementation and onTransmit
* A2DPSink: Fix onConnect and onVolume callbacks
* A2DPSink: Remove transmit callback field
2025-01-16 09:37:22 -08:00
Dryw WadeandKirk Benell b4001bfb0e Add SparkFun IoT Node LoRaWAN (#2745)
* added files to support the SparkFun IoT Node LoRaWAN board

* added rp2053 to our lorawan board defs

* adding updates/new files generated for the iot node board

* Add SPI swap

* Remove incorrect comment from IoT Node LoRawAN

* Replace missing line in boards.txt

* Re-run makeboards.py for IoT Node LoRaWAN

---------

Co-authored-by: Kirk Benell <kirk.benell@sparkfun.com>
2025-01-15 09:47:55 -08:00
Earle F. Philhower, III 0655b7d5b6 Fix ADCInput clocks for multiple inputs (#2755)
When multiple inputs were active, the frequency was being scaled two
times resulting in incorrect sampling speed.  Correct to only scale
the calculation and not the stored value (which is used in `begin`).

Fixes #2754
2025-01-14 15:58:45 -08:00
Earle F. Philhower, III 83b8d122d7 Restore Bluetooth TLV on Pico2/RPiWiFi boards (#2753) 2025-01-13 17:38:51 -08:00
timw01 8caa590f5c Correct return from NTP.waitSet() (#2736)
Fixes #2735
2025-01-04 17:06:26 -08:00
Earle F. Philhower, III ec528d34f8 Remove unneeded SDK files from libpico/etc. (#2733)
Pico-SDK changed the output extension of their compilation from "x.c.obj"
to "x.c.o" meaning the removed Newlib and STDIO SDK wrappers were still
being linked in certain situations.  Update make-libpico Cmakefile to
remove the new names.

Fixes debug `printf` output.
2025-01-03 10:42:47 -08:00
Earle F. Philhower, III 5296241949 Update version 2024-12-31 10:35:02 -08:00
Earle F. Philhower, III d84ff02f03 Allow setting PWMAudio frequency before begin (#2726)
I2S allows setting freq before ::begin, so allow same for PWMAudio.
2024-12-30 10:57:40 -08:00
Earle F. Philhower, III cc2581afd6 Properly wrap AudioBufferManager block writes (#2725)
The memcpy-version of the ABM::write updated the destination and count
but neglected to move the source forward.  If a block write crossed a
frame boundary then the 2nd frame would repeat the data from the first
half of the buffer.

Fix by incrementing the source pointer by the same amount as was written.
2024-12-29 16:26:23 -08:00
Earle F. Philhower, III bb682bbb33 Use the distributed ARM ar in libpico, not system (#2721)
Fixes #508
2024-12-29 10:29:42 -08:00
Earle F. Philhower, III 809beffc8b Add AudioOutputBase keyword 2024-12-27 10:15:05 -08:00
Earle F. Philhower, III fa22c6c627 RTD has its own key for PDF generation 2024-12-27 08:48:39 -08:00
Earle F. Philhower, III 0788a42477 RTD doesn't do formats:PDF, revert 2024-12-27 08:44:58 -08:00
Earle F. Philhower, III d732ac82ba Precalculate common PWMAudio dividers, avoid noise (#2714)
Calculating the DMA clock divider for PWMAudio can take a very long time
because there are 65K floating point divisions required.  But most audio
will be one of a dozen sample rates, so it is possible to precalculate
the rates on the host and use a small lookup table to avoid any math at
all.  Removes occasional scratching in PWMAudio when the BackgroundAudio
library changes sample rates.
2024-12-22 14:05:44 -08:00
Earle F. Philhower, III 5fb5e16be8 Add real block write for AudioRequestBuffer (#2712)
Optimize AudioRequestBuffer writing when large blocks are available (i.e.
I2S writes of full MP3 or AAC frames in BackgroundAudio).  Update I2S to use
the new call.  Reduces 1152 calls to arb::write() to a single call/return
and optimized memcpy in that case.
2024-12-21 14:15:40 -08:00
Earle F. Philhower, III 45c0b3a1b4 Move MacX86 runner up to new minimum spec (#2711)
The MacOS12 runner is dead, so move up to the lowest version still available for CI.
2024-12-21 10:27:44 -08:00
Markus Gyger 7961d2943d Overclock to 153.6 MHz (instead of 147.6 MHz) for I²S 48 kHz sample rate (#2708) 2024-12-21 07:36:57 -08:00
Kjell Braden 4d03edc7d5 Don't go through runtime initializers when there is no OTA command (#2697)
Leave that to the main app instead, so we don't reset peripherals twice.
* ota: fix copy error for riscv headers
* ota: initialize bootrom bit ops and add explanation
2024-12-19 10:05:46 -08:00
CIncinnatus d5a6888cac Fix issue with undefined LED_BUILTIN on Seeed Xiao RP2350 (#2704)
* Modify the pin definitions for XIAO RP2350

* Fix issue with undefined LED_BUILTIN
2024-12-19 09:02:32 -08:00
Earle F. Philhower, III a13d236afd Update fs.rst 2024-12-19 07:00:59 -08:00
155 changed files with 6409 additions and 1153 deletions
+1 -1
View File
@@ -196,7 +196,7 @@ jobs:
name: Mac
strategy:
matrix:
os: [macOS-12, macOS-14]
os: [macOS-13, macOS-14]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
+2
View File
@@ -3,5 +3,7 @@ system
tools/dist
docs/_build
ota/build
ota/build-rp2350
ota/build-rp2350-riscv
tools/libpico/build
platform.local.txt
+3 -3
View File
@@ -10,9 +10,6 @@
[submodule "libraries/LittleFS/lib/littlefs"]
path = libraries/LittleFS/lib/littlefs
url = https://github.com/littlefs-project/littlefs.git
[submodule "libraries/SdFat"]
path = libraries/ESP8266SdFat
url = https://github.com/earlephilhower/ESP8266SdFat.git
[submodule "libraries/Keyboard"]
path = libraries/HID_Keyboard
url = https://github.com/earlephilhower/Keyboard.git
@@ -49,3 +46,6 @@
[submodule "libraries/ESPHost"]
path = libraries/ESPHost
url = https://github.com/Networking-for-Arduino/ESPHost.git
[submodule "libraries/SdFat"]
path = libraries/SdFat
url = https://github.com/greiman/SdFat.git
+2 -2
View File
@@ -29,8 +29,8 @@ sphinx:
# fail_on_warning: true
# Optionally build your docs in additional formats such as PDF and ePub
formats:
- pdf
formats:
- pdf
# - epub
# Optional but recommended, declare the Python requirements required
+6 -1
View File
@@ -25,6 +25,7 @@ Read the [Contributing Guide](https://github.com/earlephilhower/arduino-pico/blo
* Adafruit KB2040
* Adafruit Macropad RP2040
* Adafruit Metro RP2040
* Adafruit Metro RP2350
* Adafruit QTPy RP2040
* Adafruit STEMMA Friend RP2040
* Adafruit Trinkey RP2040 QT
@@ -68,6 +69,8 @@ Read the [Contributing Guide](https://github.com/earlephilhower/arduino-pico/blo
* Melopero Cookie RP2040
* Melopero Shake RP2040
* METE HOCA Akana R1
* Makerbase MKSTHR36
* Makerbase MKSTHR42
* MyMakers RP2040
* Neko Systems BL2040 Mini
* Newsan Archi
@@ -92,11 +95,13 @@ Read the [Contributing Guide](https://github.com/earlephilhower/arduino-pico/blo
* Solder Party RP2040 Stamp
* Solder Party RP2350 Stamp
* Solder Party RP2350 Stamp XL
* SparkFun IoT RedBoard RP2350
* SparkFun MicroMod RP2040
* SparkFun ProMicro RP2040
* SparkFun ProMicro RP2350
* SparkFun Thing Plus RP2040
* SparkFun Thing Plus RP2350
* SparkFun XRP Controller
* uPesy RP2040 DevKit
* VCC-GND YD-RP2040
* Viyalab Mizu RP2040
@@ -148,7 +153,7 @@ The RP2040 PIO state machines (SMs) are used to generate jitter-free:
* I2S Input
* I2S Output
* Software UARTs (Serial ports)
* Software SPIs
# Installing via Arduino Boards Manager
## Windows-specific Notes
+2667 -706
View File
File diff suppressed because it is too large Load Diff
+5 -1
View File
@@ -110,7 +110,7 @@ extern bool __isFreeRTOS;
#endif
#ifndef PGM_VOID_P
#define PGM_VOID_P void *
#define PGM_VOID_P const void *
#endif
#ifdef __cplusplus
@@ -159,3 +159,7 @@ constexpr uint64_t __bitset(const int (&a)[N], size_t i = 0U) {
#define __GPIOCNT 30
#define __FIRSTANALOGGPIO 26
#endif
#ifdef __cplusplus
using namespace arduino;
#endif
+7 -9
View File
@@ -33,7 +33,6 @@
static std::map<const pio_program_t *, int> __pioMap[PIOCNT];
static bool __pioAllocated[PIOCNT];
static bool __pioHighGPIO[PIOCNT];
auto_init_mutex(_pioMutex);
PIOProgram::PIOProgram(const pio_program_t *pgm) {
@@ -64,16 +63,16 @@ bool PIOProgram::prepare(PIO *pio, int *sm, int *offset, int start, int cnt) {
return ret;
#endif
bool needsHigh = (start + cnt) >= 32;
DEBUGV("PIOProgram %p: Searching for high=%d, pins %d-%d\n", _pgm, needsHigh ? 1 : 0, start, start + cnt - 1);
uint gpioBaseNeeded = ((start + cnt) >= 32) ? 16 : 0;
DEBUGV("PIOProgram %p: Searching for base=%d, pins %d-%d\n", _pgm, gpioBaseNeeded, start, start + cnt - 1);
// If it's already loaded into PIO IRAM, try and allocate in that specific PIO
for (int o = 0; o < PIOCNT; o++) {
auto p = __pioMap[o].find(_pgm);
if ((p != __pioMap[o].end()) && (__pioHighGPIO[o] == needsHigh)) {
if ((p != __pioMap[o].end()) && (pio_get_gpio_base(pio_get_instance(o)) == gpioBaseNeeded)) {
int idx = pio_claim_unused_sm(pi[o], false);
if (idx >= 0) {
DEBUGV("PIOProgram %p: Reusing IMEM ON PIO %p(high=%d) for pins %d-%d\n", _pgm, pi[o], __pioHighGPIO[o] ? 1 : 0, start, start + cnt - 1);
DEBUGV("PIOProgram %p: Reusing IMEM ON PIO %p(base=%d) for pins %d-%d\n", _pgm, pi[o], pio_get_gpio_base(pio_get_instance(o)), start, start + cnt - 1);
_pio = pi[o];
_sm = idx;
*pio = pi[o];
@@ -86,12 +85,12 @@ bool PIOProgram::prepare(PIO *pio, int *sm, int *offset, int start, int cnt) {
// Not in any PIO IRAM, so try and add
for (int o = 0; o < PIOCNT; o++) {
if (__pioAllocated[o] && (__pioHighGPIO[o] == needsHigh)) {
if (__pioAllocated[o] && (pio_get_gpio_base(pio_get_instance(o)) == gpioBaseNeeded)) {
DEBUGV("PIOProgram: Checking PIO %p\n", pi[o]);
if (pio_can_add_program(pi[o], _pgm)) {
int idx = pio_claim_unused_sm(pi[o], false);
if (idx >= 0) {
DEBUGV("PIOProgram %p: Adding IMEM ON PIO %p(high=%d) for pins %d-%d\n", _pgm, pi[o], __pioHighGPIO[o] ? 1 : 0, start, start + cnt - 1);
DEBUGV("PIOProgram %p: Adding IMEM ON PIO %p(base=%d) for pins %d-%d\n", _pgm, pi[o], pio_get_gpio_base(pio_get_instance(o)), start, start + cnt - 1);
int off = pio_add_program(pi[o], _pgm);
__pioMap[o].insert({_pgm, off});
_pio = pi[o];
@@ -123,8 +122,7 @@ bool PIOProgram::prepare(PIO *pio, int *sm, int *offset, int start, int cnt) {
}
assert(!__pioAllocated[o]);
__pioAllocated[o] = true;
__pioHighGPIO[o] = needsHigh;
DEBUGV("PIOProgram %p: Allocating new PIO %p(high=%d) for pins %d-%d\n", _pgm, pi[o], __pioHighGPIO[o] ? 1 : 0, start, start + cnt - 1);
DEBUGV("PIOProgram %p: Allocating new PIO %p(base=%d) for pins %d-%d\n", _pgm, pi[o], pio_get_gpio_base(pio_get_instance(o)), start, start + cnt - 1);
__pioMap[o].insert({_pgm, off});
_pio = pi[o];
_sm = idx;
+2 -2
View File
@@ -1,5 +1,5 @@
#pragma once
#define ARDUINO_PICO_MAJOR 4
#define ARDUINO_PICO_MINOR 4
#define ARDUINO_PICO_MINOR 5
#define ARDUINO_PICO_REVISION 0
#define ARDUINO_PICO_VERSION_STR "4.4.0"
#define ARDUINO_PICO_VERSION_STR "4.5.0"
+1 -1
View File
@@ -29,7 +29,7 @@
extern "C" typedef struct uart_inst uart_inst_t;
class SerialPIO : public HardwareSerial {
class SerialPIO : public arduino::HardwareSerial {
public:
static const pin_size_t NOPIN = 0xff; // Use in constructor to disable RX or TX unit
SerialPIO(pin_size_t tx, pin_size_t rx, size_t fifoSize = 32);
+1 -1
View File
@@ -24,7 +24,7 @@
#include "Arduino.h"
#include "api/HardwareSerial.h"
class SerialSemiClass : public HardwareSerial {
class SerialSemiClass : public arduino::HardwareSerial {
public:
SerialSemiClass() {
/* noop */
+52 -8
View File
@@ -32,15 +32,20 @@ extern void serialEvent1() __attribute__((weak));
extern void serialEvent2() __attribute__((weak));
bool SerialUART::setRX(pin_size_t pin) {
#ifdef PICO_RP2350B
constexpr uint64_t valid[2] = { __bitset({1, 13, 17, 29, 33, 45}) /* UART0 */,
__bitset({5, 9, 21, 25, 37, 41}) /* UART1 */
#if defined(PICO_RP2350B)
constexpr uint64_t valid[2] = { __bitset({1, 3, 13, 15, 17, 19, 29, 31, 33, 35, 45, 47}) /* UART0 */,
__bitset({5, 7, 9, 11, 21, 23, 25, 27, 37, 39, 41, 43}) /* UART1 */
};
#elif defined(PICO_RP2350)
constexpr uint64_t valid[2] = { __bitset({1, 3, 13, 15, 17, 19, 29}) /* UART0 */,
__bitset({5, 7, 9, 11, 21, 23, 25, 27}) /* UART1 */
};
#else
constexpr uint64_t valid[2] = { __bitset({1, 13, 17, 29}) /* UART0 */,
__bitset({5, 9, 21, 25}) /* UART1 */
};
#endif
if ((!_running) && ((1LL << pin) & valid[uart_get_index(_uart)])) {
_rx = pin;
return true;
@@ -59,9 +64,13 @@ bool SerialUART::setRX(pin_size_t pin) {
}
bool SerialUART::setTX(pin_size_t pin) {
#ifdef PICO_RP2350B
constexpr uint64_t valid[2] = { __bitset({0, 12, 16, 28, 32, 44}) /* UART0 */,
__bitset({4, 8, 20, 24, 36, 40}) /* UART1 */
#if defined(PICO_RP2350B)
constexpr uint64_t valid[2] = { __bitset({0, 2, 12, 14, 16, 18, 28, 30, 32, 34, 44, 46}) /* UART0 */,
__bitset({4, 6, 8, 10, 20, 22, 24, 26, 36, 38, 40, 42}) /* UART1 */
};
#elif defined(PICO_RP2350)
constexpr uint64_t valid[2] = { __bitset({0, 2, 12, 14, 16, 18, 28}) /* UART0 */,
__bitset({4, 6, 8, 10, 20, 22, 24, 26}) /* UART1 */
};
#else
constexpr uint64_t valid[2] = { __bitset({0, 12, 16, 28}) /* UART0 */,
@@ -170,6 +179,41 @@ SerialUART::SerialUART(uart_inst_t *uart, pin_size_t tx, pin_size_t rx, pin_size
static void _uart0IRQ();
static void _uart1IRQ();
// Does the selected TX/RX need UART_AUX function (rp2350)
static gpio_function_t __gpioFunction(int pin) {
switch (pin) {
#if defined(PICO_RP2350) || defined(PICO_RP2350B)
case 2:
case 3:
case 6:
case 7:
case 10:
case 11:
case 14:
case 15:
case 18:
case 19:
case 22:
case 23:
case 26:
case 27:
case 30:
case 31:
case 34:
case 35:
case 38:
case 39:
case 42:
case 43:
case 46:
case 47:
return GPIO_FUNC_UART_AUX;
#endif
default:
return GPIO_FUNC_UART;
}
}
void SerialUART::begin(unsigned long baud, uint16_t config) {
if (_running) {
end();
@@ -180,9 +224,9 @@ void SerialUART::begin(unsigned long baud, uint16_t config) {
_fcnTx = gpio_get_function(_tx);
_fcnRx = gpio_get_function(_rx);
gpio_set_function(_tx, GPIO_FUNC_UART);
gpio_set_function(_tx, __gpioFunction(_tx));
gpio_set_outover(_tx, _invertTX ? 1 : 0);
gpio_set_function(_rx, GPIO_FUNC_UART);
gpio_set_function(_rx, __gpioFunction(_rx));
gpio_set_inover(_rx, _invertRX ? 1 : 0);
if (_rts != UART_PIN_NOT_DEFINED) {
_fcnRts = gpio_get_function(_rts);
+1 -1
View File
@@ -29,7 +29,7 @@
extern "C" typedef struct uart_inst uart_inst_t;
#define UART_PIN_NOT_DEFINED (255u)
class SerialUART : public HardwareSerial {
class SerialUART : public arduino::HardwareSerial {
public:
SerialUART(uart_inst_t *uart, pin_size_t tx, pin_size_t rx, pin_size_t rts = UART_PIN_NOT_DEFINED, pin_size_t cts = UART_PIN_NOT_DEFINED);
+1 -1
View File
@@ -24,7 +24,7 @@
#include "api/HardwareSerial.h"
#include <stdarg.h>
class SerialUSB : public HardwareSerial {
class SerialUSB : public arduino::HardwareSerial {
public:
SerialUSB() { }
void begin(unsigned long baud = 115200) override;
+2 -5
View File
@@ -71,10 +71,7 @@ void tone(uint8_t pin, unsigned int frequency, unsigned long duration) {
return; // Weird deadlock case
}
int us = 1'000'000 / frequency / 2;
if (us < 5) {
us = 5;
}
unsigned int delay = (RP2040::f_cpu() + frequency) / (frequency * 2) - 3; // rounded
auto entry = _toneMap.find(pin);
Tone *newTone;
if (entry == _toneMap.end()) {
@@ -99,7 +96,7 @@ void tone(uint8_t pin, unsigned int frequency, unsigned long duration) {
tone2_program_init(newTone->pio, newTone->sm, newTone->off, pin);
}
pio_sm_clear_fifos(newTone->pio, newTone->sm); // Remove any old updates that haven't yet taken effect
pio_sm_put_blocking(newTone->pio, newTone->sm, RP2040::usToPIOCycles(us));
pio_sm_put_blocking(newTone->pio, newTone->sm, delay);
pio_sm_exec(newTone->pio, newTone->sm, pio_encode_pull(false, false));
pio_sm_exec(newTone->pio, newTone->sm, pio_encode_mov(pio_x, pio_osr));
pio_sm_set_enabled(newTone->pio, newTone->sm, true);
+37 -1
View File
@@ -22,7 +22,11 @@
#include "RP2040USB.h"
#include <pico/stdlib.h>
#include <pico/multicore.h>
#include <hardware/vreg.h>
#include <reent.h>
#ifdef RP2350_PSRAM_CS
#include "psram.h"
#endif
RP2040 rp2040;
extern "C" {
@@ -80,9 +84,41 @@ static struct _reent *_impure_ptr1 = nullptr;
extern "C" int main() {
#if (defined(PICO_RP2040) && (F_CPU != 125000000)) || (defined(PICO_RP2350) && (F_CPU != 150000000))
set_sys_clock_khz(F_CPU / 1000, true);
#if defined(PICO_RP2040)
// From runtime_init_clocks() to bump up RP2040 V for 200Mhz+ operation
if ((F_CPU > 133000000) && (vreg_get_voltage() < VREG_VOLTAGE_1_15)) {
vreg_set_voltage(VREG_VOLTAGE_1_15);
// wait for voltage to settle; must use CPU cycles as TIMER is not yet clocked correctly
busy_wait_at_least_cycles((uint32_t)((SYS_CLK_VREG_VOLTAGE_AUTO_ADJUST_DELAY_US * (uint64_t)XOSC_HZ) / 1000000));
}
#endif
#if defined(RP2350_PSRAM_CS) && (F_CPU > 150000000)
// Need to increase the qmi divider before upping sysclk to ensure we keep the output sck w/in legal bounds
psram_reinit_timing(F_CPU);
// Per datasheet, need to do a dummy access and memory barrier before it takes effect
extern uint8_t __psram_start__;
volatile uint8_t *x = &__psram_start__;
*x ^= 0xff;
*x ^= 0xff;
asm volatile("" ::: "memory");
#endif
set_sys_clock_khz(F_CPU / 1000, true);
#if defined(RP2350_PSRAM_CS) && (F_CPU < 150000000)
psram_reinit_timing();
// Per datasheet, need to do a dummy access and memory barrier before it takes effect
extern uint8_t __psram_start__;
volatile uint8_t *x = &__psram_start__;
*x ^= 0xff;
*x ^= 0xff;
asm volatile("" ::: "memory");
#endif
#endif // over/underclock
// Let rest of core know if we're using FreeRTOS
__isFreeRTOS = initFreeRTOS ? true : false;
+1
View File
@@ -23,6 +23,7 @@
#include <errno.h>
#include <_syslist.h>
#include <sys/times.h>
#include <sys/unistd.h>
#include <pico/stdlib.h>
#include <pico/multicore.h>
+7 -7
View File
@@ -195,10 +195,7 @@ static size_t __no_inline_not_in_flash_func(get_psram_size)(void) {
///
/// @note This function expects interrupts to be enabled on entry
static void __no_inline_not_in_flash_func(set_psram_timing)(void) {
// Get secs / cycle for the system clock - get before disabling interrupts.
uint32_t sysHz = (uint32_t)clock_get_hz(clk_sys);
static void __no_inline_not_in_flash_func(set_psram_timing)(uint32_t sysHz) {
// Calculate the clock divider - goal to get clock used for PSRAM <= what
// the PSRAM IC can handle - which is defined in SFE_PSRAM_MAX_SCK_HZ
volatile uint8_t clockDivider = (sysHz + SFE_PSRAM_MAX_SCK_HZ - 1) / SFE_PSRAM_MAX_SCK_HZ;
@@ -283,7 +280,7 @@ static void __no_inline_not_in_flash_func(runtime_init_setup_psram)(/*uint32_t p
// check our interrupts and setup the timing
restore_interrupts(intr_stash);
set_psram_timing();
set_psram_timing((uint32_t)clock_get_hz(clk_sys));
// and now stash interrupts again
intr_stash = save_and_disable_interrupts();
@@ -323,8 +320,11 @@ static void __no_inline_not_in_flash_func(runtime_init_setup_psram)(/*uint32_t p
PICO_RUNTIME_INIT_FUNC_RUNTIME(runtime_init_setup_psram, PICO_RUNTIME_INIT_PSRAM);
// update timing -- used if the system clock/timing was changed.
void psram_reinit_timing() {
set_psram_timing();
void psram_reinit_timing(uint32_t hz) {
if (!hz) {
hz = (uint32_t)clock_get_hz(clk_sys);
}
set_psram_timing(hz);
}
static bool __psram_heap_init() {
+1 -1
View File
@@ -31,7 +31,7 @@
#include <Arduino.h>
void psram_reinit_timing();
void psram_reinit_timing(uint32_t hz = 0);
void *__psram_malloc(size_t size);
void __psram_free(void *ptr);
void *__psram_realloc(void *ptr, size_t size);
@@ -4,7 +4,7 @@
SPDX-License-Identifier: BSD-3-Clause
*/
#if defined(ARDUINO_RASPBERRY_PI_PICO_W)
#if defined(PICO_CYW43_SUPPORTED)
#include <btstack.h>
#include <pico/btstack_flash_bank.h>
#include <hardware/flash.h>
+5 -4
View File
@@ -18,7 +18,7 @@
; Side-set pin 0 is used for Tone output
; OSR == Halfcycle count
; OSR == Halfcycle count - 3
.program tone2
.side_set 1 opt
@@ -26,10 +26,11 @@
; pull ; TXFIFO -> OSR, or X -> OSR if no new period
; mov x, osr ; OSR -> X
.wrap_target
high:
pull noblock ; Potentially grab new HALFCYCLECOUNT, OTW copy from backup in X
mov x, osr ; OSR -> X
mov y, osr side 1 ; HALFCYCLECOUNT -> Y
mov x, osr side 1 ; OSR -> X
mov y, osr ; HALFCYCLECOUNT -> Y
highloop:
jmp y-- highloop ; while (y--) { /* noop delay */ }
@@ -38,7 +39,7 @@ low:
lowloop:
jmp y-- lowloop ; while (y--) { /* noop delay */ }
jmp high ; GOTO high
.wrap ; GOTO high
% c-sdk {
static inline void tone2_program_init(PIO pio, uint sm, uint offset, uint pin) {
+7 -8
View File
@@ -13,27 +13,26 @@
// ----- //
#define tone2_wrap_target 0
#define tone2_wrap 6
#define tone2_wrap 5
#define tone2_pio_version 0
static const uint16_t tone2_program_instructions[] = {
// .wrap_target
// .wrap_target
0x8080, // 0: pull noblock
0xa027, // 1: mov x, osr
0xb847, // 2: mov y, osr side 1
0xb827, // 1: mov x, osr side 1
0xa047, // 2: mov y, osr
0x0083, // 3: jmp y--, 3
0xb047, // 4: mov y, osr side 0
0x0085, // 5: jmp y--, 5
0x0000, // 6: jmp 0
// .wrap
// .wrap
};
#if !PICO_NO_HARDWARE
static const struct pio_program tone2_program = {
.instructions = tone2_program_instructions,
.length = 7,
.length = 6,
.origin = -1,
.pio_version = 0,
.pio_version = tone2_pio_version,
#if PICO_PIO_VERSION > 0
.used_gpio_ranges = 0x0
#endif
+2 -2
View File
@@ -56,9 +56,9 @@ extern "C" void shiftOut(pin_size_t dataPin, pin_size_t clockPin, BitOrder bitOr
}
for (i = 0; i < 8; i++) {
if (bitOrder == LSBFIRST) {
digitalWrite(dataPin, !!(val & (1 << i)));
digitalWrite(dataPin, !!(val & (1 << i)) ? HIGH : LOW);
} else {
digitalWrite(dataPin, !!(val & (1 << (7 - i))));
digitalWrite(dataPin, !!(val & (1 << (7 - i))) ? HIGH : LOW);
}
digitalWrite(clockPin, HIGH);
+2 -2
View File
@@ -54,9 +54,9 @@ author = u'Earle F. Philhower, III'
# built documents.
#
# The short X.Y version.
version = u'4.4.0'
version = u'4.5.0'
# The full version, including alpha/beta/rc tags.
release = u'4.4.0'
release = u'4.5.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
+21
View File
@@ -143,15 +143,19 @@ it using the ``mklittlefs`` tool. A working ``OpenOCD`` setup, DebugProbe, and
To download the raw filesystem, from within ``GDB`` run:
.. code::
^C (break)
(gdb) dump binary memory littlefs.bin &_FS_start &_FS_end
It may take a few seconds as ``GDB`` reads out the flash to the file. Once the raw file is downloaded it can be extracted using the ``mklittlefs`` tool from the BASH/Powershell/command line
.. code::
$ <path-to-mklittlefs>/mklittlefs -u output-dir littlefs.bin
Directory <output-dir> does not exists. Try to create it.
gmon.out > <output-dir>/gmon.out size: 24518 Bytes
gmon.bak > <output-dir>/gmon.bak size: 1 Bytes
The defaults built into ``mklittlefs`` should be appropriate for normal LittleFS filesystems built on the device or using the upload tool.
SD Library Information
@@ -170,6 +174,23 @@ second SPI port, ``SPI1``. Just use the following call in place of
SD.begin(cspin, SPI1);
Enabling SDIO operation for SD
------------------------------
SDIO support is available thanks to SdFat implementing a PIO-based SDIO controller.
This mode can significantly increase IO performance to SD cards but it requires that
all 4 DAT0..DAT3 lines to be wired to the Pico (most SD breakout boards only provide
1-but SPI mode of operation).
To enable SDIO mode, simply specify the SD_CLK, SD_CMD, and SD_DAT0 GPIO pins. The clock
and command pins can be any GPIO (not limited to legal SPI pins). The DAT0 pin can be any
GPIO with remaining DAT1...3 pins consecutively connected.
..code:: cpp
SD.begin(RP_CLK_GPIO, RP_CMD_GPIO, RP_DAT0_GPIO);
No other changes are required in the application to take advantage of this high
performance mode.
Using VFS (Virtual File System) for POSIX support
-------------------------------------------------
+35 -3
View File
@@ -30,6 +30,12 @@ I2S(INPUT)
Creates an I2S input port. Needs to be connected up to the
desired pins (see below) and started before any input can happen.
I2S(INPUT_PULLUP)
~~~~~~~~~~~~~~~~~
Creates a bi-directional I2S input and output port. Needs to be
connected up to the desired pins (see below) and started before
any input or output can happen.
bool setBCLK(pin_size_t pin)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sets the BCLK pin of the I2S device. The LRCLK/word clock will be ``pin + 1``
@@ -37,7 +43,18 @@ due to limitations of the PIO state machines. Call this before ``I2S::begin()``
bool setDATA(pin_size_t pin)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sets the DOUT or DIN pin of the I2S device. Any pin may be used.
Sets the DOUT or DIN pin of the I2S device. Any pin may be used. In bi-directional
operation, must use ``I2S::setDOUT()`` and ``I2S::setDIN`` instead.
Call before ``I2S::begin()``
bool setDOUT(pin_size_t pin)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sets the DOUT pin of the I2S device. Any pin may be used.
Call before ``I2S::begin()``
bool setDIN(pin_size_t pin)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sets the DIN pin of the I2S device. Any pin may be used.
Call before ``I2S::begin()``
bool setMCLK(pin_size_t pin)
@@ -71,7 +88,7 @@ sample rate on-the-fly.
bool setSysClk(int samplerate)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Changes the PICO system clock to optimise for the desired samplerate.
The clock changes to 147.6 MHz for samplerates that are a multiple of 8 kHz, and 135.6 MHz for multiples of 11.025 kHz.
The clock changes to 153.6 MHz for samplerates that are a multiple of 8 kHz, and 135.6 MHz for multiples of 11.025 kHz.
Note that using ``setSysClk()`` may affect the timing of other sysclk-dependent functions.
Should be called before any I2S functions and any other sysclk dependent initialisations.
@@ -115,6 +132,14 @@ void getOverUnderflow()
Returns a flag indicating if the I2S system ran our of data to send on output,
or had to throw away data on input.
void getOverflow()
~~~~~~~~~~~~~~~~~~~~~~~
Returns a flag indicating if the I2S system had to throw away data on input.
void getUnderflow()
~~~~~~~~~~~~~~~~~~~~~~~
Returns a flag indicating if the I2S system ran our of data to send on output.
size_t write(uint8_t/int8_t/int16_t/int32_t)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Writes a single sample of ``bitsPerSample`` to the buffer. It is up to the
@@ -139,7 +164,7 @@ size_t write(const uint8_t \*buffer, size_t size)
Transfers number of bytes from an application buffer to the I2S output buffer.
Be aware that ``size`` is in *bytes** and not samples. Size must be a multiple
of **4 bytes**. Will not block, so check the return value to find out how
many bytes were actually written.
many 32-bit words were actually written.
int availableForWrite()
~~~~~~~~~~~~~~~~~~~~~~~
@@ -156,6 +181,13 @@ int peek()
Returns the next sample to be read from the I2S buffer (without actually
removing it).
size_t read(uint8_t \*buffer, size_t size)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Transfers number of bytes from the I2S input buffer to an application buffer.
Be aware that ``size`` is in *bytes** and not samples. Size must be a multiple
of **4 bytes**. Will not block, so check the return value to find out how
many 32-bit words were actually read.
void onTransmit(void (\*fn)(void))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sets a callback to be called when an I2S DMA buffer is fully transmitted.
+31
View File
@@ -172,6 +172,37 @@ To learn more about PSRAM usage, see: :doc:`RP2350 PSRAM Support <psram>`
; PSRAM size: 4MB
board_upload.psram_length = 4194304
PSRAM chip select (CS)
----------------------
For RP2350 based boards, this controls what chip-select (also called: slave-select / SS) pin to use when wanting to talk to the PSRAM chip.
Note that it's not needed to set this with a board that is known to have a PSRAM chip on-board, such as a "Sparkfun Thing Plus 2350". The ``pins_arduino.h`` of that variant already has the correct definition.
To learn more about PSRAM usage, see: :doc:`RP2350 PSRAM Support <psram>`
.. code:: ini
; PSRAM CS is at GP47
build_flags =
-DRP2350_PSRAM_CS=47
Boot2 Source
------------
Boot2 is the second stage bootloader and predominantly used on the RP2040.
Its main purpose is to configure the communication with the Flash at the highest, safest speed it can.
All known boards have their correct value already configured. However, when choosing ``board = generic``,
you can freely configure the Boot2 to be for a different flash.
For possible Boot2 filenames, `please see here <https://github.com/earlephilhower/arduino-pico/tree/master/boot2/rp2040>`__.
.. code:: ini
; expect an ISSI IS25LP080 flash, SPI frequency = CPU frequency divided by 2
board_build.arduino.earlephilhower.boot2_source = boot2_is25lp080_2_padded_checksum.S
CPU Speed
---------
+13
View File
@@ -28,6 +28,19 @@ pin itself, as is the standard way in Arduino.
* The interrupt calls (``attachInterrupt``, and ``detachInterrpt``) are not implemented.
Software SPI (Master Only)
==========================
Similar to ``SoftwareSerial``, ``SoftwareSPI`` creates a PIO based SPI interface that
can be used in the same manner as the hardware SPI devices. The constructor takes the
pins desired, which can be any GPIO pins with the rule that if hardware CS is used then
it must be on pin ``SCK + 1``. Construct a ``SoftwareSPI`` object in your code as
follows and use it as needed (i.e. pass it into ``SD.begin(_CS, softwareSPI);``
.. code:: cpp
#include <SoftwareSPI.h>
SoftwareSPI softSPI(_sck, _miso, _mosi); // no HW CS support, any selection of pins can be used
SPI Slave (SPISlave)
====================
+2 -2
View File
@@ -13,7 +13,7 @@
#define PICO_SDK_VERSION_MAJOR 2
#define PICO_SDK_VERSION_MINOR 1
#define PICO_SDK_VERSION_REVISION 0
#define PICO_SDK_VERSION_STRING "2.1.0"
#define PICO_SDK_VERSION_REVISION 2
#define PICO_SDK_VERSION_STRING "2.1.2-develop"
#endif
+2 -2
View File
@@ -13,7 +13,7 @@
#define PICO_SDK_VERSION_MAJOR 2
#define PICO_SDK_VERSION_MINOR 1
#define PICO_SDK_VERSION_REVISION 0
#define PICO_SDK_VERSION_STRING "2.1.0"
#define PICO_SDK_VERSION_REVISION 2
#define PICO_SDK_VERSION_STRING "2.1.2-develop"
#endif
+1
View File
@@ -14,6 +14,7 @@ File KEYWORD1
timeval KEYWORD1
time_t KEYWORD1
SoftwareSerial KEYWORD1
AudioOutputBase KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.
+1
View File
@@ -10,5 +10,6 @@
-iwithprefixbefore/pico-sdk/lib/btstack/src
-iwithprefixbefore/pico-sdk/lib/btstack/3rd-party/bluedroid/decoder/include
-iwithprefixbefore/pico-sdk/lib/btstack/3rd-party/bluedroid/encoder/include
-iwithprefixbefore/pico-sdk/lib/btstack/3rd-party/yxml
-iwithprefixbefore/pico-sdk/lib/btstack/platform/embedded
-iwithprefixbefore/pico-sdk/src/rp2_common/cmsis/stub/CMSIS/Device/RP2040/Include
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1
View File
@@ -15,4 +15,5 @@
-iwithprefixbefore/pico-sdk/lib/btstack/src
-iwithprefixbefore/pico-sdk/lib/btstack/3rd-party/bluedroid/decoder/include
-iwithprefixbefore/pico-sdk/lib/btstack/3rd-party/bluedroid/encoder/include
-iwithprefixbefore/pico-sdk/lib/btstack/3rd-party/yxml
-iwithprefixbefore/pico-sdk/lib/btstack/platform/embedded
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.
+1
View File
@@ -13,4 +13,5 @@
-iwithprefixbefore/pico-sdk/lib/btstack/src
-iwithprefixbefore/pico-sdk/lib/btstack/3rd-party/bluedroid/decoder/include
-iwithprefixbefore/pico-sdk/lib/btstack/3rd-party/bluedroid/encoder/include
-iwithprefixbefore/pico-sdk/lib/btstack/3rd-party/yxml
-iwithprefixbefore/pico-sdk/lib/btstack/platform/embedded
+3 -2
View File
@@ -77,8 +77,9 @@ bool ADCInput::setPins(pin_size_t pin0, pin_size_t pin1, pin_size_t pin2, pin_si
}
bool ADCInput::setFrequency(int newFreq) {
_freq = newFreq * __builtin_popcount(_pinMask); // Want to sample all channels at given frequency
adc_set_clkdiv(48000000.0f / _freq - 1.0f);
_freq = newFreq;
int scaledFreq = newFreq * __builtin_popcount(_pinMask); // Want to sample all channels at given frequency
adc_set_clkdiv(48000000.0f / scaledFreq - 1.0f);
return true;
}
@@ -188,6 +188,38 @@ bool AudioBufferManager::write(uint32_t v, bool sync) {
return true;
}
size_t AudioBufferManager::write(const uint32_t *v, size_t words, bool sync) {
size_t written = 0;
if (!_running || !_isOutput) {
return 0;
}
while (words) {
AudioBuffer ** volatile p = (AudioBuffer ** volatile)&_empty;
if (!*p) {
if (!sync) {
return written;
} else {
while (!*p) {
/* noop busy wait */
}
}
}
size_t availToWriteThisBuff = _wordsPerBuffer - _userOff;
size_t toWrite = std::min(availToWriteThisBuff, words);
memcpy(&((*p)->buff[_userOff]), v, toWrite * sizeof(uint32_t));
v += toWrite;
written += toWrite;
_userOff += toWrite;
words -= toWrite;
if (_userOff == _wordsPerBuffer) {
_addToList(&_filled, _takeFromList(p));
_userOff = 0;
}
}
return written;
}
bool AudioBufferManager::read(uint32_t *v, bool sync) {
if (!_running || _isOutput) {
return false;
@@ -212,6 +244,38 @@ bool AudioBufferManager::read(uint32_t *v, bool sync) {
return true;
}
size_t AudioBufferManager::read(uint32_t *v, size_t words, bool sync) {
size_t read = 0;
if (!_running || _isOutput) {
return 0;
}
while (words) {
AudioBuffer ** volatile p = (AudioBuffer ** volatile)&_filled;
if (!*p) {
if (!sync) {
return read;
} else {
while (!*p) {
/* noop busy wait */
}
}
}
size_t availToReadThisBuff = _wordsPerBuffer - _userOff;
size_t toRead = std::min(availToReadThisBuff, words);
memcpy((void *)v, &((*p)->buff[_userOff]), toRead * sizeof(uint32_t));
v += toRead;
read += toRead;
_userOff += toRead;
words -= toRead;
if (_userOff == _wordsPerBuffer) {
_addToList(&_empty, _takeFromList(p));
_userOff = 0;
}
}
return read;
}
bool AudioBufferManager::getOverUnderflow() {
bool hold = _overunderflow;
_overunderflow = false;
@@ -34,7 +34,9 @@ public:
bool begin(int dreq, volatile void *pioFIFOAddr);
bool write(uint32_t v, bool sync = true);
size_t write(const uint32_t *v, size_t words, bool sync = true);
bool read(uint32_t *v, bool sync = true);
size_t read(uint32_t *v, size_t words, bool sync = true);
void flush();
bool getOverUnderflow();
@@ -82,7 +82,7 @@ void deviceDisconnectedCallback(BLEDevice * device) {
@text In BTstack, the Read Callback is first called to query the size of the
Characteristic Value, before it is called to provide the data.
Both times, the size has to be returned. The data is only stored in the provided
buffer, if the buffer argeument is not NULL.
buffer, if the buffer argument is not NULL.
If more than one dynamic Characteristics is used, the value handle is used
to distinguish them.
*/
+8 -4
View File
@@ -676,6 +676,9 @@ void A2DPSink::avrcp_target_packet_handler(uint8_t packet_type, uint16_t channel
volume_percentage = volume * 100 / 127;
DEBUGV("AVRCP Target : Volume set to %d%% (%d)\n", volume_percentage, volume);
_consumer->setVolume(volume);
if (_volumeCB) {
_volumeCB(_volumeData, volume);
}
break;
case AVRCP_SUBEVENT_OPERATION:
@@ -773,6 +776,11 @@ void A2DPSink::a2dp_sink_packet_handler(uint8_t packet_type, uint16_t channel, u
DEBUGV("A2DP Sink : Streaming connection is established, address %s, cid 0x%02x, local seid %d\n",
bd_addr_to_str(a2dp_conn->addr), a2dp_conn->a2dp_cid, a2dp_conn->a2dp_local_seid);
memcpy(_sourceAddress, a2dp_conn->addr, sizeof(_sourceAddress));
_connected = true;
if (_connectCB) {
_connectCB(_connectData, true);
}
break;
case A2DP_SUBEVENT_STREAM_STARTED:
@@ -784,10 +792,6 @@ void A2DPSink::a2dp_sink_packet_handler(uint8_t packet_type, uint16_t channel, u
// prepare media processing
media_processing_init(&a2dp_conn->sbc_configuration);
// audio stream is started when buffer reaches minimal level
_connected = true;
if (_connectCB) {
_connectCB(_connectData, true);
}
break;
case A2DP_SUBEVENT_STREAM_SUSPENDED:
+1 -35
View File
@@ -30,7 +30,7 @@
#include "btstack_resample.h"
#include "btstack_ring_buffer.h"
class A2DPSink : public Stream {
class A2DPSink {
public:
A2DPSink() {
_title[0] = 0;
@@ -38,33 +38,6 @@ public:
_album[0] = 0;
_genre[0] = 0;
}
virtual int available() override {
return 0; // Unreadable, this is output only
}
virtual int read() override {
return 0;
}
virtual int peek() override {
return 0;
}
virtual void flush() override {
}
virtual size_t write(const uint8_t *buffer, size_t size) override {
(void) buffer;
(void) size;
return 0;
}
virtual int availableForWrite() override {
return 0;
}
virtual size_t write(uint8_t s) override {
(void) s;
return 0;
}
bool setName(const char *name) {
if (_running) {
@@ -75,11 +48,6 @@ public:
return true;
}
void onTransmit(void (*cb)(void *), void *cbData = nullptr) {
_transmitCB = cb;
_transmitData = cbData;
}
void onAVRCP(void (*cb)(void *, avrcp_operation_id_t, int), void *cbData = nullptr) {
_avrcpCB = cb;
_avrcpData = cbData;
@@ -237,8 +205,6 @@ private:
bool _connected = false;
// Callbacks
void (*_transmitCB)(void *) = nullptr;
void *_transmitData;
void (*_avrcpCB)(void *, avrcp_operation_id_t, int) = nullptr;
void *_avrcpData;
void (*_batteryCB)(void *, avrcp_battery_status_t) = nullptr;
+2 -2
View File
@@ -223,7 +223,7 @@ size_t A2DPSource::write(const uint8_t *buffer, size_t size) {
size = std::min((size_t)availableForWrite(), size);
size_t count = 0;
size /= 2;
size /= sizeof(int16_t); // Convert size to samples
// First copy from writer to either end of
uint32_t start = _pcmWriter;
@@ -262,7 +262,7 @@ int A2DPSource::availableForWrite() {
} else {
avail = _pcmBufferSize - _pcmWriter + _pcmReader - 1;
}
avail /= sizeof(uint32_t); // availableForWrite always 32b sample pairs in this core...
avail *= sizeof(int16_t); // Convert samples to bytes
return avail;
}
@@ -125,6 +125,14 @@ public:
return _hci.scan(mask, scanTimeSec, async);
}
bool scanAsyncDone() {
return _hci.scanAsyncDone();
}
std::vector<BTDeviceInfo> scanAsyncResult() {
return _hci.scanAsyncResult();
}
bool connect(const uint8_t *addr = nullptr);
bool connected() {
@@ -151,6 +159,7 @@ public:
}
// from Print (see notes on write() methods below)
// Writes only full samples (size must be divisible by sample size in bytes)
virtual size_t write(const uint8_t *buffer, size_t size) override;
virtual int availableForWrite() override;
@@ -0,0 +1,36 @@
/*
I2S bi-directional input and output loopback example
Released to the Public Domain by Cooper Dalrymple
*/
#include <I2S.h>
I2S i2s(INPUT_PULLUP);
void setup() {
Serial.begin(115200);
i2s.setDOUT(0);
i2s.setDIN(1);
i2s.setBCLK(2); // Note: LRCLK = BCLK + 1
i2s.setBitsPerSample(16);
i2s.setFrequency(22050);
// NOTE: The following values are known to work with the Adafruit microphone:
// i2s.setBitsPerSample(32);
// i2s.setFrequency(16000);
i2s.begin();
while (1) {
int16_t l, r;
i2s.read16(&l, &r);
i2s.write16(l, r);
// NOTE: Adafruit microphone word size needs to match the BPS above.
// int32_t l, r;
// i2s.read32(&l, &r);
// i2s.write32(l, r);
}
}
void loop() {
/* Nothing here */
}
@@ -0,0 +1,39 @@
/*
I2S bi-directional input and output buffered loopback example
Released to the Public Domain by Cooper Dalrymple
*/
#include <I2S.h>
I2S i2s(INPUT_PULLUP);
#define SIZE 256
int16_t buffer[SIZE];
void setup() {
Serial.begin(115200);
i2s.setDOUT(0);
i2s.setDIN(1);
i2s.setBCLK(2); // Note: LRCLK = BCLK + 1
i2s.setBitsPerSample(16);
i2s.setFrequency(22050);
i2s.setBuffers(6, SIZE * sizeof(int16_t) / sizeof(uint32_t));
i2s.begin();
size_t count, index;
while (1) {
count = i2s.read((uint8_t *)&buffer, SIZE * sizeof(int16_t)) * sizeof(uint32_t) / sizeof(int16_t);
index = 0;
while (index < count) {
// Reduce volume by half
buffer[index++] >>= 1; // right
buffer[index++] >>= 1; // left
}
i2s.write((const uint8_t *)&buffer, count * sizeof(int16_t));
}
}
void loop() {
/* Nothing here */
}
+141 -78
View File
@@ -24,13 +24,15 @@
#include <pico/stdlib.h>
I2S::I2S(PinMode direction, pin_size_t bclk, pin_size_t data, pin_size_t mclk) {
I2S::I2S(PinMode direction, pin_size_t bclk, pin_size_t data, pin_size_t mclk, pin_size_t data_rx) {
_running = false;
_bps = 16;
_writtenHalf = false;
_isOutput = direction == OUTPUT;
_isInput = direction == INPUT || direction == INPUT_PULLUP;
_isOutput = direction == OUTPUT || direction == INPUT_PULLUP;
_pinBCLK = bclk;
_pinDOUT = data;
_pinDIN = direction == INPUT ? data : data_rx;
_pinMCLK = mclk;
_MCLKenabled = false;
#ifdef PIN_I2S_BCLK
@@ -44,14 +46,17 @@ I2S::I2S(PinMode direction, pin_size_t bclk, pin_size_t data, pin_size_t mclk) {
#endif
#ifdef PIN_I2S_DIN
if (!_isOutput) {
_pinDOUT = PIN_I2S_DIN;
if (_isInput) {
_pinDIN = PIN_I2S_DIN;
}
#endif
_freq = 48000;
_arb = nullptr;
_cb = nullptr;
_cbd = nullptr;
_arbInput = nullptr;
_cbInput = nullptr;
_cbdInput = nullptr;
_arbOutput = nullptr;
_cbOutput = nullptr;
_cbdOutput = nullptr;
_buffers = 6;
_bufferWords = 0;
_silenceSample = 0;
@@ -81,7 +86,20 @@ bool I2S::setMCLK(pin_size_t pin) {
_pinMCLK = pin;
return true;
}
bool I2S::setDATA(pin_size_t pin) {
if (_running || (pin >= __GPIOCNT) || (_isOutput && _isInput)) {
return false;
}
if (_isOutput) {
_pinDOUT = pin;
} else {
_pinDIN = pin;
}
return true;
}
bool I2S::setDOUT(pin_size_t pin) {
if (_running || (pin >= __GPIOCNT)) {
return false;
}
@@ -89,6 +107,14 @@ bool I2S::setDATA(pin_size_t pin) {
return true;
}
bool I2S::setDIN(pin_size_t pin) {
if (_running || (pin >= __GPIOCNT)) {
return false;
}
_pinDIN = pin;
return true;
}
bool I2S::setBitsPerSample(int bps) {
if (_running || ((bps != 8) && (bps != 16) && (bps != 24) && (bps != 32))) {
return false;
@@ -111,10 +137,10 @@ bool I2S::setFrequency(int newFreq) {
_freq = newFreq;
if (_running) {
if (_MCLKenabled) {
int bitClk = _freq * _bps * (_isTDM ? (double)_tdmChannels : 2.0) /* channels */ * 2.0 /* edges per clock */;
int bitClk = _freq * _bps * (_isTDM ? (double)_tdmChannels : 2.0) /* channels */ * (_isInput && _isOutput ? 4.0 : 2.0) /* edges per clock */;
pio_sm_set_clkdiv_int_frac(_pio, _sm, clock_get_hz(clk_sys) / bitClk, 0);
} else {
float bitClk = _freq * _bps * (_isTDM ? (double)_tdmChannels : 2.0) /* channels */ * 2.0 /* edges per clock */;
float bitClk = _freq * _bps * (_isTDM ? (double)_tdmChannels : 2.0) /* channels */ * (_isInput && _isOutput ? 4.0 : 2.0) /* edges per clock */;
pio_sm_set_clkdiv(_pio, _sm, (float)clock_get_hz(clk_sys) / bitClk);
}
}
@@ -123,12 +149,10 @@ bool I2S::setFrequency(int newFreq) {
bool I2S::setSysClk(int samplerate) { // optimise sys_clk for desired samplerate
if (samplerate % 11025 == 0) {
set_sys_clock_khz(I2SSYSCLK_44_1, false); // 147.6 unsuccessful - no I2S no USB
return true;
return set_sys_clock_khz(I2SSYSCLK_44_1, false);
}
if (samplerate % 8000 == 0) {
set_sys_clock_khz(I2SSYSCLK_8, false);
return true;
return set_sys_clock_khz(I2SSYSCLK_8, false);
}
return false;
}
@@ -146,7 +170,7 @@ bool I2S::setMCLKmult(int mult) {
}
bool I2S::setLSBJFormat() {
if (_running || !_isOutput) {
if (_running || !_isOutput || _isInput) {
return false;
}
_isLSBJ = true;
@@ -154,7 +178,7 @@ bool I2S::setLSBJFormat() {
}
bool I2S::setTDMFormat() {
if (_running || !_isOutput) {
if (_running || !_isOutput || _isInput) {
return false;
}
_isTDM = true;
@@ -162,7 +186,7 @@ bool I2S::setTDMFormat() {
}
bool I2S::setTDMChannels(int channels) {
if (_running || !_isOutput) {
if (_running || !_isOutput || _isInput) {
return false;
}
_tdmChannels = channels;
@@ -170,7 +194,7 @@ bool I2S::setTDMChannels(int channels) {
}
bool I2S::swapClocks() {
if (_running || !_isOutput) {
if (_running) {
return false;
}
_swapClocks = true;
@@ -179,38 +203,38 @@ bool I2S::swapClocks() {
void I2S::onTransmit(void(*fn)(void)) {
if (_isOutput) {
_cb = fn;
_cbOutput = fn;
if (_running) {
_arb->setCallback(_cb);
_arbOutput->setCallback(_cbOutput);
}
}
}
void I2S::onTransmit(void(*fn)(void *), void *cbData) {
if (_isOutput) {
_cbd = fn;
_cbdata = cbData;
_cbdOutput = fn;
_cbdataOutput = cbData;
if (_running) {
_arb->setCallback(_cbd, _cbdata);
_arbOutput->setCallback(_cbdOutput, _cbdataOutput);
}
}
}
void I2S::onReceive(void(*fn)(void)) {
if (!_isOutput) {
_cb = fn;
if (_isInput) {
_cbInput = fn;
if (_running) {
_arb->setCallback(_cb);
_arbInput->setCallback(_cbInput);
}
}
}
void I2S::onReceive(void(*fn)(void *), void *cbData) {
if (!_isOutput) {
_cbd = fn;
_cbdata = cbData;
if (_isInput) {
_cbdInput = fn;
_cbdataInput = cbData;
if (_running) {
_arb->setCallback(_cbd, _cbdata);
_arbInput->setCallback(_cbdInput, _cbdataInput);
}
}
}
@@ -231,12 +255,21 @@ bool I2S::begin() {
_isHolding = 0;
int off = 0;
if (!_swapClocks) {
_i2s = new PIOProgram(_isOutput ? (_isTDM ? &pio_tdm_out_program : (_isLSBJ ? &pio_lsbj_out_program : &pio_i2s_out_program)) : &pio_i2s_in_program);
_i2s = new PIOProgram(_isOutput ? (_isInput ? &pio_i2s_inout_program : (_isTDM ? &pio_tdm_out_program : (_isLSBJ ? &pio_lsbj_out_program : &pio_i2s_out_program))) : &pio_i2s_in_program);
} else {
_i2s = new PIOProgram(_isOutput ? (_isTDM ? &pio_tdm_out_swap_program : (_isLSBJ ? &pio_lsbj_out_swap_program : &pio_i2s_out_swap_program)) : &pio_i2s_in_swap_program);
_i2s = new PIOProgram(_isOutput ? (_isInput ? &pio_i2s_inout_swap_program : (_isTDM ? &pio_tdm_out_swap_program : (_isLSBJ ? &pio_lsbj_out_swap_program : &pio_i2s_out_swap_program))) : &pio_i2s_in_swap_program);
}
int minpin, maxpin;
if (_isOutput && _isInput) {
minpin = std::min(std::min((int)_pinDOUT, (int)_pinDIN), (int)_pinBCLK);
maxpin = std::max(std::min((int)_pinDOUT, (int)_pinDIN), (int)_pinBCLK + 1);
} else if (_isOutput) {
minpin = std::min((int)_pinDOUT, (int)_pinBCLK);
maxpin = std::max((int)_pinDOUT, (int)_pinBCLK + 1);
} else {
minpin = std::min((int)_pinDIN, (int)_pinBCLK);
maxpin = std::max((int)_pinDIN, (int)_pinBCLK + 1);
}
int minpin = std::min((int)_pinDOUT, (int)_pinBCLK);
int maxpin = std::max((int)_pinDOUT, (int)_pinBCLK + 1);
if (!_i2s->prepare(&_pio, &_sm, &off, minpin, maxpin - minpin + 1)) {
_running = false;
delete _i2s;
@@ -244,7 +277,9 @@ bool I2S::begin() {
return false;
}
if (_isOutput) {
if (_isTDM) {
if (_isInput) {
pio_i2s_inout_program_init(_pio, _sm, off, _pinDIN, _pinDOUT, _pinBCLK, _bps, _swapClocks);
} else if (_isTDM) {
pio_tdm_out_program_init(_pio, _sm, off, _pinDOUT, _pinBCLK, _bps, _swapClocks, _tdmChannels);
} else if (_isLSBJ) {
pio_lsbj_out_program_init(_pio, _sm, off, _pinDOUT, _pinBCLK, _bps, _swapClocks);
@@ -252,7 +287,7 @@ bool I2S::begin() {
pio_i2s_out_program_init(_pio, _sm, off, _pinDOUT, _pinBCLK, _bps, _swapClocks);
}
} else {
pio_i2s_in_program_init(_pio, _sm, off, _pinDOUT, _pinBCLK, _bps, _swapClocks);
pio_i2s_in_program_init(_pio, _sm, off, _pinDIN, _pinBCLK, _bps, _swapClocks);
}
setFrequency(_freq);
if (_MCLKenabled) {
@@ -268,19 +303,39 @@ bool I2S::begin() {
if (!_bufferWords) {
_bufferWords = 64 * (_bps == 32 ? 2 : 1);
}
_arb = new AudioBufferManager(_buffers, _bufferWords, _silenceSample, _isOutput ? OUTPUT : INPUT);
if (!_arb->begin(pio_get_dreq(_pio, _sm, _isOutput), _isOutput ? &_pio->txf[_sm] : (volatile void*)&_pio->rxf[_sm])) {
_running = false;
delete _arb;
_arb = nullptr;
delete _i2s;
_i2s = nullptr;
return false;
if (_isInput) {
_arbInput = new AudioBufferManager(_buffers, _bufferWords, _silenceSample, INPUT);
if (!_arbInput->begin(pio_get_dreq(_pio, _sm, false), (volatile void*)&_pio->rxf[_sm])) {
_running = false;
delete _arbInput;
_arbInput = nullptr;
delete _i2s;
_i2s = nullptr;
return false;
}
if (_cbdInput) {
_arbInput->setCallback(_cbdInput, _cbdataInput);
} else {
_arbInput->setCallback(_cbInput);
}
}
if (_cbd) {
_arb->setCallback(_cbd, _cbdata);
} else {
_arb->setCallback(_cb);
if (_isOutput) {
_arbOutput = new AudioBufferManager(_buffers, _bufferWords, _silenceSample, OUTPUT);
if (!_arbOutput->begin(pio_get_dreq(_pio, _sm, true), &_pio->txf[_sm])) {
_running = false;
delete _arbOutput;
_arbOutput = nullptr;
delete _arbInput;
_arbInput = nullptr;
delete _i2s;
_i2s = nullptr;
return false;
}
if (_cbdOutput) {
_arbOutput->setCallback(_cbdOutput, _cbdataOutput);
} else {
_arbOutput->setCallback(_cbOutput);
}
}
pio_sm_set_enabled(_pio, _sm, true);
@@ -296,8 +351,10 @@ bool I2S::end() {
}
pio_sm_set_enabled(_pio, _sm, false);
_running = false;
delete _arb;
_arb = nullptr;
delete _arbOutput;
_arbOutput = nullptr;
delete _arbInput;
_arbInput = nullptr;
delete _i2s;
_i2s = nullptr;
}
@@ -305,12 +362,12 @@ bool I2S::end() {
}
int I2S::available() {
if (!_running) {
if (!_running || !_isInput) {
return 0;
} else {
auto avail = _arb->available();
avail *= 4; // 4 samples per 32-bits
if (_bps < 24 && !_isOutput) {
auto avail = _arbInput->available();
avail *= 4; // 4 bytes per 32-bits
if (_bps < 24) {
avail += _isHolding / 8;
}
return avail;
@@ -318,7 +375,7 @@ int I2S::available() {
}
int I2S::read() {
if (!_running || _isOutput) {
if (!_running || !_isInput) {
return 0;
}
@@ -354,7 +411,7 @@ int I2S::read() {
}
int I2S::peek() {
if (!_running || _isOutput) {
if (!_running || !_isInput) {
return 0;
}
if (!_hasPeeked) {
@@ -366,7 +423,12 @@ int I2S::peek() {
void I2S::flush() {
if (_running) {
_arb->flush();
if (_isOutput) {
_arbOutput->flush();
}
if (_isInput) {
_arbInput->flush();
}
}
}
@@ -410,7 +472,7 @@ size_t I2S::write(int32_t val, bool sync) {
if (!_running || !_isOutput) {
return 0;
}
return _arb->write(val, sync);
return _arbOutput->write(val, sync);
}
size_t I2S::write8(int8_t l, int8_t r) {
@@ -443,14 +505,14 @@ size_t I2S::write32(int32_t l, int32_t r) {
}
size_t I2S::read(int32_t *val, bool sync) {
if (!_running || _isOutput) {
if (!_running || !_isInput) {
return 0;
}
return _arb->read((uint32_t *)val, sync);
return _arbInput->read((uint32_t *)val, sync);
}
bool I2S::read8(int8_t *l, int8_t *r) {
if (!_running || _isOutput) {
if (!_running || !_isInput) {
return false;
}
if (_isHolding) {
@@ -467,7 +529,7 @@ bool I2S::read8(int8_t *l, int8_t *r) {
}
bool I2S::read16(int16_t *l, int16_t *r) {
if (!_running || _isOutput) {
if (!_running || !_isInput) {
return false;
}
int32_t o;
@@ -478,7 +540,7 @@ bool I2S::read16(int16_t *l, int16_t *r) {
}
bool I2S::read24(int32_t *l, int32_t *r) {
if (!_running || _isOutput) {
if (!_running || !_isInput) {
return false;
}
read32(l, r);
@@ -489,7 +551,7 @@ bool I2S::read24(int32_t *l, int32_t *r) {
}
bool I2S::read32(int32_t *l, int32_t *r) {
if (!_running || _isOutput) {
if (!_running || !_isInput) {
return false;
}
read(l, true);
@@ -497,30 +559,31 @@ bool I2S::read32(int32_t *l, int32_t *r) {
return true;
}
size_t I2S::read(uint8_t *buffer, size_t size) {
// We can only read 32-bit chunks here
if (size & 0x3 || !_running || !_isInput) {
return 0;
}
return _arbInput->read((uint32_t *)buffer, size / sizeof(uint32_t), false);
}
size_t I2S::write(const uint8_t *buffer, size_t size) {
// We can only write 32-bit chunks here
if (size & 0x3 || !_running || !_isOutput) {
return 0;
}
size_t writtenSize = 0;
uint32_t *p = (uint32_t *)buffer;
while (size) {
if (!_arb->write(*p, false)) {
// Blocked, stop write here
return writtenSize;
} else {
p++;
size -= 4;
writtenSize += 4;
}
}
return writtenSize;
return _arbOutput->write((const uint32_t *)buffer, size / sizeof(uint32_t), false);
}
int I2S::availableForWrite() {
if (!_running || !_isOutput) {
return 0;
} else {
auto avail = _arbOutput->available();
avail *= 4; // 4 bytes per 32-bits
if (_bps < 24 && _isInput) {
avail += _isHolding / 8;
}
return avail;
}
return available();
}
+33 -10
View File
@@ -26,11 +26,13 @@
class I2S : public Stream, public AudioOutputBase {
public:
I2S(PinMode direction = OUTPUT, pin_size_t bclk = 26, pin_size_t data = 28, pin_size_t mclk = 25);
I2S(PinMode direction = OUTPUT, pin_size_t bclk = 26, pin_size_t data = 28, pin_size_t mclk = 25, pin_size_t data_rx = 22);
virtual ~I2S();
bool setBCLK(pin_size_t pin);
bool setDATA(pin_size_t pin);
bool setDOUT(pin_size_t pin);
bool setDIN(pin_size_t pin);
bool setMCLK(pin_size_t pin);
virtual bool setBitsPerSample(int bps) override;
virtual bool setBuffers(size_t buffers, size_t bufferWords, int32_t silenceSample = 0) override;
@@ -52,9 +54,6 @@ public:
virtual bool begin() override;
virtual bool end() override;
virtual bool getUnderflow() override {
return getOverUnderflow();
}
// from Stream
virtual int available() override;
@@ -71,7 +70,21 @@ public:
if (!_running) {
return false;
} else {
return _arb->getOverUnderflow();
return _isOutput ? _arbOutput->getOverUnderflow() : _arbInput->getOverUnderflow();
}
}
bool getOverflow() {
if (!_running || !_isInput) {
return false;
} else {
return _arbInput->getOverUnderflow();
}
}
virtual bool getUnderflow() override {
if (!_running || !_isOutput) {
return false;
} else {
return _arbOutput->getOverUnderflow();
}
}
@@ -114,6 +127,9 @@ public:
bool read24(int32_t *l, int32_t *r); // Note that 24b reads will be left-aligned (see above)
bool read32(int32_t *l, int32_t *r);
// Read samples into buffer
size_t read(uint8_t *buffer, size_t size);
// Note that these callback are called from **INTERRUPT CONTEXT** and hence
// should be in RAM, not FLASH, and should be quick to execute.
void onTransmit(void(*)(void));
@@ -124,6 +140,7 @@ public:
private:
pin_size_t _pinBCLK;
pin_size_t _pinDOUT;
pin_size_t _pinDIN;
pin_size_t _pinMCLK;
int _bps;
int _freq;
@@ -134,6 +151,7 @@ private:
bool _isLSBJ;
bool _isTDM;
int _tdmChannels;
bool _isInput;
bool _isOutput;
bool _swapClocks;
bool _MCLKenabled;
@@ -150,18 +168,23 @@ private:
int32_t _holdWord = 0;
int _isHolding = 0;
void (*_cb)();
void (*_cbd)(void *);
void *_cbdata;
void (*_cbInput)();
void (*_cbdInput)(void *);
void *_cbdataInput;
void (*_cbOutput)();
void (*_cbdOutput)(void *);
void *_cbdataOutput;
void MCLKbegin();
AudioBufferManager *_arb;
AudioBufferManager *_arbInput;
AudioBufferManager *_arbOutput;
PIOProgram *_i2s;
PIOProgram *_i2sMCLK;
PIO _pio, _pioMCLK;
int _sm, _smMCLK;
static const int I2SSYSCLK_44_1 = 135600; // 44.1, 88.2 kHz sample rates
static const int I2SSYSCLK_8 = 147600; // 8k, 16, 32, 48, 96, 192 kHz
static const int I2SSYSCLK_8 = 153600; // 8k, 16, 32, 48, 96, 192 kHz
};
+83
View File
@@ -194,6 +194,58 @@ right1:
; Loop back to beginning...
.program pio_i2s_inout
.side_set 2 ; 0 = bclk, 1=wclk
; The C code should place (number of bits/sample - 2) in Y and
; also update the SHIFTCTRL to be 24 or 32 as appropriate
; +----- WCLK
; |+---- BCLK
mov x, y side 0b00 [1]
left1:
out pins, 1 side 0b01
in pins, 1 side 0b01
jmp x--, left1 side 0b00 [1]
out pins, 1 side 0b01
in pins, 1 side 0b01 ; 2584 LRCK stays low until BCLK goes low
; Last bit of left has WCLK change per I2S spec
mov x, y side 0b10 [1]
right1:
out pins, 1 side 0b11
in pins, 1 side 0b11
jmp x--, right1 side 0b10 [1]
out pins, 1 side 0b11
in pins, 1 side 0b11 ; 2584 LRCK stays high until BCLK goes low
; Loop back to beginning...
.program pio_i2s_inout_swap ; Note this is the same as _out, just "in" and not "out"
.side_set 2 ; 0 = wclk, 1=bclk
; The C code should place (number of bits/sample - 2) in Y and
; also update the SHIFTCTRL to be 24 or 32 as appropriate
; +----- BCLK
; |+---- WCLK
mov x, y side 0b00 [1]
left1:
out pins, 1 side 0b10
in pins, 1 side 0b10
jmp x--, left1 side 0b00 [1]
out pins, 1 side 0b10
in pins, 1 side 0b10 ;2584 LRCK stays low until BCLK goes low
mov x, y side 0b01 [1]
right1:
out pins, 1 side 0b11
in pins, 1 side 0b11
jmp x--, right1 side 0b01 [1]
out pins, 1 side 0b11
in pins, 1 side 0b11 ; 2584 LRCK stays high until BCLK goes low
; Loop back to beginning...
% c-sdk {
@@ -314,4 +366,35 @@ static inline void pio_i2s_in_program_init(PIO pio, uint sm, uint offset, uint d
pio_sm_exec(pio, sm, pio_encode_in(pio_pins, bits - 1)); // Shift in 1st R data modulo one bit, avoiding bit shift from #2037
}
static inline void pio_i2s_inout_program_init(PIO pio, uint sm, uint offset, uint data_in_pin, uint data_out_pin, uint clock_pin_base, uint bits, bool swap) {
pio_gpio_init(pio, data_in_pin);
pio_gpio_init(pio, data_out_pin);
pio_gpio_init(pio, clock_pin_base);
pio_gpio_init(pio, clock_pin_base + 1);
pio_sm_config sm_config = swap ? pio_i2s_inout_swap_program_get_default_config(offset) : pio_i2s_inout_program_get_default_config(offset);
sm_config_set_in_pins(&sm_config, data_in_pin);
sm_config_set_out_pins(&sm_config, data_out_pin, 1);
sm_config_set_sideset_pins(&sm_config, clock_pin_base);
sm_config_set_in_shift(&sm_config, false, true, (bits <= 16) ? 2 * bits : bits);
sm_config_set_out_shift(&sm_config, false, true, (bits <= 16) ? 2 * bits : bits);
pio_sm_init(pio, sm, offset, &sm_config);
//uint pin_mask = (1u << data_out_pin) | (3u << clock_pin_base);
//pio_sm_set_pindirs_with_mask(pio, sm, pin_mask, pin_mask);
//pio_sm_set_pins(pio, sm, 0); // clear pins
pio_sm_set_consecutive_pindirs(pio, sm, data_in_pin, 1, false);
pio_sm_set_consecutive_pindirs(pio, sm, data_out_pin, 1, true);
pio_sm_set_consecutive_pindirs(pio, sm, clock_pin_base, 2, true);
pio_sm_set_set_pins(pio, sm, data_out_pin, 1);
pio_sm_set_set_pins(pio, sm, clock_pin_base, 2);
pio_sm_exec(pio, sm, pio_encode_set(pio_y, bits - 2));
pio_sm_exec(pio, sm, pio_encode_in(pio_pins, bits)); // Shift in 1st L data
pio_sm_exec(pio, sm, pio_encode_in(pio_pins, bits - 1)); // Shift in 1st R data modulo one bit, avoiding bit shift from #2037
}
%}
+112 -1
View File
@@ -351,6 +351,94 @@ static inline pio_sm_config pio_i2s_in_swap_program_get_default_config(uint offs
sm_config_set_sideset(&c, 2, false, false);
return c;
}
#endif
// ------------- //
// pio_i2s_inout //
// ------------- //
#define pio_i2s_inout_wrap_target 0
#define pio_i2s_inout_wrap 11
#define pio_i2s_inout_pio_version 0
static const uint16_t pio_i2s_inout_program_instructions[] = {
// .wrap_target
0xa122, // 0: mov x, y side 0 [1]
0x6801, // 1: out pins, 1 side 1
0x4801, // 2: in pins, 1 side 1
0x0141, // 3: jmp x--, 1 side 0 [1]
0x6801, // 4: out pins, 1 side 1
0x4801, // 5: in pins, 1 side 1
0xb122, // 6: mov x, y side 2 [1]
0x7801, // 7: out pins, 1 side 3
0x5801, // 8: in pins, 1 side 3
0x1147, // 9: jmp x--, 7 side 2 [1]
0x7801, // 10: out pins, 1 side 3
0x5801, // 11: in pins, 1 side 3
// .wrap
};
#if !PICO_NO_HARDWARE
static const struct pio_program pio_i2s_inout_program = {
.instructions = pio_i2s_inout_program_instructions,
.length = 12,
.origin = -1,
.pio_version = 0,
#if PICO_PIO_VERSION > 0
.used_gpio_ranges = 0x0
#endif
};
static inline pio_sm_config pio_i2s_inout_program_get_default_config(uint offset) {
pio_sm_config c = pio_get_default_sm_config();
sm_config_set_wrap(&c, offset + pio_i2s_inout_wrap_target, offset + pio_i2s_inout_wrap);
sm_config_set_sideset(&c, 2, false, false);
return c;
}
#endif
// ------------------ //
// pio_i2s_inout_swap //
// ------------------ //
#define pio_i2s_inout_swap_wrap_target 0
#define pio_i2s_inout_swap_wrap 11
#define pio_i2s_inout_swap_pio_version 0
static const uint16_t pio_i2s_inout_swap_program_instructions[] = {
// .wrap_target
0xa122, // 0: mov x, y side 0 [1]
0x7001, // 1: out pins, 1 side 2
0x5001, // 2: in pins, 1 side 2
0x0141, // 3: jmp x--, 1 side 0 [1]
0x7001, // 4: out pins, 1 side 2
0x5001, // 5: in pins, 1 side 2
0xa922, // 6: mov x, y side 1 [1]
0x7801, // 7: out pins, 1 side 3
0x5801, // 8: in pins, 1 side 3
0x0947, // 9: jmp x--, 7 side 1 [1]
0x7801, // 10: out pins, 1 side 3
0x5801, // 11: in pins, 1 side 3
// .wrap
};
#if !PICO_NO_HARDWARE
static const struct pio_program pio_i2s_inout_swap_program = {
.instructions = pio_i2s_inout_swap_program_instructions,
.length = 12,
.origin = -1,
.pio_version = 0,
#if PICO_PIO_VERSION > 0
.used_gpio_ranges = 0x0
#endif
};
static inline pio_sm_config pio_i2s_inout_swap_program_get_default_config(uint offset) {
pio_sm_config c = pio_get_default_sm_config();
sm_config_set_wrap(&c, offset + pio_i2s_inout_swap_wrap_target, offset + pio_i2s_inout_swap_wrap);
sm_config_set_sideset(&c, 2, false, false);
return c;
}
static inline void pio_i2s_MCLK_program_init(PIO pio, uint sm, uint offset, uint MCLK_pin) {
pio_gpio_init(pio, MCLK_pin);
@@ -441,6 +529,29 @@ static inline void pio_i2s_in_program_init(PIO pio, uint sm, uint offset, uint d
pio_sm_exec(pio, sm, pio_encode_in(pio_pins, bits)); // Shift in 1st L data
pio_sm_exec(pio, sm, pio_encode_in(pio_pins, bits - 1)); // Shift in 1st R data modulo one bit, avoiding bit shift from #2037
}
static inline void pio_i2s_inout_program_init(PIO pio, uint sm, uint offset, uint data_in_pin, uint data_out_pin, uint clock_pin_base, uint bits, bool swap) {
pio_gpio_init(pio, data_in_pin);
pio_gpio_init(pio, data_out_pin);
pio_gpio_init(pio, clock_pin_base);
pio_gpio_init(pio, clock_pin_base + 1);
pio_sm_config sm_config = swap ? pio_i2s_inout_swap_program_get_default_config(offset) : pio_i2s_inout_program_get_default_config(offset);
sm_config_set_in_pins(&sm_config, data_in_pin);
sm_config_set_out_pins(&sm_config, data_out_pin, 1);
sm_config_set_sideset_pins(&sm_config, clock_pin_base);
sm_config_set_in_shift(&sm_config, false, true, (bits <= 16) ? 2 * bits : bits);
sm_config_set_out_shift(&sm_config, false, true, (bits <= 16) ? 2 * bits : bits);
pio_sm_init(pio, sm, offset, &sm_config);
//uint pin_mask = (1u << data_out_pin) | (3u << clock_pin_base);
//pio_sm_set_pindirs_with_mask(pio, sm, pin_mask, pin_mask);
//pio_sm_set_pins(pio, sm, 0); // clear pins
pio_sm_set_consecutive_pindirs(pio, sm, data_in_pin, 1, false);
pio_sm_set_consecutive_pindirs(pio, sm, data_out_pin, 1, true);
pio_sm_set_consecutive_pindirs(pio, sm, clock_pin_base, 2, true);
pio_sm_set_set_pins(pio, sm, data_out_pin, 1);
pio_sm_set_set_pins(pio, sm, clock_pin_base, 2);
pio_sm_exec(pio, sm, pio_encode_set(pio_y, bits - 2));
pio_sm_exec(pio, sm, pio_encode_in(pio_pins, bits)); // Shift in 1st L data
pio_sm_exec(pio, sm, pio_encode_in(pio_pins, bits - 1)); // Shift in 1st R data modulo one bit, avoiding bit shift from #2037
}
#endif
+1 -1
View File
@@ -161,7 +161,7 @@ bool MDNSResponder::_prepareMDNSMessage(MDNSResponder::stcMDNSSendParameter& p_r
// Prepare header; count answers
stcMDNS_MsgHeader msgHeader(p_rSendParameter.m_u16ID, p_rSendParameter.m_bResponse, 0,
p_rSendParameter.m_bAuthorative);
// If this is a response, the answers are anwers,
// If this is a response, the answers are answers,
// else this is a query or probe and the answers go into auth section
uint16_t& ru16Answers
= (p_rSendParameter.m_bResponse ? msgHeader.m_u16ANCount : msgHeader.m_u16NSCount);
+17 -1
View File
@@ -20,6 +20,7 @@
*/
#include <Arduino.h>
#include "PWMAudio.h"
#include "PWMAudioPrecalc.h"
#include <hardware/pwm.h>
@@ -100,7 +101,8 @@ bool PWMAudio::setFrequency(int frequency) {
return true; // We're already at the right speed
}
if (_pacer < 0) {
return false;
_sampleRate = frequency;
return true;
}
uint16_t _pacer_D, _pacer_N;
// Flip fraction(N for D, D for N) because we are using it as sys_clk * fraction(mechanic of dma_timer_set_fraction) for smaller than sys_clk values
@@ -151,6 +153,7 @@ bool PWMAudio::begin() {
if (_pacer < 0) {
return false;
}
uint16_t _pacer_D = 0;
uint16_t _pacer_N = 0;
// Flip fraction(N for D, D for N) because we are using it as sys_clk * fraction(mechanic of dma_timer_set_fraction) for smaller than sys_clk values
@@ -281,6 +284,19 @@ void PWMAudio::find_pacer_fraction(int target, uint16_t *numerator, uint16_t *de
return;
}
// See if it's one of the precalculated values
for (size_t i = 0; i < sizeof(__PWMAudio_pacer) / sizeof(__PWMAudio_pacer[0]); i++) {
if (target == (int)__PWMAudio_pacer[i].freq) {
last_target = target;
bestNum = __PWMAudio_pacer[i].n;
bestDenom = __PWMAudio_pacer[i].d;
*numerator = bestNum;
*denominator = bestDenom;
return;
}
}
// Nope, do exhaustive search. This is gonna be slooooow
float targetRatio = (float)F_CPU / target;
float lowestError = HUGE_VALF;
+37
View File
@@ -0,0 +1,37 @@
// Generated by tools/makepacer.cpp, do not edit
typedef struct {
uint32_t freq;
uint16_t n;
uint16_t d;
} PWMPacerPrecalc;
#if F_CPU == 50000000
static const PWMPacerPrecalc __PWMAudio_pacer[] = {{8000, 6250, 1}, {11025, 31746, 7}, {16000, 3125, 1}, {22050, 15873, 7}, {32000, 3125, 2}, {44100, 53288, 47}, {48000, 3125, 3}, {88200, 42517, 75}, {96000, 3125, 6}, {176400, 55839, 197}, {192000, 3125, 12}};
#elif F_CPU == 100000000
static const PWMPacerPrecalc __PWMAudio_pacer[] = {{8000, 12500, 1}, {11025, 63492, 7}, {16000, 6250, 1}, {22050, 31746, 7}, {32000, 3125, 1}, {44100, 15873, 7}, {48000, 6250, 3}, {88200, 53288, 47}, {96000, 3125, 3}, {176400, 42517, 75}, {192000, 3125, 6}};
#elif F_CPU == 120000000
static const PWMPacerPrecalc __PWMAudio_pacer[] = {{8000, 15000, 1}, {11025, 32653, 3}, {16000, 7500, 1}, {22050, 59864, 11}, {32000, 3750, 1}, {44100, 62585, 23}, {48000, 2500, 1}, {88200, 62585, 46}, {96000, 1250, 1}, {176400, 62585, 92}, {192000, 625, 1}};
#elif F_CPU == 125000000
static const PWMPacerPrecalc __PWMAudio_pacer[] = {{8000, 15625, 1}, {11025, 56689, 5}, {16000, 15625, 2}, {22050, 62358, 11}, {32000, 15625, 4}, {44100, 42517, 15}, {48000, 15625, 6}, {88200, 42517, 30}, {96000, 15625, 12}, {176400, 42517, 60}, {192000, 15625, 24}};
#elif F_CPU == 128000000
static const PWMPacerPrecalc __PWMAudio_pacer[] = {{8000, 16000, 1}, {11025, 11610, 1}, {16000, 8000, 1}, {22050, 5805, 1}, {32000, 4000, 1}, {44100, 5805, 2}, {48000, 8000, 3}, {88200, 5805, 4}, {96000, 4000, 3}, {176400, 61678, 85}, {192000, 2000, 3}};
#elif F_CPU == 133000000
static const PWMPacerPrecalc __PWMAudio_pacer[] = {{8000, 16625, 1}, {11025, 24127, 2}, {16000, 16625, 2}, {22050, 24127, 4}, {32000, 16625, 4}, {44100, 24127, 8}, {48000, 16625, 6}, {88200, 24127, 16}, {96000, 16625, 12}, {176400, 47500, 63}, {192000, 16625, 24}};
#elif F_CPU == 150000000
static const PWMPacerPrecalc __PWMAudio_pacer[] = {{8000, 18750, 1}, {11025, 27211, 2}, {16000, 9375, 1}, {22050, 47619, 7}, {32000, 9375, 2}, {44100, 37415, 11}, {48000, 3125, 1}, {88200, 42517, 25}, {96000, 3125, 2}, {176400, 42517, 50}, {192000, 3125, 4}};
#elif F_CPU == 175000000
static const PWMPacerPrecalc __PWMAudio_pacer[] = {{8000, 21875, 1}, {11025, 15873, 1}, {16000, 21875, 2}, {22050, 15873, 2}, {32000, 21875, 4}, {44100, 15873, 4}, {48000, 21875, 6}, {88200, 15873, 8}, {96000, 21875, 12}, {176400, 62500, 63}, {192000, 21875, 24}};
#elif F_CPU == 200000000
static const PWMPacerPrecalc __PWMAudio_pacer[] = {{8000, 25000, 1}, {11025, 54422, 3}, {16000, 12500, 1}, {22050, 63492, 7}, {32000, 6250, 1}, {44100, 31746, 7}, {48000, 12500, 3}, {88200, 15873, 7}, {96000, 6250, 3}, {176400, 53288, 47}, {192000, 3125, 3}};
#elif F_CPU == 225000000
static const PWMPacerPrecalc __PWMAudio_pacer[] = {{8000, 28125, 1}, {11025, 20408, 1}, {16000, 28125, 2}, {22050, 10204, 1}, {32000, 28125, 4}, {44100, 5102, 1}, {48000, 9375, 2}, {88200, 63776, 25}, {96000, 9375, 4}, {176400, 62500, 49}, {192000, 9375, 8}};
#elif F_CPU == 240000000
static const PWMPacerPrecalc __PWMAudio_pacer[] = {{8000, 30000, 1}, {11025, 65306, 3}, {16000, 15000, 1}, {22050, 32653, 3}, {32000, 7500, 1}, {44100, 59864, 11}, {48000, 5000, 1}, {88200, 62585, 23}, {96000, 2500, 1}, {176400, 62585, 46}, {192000, 1250, 1}};
#elif F_CPU == 250000000
static const PWMPacerPrecalc __PWMAudio_pacer[] = {{8000, 31250, 1}, {11025, 45351, 2}, {16000, 15625, 1}, {22050, 56689, 5}, {32000, 15625, 2}, {44100, 62358, 11}, {48000, 15625, 3}, {88200, 42517, 15}, {96000, 15625, 6}, {176400, 42517, 30}, {192000, 15625, 12}};
#elif F_CPU == 275000000
static const PWMPacerPrecalc __PWMAudio_pacer[] = {{8000, 34375, 1}, {11025, 49887, 2}, {16000, 34375, 2}, {22050, 37415, 3}, {32000, 34375, 4}, {44100, 37415, 6}, {48000, 34375, 6}, {88200, 37415, 12}, {96000, 34375, 12}, {176400, 35856, 23}, {192000, 34375, 24}};
#elif F_CPU == 300000000
static const PWMPacerPrecalc __PWMAudio_pacer[] = {{8000, 37500, 1}, {11025, 27211, 1}, {16000, 18750, 1}, {22050, 27211, 2}, {32000, 9375, 1}, {44100, 47619, 7}, {48000, 6250, 1}, {88200, 37415, 11}, {96000, 3125, 1}, {176400, 42517, 25}, {192000, 3125, 2}};
#else
const PWMPacerPrecalc __PWMAudio_pacer[] = {{1, 1, 1}}; // Invalid, should never match
#endif
+26 -16
View File
@@ -37,6 +37,11 @@ const int _MOSI = 7; // AKA SPI TX
const int _CS = 5;
const int _SCK = 6;
// If you have all 4 DAT pins wired up to the Pico you can use SDIO mode
const int RP_CLK_GPIO = -1; // Set to CLK GPIO
const int RP_CMD_GPIO = -1; // Set to CMD GPIO
const int RP_DAT0_GPIO = -1; // Set to DAT0 GPIO. DAT1..3 must be consecutively connected.
// include the SD library:
#include <SPI.h>
#include <SD.h>
@@ -54,21 +59,26 @@ void setup() {
Serial.println("\nInitializing SD card...");
bool sdInitialized = false;
// Ensure the SPI pinout the SD card is connected to is configured properly
// Select the correct SPI based on _MISO pin for the RP2040
if (_MISO == 0 || _MISO == 4 || _MISO == 16) {
SPI.setRX(_MISO);
SPI.setTX(_MOSI);
SPI.setSCK(_SCK);
sdInitialized = SD.begin(_CS);
} else if (_MISO == 8 || _MISO == 12) {
SPI1.setRX(_MISO);
SPI1.setTX(_MOSI);
SPI1.setSCK(_SCK);
sdInitialized = SD.begin(_CS, SPI1);
if (RP_CLK_GPIO >= 0) {
// No special requirements on pin locations, this is PIO programmed
sdInitialized = SD.begin(RP_CLK_GPIO, RP_CMD_GPIO, RP_DAT0_GPIO);
} else {
Serial.println(F("ERROR: Unknown SPI Configuration"));
return;
// Ensure the SPI pinout the SD card is connected to is configured properly
// Select the correct SPI based on _MISO pin for the RP2040
if (_MISO == 0 || _MISO == 4 || _MISO == 16) {
SPI.setRX(_MISO);
SPI.setTX(_MOSI);
SPI.setSCK(_SCK);
sdInitialized = SD.begin(_CS);
} else if (_MISO == 8 || _MISO == 12) {
SPI1.setRX(_MISO);
SPI1.setTX(_MOSI);
SPI1.setSCK(_SCK);
sdInitialized = SD.begin(_CS, SPI1);
} else {
Serial.println(F("ERROR: Unknown SPI Configuration"));
return;
}
}
if (!sdInitialized) {
@@ -114,7 +124,7 @@ void setup() {
Serial.println();
// print the type and size of the first FAT-type volume
uint32_t volumesize;
uint64_t volumesize;
Serial.print("Volume type is: FAT");
Serial.println(SD.fatType(), DEC);
@@ -130,7 +140,7 @@ void setup() {
Serial.println((float)volumesize / 1024.0);
Serial.print("Card size: ");
Serial.println((float)SD.size() / 1000);
Serial.println((float)SD.size64() / 1000);
FSInfo fs_info;
SDFS.info(fs_info);
@@ -30,6 +30,11 @@ const int _MOSI = 7;
const int _CS = 5;
const int _SCK = 6;
// If you have all 4 DAT pins wired up to the Pico you can use SDIO mode
const int RP_CLK_GPIO = -1; // Set to CLK GPIO
const int RP_CMD_GPIO = -1; // Set to CMD GPIO
const int RP_DAT0_GPIO = -1; // Set to DAT0 GPIO. DAT1..3 must be consecutively connected.
#include <SPI.h>
#include <SD.h>
@@ -39,13 +44,31 @@ void setup() {
Serial.print("Initializing SD card...");
// Ensure the SPI pinout the SD card is connected to is configured properly
SPI.setRX(_MISO);
SPI.setTX(_MOSI);
SPI.setSCK(_SCK);
bool sdInitialized = false;
if (RP_CLK_GPIO >= 0) {
// No special requirements on pin locations, this is PIO programmed
sdInitialized = SD.begin(RP_CLK_GPIO, RP_CMD_GPIO, RP_DAT0_GPIO);
} else {
// Ensure the SPI pinout the SD card is connected to is configured properly
// Select the correct SPI based on _MISO pin for the RP2040
if (_MISO == 0 || _MISO == 4 || _MISO == 16) {
SPI.setRX(_MISO);
SPI.setTX(_MOSI);
SPI.setSCK(_SCK);
sdInitialized = SD.begin(_CS);
} else if (_MISO == 8 || _MISO == 12) {
SPI1.setRX(_MISO);
SPI1.setTX(_MOSI);
SPI1.setSCK(_SCK);
sdInitialized = SD.begin(_CS, SPI1);
} else {
Serial.println(F("ERROR: Unknown SPI Configuration"));
return;
}
}
// see if the card is present and can be initialized:
if (!SD.begin(_CS)) {
if (!sdInitialized) {
Serial.println("Card failed, or not present");
// don't do anything more:
return;
+28 -5
View File
@@ -30,6 +30,11 @@ const int _MOSI = 7;
const int _CS = 5;
const int _SCK = 6;
// If you have all 4 DAT pins wired up to the Pico you can use SDIO mode
const int RP_CLK_GPIO = -1; // Set to CLK GPIO
const int RP_CMD_GPIO = -1; // Set to CMD GPIO
const int RP_DAT0_GPIO = -1; // Set to DAT0 GPIO. DAT1..3 must be consecutively connected.
#include <SPI.h>
#include <SD.h>
@@ -39,13 +44,31 @@ void setup() {
Serial.print("Initializing SD card...");
// Ensure the SPI pinout the SD card is connected to is configured properly
SPI.setRX(_MISO);
SPI.setTX(_MOSI);
SPI.setSCK(_SCK);
bool sdInitialized = false;
if (RP_CLK_GPIO >= 0) {
// No special requirements on pin locations, this is PIO programmed
sdInitialized = SD.begin(RP_CLK_GPIO, RP_CMD_GPIO, RP_DAT0_GPIO);
} else {
// Ensure the SPI pinout the SD card is connected to is configured properly
// Select the correct SPI based on _MISO pin for the RP2040
if (_MISO == 0 || _MISO == 4 || _MISO == 16) {
SPI.setRX(_MISO);
SPI.setTX(_MOSI);
SPI.setSCK(_SCK);
sdInitialized = SD.begin(_CS);
} else if (_MISO == 8 || _MISO == 12) {
SPI1.setRX(_MISO);
SPI1.setTX(_MOSI);
SPI1.setSCK(_SCK);
sdInitialized = SD.begin(_CS, SPI1);
} else {
Serial.println(F("ERROR: Unknown SPI Configuration"));
return;
}
}
// see if the card is present and can be initialized:
if (!SD.begin(_CS)) {
if (!sdInitialized) {
Serial.println("Card failed, or not present");
// don't do anything more:
return;
+28 -5
View File
@@ -28,6 +28,11 @@ const int _MOSI = 7;
const int _CS = 5;
const int _SCK = 6;
// If you have all 4 DAT pins wired up to the Pico you can use SDIO mode
const int RP_CLK_GPIO = -1; // Set to CLK GPIO
const int RP_CMD_GPIO = -1; // Set to CMD GPIO
const int RP_DAT0_GPIO = -1; // Set to DAT0 GPIO. DAT1..3 must be consecutively connected.
#include <SPI.h>
#include <SD.h>
@@ -39,12 +44,30 @@ void setup() {
Serial.print("Initializing SD card...");
// Ensure the SPI pinout the SD card is connected to is configured properly
SPI.setRX(_MISO);
SPI.setTX(_MOSI);
SPI.setSCK(_SCK);
bool sdInitialized = false;
if (RP_CLK_GPIO >= 0) {
// No special requirements on pin locations, this is PIO programmed
sdInitialized = SD.begin(RP_CLK_GPIO, RP_CMD_GPIO, RP_DAT0_GPIO);
} else {
// Ensure the SPI pinout the SD card is connected to is configured properly
// Select the correct SPI based on _MISO pin for the RP2040
if (_MISO == 0 || _MISO == 4 || _MISO == 16) {
SPI.setRX(_MISO);
SPI.setTX(_MOSI);
SPI.setSCK(_SCK);
sdInitialized = SD.begin(_CS);
} else if (_MISO == 8 || _MISO == 12) {
SPI1.setRX(_MISO);
SPI1.setTX(_MOSI);
SPI1.setSCK(_SCK);
sdInitialized = SD.begin(_CS, SPI1);
} else {
Serial.println(F("ERROR: Unknown SPI Configuration"));
return;
}
}
if (!SD.begin(_CS)) {
if (!sdInitialized) {
Serial.println("initialization failed!");
return;
}
+28 -5
View File
@@ -28,6 +28,11 @@ const int _MOSI = 7;
const int _CS = 5;
const int _SCK = 6;
// If you have all 4 DAT pins wired up to the Pico you can use SDIO mode
const int RP_CLK_GPIO = -1; // Set to CLK GPIO
const int RP_CMD_GPIO = -1; // Set to CMD GPIO
const int RP_DAT0_GPIO = -1; // Set to DAT0 GPIO. DAT1..3 must be consecutively connected.
#include <SPI.h>
#include <SD.h>
@@ -39,12 +44,30 @@ void setup() {
Serial.print("Initializing SD card...");
// Ensure the SPI pinout the SD card is connected to is configured properly
SPI.setRX(_MISO);
SPI.setTX(_MOSI);
SPI.setSCK(_SCK);
bool sdInitialized = false;
if (RP_CLK_GPIO >= 0) {
// No special requirements on pin locations, this is PIO programmed
sdInitialized = SD.begin(RP_CLK_GPIO, RP_CMD_GPIO, RP_DAT0_GPIO);
} else {
// Ensure the SPI pinout the SD card is connected to is configured properly
// Select the correct SPI based on _MISO pin for the RP2040
if (_MISO == 0 || _MISO == 4 || _MISO == 16) {
SPI.setRX(_MISO);
SPI.setTX(_MOSI);
SPI.setSCK(_SCK);
sdInitialized = SD.begin(_CS);
} else if (_MISO == 8 || _MISO == 12) {
SPI1.setRX(_MISO);
SPI1.setTX(_MOSI);
SPI1.setSCK(_SCK);
sdInitialized = SD.begin(_CS, SPI1);
} else {
Serial.println(F("ERROR: Unknown SPI Configuration"));
return;
}
}
if (!SD.begin(_CS)) {
if (!sdInitialized) {
Serial.println("initialization failed!");
return;
}
+24 -14
View File
@@ -42,6 +42,11 @@ const int _MOSI = 7; // AKA SPI TX
const int _CS = 5;
const int _SCK = 6;
// If you have all 4 DAT pins wired up to the Pico you can use SDIO mode
const int RP_CLK_GPIO = -1; // Set to CLK GPIO
const int RP_CMD_GPIO = -1; // Set to CMD GPIO
const int RP_DAT0_GPIO = -1; // Set to DAT0 GPIO. DAT1..3 must be consecutively connected.
#include <SPI.h>
#include <SD.h>
@@ -58,21 +63,26 @@ void setup() {
Serial.println("\nInitializing SD card...");
bool sdInitialized = false;
// Ensure the SPI pinout the SD card is connected to is configured properly
// Select the correct SPI based on _MISO pin for the RP2040
if (_MISO == 0 || _MISO == 4 || _MISO == 16) {
SPI.setRX(_MISO);
SPI.setTX(_MOSI);
SPI.setSCK(_SCK);
sdInitialized = SD.begin(_CS);
} else if (_MISO == 8 || _MISO == 12) {
SPI1.setRX(_MISO);
SPI1.setTX(_MOSI);
SPI1.setSCK(_SCK);
sdInitialized = SD.begin(_CS, SPI1);
if (RP_CLK_GPIO >= 0) {
// No special requirements on pin locations, this is PIO programmed
sdInitialized = SD.begin(RP_CLK_GPIO, RP_CMD_GPIO, RP_DAT0_GPIO);
} else {
Serial.println(F("ERROR: Unknown SPI Configuration"));
return;
// Ensure the SPI pinout the SD card is connected to is configured properly
// Select the correct SPI based on _MISO pin for the RP2040
if (_MISO == 0 || _MISO == 4 || _MISO == 16) {
SPI.setRX(_MISO);
SPI.setTX(_MOSI);
SPI.setSCK(_SCK);
sdInitialized = SD.begin(_CS);
} else if (_MISO == 8 || _MISO == 12) {
SPI1.setRX(_MISO);
SPI1.setTX(_MOSI);
SPI1.setSCK(_SCK);
sdInitialized = SD.begin(_CS, SPI1);
} else {
Serial.println(F("ERROR: Unknown SPI Configuration"));
return;
}
}
if (!sdInitialized) {
+6
View File
@@ -36,11 +36,17 @@ public:
SDFS.setConfig(SDFSConfig(csPin, SPI_HALF_SPEED, spi));
return SDFS.begin();
}
bool begin(uint8_t csPin, uint32_t cfg = SPI_HALF_SPEED, HardwareSPI &spi = SPI) {
SDFS.setConfig(SDFSConfig(csPin, cfg, spi));
return SDFS.begin();
}
bool begin(uint8_t clkPin, uint8_t cmdPin, uint8_t dat0Pin) {
SDFS.setConfig(SDFSConfig(clkPin, cmdPin, dat0Pin));
return SDFS.begin();
}
void end(bool endSPI = true) {
SDFS.end();
if (endSPI && _spi) {
+4 -4
View File
@@ -63,13 +63,13 @@ FileImplPtr SDFSImpl::open(const char* path, OpenMode openMode, AccessMode acces
}
free(pathStr);
}
File32 fd = _fs.open(path, flags);
FsFile fd = _fs.open(path, flags);
if (!fd) {
DEBUGV("SDFSImpl::openFile: fd=%p path=`%s` openMode=%d accessMode=%d",
&fd, path, openMode, accessMode);
return FileImplPtr();
}
auto sharedFd = std::make_shared<File32>(fd);
auto sharedFd = std::make_shared<FsFile>(fd);
return std::make_shared<SDFSFileImpl>(this, sharedFd, path);
}
@@ -88,7 +88,7 @@ DirImplPtr SDFSImpl::openDir(const char* path) {
}
// At this point we have a name of "/blah/blah/blah" or "blah" or ""
// If that references a directory, just open it and we're done.
File32 dirFile;
FsFile dirFile;
const char *filter = "";
if (!pathStr[0]) {
// openDir("") === openDir("/")
@@ -133,7 +133,7 @@ DirImplPtr SDFSImpl::openDir(const char* path) {
DEBUGV("SDFSImpl::openDir: path=`%s`\n", path);
return DirImplPtr();
}
auto sharedDir = std::make_shared<File32>(dirFile);
auto sharedDir = std::make_shared<FsFile>(dirFile);
auto ret = std::make_shared<SDFSDirImpl>(filter, this, sharedDir, pathStr);
free(pathStr);
return ret;
+42 -26
View File
@@ -45,7 +45,8 @@ class SDFSConfig : public FSConfig {
public:
static constexpr uint32_t FSId = 0x53444653;
SDFSConfig(uint8_t csPin = 4, uint32_t spi = SD_SCK_MHZ(10), HardwareSPI &port = SPI) : FSConfig(FSId, false), _csPin(csPin), _part(0), _spiSettings(spi), _spi(&port) { }
SDFSConfig(uint8_t csPin = 4, uint32_t spi = SD_SCK_MHZ(10), HardwareSPI &port = SPI) : FSConfig(FSId, false), _sdio(false), _clkPin(255), _csPin(csPin), _cmdPin(255), _dat0Pin(255), _part(0), _spiSettings(spi), _spi(&port) { }
SDFSConfig(uint8_t clkPin, uint8_t cmdPin, uint8_t dataPin) : FSConfig(FSId, false), _sdio(true), _clkPin(clkPin), _cmdPin(cmdPin), _dat0Pin(dataPin), _part(0), _spiSettings(SD_SCK_MHZ(1)), _spi(nullptr) { }
SDFSConfig setAutoFormat(bool val = true) {
_autoFormat = val;
@@ -69,7 +70,11 @@ public:
}
// Inherit _type and _autoFormat
bool _sdio;
uint8_t _clkPin; // SDIO only;
uint8_t _csPin;
uint8_t _cmdPin; // SDIO only
uint8_t _dat0Pin; // SDIO only
uint8_t _part;
uint32_t _spiSettings;
HardwareSPI *_spi;
@@ -131,11 +136,20 @@ public:
if (_mounted) {
return true;
}
SdSpiConfig ssc(_cfg._csPin, SHARED_SPI, _cfg._spiSettings, _cfg._spi);
_mounted = _fs.begin(ssc);
if (!_mounted && _cfg._autoFormat) {
format();
if (!_cfg._sdio) {
SdSpiConfig ssc(_cfg._csPin, SHARED_SPI, _cfg._spiSettings, _cfg._spi);
_mounted = _fs.begin(ssc);
if (!_mounted && _cfg._autoFormat) {
format();
_mounted = _fs.begin(ssc);
}
} else {
SdioConfig ssc(_cfg._clkPin, _cfg._cmdPin, _cfg._dat0Pin);
_mounted = _fs.begin(ssc);
if (!_mounted && _cfg._autoFormat) {
format();
_mounted = _fs.begin(ssc);
}
}
FsDateTime::setCallback(dateTimeCB);
return _mounted;
@@ -153,8 +167,7 @@ public:
return false;
}
bzero(st, sizeof(*st));
File32 f;
f = _fs.open(path, O_RDONLY);
FsFile f = _fs.open(path, O_RDONLY);
if (!f) {
return false;
}
@@ -169,8 +182,8 @@ public:
if (f.getCreateDateTime(&date, &time)) {
st->ctime = FatToTimeT(date, time);
}
if (f.getAccessDate(&date)) {
st->atime = FatToTimeT(date, 0);
if (f.getAccessDateTime(&date, &time)) {
st->atime = FatToTimeT(date, time);
}
f.close();
return true;
@@ -272,7 +285,7 @@ protected:
class SDFSFileImpl : public FileImpl {
public:
SDFSFileImpl(SDFSImpl *fs, std::shared_ptr<File32> fd, const char *name)
SDFSFileImpl(SDFSImpl *fs, std::shared_ptr<FsFile> fd, const char *name)
: _fs(fs), _fd(fd), _opened(true) {
_name = std::shared_ptr<char>(new char[strlen(name) + 1], std::default_delete<char[]>());
strcpy(_name.get(), name);
@@ -284,7 +297,7 @@ public:
}
int availableForWrite() override {
return _opened ? _fd->availableSpaceForWrite() : 0;
return _opened ? _fd->availableForWrite() : 0;
}
size_t write(const uint8_t *buf, size_t size) override {
@@ -373,9 +386,9 @@ public:
time_t getLastWrite() override {
time_t ftime = 0;
if (_opened && _fd) {
DirFat_t tmp;
if (_fd.get()->dirEntry(&tmp)) {
ftime = SDFSImpl::FatToTimeT(*(uint16_t*)tmp.modifyDate, *(uint16_t*)tmp.modifyTime);
uint16_t date, time;
if (_fd.get()->getModifyDateTime(&date, &time)) {
ftime = SDFSImpl::FatToTimeT(date, time);
}
}
return ftime;
@@ -384,9 +397,9 @@ public:
time_t getCreationTime() override {
time_t ftime = 0;
if (_opened && _fd) {
DirFat_t tmp;
if (_fd.get()->dirEntry(&tmp)) {
ftime = SDFSImpl::FatToTimeT(*(uint16_t*)tmp.createDate, *(uint16_t*)tmp.createTime);
uint16_t date, time;
if (_fd.get()->getCreateDateTime(&date, &time)) {
ftime = SDFSImpl::FatToTimeT(date, time);
}
}
return ftime;
@@ -394,14 +407,14 @@ public:
protected:
SDFSImpl* _fs;
std::shared_ptr<File32> _fd;
std::shared_ptr<FsFile> _fd;
std::shared_ptr<char> _name;
bool _opened;
};
class SDFSDirImpl : public DirImpl {
public:
SDFSDirImpl(const String& pattern, SDFSImpl* fs, std::shared_ptr<File32> dir, const char *dirPath = nullptr)
SDFSDirImpl(const String& pattern, SDFSImpl* fs, std::shared_ptr<FsFile> dir, const char *dirPath = nullptr)
: _pattern(pattern), _fs(fs), _dir(dir), _valid(false), _dirPath(nullptr) {
if (dirPath) {
_dirPath = std::shared_ptr<char>(new char[strlen(dirPath) + 1], std::default_delete<char[]>());
@@ -466,19 +479,22 @@ public:
bool next() override {
const int n = _pattern.length();
do {
File32 file;
FsFile file;
file.openNext(_dir.get(), O_READ);
if (file) {
_valid = 1;
_size = file.fileSize();
_isFile = file.isFile();
_isDirectory = file.isDir();
DirFat_t tmp;
if (file.dirEntry(&tmp)) {
_time = SDFSImpl::FatToTimeT(*(uint16_t*)tmp.modifyDate, *(uint16_t*)tmp.modifyTime);
_creation = SDFSImpl::FatToTimeT(*(uint16_t*)tmp.createDate, *(uint16_t*)tmp.createTime);
uint16_t date, time;
if (file.getModifyDateTime(&date, &time)) {
_time = SDFSImpl::FatToTimeT(date, time);
} else {
_time = 0;
}
if (file.getCreateDateTime(&date, &time)) {
_creation = SDFSImpl::FatToTimeT(date, time);
} else {
_creation = 0;
}
file.getName(_lfn, sizeof(_lfn));
@@ -499,9 +515,9 @@ public:
protected:
String _pattern;
SDFSImpl* _fs;
std::shared_ptr<File32> _dir;
std::shared_ptr<FsFile> _dir;
bool _valid;
char _lfn[64];
char _lfn[256];
time_t _time;
time_t _creation;
std::shared_ptr<char> _dirPath;
+14 -86
View File
@@ -45,47 +45,6 @@ SPIClassRP2040::SPIClassRP2040(spi_inst_t *spi, pin_size_t rx, pin_size_t cs, pi
_CS = cs;
}
inline spi_cpol_t SPIClassRP2040::cpol() {
switch (_spis.getDataMode()) {
case SPI_MODE0:
return SPI_CPOL_0;
case SPI_MODE1:
return SPI_CPOL_0;
case SPI_MODE2:
return SPI_CPOL_1;
case SPI_MODE3:
return SPI_CPOL_1;
}
// Error
return SPI_CPOL_0;
}
inline spi_cpha_t SPIClassRP2040::cpha() {
switch (_spis.getDataMode()) {
case SPI_MODE0:
return SPI_CPHA_0;
case SPI_MODE1:
return SPI_CPHA_1;
case SPI_MODE2:
return SPI_CPHA_0;
case SPI_MODE3:
return SPI_CPHA_1;
}
// Error
return SPI_CPHA_0;
}
inline uint8_t SPIClassRP2040::reverseByte(uint8_t b) {
b = (b & 0xF0) >> 4 | (b & 0x0F) << 4;
b = (b & 0xCC) >> 2 | (b & 0x33) << 2;
b = (b & 0xAA) >> 1 | (b & 0x55) << 1;
return b;
}
inline uint16_t SPIClassRP2040::reverse16Bit(uint16_t w) {
return (reverseByte(w & 0xff) << 8) | (reverseByte(w >> 8));
}
// The HW can't do LSB first, only MSB first, so need to bitreverse
void SPIClassRP2040::adjustBuffer(const void *s, void *d, size_t cnt, bool by16) {
if (_spis.getBitOrder() == MSBFIRST) {
@@ -94,13 +53,13 @@ void SPIClassRP2040::adjustBuffer(const void *s, void *d, size_t cnt, bool by16)
const uint8_t *src = (const uint8_t *)s;
uint8_t *dst = (uint8_t *)d;
for (size_t i = 0; i < cnt; i++) {
*(dst++) = reverseByte(*(src++));
*(dst++) = _helper.reverseByte(*(src++));
}
} else { /* by16 */
const uint16_t *src = (const uint16_t *)s;
uint16_t *dst = (uint16_t *)d;
for (size_t i = 0; i < cnt; i++) {
*(dst++) = reverse16Bit(*(src++));
*(dst++) = _helper.reverse16Bit(*(src++));
}
}
}
@@ -110,11 +69,11 @@ byte SPIClassRP2040::transfer(uint8_t data) {
if (!_initted) {
return 0;
}
data = (_spis.getBitOrder() == MSBFIRST) ? data : reverseByte(data);
DEBUGSPI("SPI::transfer(%02x), cpol=%d, cpha=%d\n", data, cpol(), cpha());
data = (_spis.getBitOrder() == MSBFIRST) ? data : _helper.reverseByte(data);
DEBUGSPI("SPI::transfer(%02x), cpol=%d, cpha=%d\n", data, _helper.cpol(_spis), _helper.cpha(_spis));
hw_write_masked(&spi_get_hw(_spi)->cr0, (8 - 1) << SPI_SSPCR0_DSS_LSB, SPI_SSPCR0_DSS_BITS); // Fast set to 8-bits
spi_write_read_blocking(_spi, &data, &ret, 1);
ret = (_spis.getBitOrder() == MSBFIRST) ? ret : reverseByte(ret);
ret = (_spis.getBitOrder() == MSBFIRST) ? ret : _helper.reverseByte(ret);
DEBUGSPI("SPI: read back %02x\n", ret);
return ret;
}
@@ -124,11 +83,11 @@ uint16_t SPIClassRP2040::transfer16(uint16_t data) {
if (!_initted) {
return 0;
}
data = (_spis.getBitOrder() == MSBFIRST) ? data : reverse16Bit(data);
DEBUGSPI("SPI::transfer16(%04x), cpol=%d, cpha=%d\n", data, cpol(), cpha());
data = (_spis.getBitOrder() == MSBFIRST) ? data : _helper.reverse16Bit(data);
DEBUGSPI("SPI::transfer16(%04x), cpol=%d, cpha=%d\n", data, _helper.cpol(_spis), _helper.cpha(_spis));
hw_write_masked(&spi_get_hw(_spi)->cr0, (16 - 1) << SPI_SSPCR0_DSS_LSB, SPI_SSPCR0_DSS_BITS); // Fast set to 16-bits
spi_write16_read16_blocking(_spi, &data, &ret, 1);
ret = (_spis.getBitOrder() == MSBFIRST) ? ret : reverse16Bit(ret);
ret = (_spis.getBitOrder() == MSBFIRST) ? ret : _helper.reverse16Bit(ret);
DEBUGSPI("SPI: read back %02x\n", ret);
return ret;
}
@@ -172,21 +131,14 @@ void SPIClassRP2040::transfer(const void *txbuf, void *rxbuf, size_t count) {
// If its LSB this isn't nearly as fun, we'll just let transfer(x) do it :(
for (size_t i = 0; i < count; i++) {
*rxbuff = transfer(*txbuff);
*rxbuff = (_spis.getBitOrder() == MSBFIRST) ? *rxbuff : reverseByte(*rxbuff);
*rxbuff = (_spis.getBitOrder() == MSBFIRST) ? *rxbuff : _helper.reverseByte(*rxbuff);
txbuff++;
rxbuff++;
}
DEBUGSPI("SPI::transfer completed\n");
}
#ifdef PICO_RP2350B
#define GPIOIRQREGS 6
#else
#define GPIOIRQREGS 4
#endif
void SPIClassRP2040::beginTransaction(SPISettings settings) {
noInterrupts(); // Avoid possible race conditions if IRQ comes in while main app is in middle of this
DEBUGSPI("SPI::beginTransaction(clk=%lu, bo=%s)\n", settings.getClockFreq(), (settings.getBitOrder() == MSBFIRST) ? "MSB" : "LSB");
if (_initted && settings == _spis) {
DEBUGSPI("SPI: Reusing existing initted SPI\n");
@@ -202,39 +154,15 @@ void SPIClassRP2040::beginTransaction(SPISettings settings) {
DEBUGSPI("SPI: actual baudrate=%u\n", spi_get_baudrate(_spi));
}
_spis = settings;
spi_set_format(_spi, 8, cpol(), cpha(), SPI_MSB_FIRST);
spi_set_format(_spi, 8, _helper.cpol(_spis), _helper.cpha(_spis), SPI_MSB_FIRST);
_initted = true;
}
// Disable any IRQs that are being used for SPI
io_bank0_irq_ctrl_hw_t *irq_ctrl_base = get_core_num() ? &iobank0_hw->proc1_irq_ctrl : &iobank0_hw->proc0_irq_ctrl;
DEBUGSPI("SPI: IRQ masks before = %08x %08x %08x %08x %08x %08x\n", (unsigned)irq_ctrl_base->inte[0], (unsigned)irq_ctrl_base->inte[1], (unsigned)irq_ctrl_base->inte[2], (unsigned)irq_ctrl_base->inte[3], (GPIOIRQREGS > 4) ? (unsigned)irq_ctrl_base->inte[4] : 0, (GPIOIRQREGS > 5) ? (unsigned)irq_ctrl_base->inte[5] : 0);
for (auto entry : _usingIRQs) {
int gpio = entry.first;
// There is no gpio_get_irq, so manually twiddle the register
io_rw_32 *en_reg = &irq_ctrl_base->inte[gpio / 8];
uint32_t val = ((*en_reg) >> (4 * (gpio % 8))) & 0xf;
_usingIRQs.insert_or_assign(gpio, val);
DEBUGSPI("SPI: GPIO %d = %lu\n", gpio, val);
(*en_reg) ^= val << (4 * (gpio % 8));
}
DEBUGSPI("SPI: IRQ masks after = %08x %08x %08x %08x %08x %08x\n", (unsigned)irq_ctrl_base->inte[0], (unsigned)irq_ctrl_base->inte[1], (unsigned)irq_ctrl_base->inte[2], (unsigned)irq_ctrl_base->inte[3], (GPIOIRQREGS > 4) ? (unsigned)irq_ctrl_base->inte[4] : 0, (GPIOIRQREGS > 5) ? (unsigned)irq_ctrl_base->inte[5] : 0);
interrupts();
_helper.maskInterrupts();
}
void SPIClassRP2040::endTransaction(void) {
noInterrupts(); // Avoid race condition so the GPIO IRQs won't come back until all state is restored
DEBUGSPI("SPI::endTransaction()\n");
// Re-enable IRQs
for (auto entry : _usingIRQs) {
int gpio = entry.first;
int mode = entry.second;
gpio_set_irq_enabled(gpio, mode, true);
}
io_bank0_irq_ctrl_hw_t *irq_ctrl_base = get_core_num() ? &iobank0_hw->proc1_irq_ctrl : &iobank0_hw->proc0_irq_ctrl;
(void) irq_ctrl_base;
DEBUGSPI("SPI: IRQ masks = %08x %08x %08x %08x %08x %08x\n", (unsigned)irq_ctrl_base->inte[0], (unsigned)irq_ctrl_base->inte[1], (unsigned)irq_ctrl_base->inte[2], (unsigned)irq_ctrl_base->inte[3], (GPIOIRQREGS > 4) ? (unsigned)irq_ctrl_base->inte[4] : 0, (GPIOIRQREGS > 5) ? (unsigned)irq_ctrl_base->inte[5] : 0);
interrupts();
_helper.unmaskInterrupts();
}
bool SPIClassRP2040::transferAsync(const void *send, void *recv, size_t bytes) {
@@ -265,7 +193,7 @@ bool SPIClassRP2040::transferAsync(const void *send, void *recv, size_t bytes) {
return false;
}
for (size_t i = 0; i < bytes; i++) {
_dmaBuffer[i] = reverseByte(txbuff[i]);
_dmaBuffer[i] = _helper.reverseByte(txbuff[i]);
}
}
_dmaBytes = bytes;
@@ -312,7 +240,7 @@ bool SPIClassRP2040::finishedAsync() {
spi_get_hw(_spi)->dmacr = 0;
if (_spis.getBitOrder() != MSBFIRST) {
for (int i = 0; i < _dmaBytes; i++) {
_rxFinalBuffer[i] = reverseByte(_rxFinalBuffer[i]);
_rxFinalBuffer[i] = _helper.reverseByte(_rxFinalBuffer[i]);
}
free(_dmaBuffer);
_dmaBuffer = nullptr;
+5 -9
View File
@@ -23,7 +23,7 @@
#include <Arduino.h>
#include <api/HardwareSPI.h>
#include <hardware/spi.h>
#include <map>
#include "SPIHelper.h"
class SPIClassRP2040 : public arduino::HardwareSPI {
public:
@@ -76,19 +76,16 @@ public:
// List of GPIO IRQs to disable during a transaction
virtual void usingInterrupt(int interruptNumber) override {
_usingIRQs.insert({interruptNumber, 0});
_helper.usingInterrupt(interruptNumber);
}
virtual void notUsingInterrupt(int interruptNumber) override {
_usingIRQs.erase(interruptNumber);
_helper.notUsingInterrupt(interruptNumber);
}
virtual void attachInterrupt() override { /* noop */ }
virtual void detachInterrupt() override { /* noop */ }
private:
spi_cpol_t cpol();
spi_cpha_t cpha();
uint8_t reverseByte(uint8_t b);
uint16_t reverse16Bit(uint16_t w);
void adjustBuffer(const void *s, void *d, size_t cnt, bool by16);
spi_inst_t *_spi;
@@ -98,8 +95,6 @@ private:
bool _running; // SPI port active
bool _initted; // Transaction begun
std::map<int, int> _usingIRQs;
// DMA
int _channelDMA;
int _channelSendDMA;
@@ -107,6 +102,7 @@ private:
int _dmaBytes;
uint8_t *_rxFinalBuffer;
uint32_t _dummy;
SPIHelper _helper;
};
extern SPIClassRP2040 SPI;
+180
View File
@@ -0,0 +1,180 @@
/*
SPI internal helper utils library for the Raspberry Pi Pico RP2040
Copyright (c) 2025 Earle F. Philhower, III <earlephilhower@yahoo.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <Arduino.h>
#include <map>
#include <hardware/spi.h>
#include <hardware/gpio.h>
#include <hardware/structs/iobank0.h>
#include <hardware/irq.h>
/**
@brief Helper routined shared by SPI and SoftwareSPI
*/
class SPIHelper {
public:
SPIHelper() { /* noop */ }
~SPIHelper() { /* noop */ }
/**
@brief Returns the SDK CPOL setting for a given SPISettings configuration
@param _spis SPISettings to parse
@returns SDK-defined CPOL value
*/
inline spi_cpol_t cpol(const SPISettings &_spis) {
switch (_spis.getDataMode()) {
case SPI_MODE0:
return SPI_CPOL_0;
case SPI_MODE1:
return SPI_CPOL_0;
case SPI_MODE2:
return SPI_CPOL_1;
case SPI_MODE3:
return SPI_CPOL_1;
}
// Error
return SPI_CPOL_0;
}
/**
@brief Returns the SDK CPHA setting for a given SPISettings configuration
@param _spis SPISettings to parse
@returns SDK-defined CPHA value
*/
inline spi_cpha_t cpha(const SPISettings &_spis) {
switch (_spis.getDataMode()) {
case SPI_MODE0:
return SPI_CPHA_0;
case SPI_MODE1:
return SPI_CPHA_1;
case SPI_MODE2:
return SPI_CPHA_0;
case SPI_MODE3:
return SPI_CPHA_1;
}
// Error
return SPI_CPHA_0;
}
/**
@brief Reverses bits in a byte for MSB->LSB swapping
@param b Input byte
@returns Bit-reversed byte
*/
inline uint8_t reverseByte(uint8_t b) {
b = (b & 0xF0) >> 4 | (b & 0x0F) << 4;
b = (b & 0xCC) >> 2 | (b & 0x33) << 2;
b = (b & 0xAA) >> 1 | (b & 0x55) << 1;
return b;
}
/**
@brief MSB->LSB bit reversal for 16b quantities
@param w 16-b input value
@returns 16-bit reversed value
*/
inline uint16_t reverse16Bit(uint16_t w) {
return (reverseByte(w & 0xff) << 8) | (reverseByte(w >> 8));
}
#ifdef PICO_RP2350B
static constexpr int GPIOIRQREGS = 6;
#else
static constexpr int GPIOIRQREGS = 4;
#endif
/**
@brief Disables any GPIO interrupts registered before an SPI transaction begins
*/
void maskInterrupts() {
if (_usingIRQs.empty()) {
return;
}
noInterrupts(); // Avoid possible race conditions if IRQ comes in while main app is in middle of this
// Disable any IRQs that are being used for SPI
io_bank0_irq_ctrl_hw_t *irq_ctrl_base = get_core_num() ? &iobank0_hw->proc1_irq_ctrl : &iobank0_hw->proc0_irq_ctrl;
DEBUGSPI("SPI: IRQ masks before = %08x %08x %08x %08x %08x %08x\n", (unsigned)irq_ctrl_base->inte[0],
(unsigned)irq_ctrl_base->inte[1], (unsigned)irq_ctrl_base->inte[2], (unsigned)irq_ctrl_base->inte[3],
(GPIOIRQREGS > 4) ? (unsigned)irq_ctrl_base->inte[4] : 0, (GPIOIRQREGS > 5) ? (unsigned)irq_ctrl_base->inte[5] : 0);
for (auto entry : _usingIRQs) {
int gpio = entry.first;
// There is no gpio_get_irq, so manually twiddle the register
io_rw_32 *en_reg = &irq_ctrl_base->inte[gpio / 8];
uint32_t val = ((*en_reg) >> (4 * (gpio % 8))) & 0xf;
_usingIRQs.insert_or_assign(gpio, val);
DEBUGSPI("SPI: GPIO %d = %lu\n", gpio, val);
(*en_reg) ^= val << (4 * (gpio % 8));
}
DEBUGSPI("SPI: IRQ masks after = %08x %08x %08x %08x %08x %08x\n", (unsigned)irq_ctrl_base->inte[0],
(unsigned)irq_ctrl_base->inte[1], (unsigned)irq_ctrl_base->inte[2], (unsigned)irq_ctrl_base->inte[3],
(GPIOIRQREGS > 4) ? (unsigned)irq_ctrl_base->inte[4] : 0, (GPIOIRQREGS > 5) ? (unsigned)irq_ctrl_base->inte[5] : 0);
interrupts();
}
/**
@brief Restores GPIO interrupts masks after an SPI transaction completes
*/
void unmaskInterrupts() {
if (_usingIRQs.empty()) {
return;
}
noInterrupts(); // Avoid race condition so the GPIO IRQs won't come back until all state is restored
DEBUGSPI("SPI::endTransaction()\n");
// Re-enable IRQs
for (auto entry : _usingIRQs) {
int gpio = entry.first;
int mode = entry.second;
gpio_set_irq_enabled(gpio, mode, true);
}
io_bank0_irq_ctrl_hw_t *irq_ctrl_base = get_core_num() ? &iobank0_hw->proc1_irq_ctrl : &iobank0_hw->proc0_irq_ctrl;
(void) irq_ctrl_base;
DEBUGSPI("SPI: IRQ masks = %08x %08x %08x %08x %08x %08x\n", (unsigned)irq_ctrl_base->inte[0], (unsigned)irq_ctrl_base->inte[1],
(unsigned)irq_ctrl_base->inte[2], (unsigned)irq_ctrl_base->inte[3], (GPIOIRQREGS > 4) ? (unsigned)irq_ctrl_base->inte[4] : 0,
(GPIOIRQREGS > 5) ? (unsigned)irq_ctrl_base->inte[5] : 0);
interrupts();
}
/**
@brief Adds an interrupt to be masked during SPI transactions
@param interruptNumber GPIO number to mask off
*/
void usingInterrupt(int interruptNumber) {
_usingIRQs.insert({interruptNumber, 0});
}
/**
@brief Removes an interrupt from the to-be-masked list for SPI transactions
@param interruptNumber GPIO number to remove
*/
void notUsingInterrupt(int interruptNumber) {
_usingIRQs.erase(interruptNumber);
}
private:
std::map<int, int> _usingIRQs;
};
+1
Submodule libraries/SdFat added at 67e26476f1
@@ -0,0 +1,89 @@
/*
SD card basic file example with Software SPI
This example shows how to create and destroy an SD card file
The circuit:
SD card attached to Pico as follows:
** SCK - GPIO0
** CS - GPIO1
** MISO (AKA RX) - GPIO2
** MOSI (AKA TX) - GPIO3
created Nov 2010
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe
This example code is in the public domain.
*/
#include <SoftwareSPI.h>
const int _SCK = 0;
const int _CS = 1; // Must be SCK+1 for HW CS support
const int _MISO = 2;
const int _MOSI = 3;
SoftwareSPI softSPI(_SCK, _MISO, _MOSI, _CS);
#include <SD.h>
File myFile;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(115200);
do {
delay(100); // wait for serial port to connect. Needed for native USB port only
} while (!Serial);
if (_CS != _SCK + 1) {
Serial.printf("Error, CS (%d) must be defined as SCK (%d) + 1 \n", _CS, _SCK);
return;
}
Serial.print("Initializing SD card...");
bool sdInitialized = false;
sdInitialized = SD.begin(_CS, softSPI);
if (!sdInitialized) {
Serial.println("initialization failed!");
return;
}
Serial.println("initialization done.");
if (SD.exists("example.txt")) {
Serial.println("example.txt exists.");
} else {
Serial.println("example.txt doesn't exist.");
}
// open a new file and immediately close it:
Serial.println("Creating example.txt...");
myFile = SD.open("example.txt", FILE_WRITE);
myFile.close();
// Check to see if the file exists:
if (SD.exists("example.txt")) {
Serial.println("example.txt exists.");
} else {
Serial.println("example.txt doesn't exist.");
}
// delete the file:
Serial.println("Removing example.txt...");
SD.remove("example.txt");
if (SD.exists("example.txt")) {
Serial.println("example.txt exists.");
} else {
Serial.println("example.txt doesn't exist.");
}
}
void loop() {
// nothing happens after setup finishes.
}
@@ -0,0 +1,102 @@
/*
This sketch establishes a TCP connection to a "quote of the day" service.
It sends a "hello" message, and then prints received data.
*/
#include <W5500lwIP.h>
const char* host = "djxmmx.net";
const uint16_t port = 17;
#include <SoftwareSPI.h>
const int _SCK = 0; // Any pin allowed
const int _CS = 1; // Must be SCK+1 for HW CS support
const int _MISO = 28; // Note that MOSI and MISO don't need to be contiguous. Any pins allowed
const int _MOSI = 3; // Any pin not used elsewhere
const int _INT = 4; // W5500 IRQ line
SoftwareSPI softSPI(_SCK, _MISO, _MOSI, _CS);
Wiznet5500lwIP eth(_CS, softSPI, _INT);
void setup() {
Serial.begin(115200);
delay(5000);
if (_CS != _SCK + 1) {
Serial.printf("Error, CS (%d) must be defined as SCK (%d) + 1 \n", _CS, _SCK);
return;
}
Serial.println();
Serial.println();
Serial.println("Starting Ethernet port");
// Start the Ethernet port
if (!eth.begin()) {
Serial.println("No wired Ethernet hardware detected. Check pinouts, wiring.");
while (1) {
delay(1000);
}
}
while (!eth.connected()) {
Serial.print(".");
delay(500);
}
Serial.println("");
Serial.println("Ethernet connected");
Serial.println("IP address: ");
Serial.println(eth.localIP());
}
void loop() {
static bool wait = false;
Serial.print("connecting to ");
Serial.print(host);
Serial.print(':');
Serial.println(port);
// Use WiFiClient class to create TCP connections
WiFiClient client;
if (!client.connect(host, port)) {
Serial.println("connection failed");
delay(5000);
return;
}
// This will send a string to the server
Serial.println("sending data to server");
if (client.connected()) {
client.println("hello from RP2040");
}
// wait for data to be available
unsigned long timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 5000) {
Serial.println(">>> Client Timeout !");
client.stop();
delay(60000);
return;
}
}
// Read all the lines of the reply from server and print them to Serial
Serial.println("receiving from remote server");
// not testing 'client.connected()' since we do not need to send data here
while (client.available()) {
char ch = static_cast<char>(client.read());
Serial.print(ch);
}
// Close the connection
Serial.println();
Serial.println("closing connection");
client.stop();
if (wait) {
delay(300000); // execute once every 5 minutes, don't flood remote service
}
wait = true;
}

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