Compare commits

..
59 Commits
Author SHA1 Message Date
Earle F. Philhower, III 47c2cd2b0b Update version 2025-05-02 08:59:52 -07:00
Ahmed ARIFandAhmed ARIF 59614a99c8 optimize parity calculations in SerialPIO (#2932) (#2933)
use bit manipulation technique from http://www.graphics.stanford.edu/~seander/bithacks.html#ParityParallel for parity calculation

Co-authored-by: Ahmed ARIF <contact@eotics.com>
2025-05-01 14:06:52 -07:00
Earle F. Philhower, III 227d71ed18 Fix RP2350B SPI RX pin list (#2931)
Fixes #2930
2025-04-29 16:29:45 -07:00
Earle F. Philhower, III 5e74bbbbb2 Rewrite SerialPIO receive path, ensure proper edge (#2929)
The SerialPIO(SoftwareSerial) receive path was convoluted and required
a lot of work on the host to get the actual data out.  It also wasn't
always sampling on the proper edge leading to errors whenever clocks
or hold times shifted slightly.

Rewrite the SerialPIO RX path to explicitily wait for start bit,
pause 1/2 bit time, then idle for a full bit time for all bits.
Takes more PIO instruction memory but works flawlessly even with
mismatched clocks.

Tested with a loopback from HW UART to SW UART with a 5% clock
mismatch @ 19200 baud without reception errors, whereas the
original code would fail with less than a 0.5% variation.

Fixes #2928

````

SoftwareSerial s(15, -1);
void setup() {
  Serial1.setTX(0);
  Serial1.begin(19200 + 1920/2, SERIAL_8N1);
  s.begin(19200, SERIAL_8N1);
}

void loop() {
  Serial.println("---");
  Serial1.write("Had we but world enough and time", 32);
  uint32_t now = millis();
  while (millis() - now < 500) {
    while (s.available()) {
      auto c = s.read();
      Serial.printf("%02x '%c'\n", c, c);
    }
  }
}
````
2025-04-29 13:39:34 -07:00
Earle F. Philhower, III 8d58a9207f Update LittleFS and Adafruit USB libraries (#2919)
Only very minor changes to the submodules were noted.  Should not have
any effect on this core.
2025-04-18 18:00:56 -07:00
Earle F. Philhower, III bc5b2c24ff Fix rp2040.getCycleCount() from core1 (#2915)
Fixes #2914

There are 2 systick units, one per core.  Set up and start core1's
systick unit and track each core's epoch separately.

Document a method of preserving 100% user-only code on core1
and add a core1_disable_systick boolean flag that works like the
separate stack one.
2025-04-18 09:16:36 -07:00
Wai WengandKong Wai Weng 40b9d5b07e Add pin definitions for I2C1 on Cytron IRIV (#2916)
Co-authored-by: Kong Wai Weng <waiweng@cytron.io>
2025-04-18 08:59:23 -07:00
Earle F. Philhower, III 07ea22d877 Generate PWMAudio pacer frequencies for 176/276MHz (#2913)
Overclock settings changed, need to update the precalculated pacer
fractions for PWMAudio.
2025-04-17 08:21:14 -07:00
Earle F. Philhower, III 253e946dcb Update tools README.md 2025-04-17 07:04:26 -07:00
Earle F. Philhower, III 60d28d6c92 Add PIO.h header verification to CI (#2911)
* Add PIO.h header verification to CI

Ensure all PIO .pio.h headers match the .pio sources in the tree

* Install all tools for Style check

* Clean up mismatched PIO headers

No functional changes, but the PDM pdm.pio file did not init a data pin
while the pdm.pio.h (the one actually used in the core) did.  Correct to
match.

* No need for submodules in the style check
2025-04-16 14:56:31 -07:00
Earle F. Philhower, III e8bd9daa82 Update version 2025-04-16 13:22:14 -07:00
Earle F. Philhower, III 9747990c16 Fix remaining PICO_RP2350B reference (#2910)
Minor fix to #2898
2025-04-16 08:28:53 -07:00
6e48cffd62 add adafruit fruit jam and feather rp2350 adalogger (#2907)
* add new RP2350 Metro!

* lol

* fruity!

* Define HSTX pins on Adafruit boards with HSTX or DVI connectors

* fixname

* update rp2350b for fruit jam

* add rp2350 adalogger (#9)

adding rp2350 adalogger

* update psram in makeboards

* Update adafruit_fruitjam.json

---------

Co-authored-by: ladyada <limor@ladyada.net>
Co-authored-by: Jeff Epler <jepler@gmail.com>
2025-04-15 10:03:21 -07:00
Earle F. Philhower, III 9ac7892bd6 Update W55RP20 example for proper CS pin (#2906)
Fixes #2903
2025-04-15 08:17:47 -07:00
Earle F. Philhower, III 073094fe0e Update adc.rst for RP2350B 2025-04-15 07:39:17 -07:00
Earle F. Philhower, III 2a46bcfc0f Update contrib.rst
Update the PICO_RP2350A macro usage
2025-04-14 11:41:20 -07:00
Earle F. Philhower, III e05dd50d62 Convert to SDK RP2350A/B determination (#2898)
* Convert to SDK RP2350A/B determination

Fixes #2878

The SDK uses `defined(PICO_RP2350) && !PICO_RP2350A` to indicate an RP2350B
chip, not the define PICO_RP2350B.

Match the SDK's usage by converting from `defined(PICO_RP2350B)` to
`defined(PICO_RP2350) && !PICO_RP2350A` and update the chip variants
accordingly.

* Need to explicitly override PICO_RP2350A for all

The *SDK*'s board definition file hardcodes a PICO_RP2350A value for
all boards, but we use the same board file for both A and B variants.
Override the SDK board definition in the variant definition file.

* Generic RP2350 needs 2-stage PICO_RP2350A setting

Also ensure SDK board definition included before pins_arduino.h for
clearing up redefinition errors.

* Factor out undef PICO_RP2350A

* Update Arduino.h
2025-04-08 16:02:54 -07:00
Earle F. Philhower, III 54885d79e0 Add explicit using arduino::IPAddress to headers (#2894)
Fix issue with WiFiNINA includes.  Fixes #2887
2025-04-07 10:17:03 -07:00
Earle F. Philhower, III ecf2b2e39f Add WiFi region for Pico2W (#2872)
Fixes #2871
2025-03-19 08:47:12 -07:00
Earle F. Philhower, III 49397a7f3d Update version 2025-03-18 17:03:18 -07:00
Earle F. Philhower, III aabbba67ce Add some Doxygen documentation to core and libraries (#2780) 2025-03-18 17:00:44 -07:00
Earle F. Philhower, III 50b9ea99bd Add Olimex Pico2XL and Pico2XXL (#2868)
Fixes #2820
2025-03-18 16:40:51 -07:00
Earle F. Philhower, III beece2ec9d Add <1MB FS options for multi-size boards (#2867)
Boards with selectable flash sizes only had a 1MB FS as the smallest
option on 2MB boards.  For the normal Pico @ 2MB, though, we supported
filesystems down to 64KB.  Add those same options to the 2MB SKUs
of configurable boards.
2025-03-18 16:29:54 -07:00
Earle F. Philhower, III 1a8735700f Use flash size menu for Olimex boards (#2866)
Remove duplicated boards with just different flash sizes.  Use the flash
size menu to select 2 or 16 MB units.
2025-03-18 15:26:34 -07:00
Earle F. Philhower, III cc1af990b4 Add Pimoroni Servo2040 (#2865)
Fixes #2730 .  Untested, based off of schematics
2025-03-18 15:11:25 -07:00
Eris Fairbanks 0ec1dc6724 Bidirectional TDM Support (#2843)
* Initial commit.

* Works with AK4619 in TDM128 I2S compatibility mode set to rising BCLK.

* Works with I2S compat mode with BCLK mode set to 0 on AK4619.
2025-03-14 11:35:37 -07:00
Earle F. Philhower, III 15d1c6813a Redo UF2 discovery for Windows compatibility (#2853)
Windows Python doesn't seem to kill the worker Thread properly when the IDE
is exited, leading to a) multiple Python3 instances on a PC after many uses
and b) errors updating the core when it tries to re-install Python3 while
still having the older version's EXE loaded and in use.

When an exception happens on the input() call under Windows, it seems like it
can still leave a thread running.  Add one more flag, caught in a global
exception handler.

Works around https://github.com/arduino/arduino-cli/issues/2867
2025-03-14 10:08:37 -07:00
Earle F. Philhower, III cdf0a65d0f Fix invalid overclock speeds 175 and 275 MHz (#2855)
Fixes #2854

Change 175->176 and 275->276 in CPU speed menu to avoid panic when
attempting to set a clock that wasn't exactly possible.
2025-03-13 20:18:50 -07:00
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
178 changed files with 9193 additions and 2085 deletions
+10 -6
View File
@@ -10,7 +10,7 @@ jobs:
# Consistent style, spelling
astyle:
name: Spelling, Style, Boards, Package
name: Spelling, Style, Boards, Package, PIO
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@@ -21,11 +21,6 @@ jobs:
with:
skip: ./ArduinoCore-API,./libraries/ESP8266SdFat,./libraries/Adafruit_TinyUSB_Arduino,./libraries/LittleFS/lib,./tools/pyserial,./pico-sdk,./.github,./docs/i2s.rst,./cores/rp2040/api,./libraries/FreeRTOS,./tools/libbearssl/bearssl,./include,./libraries/WiFi/examples/BearSSL_Server,./ota/uzlib,./libraries/http-parser/lib,./libraries/WebServer/examples/HelloServerBearSSL/HelloServerBearSSL.ino,./libraries/HTTPUpdateServer/examples/SecureBearSSLUpdater/SecureBearSSLUpdater.ino,./.git,./libraries/FatFS/lib/fatfs,./libraries/FatFS/src/diskio.h,./libraries/FatFS/src/ff.cpp,./libraries/FatFS/src/ffconf.h,./libraries/FatFS/src/ffsystem.cpp,./libraries/FatFS/src/ff.h,./libraries/lwIP_WINC1500/src/driver,./libraries/lwIP_WINC1500/src/common,./libraries/lwIP_WINC1500/src/bus_wrapper,./libraries/lwIP_WINC1500/src/spi_flash
ignore_words_list: ser,dout,shiftIn,acount,froms
- name: Get submodules for following tests
run: git submodule update --init
- name: Check package references
run: |
./tests/ci/pkgrefs_test.sh
- name: Check boards.txt was not edited after makeboards.py
run: |
./tools/makeboards.py
@@ -38,6 +33,15 @@ jobs:
./tests/restyle.sh
# If anything changed, GIT should return an error and fail the test
git diff --exit-code
- name: Check compiled PIO files
run: |
(cd ./tools && ./get.py)
./tools/makepio.py
# If anything changed, GIT should return an error and fail the test
git diff -w --exit-code
- name: Check package references
run: |
./tests/ci/pkgrefs_test.sh
# Build all examples on linux (core and Arduino IDE)
build-linux:
+9 -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,16 +69,21 @@ 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
* nullbits Bit-C PRO
* Olimex Pico2XL
* Olimex Pico2XXL
* Olimex RP2040-Pico30
* Pimoroni PGA2040
* Pimoroni Pico Plus 2
* Pimoroni Pico Plus 2W
* Pimoroni Plasma2040
* Pimoroni Plasma2350
* Pimoroni Servo2040
* Pimoroni Tiny2040
* Pimoroni Tiny2350
* Pintronix PinMax
@@ -92,11 +98,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 +156,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
+4594 -1633
View File
File diff suppressed because it is too large Load Diff
+19 -2
View File
@@ -27,10 +27,23 @@
#include "RP2040Version.h"
#include "api/ArduinoAPI.h"
#include "api/itoa.h" // ARM toolchain doesn't provide itoa etc, provide them
#include <pico.h>
#undef PICO_RP2350A // Set in the RP2350 SDK boards file, overridden in the variant pins_arduino.h
#include <pins_arduino.h>
#include <hardware/gpio.h> // Required for the port*Register macros
#include "debug_internal.h"
// Chip sanity checking. SDK uses interesting way of separating 2350A from 2350B, see https://github.com/raspberrypi/pico-sdk/issues/2364
#if (!defined(PICO_RP2040) && !defined(PICO_RP2350)) || defined(PICO_RP2040) && defined(PICO_RP2350)
#error Invalid core definition. Either PICO_RP2040 or PICO_RP2350 must be defined.
#endif
#if defined(PICO_RP2350) && !defined(PICO_RP2350A)
#error Invalid RP2350 definition. Need to set PICO_RP2350A=0/1 for A/B variant
#endif
#if defined(PICO_RP2350B)
#error Do not define PICO_RP2350B. Use PICO_RP2350A=0 to indicate RP2350B. See the SDK for more details
#endif
// Try and make the best of the old Arduino abs() macro. When in C++, use
// the sane std::abs() call, but for C code use their macro since stdlib abs()
// is int but their macro "works" for everything (with potential side effects)
@@ -110,7 +123,7 @@ extern bool __isFreeRTOS;
#endif
#ifndef PGM_VOID_P
#define PGM_VOID_P void *
#define PGM_VOID_P const void *
#endif
#ifdef __cplusplus
@@ -152,10 +165,14 @@ constexpr uint64_t __bitset(const int (&a)[N], size_t i = 0U) {
#define PSRAM __attribute__((section("\".psram\"")))
// General GPIO/ADC layout info
#ifdef PICO_RP2350B
#if defined(PICO_RP2350) && !PICO_RP2350A
#define __GPIOCNT 48
#define __FIRSTANALOGGPIO 40
#else
#define __GPIOCNT 30
#define __FIRSTANALOGGPIO 26
#endif
#ifdef __cplusplus
using namespace arduino;
#endif
+11
View File
@@ -20,10 +20,21 @@
#pragma once
/**
@brief Wrapper class for polling the BOOTSEL button
*/
class __Bootsel {
public:
__Bootsel() { }
/**
@brief Get state of the BOOTSEL pin
@returns True if BOOTSEL pushed
*/
operator bool();
};
/**
@brief BOOTSEL accessor instance
*/
extern __Bootsel BOOTSEL;
+1
View File
@@ -1 +1,2 @@
#include "api/IPAddress.h"
using arduino::IPAddress;
+189 -19
View File
@@ -182,13 +182,16 @@ extern "C" void loop1() __attribute__((weak));
extern "C" bool core1_separate_stack;
extern "C" uint32_t* core1_separate_stack_address;
/**
@brief RP2040/RP2350 helper function for HW-specific features
*/
class RP2040 {
public:
RP2040() { /* noop */ }
~RP2040() { /* noop */ }
void begin() {
_epoch = 0;
void begin(int cpuid) {
_epoch[cpuid] = 0;
#if !defined(__riscv) && !defined(__PROFILE)
if (!__isFreeRTOS) {
// Enable SYSTICK exception
@@ -197,43 +200,70 @@ public:
systick_hw->rvr = 0x00FFFFFF;
} else {
#endif
int off = 0;
_ccountPgm = new PIOProgram(&ccount_program);
_ccountPgm->prepare(&_pio, &_sm, &off);
ccount_program_init(_pio, _sm, off);
pio_sm_set_enabled(_pio, _sm, true);
// Only start 1 instance of the PIO SM
if (cpuid == 0) {
int off = 0;
_ccountPgm = new PIOProgram(&ccount_program);
_ccountPgm->prepare(&_pio, &_sm, &off);
ccount_program_init(_pio, _sm, off);
pio_sm_set_enabled(_pio, _sm, true);
}
#if !defined(__riscv) && !defined(__PROFILE)
}
#endif
}
// Convert from microseconds to PIO clock cycles
/**
@brief Convert from microseconds to PIO clock cycles
@returns the PIO cycles for a given microsecond delay
*/
static int usToPIOCycles(int us) {
// Parenthesis needed to guarantee order of operations to avoid 32bit overflow
return (us * (clock_get_hz(clk_sys) / 1'000'000));
}
// Get current clock frequency
/**
@brief Gets the active CPU speed (may differ from F_CPU
@returns CPU frequency in Hz
*/
static int f_cpu() {
return clock_get_hz(clk_sys);
}
// Get current CPU core number
/**
@brief Get the core ID that is currently executing this code
@returns 0 for Core 0, 1 for Core 1
*/
static int cpuid() {
return sio_hw->cpuid;
}
// Get CPU cycle count. Needs to do magic to extens 24b HW to something longer
volatile uint64_t _epoch = 0;
/**
@brief CPU cycle counter epoch (24-bit cycle). For internal use
*/
volatile uint64_t _epoch[2] = {};
/**
@brief Get the count of CPU clock cycles since power on.
@details
The 32-bit count will overflow every 4 billion cycles, so consider using ``getCycleCount64`` for
longer measurements
@returns CPU clock cycles since power up
*/
inline uint32_t getCycleCount() {
#if !defined(__riscv) && !defined(__PROFILE)
// Get CPU cycle count. Needs to do magic to extend 24b HW to something longer
if (!__isFreeRTOS) {
uint32_t epoch;
uint32_t ctr;
do {
epoch = (uint32_t)_epoch;
epoch = (uint32_t)_epoch[sio_hw->cpuid];
ctr = systick_hw->cvr;
} while (epoch != (uint32_t)_epoch);
} while (epoch != (uint32_t)_epoch[sio_hw->cpuid]);
return epoch + (1 << 24) - ctr; /* CTR counts down from 1<<24-1 */
} else {
#endif
@@ -242,16 +272,20 @@ public:
}
#endif
}
/**
@brief Get the count of CPU clock cycles since power on as a 64-bit quantrity
@returns CPU clock cycles since power up
*/
inline uint64_t getCycleCount64() {
#if !defined(__riscv) && !defined(__PROFILE)
if (!__isFreeRTOS) {
uint64_t epoch;
uint64_t ctr;
do {
epoch = _epoch;
epoch = _epoch[sio_hw->cpuid];
ctr = systick_hw->cvr;
} while (epoch != _epoch);
} while (epoch != _epoch[sio_hw->cpuid]);
return epoch + (1LL << 24) - ctr;
} else {
#endif
@@ -261,23 +295,53 @@ public:
#endif
}
/**
@brief Gets total unused heap (dynamic memory)
@details
Note that the allocations of the size of the total free heap may fail due to fragmentation.
For example, ``getFreeHeap`` can report 100KB available, but an allocation of 90KB may fail
because there may not be a contiguous 90KB space available
@returns Free heap in bytes
*/
inline int getFreeHeap() {
return getTotalHeap() - getUsedHeap();
}
/**
@brief Gets total used heap (dynamic memory)
@returns Used heap in bytes
*/
inline int getUsedHeap() {
struct mallinfo m = mallinfo();
return m.uordblks;
}
/**
@brief Gets total heap (dynamic memory) compiled into the program
@returns Total heap size in bytes
*/
inline int getTotalHeap() {
return &__StackLimit - &__bss_end__;
}
/**
@brief On the RP2350, returns the amount of heap (dynamic memory) available in PSRAM
@returns Total free heap in PSRAM, or 0 if no PSRAM present
*/
inline int getFreePSRAMHeap() {
return getTotalPSRAMHeap() - getUsedPSRAMHeap();
}
/**
@brief On the RP2350, returns the total amount of PSRAM heap (dynamic memory) used
@returns Bytes used in PSRAM, or 0 if no PSRAM present
*/
inline int getUsedPSRAMHeap() {
#if defined(RP2350_PSRAM_CS)
extern size_t __psram_total_used();
@@ -287,6 +351,11 @@ public:
#endif
}
/**
@brief On the RP2350, gets total heap (dynamic memory) compiled into the program
@returns Total PSRAM heap size in bytes, or 0 if no PSRAM present
*/
inline int getTotalPSRAMHeap() {
#if defined(RP2350_PSRAM_CS)
extern size_t __psram_total_space();
@@ -296,6 +365,11 @@ public:
#endif
}
/**
@brief Gets the current stack pointer in a ARM/RISC-V safe manner
@returns Current SP
*/
inline uint32_t getStackPointer() {
uint32_t *sp;
#if defined(__riscv)
@@ -306,6 +380,14 @@ public:
return (uint32_t)sp;
}
/**
@brief Calculates approximately how much stack space is still available for the running core. Handles multiprocessing and separate stacks.
@details
Not valid in FreeRTOS. Use the FreeRTOS internal functions to access this information.
@returns Approximation of the amount of stack available for use on the specific core
*/
inline int getFreeStack() {
const unsigned int sp = getStackPointer();
uint32_t ref = 0x20040000;
@@ -319,6 +401,11 @@ public:
return sp - ref;
}
/**
@brief On the RP2350, gets the size of attached PSRAM
@returns PSRAM size in bytes, or 0 if no PSRAM present
*/
inline size_t getPSRAMSize() {
#if defined(RP2350_PSRAM_CS)
extern size_t __psram_size;
@@ -328,20 +415,48 @@ public:
#endif
}
/**
@brief Freezes the other core in a flash-write-safe state. Not generally needed by applications
@details
When the external flash chip is erasing or writing, the Pico cannot fetch instructions from it.
In this case both the core doing the writing and the other core (if active) need to run from a
routine that's contained in RAM. This call forces the other core into a tight, RAM-based loop
safe for this operation. When flash erase/write is completed, ``resumeOtherCore`` to return
it to operation.
Be sure to disable any interrupts or task switches before calling to avoid deadlocks.
If the second core is not started, this is a no-op.
*/
void idleOtherCore() {
fifo.idleOtherCore();
}
/**
@brief Resumes normal operation of the other core
*/
void resumeOtherCore() {
fifo.resumeOtherCore();
}
/**
@brief Hard resets the 2nd core (CORE1).
@details
Because core1 will restart with the heap and global variables not in the same state as
power-on, this call may not work as desired and a full CPU reset may be necessary in
certain cases.
*/
void restartCore1() {
multicore_reset_core1();
fifo.clear();
multicore_launch_core1(main1);
}
/**
@brief Warm-reboots the chip in normal mode
*/
void reboot() {
watchdog_reboot(0, 0, 10);
while (1) {
@@ -349,10 +464,16 @@ public:
}
}
/**
@brief Warm-reboots the chip in normal mode
*/
inline void restart() {
reboot();
}
/**
@brief Warm-reboots the chip into the USB bootloader mode
*/
inline void rebootToBootloader() {
reset_usb_boot(0, 0);
while (1) {
@@ -364,16 +485,32 @@ public:
static void enableDoubleResetBootloader();
#endif
/**
@brief Starts the hardware watchdog timer. The CPU will reset if the watchdog is not fed every delay_ms
@param [in] delay_ms Milliseconds without a wdt_reset before rebooting
*/
void wdt_begin(uint32_t delay_ms) {
watchdog_enable(delay_ms, 1);
}
/**
@brief Feeds the watchdog timer, resetting it for another delay_ms countdown
*/
void wdt_reset() {
watchdog_update();
}
/**
@brief Best-effort reasons for chip reset
*/
enum resetReason_t {UNKNOWN_RESET, PWRON_RESET, RUN_PIN_RESET, SOFT_RESET, WDT_RESET, DEBUG_RESET, GLITCH_RESET, BROWNOUT_RESET};
/**
@brief Attempts to determine the reason for the last chip reset. May not always be able to determine accurately
@returns Reason for reset
*/
resetReason_t getResetReason(void) {
io_rw_32 *WD_reason_reg = (io_rw_32 *)(WATCHDOG_BASE + WATCHDOG_REASON_OFFSET);
@@ -427,6 +564,10 @@ public:
return UNKNOWN_RESET;
}
/**
@brief Get unique ID string for the running board
@returns String with the unique board ID as determined by the SDK
*/
const char *getChipID() {
static char id[2 * PICO_UNIQUE_BOARD_ID_SIZE_BYTES + 1] = { 0 };
if (!id[0]) {
@@ -437,6 +578,17 @@ public:
#pragma GCC push_options
#pragma GCC optimize ("Os")
/**
@brief Perform a memcpy using a DMA engine for speed
@details
Uses the DMA to copy to and from RAM. Only works on 4-byte aligned, 4-byte multiple length
sources and destination (i.e. word-aligned, word-length). Falls back to normal memcpy otherwise.
@param [out] dest Memcpy destination, 4-byte aligned
@param [in] src Memcpy source, 4-byte aligned
@param [in] n Count in bytes to transfer (should be a multiple of 4 bytes)
*/
void *memcpyDMA(void *dest, const void *src, size_t n) {
// Allocate a DMA channel on 1st call, reuse it every call after
if (memcpyDMAChannel < 1) {
@@ -465,14 +617,32 @@ public:
}
#pragma GCC pop_options
// Multicore comms FIFO
/**
@brief Multicore communications FIFO
*/
_MFIFO fifo;
/**
@brief Return a 32-bit from the hardware random number generator
@returns Random value using appropriate hardware (RP2350 has true RNG, RP2040 has a less true RNG method)
*/
uint32_t hwrand32() {
return get_rand_32();
}
/**
@brief Determines if code is running on a Pico or a PicoW
@details
Code compiled for the RP2040 PicoW can run on the RP2040 Pico. This call lets an application
identify if the current device is really a Pico or PicoW and handle appropriately. For
the RP2350, this runtime detection is not available and the call returns whether it was
compiled for the CYW43 WiFi driver
@returns True if running on a PicoW board with CYW43 WiFi chip.
*/
bool isPicoW() {
#if !defined(PICO_CYW43_SUPPORTED)
return false;
@@ -499,8 +669,8 @@ public:
private:
static void _SystickHandler() {
rp2040._epoch += 1LL << 24;
static void __no_inline_not_in_flash_func(_SystickHandler)() {
rp2040._epoch[sio_hw->cpuid] += 1LL << 24;
}
PIO _pio;
int _sm;
+3 -3
View File
@@ -1,5 +1,5 @@
#pragma once
#define ARDUINO_PICO_MAJOR 4
#define ARDUINO_PICO_MINOR 4
#define ARDUINO_PICO_REVISION 2
#define ARDUINO_PICO_VERSION_STR "4.4.2"
#define ARDUINO_PICO_MINOR 5
#define ARDUINO_PICO_REVISION 3
#define ARDUINO_PICO_VERSION_STR "4.5.3"
+17 -3
View File
@@ -24,7 +24,9 @@
// Input/output will be handled by OpenOCD
// From https://developer.arm.com/documentation/dui0471/g/Semihosting/Semihosting-operations?lang=en
/**
@brief Semihosting host API opcodes, from https://developer.arm.com/documentation/dui0471/g/Semihosting/Semihosting-operations?lang=en
*/
typedef enum {
SEMIHOST_SYS_CLOSE = 0x02,
SEMIHOST_SYS_CLOCK = 0x10,
@@ -52,7 +54,13 @@ typedef enum {
#ifdef __arm__
// From https://github.com/ErichStyger/mcuoneclipse/blob/master/Examples/MCUXpresso/FRDM-K22F/FRDM-K22F_Semihosting/source/McuSemihost.c
/**
@brief Execute a semihosted request, from https://github.com/ErichStyger/mcuoneclipse/blob/master/Examples/MCUXpresso/FRDM-K22F/FRDM-K22F_Semihosting/source/McuSemihost.c
@param [in] reason Opcode to execute
@param [in] arg Any arguments for the opcode
@returns Result of operation
*/
static inline int __attribute__((always_inline)) Semihost(int reason, void *arg) {
int value;
__asm volatile(
@@ -69,7 +77,13 @@ static inline int __attribute__((always_inline)) Semihost(int reason, void *arg)
}
#else
// https://groups.google.com/a/groups.riscv.org/g/sw-dev/c/n-5VQ9PHZ4w/m/KbzH5t9MBgAJ
/**
@brief Execute a semihosted request, from https://groups.google.com/a/groups.riscv.org/g/sw-dev/c/n-5VQ9PHZ4w/m/KbzH5t9MBgAJ
@param [in] reason Opcode to execute
@param [in] argPack Any arguments for the opcode
@returns Result of operation
*/
static inline int __attribute__((always_inline)) Semihost(int reason, void *argPack) {
register int value asm("a0") = reason;
register void *ptr asm("a1") = argPack;
+11 -18
View File
@@ -68,13 +68,10 @@ static PIOProgram *_getRxProgram(int bits) {
}
// ------------------------------------------------------------------------
// TODO - this works, but there must be a faster/better way...
static int _parity(int bits, int data) {
int p = 0;
for (int b = 0; b < bits; b++) {
p ^= (data & (1 << b)) ? 1 : 0;
}
return p;
static int __not_in_flash_func(_parity)(int data) {
data ^= data >> 4;
data &= 0xf;
return (0x6996 >> data) & 1;
}
// We need to cache generated SerialPIOs so we can add data to them from
@@ -98,20 +95,16 @@ void __not_in_flash_func(SerialPIO::_handleIRQ)() {
}
while (!pio_sm_is_rx_fifo_empty(_rxPIO, _rxSM)) {
uint32_t decode = _rxPIO->rxf[_rxSM];
decode >>= 33 - _rxBits;
uint32_t val = 0;
for (int b = 0; b < _bits + 1; b++) {
val |= (decode & (1 << (b * 2))) ? 1 << b : 0;
}
uint32_t val = decode >> (32 - _rxBits - 1);
if (_parity == UART_PARITY_EVEN) {
int p = ::_parity(_bits, val);
int p = ::_parity(val);
int r = (val & (1 << _bits)) ? 1 : 0;
if (p != r) {
// TODO - parity error
continue;
}
} else if (_parity == UART_PARITY_ODD) {
int p = ::_parity(_bits, val);
int p = ::_parity(val);
int r = (val & (1 << _bits)) ? 1 : 0;
if (p == r) {
// TODO - parity error
@@ -234,7 +227,7 @@ void SerialPIO::begin(unsigned long baud, uint16_t config) {
_writer = 0;
_reader = 0;
_rxBits = 2 * (_bits + _stop + (_parity != UART_PARITY_NONE ? 1 : 0) + 1) - 1;
_rxBits = _bits + (_parity != UART_PARITY_NONE ? 1 : 0);
_rxPgm = _getRxProgram(_rxBits);
int off;
if (!_rxPgm->prepare(&_rxPIO, &_rxSM, &off, _rx, 1)) {
@@ -249,7 +242,7 @@ void SerialPIO::begin(unsigned long baud, uint16_t config) {
pio_sm_clear_fifos(_rxPIO, _rxSM); // Remove any existing data
// Put phase divider into OSR w/o using add'l program memory
pio_sm_put_blocking(_rxPIO, _rxSM, clock_get_hz(clk_sys) / (_baud * 2) - 7 /* insns in PIO halfbit loop */);
pio_sm_put_blocking(_rxPIO, _rxSM, clock_get_hz(clk_sys) / (_baud * 2) - 3);
pio_sm_exec(_rxPIO, _rxSM, pio_encode_pull(false, false));
// Join the TX FIFO to the RX one now that we don't need it
@@ -378,10 +371,10 @@ size_t SerialPIO::write(uint8_t c) {
if (_parity == UART_PARITY_NONE) {
val |= 7 << _bits; // Set 2 stop bits, the HW will only transmit the required number
} else if (_parity == UART_PARITY_EVEN) {
val |= ::_parity(_bits, c) << _bits;
val |= ::_parity(c) << _bits;
val |= 7 << (_bits + 1);
} else {
val |= (1 ^ ::_parity(_bits, c)) << _bits;
val |= (1 ^ ::_parity(c)) << _bits;
val |= 7 << (_bits + 1);
}
val <<= 1; // Start bit = low
+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 */
+54 -10
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_RP2350) && !PICO_RP2350A // 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_RP2350) && !PICO_RP2350A // 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 */,
@@ -86,7 +95,7 @@ bool SerialUART::setTX(pin_size_t pin) {
}
bool SerialUART::setRTS(pin_size_t pin) {
#ifdef PICO_RP2350B
#if defined(PICO_RP2350) && !PICO_RP2350A // RP2350B
constexpr uint64_t valid[2] = { __bitset({3, 15, 19, 31, 35, 47}) /* UART0 */,
__bitset({7, 11, 23, 27, 39, 43}) /* UART1 */
};
@@ -113,7 +122,7 @@ bool SerialUART::setRTS(pin_size_t pin) {
}
bool SerialUART::setCTS(pin_size_t pin) {
#ifdef PICO_RP2350B
#if defined(PICO_RP2350) && !PICO_RP2350A // RP2350B
constexpr uint64_t valid[2] = { __bitset({2, 14, 18, 30, 34, 46}) /* UART0 */,
__bitset({6, 10, 22, 26, 38, 42}) /* UART1 */
};
@@ -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) && !PICO_RP2350A
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;
+29 -1
View File
@@ -22,9 +22,18 @@
#include "SerialPIO.h"
/**
@brief Implements a UART port using PIO for input and output
*/
class SoftwareSerial : public SerialPIO {
public:
// Note the rx/tx pins are swapped in PIO vs SWSerial
/**
@brief Constructs a PIO-based UART
@param [in] rx GPIO for RX pin or -1 for transmit-only
@param [in] tx GPIO for TX pin or -1 for receive-only
@param [in] invert True to invert the receive and transmit lines
*/
SoftwareSerial(pin_size_t rx, pin_size_t tx, bool invert = false) : SerialPIO(tx, rx) {
_invert = invert;
}
@@ -32,18 +41,37 @@ public:
~SoftwareSerial() {
}
/**
@brief Starts the PIO UART
@param [in] baud Serial bit rate
*/
virtual void begin(unsigned long baud = 115200) override {
begin(baud, SERIAL_8N1);
};
/**
@brief Starts the PIO UART
@param [in] baud Serial bit rate
@param [in] config Start/Stop/Len configuration (i.e. SERIAL_8N1 or SERIAL_7E2)
*/
void begin(unsigned long baud, uint16_t config) override {
setInvertTX(_invert);
setInvertRX(_invert);
SerialPIO::begin(baud, config);
}
/**
@brief No-op on this core
*/
void listen() { /* noop */ }
/**
@brief No-op on this core
@returns True always
*/
bool isListening() {
return true;
}
+43 -2
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" {
@@ -47,9 +51,14 @@ void initVariant() { }
// Optional 2nd core setup and loop
bool core1_separate_stack __attribute__((weak)) = false;
bool core1_disable_systick __attribute__((weak)) = false;
extern void setup1() __attribute__((weak));
extern void loop1() __attribute__((weak));
extern "C" void main1() {
if (!core1_disable_systick) {
// Don't install the SYSTICK exception handler. rp2040.getCycleCount will not work properly on core1
rp2040.begin(1);
}
rp2040.fifo.registerCore();
if (setup1) {
setup1();
@@ -80,9 +89,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;
@@ -92,7 +133,7 @@ extern "C" int main() {
_REENT_INIT_PTR(_impure_ptr1);
}
rp2040.begin();
rp2040.begin(0);
initVariant();
+14 -9
View File
@@ -73,20 +73,25 @@ static inline void pio_tx_program_init(PIO pio, uint sm, uint offset, uint pin_t
; IN pin 0 and JMP pin are both mapped to the GPIO used as UART RX.
start:
set x, 18 ; Preload bit counter...we'll shift in the start bit and stop bit, and each bit will be double-recorded (to be fixed by RP2040 code)
set x, 18 ; Preload bit counter...overwritten by the app
wait 0 pin 0 ; Stall until start bit is asserted
bitloop:
; Delay until 1/2 way into the bit time
mov y, osr
wait_half:
jmp y-- wait_half
wait_mid_start:
jmp y-- wait_mid_start
; Read in the bit
in pins, 1 ; Shift data bit into ISR
jmp x-- bitloop ; Loop all bits
push ; Stuff it and wait for next start
bitloop:
mov y, osr
bitloop1:
jmp y-- bitloop1
mov y, osr
bitloop2:
jmp y-- bitloop2
in pins, 1
jmp x-- bitloop
push
% c-sdk {
static inline void pio_rx_program_init(PIO pio, uint sm, uint offset, uint pin) {
+9 -5
View File
@@ -71,7 +71,7 @@ static inline void pio_tx_program_init(PIO pio, uint sm, uint offset, uint pin_t
// ------ //
#define pio_rx_wrap_target 0
#define pio_rx_wrap 6
#define pio_rx_wrap 10
#define pio_rx_pio_version 0
static const uint16_t pio_rx_program_instructions[] = {
@@ -80,16 +80,20 @@ static const uint16_t pio_rx_program_instructions[] = {
0x2020, // 1: wait 0 pin, 0
0xa047, // 2: mov y, osr
0x0083, // 3: jmp y--, 3
0x4001, // 4: in pins, 1
0x0042, // 5: jmp x--, 2
0x8020, // 6: push block
0xa047, // 4: mov y, osr
0x0085, // 5: jmp y--, 5
0xa047, // 6: mov y, osr
0x0087, // 7: jmp y--, 7
0x4001, // 8: in pins, 1
0x0044, // 9: jmp x--, 4
0x8020, // 10: push block
// .wrap
};
#if !PICO_NO_HARDWARE
static const struct pio_program pio_rx_program = {
.instructions = pio_rx_program_instructions,
.length = 7,
.length = 11,
.origin = -1,
.pio_version = 0,
#if PICO_PIO_VERSION > 0
+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);
+3 -3
View File
@@ -17,14 +17,14 @@
#define tone2_pio_version 0
static const uint16_t tone2_program_instructions[] = {
// .wrap_target
// .wrap_target
0x8080, // 0: pull noblock
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
// .wrap
// .wrap
};
#if !PICO_NO_HARDWARE
@@ -32,7 +32,7 @@ static const struct pio_program tone2_program = {
.instructions = tone2_program_instructions,
.length = 6,
.origin = -1,
.pio_version = tone2_pio_version,
.pio_version = 0,
#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);
+7 -6
View File
@@ -12,9 +12,9 @@ need to be periodically sampled to be read by applications, easily, such as:
* Light dependent resistors (LDR), etc.
Up to 4 analog samples can be recorded by the hardware (``A0`` ... ``A3``), and all
recording is done at 16-bit levels (but be aware that the ADC in the Pico will only
ever return values between 0...4095).
Up to 4 (or 8 in the case of the RP2350B) analog samples can be recorded by the
hardware (``A0`` ... ``A3``), and all recording is done at 16-bit levels (but be
aware that the ADC in the Pico will only ever return values between 0...4095).
The interface for the ``ADCInput`` device is very similar to the ``I2S`` input
device, and most code can be ported simply by instantiating a ``ADCInput``
@@ -26,11 +26,12 @@ allowed while in use.
ADC Input API
-------------
ADCInput(pin0 [, pin1, pin2, pin3])
ADCInput(pin0 [, pin1, pin2, pin3[, pin4, pin5, pin6, pin7])
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Creates an ADC input object which will record the pins specified in the code.
Only pins ``A0`` ... ``A3`` can be used, and they must be specified in increasing
order (i.e. ``ADCInput(A0, A1);`` is valid, but ``ADCInput(A1, A0)`` is not.
Only pins ``A0`` ... ``A3`` (``A7`` on RP2350B) can be used, and they must be
specified in increasing order (i.e. ``ADCInput(A0, A1);`` is valid,
but ``ADCInput(A1, A0)`` is not.
bool setBuffers(size_t buffers, size_t bufferWords)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+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.2'
version = u'4.5.3'
# The full version, including alpha/beta/rc tags.
release = u'4.4.2'
release = u'4.5.3'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
+2 -2
View File
@@ -112,7 +112,7 @@ For only RP2350A variants (using the compile options, not the onboard ID registe
.. code:: cpp
#if defined(PICO_RP2350) && !defined(PICO_RP2350B)
#if defined(PICO_RP2350A) && PICO_RP2350A
...RP2350A only code...
#endif
@@ -121,7 +121,7 @@ and not the chip ID register):
.. code:: cpp
#if defined(PICO_RP2350B)
#if defined(PICO_RP2350A) && !PICO_RP2350A
...48-GPIO version code here
#endif
+34 -2
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)
@@ -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.
+22
View File
@@ -16,6 +16,25 @@ not necessarily simultaneously!).
See the ``Multicore.ino`` example in the ``rp2040`` example directory for a
quick introduction.
Core 1 Operation
----------------
By default, core1 (the second core) has no non-user written code running on it.
No interrupts, exceptions, or other background processing is done (but the core
is still subject to hardware stalls due to on-die memory resource conflicts).
When flash erase or write operations (i.e. ``LittleFS`` or ``EEPROM``) are called
from core0, core1 **will** be paused.
If ``rp2040.getCycleCount`` is needed to operate on the second core, then a
periodic (once ever 16M clock cycles) ``SYSTICK`` exception will happen behind
the scenes. For extremely time-critical operations this may not be desirable
and can be disabled by defining a new ``bool`` variable to ``true`` anywhere
in your sketch:
.. code:: cpp
bool core1_disable_systick = true;
Stack Sizes
-----------
@@ -67,6 +86,9 @@ void rp2040.restartCore1()
~~~~~~~~~~~~~~~~~~~~~~~~~~
Hard resets Core1 from Core 0 and restarts its operation from ``setup1()``.
This can cause unpredictable behavior because globals and the heap
are shared between cores and not re-initialized with this call. Use with
extreme caution.
Communicating Between Cores
---------------------------
+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
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
@@ -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.
+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.
+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
+2 -2
View File
@@ -49,7 +49,7 @@ bool ADCInput::setBuffers(size_t buffers, size_t bufferWords) {
int ADCInput::_mask(pin_size_t p) {
switch (p) {
#if !defined(PICO_RP2350B)
#if defined(PICO_RP2350) && !PICO_RP2350A // RP2350B
case 26: return 1;
case 27: return 2;
case 28: return 4;
@@ -106,7 +106,7 @@ bool ADCInput::begin() {
// Set up the GPIOs to go to ADC
adc_init();
int cnt = 0;
#if !defined(PICO_RP2350B)
#if defined(PICO_RP2350) && !PICO_RP2350A // RP2350B
int startpin = 26;
int maxpin = 29;
#else
@@ -204,7 +204,6 @@ size_t AudioBufferManager::write(const uint32_t *v, size_t words, bool sync) {
/* noop busy wait */
}
}
}
size_t availToWriteThisBuff = _wordsPerBuffer - _userOff;
size_t toWrite = std::min(availToWriteThisBuff, words);
@@ -245,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;
@@ -36,6 +36,7 @@ public:
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.
*/
+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 -59
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);
}
}
@@ -144,7 +170,7 @@ bool I2S::setMCLKmult(int mult) {
}
bool I2S::setLSBJFormat() {
if (_running || !_isOutput) {
if (_running || !_isOutput || _isInput) {
return false;
}
_isLSBJ = true;
@@ -168,7 +194,7 @@ bool I2S::setTDMChannels(int channels) {
}
bool I2S::swapClocks() {
if (_running || !_isOutput) {
if (_running) {
return false;
}
_swapClocks = true;
@@ -177,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);
}
}
}
@@ -229,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 ? (_isTDM ? &pio_tdm_inout_program : &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 ? (_isTDM ? &pio_tdm_inout_swap_program : &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;
@@ -242,7 +277,13 @@ bool I2S::begin() {
return false;
}
if (_isOutput) {
if (_isTDM) {
if (_isInput) {
if (_isTDM) {
pio_tdm_inout_program_init(_pio, _sm, off, _pinDIN, _pinDOUT, _pinBCLK, _bps, _swapClocks, _tdmChannels);
} else {
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);
@@ -250,7 +291,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) {
@@ -266,19 +307,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);
@@ -294,8 +355,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;
}
@@ -303,12 +366,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;
@@ -316,7 +379,7 @@ int I2S::available() {
}
int I2S::read() {
if (!_running || _isOutput) {
if (!_running || !_isInput) {
return 0;
}
@@ -352,7 +415,7 @@ int I2S::read() {
}
int I2S::peek() {
if (!_running || _isOutput) {
if (!_running || !_isInput) {
return 0;
}
if (!_hasPeeked) {
@@ -364,7 +427,12 @@ int I2S::peek() {
void I2S::flush() {
if (_running) {
_arb->flush();
if (_isOutput) {
_arbOutput->flush();
}
if (_isInput) {
_arbInput->flush();
}
}
}
@@ -408,7 +476,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) {
@@ -441,14 +509,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) {
@@ -465,7 +533,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;
@@ -476,7 +544,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);
@@ -487,7 +555,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);
@@ -495,17 +563,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;
}
return _arb->write((const uint32_t *)buffer, size / sizeof(uint32_t), false);
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();
}
+32 -9
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,13 +168,18 @@ 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;
+154
View File
@@ -104,6 +104,41 @@ lastbit:
; Loop back to the beginning
.program pio_tdm_inout
.side_set 2 ; 0 = bclk, 1 = wclk
; The C code should place (number of bits * channels - 1) in Y and update SHIFTCTRL
; to be 32 (as per the TDM specs)
; +----- WCLK
; |+---- BCLK
mov x, y side 0b01 [1]
bitloop:
out pins, 1 side 0b00 ; Output changes on falling edge
in pins, 1 side 0b00 ; Sample input on falling edge
jmp x-- bitloop side 0b11 [1] ; Last bit toggles WCLK to mark frame boundary
lastbit:
in pins, 1 side 0b10
out pins, 1 side 0b10
; Loop back to the beginning
.program pio_tdm_inout_swap
.side_set 2 ; 0 = bclk, 1 = wclk
; The C code should place (number of bits * channels - 1) in Y and update SHIFTCTRL
; to be 32 (as per the TDM specs)
; +----- WCLK
; |+---- BCLK
mov x, y side 0b10 [1]
bitloop:
out pins, 1 side 0b00 ; Output changes on falling edge
in pins, 1 side 0b00 ; Sample input on falling edge
jmp x-- bitloop side 0b11 [1] ; Last bit toggles WCLK to mark frame boundary
lastbit:
in pins, 1 side 0b01
out pins, 1 side 0b01
; Loop back to the beginning
.program pio_lsbj_out
.side_set 2 ; 0 = bclk, 1=wclk
@@ -194,6 +229,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 {
@@ -261,6 +348,42 @@ static inline void pio_tdm_out_program_init(PIO pio, uint sm, uint offset, uint
pio_sm_exec(pio, sm, pio_encode_out(pio_osr, 32));
}
static inline void pio_tdm_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, uint channels) {
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 c = swap ? pio_tdm_inout_swap_program_get_default_config(offset) : pio_tdm_inout_program_get_default_config(offset);
sm_config_set_in_pins(&c, data_in_pin);
sm_config_set_out_pins(&c, data_out_pin, 1);
sm_config_set_sideset_pins(&c, clock_pin_base);
sm_config_set_in_shift(&c, false, true, 32);
sm_config_set_out_shift(&c, false, true, 32);
sm_config_set_fifo_join(&c, PIO_FIFO_JOIN_NONE);
pio_sm_init(pio, sm, offset, &c);
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);
// Initialize PIO state for TDM
// Can't set constant > 31, so push and pop/mov if needed
if (bits * channels - 1 > 31) {
pio_sm_put_blocking(pio, sm, bits * channels - 2);
pio_sm_exec(pio, sm, pio_encode_pull(false, false));
pio_sm_exec(pio, sm, pio_encode_mov(pio_y, pio_osr));
} else {
pio_sm_exec(pio, sm, pio_encode_set(pio_y, bits * channels - 2));
}
// Need to make OSR believe there's nothing left to shift out
pio_sm_exec(pio, sm, pio_encode_out(pio_osr, 32));
}
static inline void pio_lsbj_out_program_init(PIO pio, uint sm, uint offset, uint data_pin, uint clock_pin_base, uint bits, bool swap) {
pio_gpio_init(pio, data_pin);
@@ -314,4 +437,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
}
%}
+218
View File
@@ -193,6 +193,82 @@ static inline pio_sm_config pio_tdm_out_swap_program_get_default_config(uint off
}
#endif
// ------------- //
// pio_tdm_inout //
// ------------- //
#define pio_tdm_inout_wrap_target 0
#define pio_tdm_inout_wrap 5
#define pio_tdm_inout_pio_version 0
static const uint16_t pio_tdm_inout_program_instructions[] = {
// .wrap_target
0xa922, // 0: mov x, y side 1 [1]
0x6001, // 1: out pins, 1 side 0
0x4001, // 2: in pins, 1 side 0
0x1941, // 3: jmp x--, 1 side 3 [1]
0x5001, // 4: in pins, 1 side 2
0x7001, // 5: out pins, 1 side 2
// .wrap
};
#if !PICO_NO_HARDWARE
static const struct pio_program pio_tdm_inout_program = {
.instructions = pio_tdm_inout_program_instructions,
.length = 6,
.origin = -1,
.pio_version = 0,
#if PICO_PIO_VERSION > 0
.used_gpio_ranges = 0x0
#endif
};
static inline pio_sm_config pio_tdm_inout_program_get_default_config(uint offset) {
pio_sm_config c = pio_get_default_sm_config();
sm_config_set_wrap(&c, offset + pio_tdm_inout_wrap_target, offset + pio_tdm_inout_wrap);
sm_config_set_sideset(&c, 2, false, false);
return c;
}
#endif
// ------------------ //
// pio_tdm_inout_swap //
// ------------------ //
#define pio_tdm_inout_swap_wrap_target 0
#define pio_tdm_inout_swap_wrap 5
#define pio_tdm_inout_swap_pio_version 0
static const uint16_t pio_tdm_inout_swap_program_instructions[] = {
// .wrap_target
0xb122, // 0: mov x, y side 2 [1]
0x6001, // 1: out pins, 1 side 0
0x4001, // 2: in pins, 1 side 0
0x1941, // 3: jmp x--, 1 side 3 [1]
0x4801, // 4: in pins, 1 side 1
0x6801, // 5: out pins, 1 side 1
// .wrap
};
#if !PICO_NO_HARDWARE
static const struct pio_program pio_tdm_inout_swap_program = {
.instructions = pio_tdm_inout_swap_program_instructions,
.length = 6,
.origin = -1,
.pio_version = 0,
#if PICO_PIO_VERSION > 0
.used_gpio_ranges = 0x0
#endif
};
static inline pio_sm_config pio_tdm_inout_swap_program_get_default_config(uint offset) {
pio_sm_config c = pio_get_default_sm_config();
sm_config_set_wrap(&c, offset + pio_tdm_inout_swap_wrap_target, offset + pio_tdm_inout_swap_wrap);
sm_config_set_sideset(&c, 2, false, false);
return c;
}
#endif
// ------------ //
// pio_lsbj_out //
// ------------ //
@@ -351,6 +427,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);
@@ -402,6 +566,36 @@ static inline void pio_tdm_out_program_init(PIO pio, uint sm, uint offset, uint
// Need to make OSR believe there's nothing left to shift out, or the 1st word will be the count we just passed in, not a sample
pio_sm_exec(pio, sm, pio_encode_out(pio_osr, 32));
}
static inline void pio_tdm_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, uint channels) {
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 c = swap ? pio_tdm_inout_swap_program_get_default_config(offset) : pio_tdm_inout_program_get_default_config(offset);
sm_config_set_in_pins(&c, data_in_pin);
sm_config_set_out_pins(&c, data_out_pin, 1);
sm_config_set_sideset_pins(&c, clock_pin_base);
sm_config_set_in_shift(&c, false, true, 32);
sm_config_set_out_shift(&c, false, true, 32);
sm_config_set_fifo_join(&c, PIO_FIFO_JOIN_NONE);
pio_sm_init(pio, sm, offset, &c);
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);
// Initialize PIO state for TDM
// Can't set constant > 31, so push and pop/mov if needed
if (bits * channels - 1 > 31) {
pio_sm_put_blocking(pio, sm, bits * channels - 2);
pio_sm_exec(pio, sm, pio_encode_pull(false, false));
pio_sm_exec(pio, sm, pio_encode_mov(pio_y, pio_osr));
} else {
pio_sm_exec(pio, sm, pio_encode_set(pio_y, bits * channels - 2));
}
// Need to make OSR believe there's nothing left to shift out
pio_sm_exec(pio, sm, pio_encode_out(pio_osr, 32));
}
static inline void pio_lsbj_out_program_init(PIO pio, uint sm, uint offset, uint data_pin, uint clock_pin_base, uint bits, bool swap) {
pio_gpio_init(pio, data_pin);
pio_gpio_init(pio, clock_pin_base);
@@ -441,6 +635,30 @@ 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);
+1 -1
View File
@@ -31,7 +31,7 @@ static inline void pdm_pio_program_init(PIO pio, uint sm, uint offset, uint clkP
pio_sm_set_consecutive_pindirs(pio, sm, dataPin, 1, false);
pio_sm_set_consecutive_pindirs(pio, sm, clkPin, 1, true);
pio_sm_set_pins_with_mask(pio, sm, 0, (1u << clkPin) );
//pio_gpio_init(pio, dataPin);
pio_gpio_init(pio, dataPin);
pio_gpio_init(pio, clkPin);
pio_sm_init(pio, sm, offset, &c);
+4 -4
View File
@@ -18,8 +18,8 @@ static const PWMPacerPrecalc __PWMAudio_pacer[] = {{8000, 16000, 1}, {11025, 116
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 == 176000000
static const PWMPacerPrecalc __PWMAudio_pacer[] = {{8000, 22000, 1}, {11025, 63855, 4}, {16000, 11000, 1}, {22050, 55873, 7}, {32000, 5500, 1}, {44100, 55873, 14}, {48000, 11000, 3}, {88200, 55873, 28}, {96000, 5500, 3}, {176400, 55873, 56}, {192000, 2750, 3}};
#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
@@ -28,8 +28,8 @@ static const PWMPacerPrecalc __PWMAudio_pacer[] = {{8000, 28125, 1}, {11025, 204
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 == 276000000
static const PWMPacerPrecalc __PWMAudio_pacer[] = {{8000, 34500, 1}, {11025, 25034, 1}, {16000, 17250, 1}, {22050, 12517, 1}, {32000, 8625, 1}, {44100, 12517, 2}, {48000, 5750, 1}, {88200, 12517, 4}, {96000, 2875, 1}, {176400, 12517, 8}, {192000, 2875, 2}};
#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
+19 -91
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;
@@ -335,8 +263,8 @@ void SPIClassRP2040::abortAsync() {
bool SPIClassRP2040::setRX(pin_size_t pin) {
#ifdef PICO_RP2350B
constexpr uint64_t valid[2] = { __bitset({0, 4, 16, 20, 32, 26}) /* SPI0 */,
#if defined(PICO_RP2350) && !PICO_RP2350A // RP2350B
constexpr uint64_t valid[2] = { __bitset({0, 4, 16, 20, 32, 36}) /* SPI0 */,
__bitset({8, 12, 24, 28, 40, 44}) /* SPI1 */
};
#else
@@ -362,7 +290,7 @@ bool SPIClassRP2040::setRX(pin_size_t pin) {
}
bool SPIClassRP2040::setCS(pin_size_t pin) {
#ifdef PICO_RP2350B
#if defined(PICO_RP2350) && !PICO_RP2350A // RP2350B
constexpr uint64_t valid[2] = { __bitset({1, 5, 17, 21, 33, 37}) /* SPI0 */,
__bitset({9, 13, 25, 29, 41, 45}) /* SPI1 */
};
@@ -389,7 +317,7 @@ bool SPIClassRP2040::setCS(pin_size_t pin) {
}
bool SPIClassRP2040::setSCK(pin_size_t pin) {
#ifdef PICO_RP2350B
#if defined(PICO_RP2350) && !PICO_RP2350A // RP2350B
constexpr uint64_t valid[2] = { __bitset({2, 6, 18, 22, 34, 38}) /* SPI0 */,
__bitset({10, 14, 26, 30, 42, 46}) /* SPI1 */
};
@@ -416,7 +344,7 @@ bool SPIClassRP2040::setSCK(pin_size_t pin) {
}
bool SPIClassRP2040::setTX(pin_size_t pin) {
#ifdef PICO_RP2350B
#if defined(PICO_RP2350) && !PICO_RP2350A // RP2350B
constexpr uint64_t valid[2] = { __bitset({3, 7, 19, 23, 35, 39}) /* SPI0 */,
__bitset({11, 15, 27, 31, 43, 47}) /* SPI1 */
};
+171 -21
View File
@@ -23,72 +23,223 @@
#include <Arduino.h>
#include <api/HardwareSPI.h>
#include <hardware/spi.h>
#include <map>
#include "SPIHelper.h"
/**
@brief Implements a hardware-based SPI interface using the Pico's SPI blocks
*/
class SPIClassRP2040 : public arduino::HardwareSPI {
public:
/**
@brief Create a PIO-based SPI instance, pins can be changed before begin() call
@param [in] spi SPI hardware instance (spi0/spi1)
@param [in] rx MISO GPIO
@param [in] cs CS GPIO
@param [in] sck SCK GPIO
@param [in] tx MOSI GPIO
*/
SPIClassRP2040(spi_inst_t *spi, pin_size_t rx, pin_size_t cs, pin_size_t sck, pin_size_t tx);
// Send or receive 8- or 16-bit data. Returns read back value
/**
@brief Send an 8-bit byte of data and return read-back 8-bit value
@param [in] data Data to send
@returns Read back byte from SPI interface
*/
byte transfer(uint8_t data) override;
/**
@brief Send a 16-bit quantity over SPI and return read-back 16-bit value under a single CS assertion
@param [in] data Data to send
@returns Read back 16-bit quantity
*/
uint16_t transfer16(uint16_t data) override;
// Sends buffer in 8 bit chunks. Overwrites buffer with read data
/**
@brief Sends buffer in 8 bit chunks under a single CS. Overwrites buffer with read data
@param [in, out] buf Buffer to read and write back into
@param [in] count Number of bytes to transmit/read
*/
void transfer(void *buf, size_t count) override;
// Sends one buffer and receives into another, much faster! can set rx or txbuf to nullptr
/**
@brief Sends one buffer and receives into another under a single CS. Can set rx or txbuf to nullptr
@param [in] txbuf Buffer to transmit or nullptr to send 0s
@param [out] rxbuf Buffer to read back into or nullptr to ignore returned data
@param [in] count Numbner of bytes to transmit/receive
*/
void transfer(const void *txbuf, void *rxbuf, size_t count) override;
// DMA/asynchronous transfers. Do not combime with synchronous runs or bad stuff will happen
// All buffers must be valid for entire DMA and not touched until `finished()` returns true.
/**
@brief Perform a transfer() using DMA in the background. Returns immediately, need to check for completion
@details
Do not combine asynchronous and synchronous transfers. All buffers must be valid until
the transfer reports that it is completed (``finished`` returns true).
@param [in] send Buffer to transmit, must remain valid through entire operation
@param [out] recv Buffer to receive, must remain valid through entire operation
@param [in] bytes Number of bytes to transfer under single CS
*/
bool transferAsync(const void *send, void *recv, size_t bytes);
bool finishedAsync(); // Call to check if the async operations is completed and the buffer can be reused/read
void abortAsync(); // Cancel an outstanding async operation
/**
@brief Call to check if the async operations is completed and the buffer can be reused/read
@returns True if the asynchronous SPI operation has completed and ``recv`` buffer is valid
*/
bool finishedAsync();
/**
@brief Aborts an ongoing asynchronous SPI operation, if one is still operating
@details
Not normally needed, but in the case where a large, long SPI operation needs to be aborted
this call allows an application to safely stop the SPI and dispose of the ``recv`` and
``send`` buffers
*/
void abortAsync();
// Call before/after every complete transaction
/**
@brief Begin an SPI transaction, sets SPI speed and masks necessary interrupts
@param [in] SPISettings SPI configuration parameters, including the clock speed
*/
void beginTransaction(SPISettings settings) override;
/**
@brief Ends an SPI transaction, unmasks and masked GPIO interrupts
*/
void endTransaction(void) override;
// Assign pins, call before begin()
/**
@brief Sets the MISO(RX) pin. Call before begin()
@param [in] pin The GPIO number to assign to
@returns True on success
*/
bool setRX(pin_size_t pin);
/**
@brief Sets the MISO(RX) pin. Call before begin()
@param [in] pin The GPIO number to assign to
@returns True on success
*/
inline bool setMISO(pin_size_t pin) {
return setRX(pin);
}
/**
@brief Sets the CS pin. Call before begin()
@param [in] pin The GPIO number to assign to
@returns True on success
*/
bool setCS(pin_size_t pin);
/**
@brief Sets the SCK pin. Call before begin()
@param [in] pin The GPIO number to assign to
@returns True on success
*/
bool setSCK(pin_size_t pin);
/**
@brief Sets the MOSI(TX) pin. Call before begin()
@param [in] pin The GPIO number to assign to
@returns True on success
*/
bool setTX(pin_size_t pin);
/**
@brief Sets the MOSI(TX) pin. Call before begin()
@param [in] pin The GPIO number to assign to
@returns True on success
*/
inline bool setMOSI(pin_size_t pin) {
return setTX(pin);
}
// Call once to init/deinit SPI class, select pins, etc.
/**
@brief Call once to init/deinit SPI class, select pins, etc.
*/
virtual void begin() override {
begin(false);
}
/**
@brief Call once to init/deinit SPI class, select pins, etc.
@param [in] hwCS Pass in true to enable HW-controlled CS. Otherwise application needs to assert/deassert CS.
*/
void begin(bool hwCS);
/**
@brief Call to deinit and disable the SPI interface.
*/
void end() override;
// Deprecated - do not use!
/**
@brief Deprecated, do not use
@param [in] order Deprecated
*/
void setBitOrder(BitOrder order) __attribute__((deprecated));
/**
@brief Deprecated, do not use
@param [in] order Deprecated
*/
void setDataMode(uint8_t uc_mode) __attribute__((deprecated));
/**
@brief Deprecated, do not use
@param [in] order Deprecated
*/
void setClockDivider(uint8_t uc_div) __attribute__((deprecated));
// List of GPIO IRQs to disable during a transaction
/**
@brief Ensure specific GPIO interrupt is disabled during and SPI transaction to protect against re-entrancy. Multiple GPIOs supported by multiple calls.
@param [in] interruptNumber GPIO pin to mask
*/
virtual void usingInterrupt(int interruptNumber) override {
_usingIRQs.insert({interruptNumber, 0});
_helper.usingInterrupt(interruptNumber);
}
/**
@brief Remove a GPIO from the masked-during-transaction list.
@param [in] interruptNumber GPIO pin to unmask
*/
virtual void notUsingInterrupt(int interruptNumber) override {
_usingIRQs.erase(interruptNumber);
_helper.notUsingInterrupt(interruptNumber);
}
virtual void attachInterrupt() override { /* noop */ }
virtual void detachInterrupt() override { /* noop */ }
/**
@brief Deprecated, do not use
*/
virtual void attachInterrupt() override __attribute__((deprecated)) { /* noop */ }
/**
@brief Deprecated, do not use
*/
virtual void detachInterrupt() override __attribute__((deprecated)) { /* 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 +249,6 @@ private:
bool _running; // SPI port active
bool _initted; // Transaction begun
std::map<int, int> _usingIRQs;
// DMA
int _channelDMA;
int _channelSendDMA;
@@ -107,6 +256,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));
}
#if defined(PICO_RP2350) && !PICO_RP2350A // 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;
};
+4 -4
View File
@@ -79,7 +79,7 @@ inline spi_cpha_t SPISlaveClass::cpha(SPISettings _spis) {
}
bool SPISlaveClass::setRX(pin_size_t pin) {
#ifdef PICO_RP2350B
#if defined(PICO_RP2350) && !PICO_RP2350A // RP2350B
constexpr uint64_t valid[2] = { __bitset({0, 4, 16, 20, 32, 26}) /* SPI0 */,
__bitset({8, 12, 24, 28, 40, 44}) /* SPI1 */
};
@@ -106,7 +106,7 @@ bool SPISlaveClass::setRX(pin_size_t pin) {
}
bool SPISlaveClass::setCS(pin_size_t pin) {
#ifdef PICO_RP2350B
#if defined(PICO_RP2350) && !PICO_RP2350A // RP2350B
constexpr uint64_t valid[2] = { __bitset({1, 5, 17, 21, 33, 37}) /* SPI0 */,
__bitset({9, 13, 25, 29, 41, 45}) /* SPI1 */
};
@@ -133,7 +133,7 @@ bool SPISlaveClass::setCS(pin_size_t pin) {
}
bool SPISlaveClass::setSCK(pin_size_t pin) {
#ifdef PICO_RP2350B
#if defined(PICO_RP2350) && !PICO_RP2350A // RP2350B
constexpr uint64_t valid[2] = { __bitset({2, 6, 18, 22, 34, 38}) /* SPI0 */,
__bitset({10, 14, 26, 30, 42, 46}) /* SPI1 */
};
@@ -160,7 +160,7 @@ bool SPISlaveClass::setSCK(pin_size_t pin) {
}
bool SPISlaveClass::setTX(pin_size_t pin) {
#ifdef PICO_RP2350B
#if defined(PICO_RP2350) && !PICO_RP2350A // RP2350B
constexpr uint64_t valid[2] = { __bitset({3, 7, 19, 23, 35, 39}) /* SPI0 */,
__bitset({11, 15, 27, 31, 43, 47}) /* SPI1 */
};
@@ -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;
}
+43
View File
@@ -0,0 +1,43 @@
#######################################
# Syntax Coloring Map SPI
#######################################
#######################################
# Instances (KEYWORD2)
#######################################
SoftwareSPI KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
begin KEYWORD2
end KEYWORD2
beginTransaction KEYWORD2
endTransaction KEYWORD2
SPISettings KEYWORD2
transfer KEYWORD2
transfer16 KEYWORD2
setBitOrder KEYWORD2
setDataMode KEYWORD2
setClockDivider KEYWORD2
setSCK KEYWORD2
setMOSI KEYWORD2
setMISO KEYWORD2
setCS KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################
SPI_CLOCK_DIV4 LITERAL1
SPI_CLOCK_DIV16 LITERAL1
SPI_CLOCK_DIV64 LITERAL1
SPI_CLOCK_DIV128 LITERAL1
SPI_CLOCK_DIV2 LITERAL1
SPI_CLOCK_DIV8 LITERAL1
SPI_CLOCK_DIV32 LITERAL1
SPI_CLOCK_DIV64 LITERAL1
SPI_MODE0 LITERAL1
SPI_MODE1 LITERAL1
SPI_MODE2 LITERAL1
SPI_MODE3 LITERAL1
+10
View File
@@ -0,0 +1,10 @@
name=SoftwareSPI
version=1.0
author=Earle F. Philhower, III <earlephilhower@yahoo.com>
maintainer=Earle F. Philhower, III <earlephilhower@yahoo.com>
sentence=Uses the PIO to provide an SPI interface on any pin.
paragraph=
category=Signal Input/Output
url=http://arduino.cc/en/Reference/SPI
architectures=rp2040
dot_a_linkage=true
+270
View File
@@ -0,0 +1,270 @@
/*
PIO-based SPI Master 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 "SoftwareSPI.h"
#include <hardware/gpio.h>
#include <hardware/structs/iobank0.h>
#include <hardware/irq.h>
#include "spi.pio.h"
#ifdef USE_TINYUSB
// For Serial when selecting TinyUSB. Can't include in the core because Arduino IDE
// will not link in libraries called from the core. Instead, add the header to all
// the standard libraries in the hope it will still catch some user cases where they
// use these libraries.
// See https://github.com/earlephilhower/arduino-pico/issues/167#issuecomment-848622174
#include <Adafruit_TinyUSB.h>
#endif
SoftwareSPI::SoftwareSPI(pin_size_t sck, pin_size_t miso, pin_size_t mosi, pin_size_t cs) {
_running = false;
_initted = false;
_spis = SPISettings(1, LSBFIRST, SPI_MODE0); // Ensure spi_init called by setting current freq to 0
_sck = sck;
_miso = miso;
_mosi = mosi;
_cs = cs;
}
void SoftwareSPI::_adjustPIO(int bits) {
if (_bits == bits) {
return; // Nothing to do!
}
// Manually set the shiftctl and possibly Y for 8 bits
pio_sm_set_enabled(_pio, _sm, false);
uint32_t v = _pio->sm[_sm].shiftctrl ;
v &= ~0x3e000000 | ~0x01f00000;
if (bits == 8) {
v |= 0x108 << 20; // Hardcode push/pull threshold 0'b0100001000, there is no simple accessor I can find
} else {
v |= 0x210 << 20; // 0b'1000010000
}
_pio->sm[_sm].shiftctrl = v;
if (_hwCS) {
pio_sm_exec(_pio, _sm, pio_encode_set(pio_x, bits - 2));
pio_sm_exec(_pio, _sm, pio_encode_set(pio_y, bits - 2));
}
pio_sm_set_enabled(_pio, _sm, true);
_bits = bits;
}
byte SoftwareSPI::transfer(uint8_t data) {
uint8_t ret;
if (!_initted) {
return 0;
}
data = (_spis.getBitOrder() == MSBFIRST) ? data : _helper.reverseByte(data);
DEBUGSPI("SoftwareSPI::transfer(%02x), cpol=%d, cpha=%d\n", data, _helper.cpol(_spis), _helper.cpha(_spis));
_adjustPIO(8);
io_rw_8 *txfifo = (io_rw_8 *) &_pio->txf[_sm];
io_rw_8 *rxfifo = (io_rw_8 *) &_pio->rxf[_sm];
while (pio_sm_is_tx_fifo_full(_pio, _sm)) { /* noop wait */ }
*txfifo = data;
while (pio_sm_is_rx_fifo_empty(_pio, _sm)) { /* noop wait for in data */ }
ret = *rxfifo;
ret = (_spis.getBitOrder() == MSBFIRST) ? ret : _helper.reverseByte(ret);
DEBUGSPI("SoftwareSPI: read back %02x\n", ret);
return ret;
}
uint16_t SoftwareSPI::transfer16(uint16_t data) {
uint16_t ret;
if (!_initted) {
return 0;
}
data = (_spis.getBitOrder() == MSBFIRST) ? data : _helper.reverse16Bit(data);
DEBUGSPI("SoftwareSPI::transfer16(%04x), cpol=%d, cpha=%d\n", data, _helper.cpol(_spis), _helper.cpha(_spis));
_adjustPIO(16);
io_rw_16 *txfifo = (io_rw_16 *) &_pio->txf[_sm];
io_rw_16 *rxfifo = (io_rw_16 *) &_pio->rxf[_sm];
while (pio_sm_is_tx_fifo_full(_pio, _sm)) { /* noop wait */ }
*txfifo = data;
while (pio_sm_is_rx_fifo_empty(_pio, _sm)) { /* noop wait for in data */ }
ret = *rxfifo;
ret = (_spis.getBitOrder() == MSBFIRST) ? ret : _helper.reverse16Bit(ret);
DEBUGSPI("SoftwareSPI: read back %04x\n", ret);
return ret;
}
void SoftwareSPI::transfer(void *buf, size_t count) {
transfer(buf, buf, count);
}
void SoftwareSPI::transfer(const void *csrc, void *cdest, size_t count) {
if (!_initted) {
return;
}
DEBUGSPI("SoftwareSPI::transfer(%p, %p %d)\n", csrc, cdest, count);
const uint8_t *src = reinterpret_cast<const uint8_t *>(csrc);
uint8_t *dest = reinterpret_cast<uint8_t *>(cdest);
_adjustPIO(8);
io_rw_8 *txfifo = (io_rw_8 *) &_pio->txf[_sm];
io_rw_8 *rxfifo = (io_rw_8 *) &_pio->rxf[_sm];
int txleft = count;
int rxleft = count;
if (_spis.getBitOrder() == !MSBFIRST) {
// We're going to hack like heck here and reverse the txbuf into the receive buff (because txbuff is const
// Then by construction SPI will send before it received, we can use the rx buff to trans and recv
for (size_t i = 0; i < count; i++) {
dest[i] = _helper.reverseByte(src[i]);
}
src = dest; // We'll transmit the flipped data...
}
while (txleft || rxleft) {
while (txleft && !pio_sm_is_tx_fifo_full(_pio, _sm)) {
*txfifo = *src++;
txleft--;
}
while (rxleft && !pio_sm_is_rx_fifo_empty(_pio, _sm)) {
*dest++ = *rxfifo;
rxleft--;
}
}
if (_spis.getBitOrder() == !MSBFIRST) {
// Now we have data in recv but also need to flip it before returning to the app
for (size_t i = 0; i < count; i++) {
dest[i] = _helper.reverseByte(dest[i]);
}
}
DEBUGSPI("SoftwareSPI::transfer completed\n");
}
void SoftwareSPI::beginTransaction(SPISettings settings) {
DEBUGSPI("SoftwareSPI::beginTransaction(clk=%lu, bo=%s)\n", settings.getClockFreq(), (settings.getBitOrder() == MSBFIRST) ? "MSB" : "LSB");
if (_initted && settings == _spis) {
DEBUGSPI("SoftwareSPI: Reusing existing initted SPI\n");
} else {
/* Only de-init if the clock changes frequency */
if (settings.getClockFreq() != _spis.getClockFreq()) {
DEBUGSPI("SoftwareSPI: initting SPI\n");
float divider = (float)rp2040.f_cpu() / (float)settings.getClockFreq();
divider /= _hwCS ? 4.0f : 4.0f;
pio_sm_set_clkdiv(_pio, _sm, divider);
DEBUGSPI("SoftwareSPI: divider=%f\n", divider);
}
_spis = settings;
// Note we can only change frequency, not CPOL/CPHA (which would be physically not too useful anyway)
_initted = true;
}
_helper.maskInterrupts();
}
void SoftwareSPI::endTransaction(void) {
DEBUGSPI("SoftwareSPI::endTransaction()\n");
_helper.unmaskInterrupts();
}
bool SoftwareSPI::setCS(pin_size_t pin) {
if (pin < 1) {
// CS is SCK+1, so has to be at least GPIO1
return false;
}
if (!_running || (_cs == pin)) {
_cs = pin;
_sck = _cs - 1;
return true;
}
return false;
}
bool SoftwareSPI::setSCK(pin_size_t pin) {
if (!_running || (_sck == pin)) {
_sck = pin;
_cs = pin + 1;
return true;
}
return false;
}
bool SoftwareSPI::setMISO(pin_size_t pin) {
if (!_running || (_miso == pin)) {
_miso = pin;
return true;
}
return false;
}
bool SoftwareSPI::setMOSI(pin_size_t pin) {
if (!_running || (_mosi == pin)) {
_mosi = pin;
return true;
}
return false;
}
void SoftwareSPI::begin(bool hwCS) {
DEBUGSPI("SoftwareSPI::begin(%d), rx=%d, cs=%d, sck=%d, tx=%d\n", hwCS, _miso, _cs, _sck, _mosi);
float divider = (float)rp2040.f_cpu() / (float)_spis.getClockFreq();
DEBUGSPI("SoftwareSPI: divider=%f\n", divider);
if (!hwCS) {
_spi = new PIOProgram(_helper.cpha(_spis) == SPI_CPHA_0 ? &spi_cpha0_program : &spi_cpha1_program);
if (!_spi->prepare(&_pio, &_sm, &_off, _sck, 1)) {
_running = false;
delete _spi;
_spi = nullptr;
return;
}
pio_spi_init(_pio, _sm, _off, 8, divider / 4.0f, _helper.cpha(_spis), _helper.cpol(_spis), _sck, _mosi, _miso);
} else {
_spi = new PIOProgram(_helper.cpha(_spis) == SPI_CPHA_0 ? &spi_cpha0_cs_program : &spi_cpha1_cs_program);
if (!_spi->prepare(&_pio, &_sm, &_off, _sck, 2)) {
_running = false;
delete _spi;
_spi = nullptr;
return;
}
pio_spi_cs_init(_pio, _sm, _off, 8, divider / 4.0f, _helper.cpha(_spis), _helper.cpol(_spis), _sck, _mosi, _miso);
}
_hwCS = hwCS;
_bits = 8;
// Give a default config in case user doesn't use beginTransaction
beginTransaction(_spis);
endTransaction();
}
void SoftwareSPI::end() {
DEBUGSPI("SoftwareSPI::end()\n");
if (_initted) {
DEBUGSPI("SoftwareSPI: deinitting currently active SPI\n");
_initted = false;
pio_sm_set_enabled(_pio, _sm, false);
// TODO - We don't have a good PIOProgram reclamation method so this will possibly leak an SM
}
_spis = SPISettings(0, LSBFIRST, SPI_MODE0);
}
void SoftwareSPI::setBitOrder(BitOrder order) {
_spis = SPISettings(_spis.getClockFreq(), order, _spis.getDataMode());
beginTransaction(_spis);
endTransaction();
}
void SoftwareSPI::setDataMode(uint8_t uc_mode) {
_spis = SPISettings(_spis.getClockFreq(), _spis.getBitOrder(), uc_mode);
beginTransaction(_spis);
endTransaction();
}
void SoftwareSPI::setClockDivider(uint8_t uc_div) {
(void) uc_div; // no-op
}
+223
View File
@@ -0,0 +1,223 @@
/*
PIO-based SPI Master 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
*/
#pragma once
#include <Arduino.h>
#include <SPI.h> // For SPIHelper
#include <api/HardwareSPI.h>
#include <hardware/spi.h>
/**
@brief Implements a PIO-based SPI interface without pin restrictions
*/
class SoftwareSPI : public arduino::HardwareSPI {
public:
/**
@brief Create a PIO-based SPI instance
@param [in] sck SCK GPIO
@param [in] miso MISO GPIO
@param [in] mosi MOSI GPIO
@param [in] cs Optional CS pin for HW CS, must be SCK+1
*/
SoftwareSPI(pin_size_t sck, pin_size_t miso, pin_size_t mosi, pin_size_t cs = -1);
/**
@brief Send an 8-bit byte of data and return read-back 8-bit value
@param [in] data Data to send
@returns Read back byte from SPI interface
*/
byte transfer(uint8_t data) override;
/**
@brief Send a 16-bit quantity over SPI and return read-back 16-bit value under a single CS assertion
@param [in] data Data to send
@returns Read back 16-bit quantity
*/
uint16_t transfer16(uint16_t data) override;
/**
@brief Sends buffer in 8 bit chunks under a single CS. Overwrites buffer with read data
@param [in, out] buf Buffer to read and write back into
@param [in] count Number of bytes to transmit/read
*/
void transfer(void *buf, size_t count) override;
/**
@brief Sends one buffer and receives into another under a single CS. Can set rx or txbuf to nullptr
@param [in] txbuf Buffer to transmit or nullptr to send 0s
@param [out] rxbuf Buffer to read back into or nullptr to ignore returned data
@param [in] count Numbner of bytes to transmit/receive
*/
void transfer(const void *txbuf, void *rxbuf, size_t count) override;
/**
@brief Begin an SPI transaction, sets SPI speed and masks necessary interrupts
@param [in] SPISettings SPI configuration parameters, including the clock speed
*/
void beginTransaction(SPISettings settings) override;
/**
@brief Ends an SPI transaction, unmasks and masked GPIO interrupts
*/
void endTransaction(void) override;
/**
@brief Sets the MISO(RX) pin. Call before begin()
@param [in] pin The GPIO number to assign to
@returns True on success
*/
bool setMISO(pin_size_t pin);
/**
@brief Sets the MISO(RX) pin. Call before begin()
@param [in] pin The GPIO number to assign to
@returns True on success
*/
inline bool setRX(pin_size_t pin) {
return setMISO(pin);
}
/**
@brief Sets the CS pin. Call before begin()
@param [in] pin The GPIO number to assign to
@returns True on success
*/
bool setCS(pin_size_t pin);
/**
@brief Sets the SCK pin. Call before begin()
@param [in] pin The GPIO number to assign to
@returns True on success
*/
bool setSCK(pin_size_t pin);
/**
@brief Sets the MOSI(TX) pin. Call before begin()
@param [in] pin The GPIO number to assign to
@returns True on success
*/
bool setMOSI(pin_size_t pin);
/**
@brief Sets the MOSI(TX) pin. Call before begin()
@param [in] pin The GPIO number to assign to
@returns True on success
*/
inline bool setTX(pin_size_t pin) {
return setMOSI(pin);
}
/**
@brief Call once to init/deinit SPI class, select pins, etc.
*/
virtual void begin() override {
begin(false);
}
/**
@brief Call once to init/deinit SPI class, select pins, etc.
@param [in] hwCS Pass in true to enable HW-controlled CS. Otherwise application needs to assert/deassert CS.
*/
void begin(bool hwCS);
/**
@brief Call to deinit and disable the SPI interface.
*/
void end() override;
/**
@brief Deprecated, do not use
@param [in] order Deprecated
*/
void setBitOrder(BitOrder order) __attribute__((deprecated));
/**
@brief Deprecated, do not use
@param [in] uc_mode Deprecated
*/
void setDataMode(uint8_t uc_mode) __attribute__((deprecated));
/**
@brief Deprecated, do not use
@param [in] uc_div Deprecated
*/
void setClockDivider(uint8_t uc_div) __attribute__((deprecated));
/**
@brief Ensure specific GPIO interrupt is disabled during and SPI transaction to protect against re-entrancy. Multiple GPIOs supported by multiple calls.
@param [in] interruptNumber GPIO pin to mask
*/
virtual void usingInterrupt(int interruptNumber) override {
_helper.usingInterrupt(interruptNumber);
}
/**
@brief Remove a GPIO from the masked-during-transaction list.
@param [in] interruptNumber GPIO pin to unmask
*/
virtual void notUsingInterrupt(int interruptNumber) override {
_helper.notUsingInterrupt(interruptNumber);
}
/**
@brief Deprecated, do not use
*/
virtual void attachInterrupt() override __attribute__((deprecated)) { /* noop */ }
/**
@brief Deprecated, do not use
*/
virtual void detachInterrupt() override __attribute__((deprecated)) { /* noop */ }
private:
void _adjustPIO(int bits);
PIOProgram *_spi;
PIO _pio;
int _sm;
int _off;
SPISettings _spis;
pin_size_t _sck, _miso, _mosi, _cs;
bool _hwCS;
bool _running; // SPI port active
bool _initted; // Transaction begun
int _bits;
SPIHelper _helper;
};
+168
View File
@@ -0,0 +1,168 @@
;
; Copyright (c) 2020 Raspberry Pi (Trading) Ltd.
;
; SPDX-License-Identifier: BSD-3-Clause
;
; These programs implement full-duplex SPI, with a SCK period of 4 clock
; cycles. A different program is provided for each value of CPHA, and CPOL is
; achieved using the hardware GPIO inversion available in the IO controls.
;
; Transmit-only SPI can go twice as fast -- see the ST7789 example!
.pio_version 0 // only requires PIO version 0
.program spi_cpha0
.side_set 1
; Pin assignments:
; - SCK is side-set pin 0
; - MOSI is OUT pin 0
; - MISO is IN pin 0
;
; Autopush and autopull must be enabled, and the serial frame size is set by
; configuring the push/pull threshold. Shift left/right is fine, but you must
; justify the data yourself. This is done most conveniently for frame sizes of
; 8 or 16 bits by using the narrow store replication and narrow load byte
; picking behaviour of RP2040's IO fabric.
; Clock phase = 0: data is captured on the leading edge of each SCK pulse, and
; transitions on the trailing edge, or some time before the first leading edge.
out pins, 1 side 0 [1] ; Stall here on empty (sideset proceeds even if
in pins, 1 side 1 [1] ; instruction stalls, so we stall with SCK low)
.program spi_cpha1
.side_set 1
; Clock phase = 1: data transitions on the leading edge of each SCK pulse, and
; is captured on the trailing edge.
out x, 1 side 0 ; Stall here on empty (keep SCK deasserted)
mov pins, x side 1 [1] ; Output data, assert SCK (mov pins uses OUT mapping)
in pins, 1 side 0 ; Input data, deassert SCK
% c-sdk {
#include "hardware/gpio.h"
static inline void pio_spi_init(PIO pio, uint sm, uint prog_offs, uint n_bits,
float clkdiv, bool cpha, bool cpol, uint pin_sck, uint pin_mosi, uint pin_miso) {
pio_sm_config c = cpha ? spi_cpha1_program_get_default_config(prog_offs) : spi_cpha0_program_get_default_config(prog_offs);
sm_config_set_out_pins(&c, pin_mosi, 1);
sm_config_set_in_pins(&c, pin_miso);
sm_config_set_sideset_pins(&c, pin_sck);
// Only support MSB-first in this example code (shift to left, auto push/pull, threshold=nbits)
sm_config_set_out_shift(&c, false, true, n_bits);
sm_config_set_in_shift(&c, false, true, n_bits);
sm_config_set_clkdiv(&c, clkdiv);
// MOSI, SCK output are low, MISO is input
pio_sm_set_pins_with_mask(pio, sm, 0, (1u << pin_sck) | (1u << pin_mosi));
pio_sm_set_pindirs_with_mask(pio, sm, (1u << pin_sck) | (1u << pin_mosi), (1u << pin_sck) | (1u << pin_mosi) | (1u << pin_miso));
pio_gpio_init(pio, pin_mosi);
pio_gpio_init(pio, pin_miso);
pio_gpio_init(pio, pin_sck);
// The pin muxes can be configured to invert the output (among other things
// and this is a cheesy way to get CPOL=1
gpio_set_outover(pin_sck, cpol ? GPIO_OVERRIDE_INVERT : GPIO_OVERRIDE_NORMAL);
// SPI is synchronous, so bypass input synchroniser to reduce input delay.
hw_set_bits(&pio->input_sync_bypass, 1u << pin_miso);
pio_sm_init(pio, sm, prog_offs, &c);
pio_sm_set_enabled(pio, sm, true);
}
%}
; SPI with Chip Select
; -----------------------------------------------------------------------------
;
; For your amusement, here are some SPI programs with an automatic chip select
; (asserted once data appears in TX FIFO, deasserts when FIFO bottoms out, has
; a nice front/back porch).
;
; The number of bits per FIFO entry is configured via the Y register
; and the autopush/pull threshold. From 2 to 32 bits.
;
; Pin assignments:
; - SCK is side-set bit 0
; - CSn is side-set bit 1
; - MOSI is OUT bit 0 (host-to-device)
; - MISO is IN bit 0 (device-to-host)
;
; This program only supports one chip select -- use GPIO if more are needed
;
; Provide a variation for each possibility of CPHA; for CPOL we can just
; invert SCK in the IO muxing controls (downstream from PIO)
; CPHA=0: data is captured on the leading edge of each SCK pulse (including
; the first pulse), and transitions on the trailing edge
.program spi_cpha0_cs
.side_set 2
.wrap_target
bitloop:
out pins, 1 side 0x0 [1]
in pins, 1 side 0x1
jmp x-- bitloop side 0x1
out pins, 1 side 0x0
mov x, y side 0x0 ; Reload bit counter from Y
in pins, 1 side 0x1
jmp !osre bitloop side 0x1 ; Fall-through if TXF empties
nop side 0x0 [1] ; CSn back porch
public entry_point: ; Must set X,Y to n-2 before starting!
pull ifempty side 0x2 [1] ; Block with CSn high (minimum 2 cycles)
.wrap ; Note ifempty to avoid time-of-check race
; CPHA=1: data transitions on the leading edge of each SCK pulse, and is
; captured on the trailing edge
.program spi_cpha1_cs
.side_set 2
.wrap_target
bitloop:
out pins, 1 side 0x1 [1]
in pins, 1 side 0x0
jmp x-- bitloop side 0x0
out pins, 1 side 0x1
mov x, y side 0x1
in pins, 1 side 0x0
jmp !osre bitloop side 0x0
public entry_point: ; Must set X,Y to n-2 before starting!
pull ifempty side 0x2 [1] ; Block with CSn high (minimum 2 cycles)
nop side 0x0 [1]; CSn front porch
.wrap
% c-sdk {
#include "hardware/gpio.h"
static inline void pio_spi_cs_init(PIO pio, uint sm, uint prog_offs, uint n_bits, float clkdiv, bool cpha, bool cpol,
uint pin_sck, uint pin_mosi, uint pin_miso) {
pio_sm_config c = cpha ? spi_cpha1_cs_program_get_default_config(prog_offs) : spi_cpha0_cs_program_get_default_config(prog_offs);
sm_config_set_out_pins(&c, pin_mosi, 1);
sm_config_set_in_pins(&c, pin_miso);
sm_config_set_sideset_pins(&c, pin_sck);
sm_config_set_out_shift(&c, false, true, n_bits);
sm_config_set_in_shift(&c, false, true, n_bits);
sm_config_set_clkdiv(&c, clkdiv);
pio_sm_set_pins_with_mask(pio, sm, (2u << pin_sck), (3u << pin_sck) | (1u << pin_mosi));
pio_sm_set_pindirs_with_mask(pio, sm, (3u << pin_sck) | (1u << pin_mosi), (3u << pin_sck) | (1u << pin_mosi) | (1u << pin_miso));
pio_gpio_init(pio, pin_mosi);
pio_gpio_init(pio, pin_miso);
pio_gpio_init(pio, pin_sck);
pio_gpio_init(pio, pin_sck + 1);
gpio_set_outover(pin_sck, cpol ? GPIO_OVERRIDE_INVERT : GPIO_OVERRIDE_NORMAL);
hw_set_bits(&pio->input_sync_bypass, 1u << pin_miso);
uint entry_point = prog_offs + (cpha ? spi_cpha1_cs_offset_entry_point : spi_cpha0_cs_offset_entry_point);
pio_sm_init(pio, sm, entry_point, &c);
pio_sm_exec(pio, sm, pio_encode_set(pio_x, n_bits - 2));
pio_sm_exec(pio, sm, pio_encode_set(pio_y, n_bits - 2));
pio_sm_set_enabled(pio, sm, true);
}
%}
+218
View File
@@ -0,0 +1,218 @@
// -------------------------------------------------- //
// This file is autogenerated by pioasm; do not edit! //
// -------------------------------------------------- //
#pragma once
#if !PICO_NO_HARDWARE
#include "hardware/pio.h"
#endif
// --------- //
// spi_cpha0 //
// --------- //
#define spi_cpha0_wrap_target 0
#define spi_cpha0_wrap 1
#define spi_cpha0_pio_version 0
static const uint16_t spi_cpha0_program_instructions[] = {
// .wrap_target
0x6101, // 0: out pins, 1 side 0 [1]
0x5101, // 1: in pins, 1 side 1 [1]
// .wrap
};
#if !PICO_NO_HARDWARE
static const struct pio_program spi_cpha0_program = {
.instructions = spi_cpha0_program_instructions,
.length = 2,
.origin = -1,
.pio_version = 0,
#if PICO_PIO_VERSION > 0
.used_gpio_ranges = 0x0
#endif
};
static inline pio_sm_config spi_cpha0_program_get_default_config(uint offset) {
pio_sm_config c = pio_get_default_sm_config();
sm_config_set_wrap(&c, offset + spi_cpha0_wrap_target, offset + spi_cpha0_wrap);
sm_config_set_sideset(&c, 1, false, false);
return c;
}
#endif
// --------- //
// spi_cpha1 //
// --------- //
#define spi_cpha1_wrap_target 0
#define spi_cpha1_wrap 2
#define spi_cpha1_pio_version 0
static const uint16_t spi_cpha1_program_instructions[] = {
// .wrap_target
0x6021, // 0: out x, 1 side 0
0xb101, // 1: mov pins, x side 1 [1]
0x4001, // 2: in pins, 1 side 0
// .wrap
};
#if !PICO_NO_HARDWARE
static const struct pio_program spi_cpha1_program = {
.instructions = spi_cpha1_program_instructions,
.length = 3,
.origin = -1,
.pio_version = 0,
#if PICO_PIO_VERSION > 0
.used_gpio_ranges = 0x0
#endif
};
static inline pio_sm_config spi_cpha1_program_get_default_config(uint offset) {
pio_sm_config c = pio_get_default_sm_config();
sm_config_set_wrap(&c, offset + spi_cpha1_wrap_target, offset + spi_cpha1_wrap);
sm_config_set_sideset(&c, 1, false, false);
return c;
}
#include "hardware/gpio.h"
static inline void pio_spi_init(PIO pio, uint sm, uint prog_offs, uint n_bits,
float clkdiv, bool cpha, bool cpol, uint pin_sck, uint pin_mosi, uint pin_miso) {
pio_sm_config c = cpha ? spi_cpha1_program_get_default_config(prog_offs) : spi_cpha0_program_get_default_config(prog_offs);
sm_config_set_out_pins(&c, pin_mosi, 1);
sm_config_set_in_pins(&c, pin_miso);
sm_config_set_sideset_pins(&c, pin_sck);
// Only support MSB-first in this example code (shift to left, auto push/pull, threshold=nbits)
sm_config_set_out_shift(&c, false, true, n_bits);
sm_config_set_in_shift(&c, false, true, n_bits);
sm_config_set_clkdiv(&c, clkdiv);
// MOSI, SCK output are low, MISO is input
pio_sm_set_pins_with_mask(pio, sm, 0, (1u << pin_sck) | (1u << pin_mosi));
pio_sm_set_pindirs_with_mask(pio, sm, (1u << pin_sck) | (1u << pin_mosi), (1u << pin_sck) | (1u << pin_mosi) | (1u << pin_miso));
pio_gpio_init(pio, pin_mosi);
pio_gpio_init(pio, pin_miso);
pio_gpio_init(pio, pin_sck);
// The pin muxes can be configured to invert the output (among other things
// and this is a cheesy way to get CPOL=1
gpio_set_outover(pin_sck, cpol ? GPIO_OVERRIDE_INVERT : GPIO_OVERRIDE_NORMAL);
// SPI is synchronous, so bypass input synchroniser to reduce input delay.
hw_set_bits(&pio->input_sync_bypass, 1u << pin_miso);
pio_sm_init(pio, sm, prog_offs, &c);
pio_sm_set_enabled(pio, sm, true);
}
#endif
// ------------ //
// spi_cpha0_cs //
// ------------ //
#define spi_cpha0_cs_wrap_target 0
#define spi_cpha0_cs_wrap 8
#define spi_cpha0_cs_pio_version 0
#define spi_cpha0_cs_offset_entry_point 8u
static const uint16_t spi_cpha0_cs_program_instructions[] = {
// .wrap_target
0x6101, // 0: out pins, 1 side 0 [1]
0x4801, // 1: in pins, 1 side 1
0x0840, // 2: jmp x--, 0 side 1
0x6001, // 3: out pins, 1 side 0
0xa022, // 4: mov x, y side 0
0x4801, // 5: in pins, 1 side 1
0x08e0, // 6: jmp !osre, 0 side 1
0xa142, // 7: nop side 0 [1]
0x91e0, // 8: pull ifempty block side 2 [1]
// .wrap
};
#if !PICO_NO_HARDWARE
static const struct pio_program spi_cpha0_cs_program = {
.instructions = spi_cpha0_cs_program_instructions,
.length = 9,
.origin = -1,
.pio_version = 0,
#if PICO_PIO_VERSION > 0
.used_gpio_ranges = 0x0
#endif
};
static inline pio_sm_config spi_cpha0_cs_program_get_default_config(uint offset) {
pio_sm_config c = pio_get_default_sm_config();
sm_config_set_wrap(&c, offset + spi_cpha0_cs_wrap_target, offset + spi_cpha0_cs_wrap);
sm_config_set_sideset(&c, 2, false, false);
return c;
}
#endif
// ------------ //
// spi_cpha1_cs //
// ------------ //
#define spi_cpha1_cs_wrap_target 0
#define spi_cpha1_cs_wrap 8
#define spi_cpha1_cs_pio_version 0
#define spi_cpha1_cs_offset_entry_point 7u
static const uint16_t spi_cpha1_cs_program_instructions[] = {
// .wrap_target
0x6901, // 0: out pins, 1 side 1 [1]
0x4001, // 1: in pins, 1 side 0
0x0040, // 2: jmp x--, 0 side 0
0x6801, // 3: out pins, 1 side 1
0xa822, // 4: mov x, y side 1
0x4001, // 5: in pins, 1 side 0
0x00e0, // 6: jmp !osre, 0 side 0
0x91e0, // 7: pull ifempty block side 2 [1]
0xa142, // 8: nop side 0 [1]
// .wrap
};
#if !PICO_NO_HARDWARE
static const struct pio_program spi_cpha1_cs_program = {
.instructions = spi_cpha1_cs_program_instructions,
.length = 9,
.origin = -1,
.pio_version = 0,
#if PICO_PIO_VERSION > 0
.used_gpio_ranges = 0x0
#endif
};
static inline pio_sm_config spi_cpha1_cs_program_get_default_config(uint offset) {
pio_sm_config c = pio_get_default_sm_config();
sm_config_set_wrap(&c, offset + spi_cpha1_cs_wrap_target, offset + spi_cpha1_cs_wrap);
sm_config_set_sideset(&c, 2, false, false);
return c;
}
#include "hardware/gpio.h"
static inline void pio_spi_cs_init(PIO pio, uint sm, uint prog_offs, uint n_bits, float clkdiv, bool cpha, bool cpol,
uint pin_sck, uint pin_mosi, uint pin_miso) {
pio_sm_config c = cpha ? spi_cpha1_cs_program_get_default_config(prog_offs) : spi_cpha0_cs_program_get_default_config(prog_offs);
sm_config_set_out_pins(&c, pin_mosi, 1);
sm_config_set_in_pins(&c, pin_miso);
sm_config_set_sideset_pins(&c, pin_sck);
sm_config_set_out_shift(&c, false, true, n_bits);
sm_config_set_in_shift(&c, false, true, n_bits);
sm_config_set_clkdiv(&c, clkdiv);
pio_sm_set_pins_with_mask(pio, sm, (2u << pin_sck), (3u << pin_sck) | (1u << pin_mosi));
pio_sm_set_pindirs_with_mask(pio, sm, (3u << pin_sck) | (1u << pin_mosi), (3u << pin_sck) | (1u << pin_mosi) | (1u << pin_miso));
pio_gpio_init(pio, pin_mosi);
pio_gpio_init(pio, pin_miso);
pio_gpio_init(pio, pin_sck);
pio_gpio_init(pio, pin_sck + 1);
gpio_set_outover(pin_sck, cpol ? GPIO_OVERRIDE_INVERT : GPIO_OVERRIDE_NORMAL);
hw_set_bits(&pio->input_sync_bypass, 1u << pin_miso);
uint entry_point = prog_offs + (cpha ? spi_cpha1_cs_offset_entry_point : spi_cpha0_cs_offset_entry_point);
pio_sm_init(pio, sm, entry_point, &c);
pio_sm_exec(pio, sm, pio_encode_set(pio_x, n_bits - 2));
pio_sm_exec(pio, sm, pio_encode_set(pio_y, n_bits - 2));
pio_sm_set_enabled(pio, sm, true);
}
#endif
+7
View File
@@ -97,12 +97,18 @@ bool UpdaterClass::begin(size_t size, int command) {
_md5 = MD5Builder();
if (command == U_FLASH) {
// Basic sanity, if it's larger than entire FS then it can't possibly succeed
if (&_FS_start + size > &_FS_end) {
_setError(UPDATE_ERROR_SPACE);
return false;
}
LittleFS.begin();
_fp = LittleFS.open("firmware.bin", "w+");
if (!_fp) {
#ifdef DEBUG_UPDATER
DEBUG_UPDATER.println(F("[begin] unable to create file"));
#endif
_setError(UPDATE_ERROR_SPACE);
return false;
}
updateStartAddress = 0; // Not used
@@ -288,6 +294,7 @@ bool UpdaterClass::end(bool evenIfRemaining) {
bool UpdaterClass::_writeBuffer() {
if (_command == U_FLASH) {
if (_bufferLen != _fp.write(_buffer, _bufferLen)) {
_setError(UPDATE_ERROR_SPACE);
return false;
}
} else {
@@ -35,8 +35,8 @@
#if USE_WIFI
#include <WiFi.h>
#elif USE_WIRED
#include <W5500lwIP.h> // Or W5100lwIP.h or ENC28J60lwIP.h
Wiznet5500lwIP eth(1 /* chip select */); // or Wiznet5100lwIP or ENC28J60lwIP
#include <W5500lwIP.h> // or W6100lwIP.h or W5100lwIP.h or ENC28J60lwIP.h
Wiznet5500lwIP eth(1 /* SPI chip select */); // or Wiznet6100lwIP or Wiznet5100lwIP or ENC28J60lwIP
#endif
#include <WiFiClient.h>
@@ -216,9 +216,9 @@ void handleFileList() {
// as an HTTP chunk
Serial.println(output);
server.sendContent(output);
output = ',';
output = ",";
} else {
output = '[';
output = "[";
}
output += "{\"type\":\"";
+1
View File
@@ -21,6 +21,7 @@
#pragma once
#include <Arduino.h>
#include <Udp.h>
#include <include/slist.h>
+16 -3
View File
@@ -49,7 +49,7 @@ TwoWire::TwoWire(i2c_inst_t *i2c, pin_size_t sda, pin_size_t scl) {
}
bool TwoWire::setSDA(pin_size_t pin) {
#ifdef PICO_RP2350B
#if defined(PICO_RP2350) && !PICO_RP2350A // RP2350B
constexpr uint64_t valid[2] = { __bitset({0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44}) /* I2C0 */,
__bitset({2, 6, 10, 14, 18, 22, 26, 30, 34, 38, 42, 46}) /* I2C1 */
};
@@ -76,7 +76,7 @@ bool TwoWire::setSDA(pin_size_t pin) {
}
bool TwoWire::setSCL(pin_size_t pin) {
#ifdef PICO_RP2350B
#if defined(PICO_RP2350) && !PICO_RP2350A // RP2350B
constexpr uint64_t valid[2] = { __bitset({1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45}) /* I2C0 */,
__bitset({3, 7, 11, 15, 19, 23, 27, 31, 35, 39, 43, 47}) /* I2C1 */
};
@@ -489,6 +489,14 @@ void TwoWire::flush(void) {
// data transfer.
}
bool TwoWire::busIdle() {
// Check hardware status
uint32_t status = _i2c->hw->status;
bool tfe = (status & I2C_IC_STATUS_TFE_BITS);
bool mast = (status & I2C_IC_STATUS_MST_ACTIVITY_BITS);
return (tfe && !mast);
}
// DMA/asynchronous transfers. Do not combime with synchronous runs or bad stuff will happen
// All buffers must be valid for entire DMA and not touched until `finishedAsync()` returns true.
bool TwoWire::writeReadAsync(uint8_t address, const void *wbuffer, size_t wbytes, const void *rbuffer, size_t rbytes, bool sendStop) {
@@ -496,6 +504,10 @@ bool TwoWire::writeReadAsync(uint8_t address, const void *wbuffer, size_t wbytes
return false;
}
if (!busIdle()) {
return false;
}
if (!_dmaRunning) {
beginAsync();
if (!_dmaRunning) {
@@ -507,7 +519,7 @@ bool TwoWire::writeReadAsync(uint8_t address, const void *wbuffer, size_t wbytes
abortAsync();
// Create or enlarge dma command buffer, we need one entry for every i2c byte we want to write/read
const size_t bufLen = (wbytes + rbytes) * 2;
const size_t bufLen = (wbytes + rbytes) * sizeof(uint16_t);
if (_dmaSendBufferLen < bufLen) {
if (_dmaSendBuffer) {
free(_dmaSendBuffer);
@@ -518,6 +530,7 @@ bool TwoWire::writeReadAsync(uint8_t address, const void *wbuffer, size_t wbytes
if (!_dmaSendBuffer) {
return false;
}
_dmaSendBufferLen = bufLen;
}
// Fill the dma command buffer
+1
View File
@@ -87,6 +87,7 @@ public:
bool writeReadAsync(uint8_t address, const void *wbuffer, size_t wbytes, const void *rbuffer, size_t rbytes, bool sendStop = true);
bool writeAsync(uint8_t address, const void *buffer, size_t bytes, bool sendStop = true);
bool readAsync(uint8_t address, void *buffer, size_t bytes, bool sendStop = true);
bool busIdle();
bool finishedAsync(); // Call to check if the async operations is completed and the buffer can be reused/read
void abortAsync(); // Cancel an outstanding async I2C operation
void onFinishedAsync(void(*function)(void)); // Set callback for async operation
+1 -1
View File
@@ -75,7 +75,7 @@ void __removeEthernetPacketHandler(int id) {
}
#define GPIOSTACKSIZE 8
#ifdef PICO_RP2350B
#if defined(PICO_RP2350) && !PICO_RP2350A // RP2350B
#define GPIOIRQREGS 6
#define GPIOIRQREGSINIT 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff
#else

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