Compare commits

...
92 Commits
Author SHA1 Message Date
Earle F. Philhower, III 7851dc8cb7 Update version 2023-03-10 09:08:28 -08:00
Philipp Molitor 75c553c391 Fix pin assigment for Waveshare RP2040 1.28 LCD PIN_BAT_ADC (#1292) 2023-03-10 04:31:33 -08:00
Earle F. Philhower, III 6bff270402 Manually add MDNS multicast Ethernet MACs to CYW43 (#1290)
SDK 1.5 changed the behavior of the underlying CYW43 blob, and it seems
to block MDNS multicast by default.  Manually add back the Ethernet MACs
used for MDNS multicast in IPV4 and IPV6.

Fixes #1267
2023-03-09 14:15:14 -08:00
nanoparticle 72f1e53106 Add board definition for Neko Systems BL2040 Mini (#1258) 2023-03-09 10:30:54 -08:00
Earle F. Philhower, III e6c7b97b5e Adjust LWIP intf to avoid hangs/crashes under load (#1286)
It seems possible now for TCP connection _pcbs to disappear while being
processed, due to the new async context configuration.  This would cause
LWIP to panic when a NULL pcb was passed in.

Check for and avoid passing in null PCBs in the ClientContext.

Undo special-casing of sys_check_timeouts wrapper

AdvancedWebServer with heavy F5-refresh and #1274 test both pass.

Fixes #1274
2023-03-08 11:48:23 -08:00
whimsee 54f9d3c414 Reassign I2C pins to correct buses (#1255) 2023-03-05 14:56:53 -08:00
Tim Boldtandtimboldt 9e272733cf Add instructions for making I2S input work with Adafruit microphone (#1272)
Co-authored-by: timboldt <tim.boldt@gmail.com>
2023-03-05 14:24:31 -08:00
Earle F. Philhower, III 51afd3440f Add Bluetooth to the PIO CI (#1269) 2023-03-05 08:48:24 -08:00
Sanjay Govind f67bc43584 Add Bluetooth support to Platform.io (#1259) 2023-03-05 08:23:22 -08:00
Earle F. Philhower, III 79e1af7bde Add Keyboard LED callback for USB and BT (not BLE) (#1265)
BLE seems to require some kind of characteristic callback that is not yeet
implemented here.  USB and BT tested and examples updated.
2023-03-04 14:18:40 -08:00
Earle F. Philhower, III 173c44417c Allow setting names for BT/BLE HID devices (#1260) 2023-03-04 12:38:34 -08:00
Earle F. Philhower, III 7aa1c08d17 Use generic HID classes to minimize code duplic'n (#1254)
Move the Joystick, Keyboard, and Mouse into a base class which handles
the operation/input, and a subclass which will implement the reporting
as a HID device via USB, Bluetooth Classic, or Bluetooth Low Energy (BLE).

Reduce copies of library code and makes maintainability much better.
2023-03-03 11:12:09 -08:00
Rei Vilo 0be1d9c3ea Fix picow default libname in platform.txt (#1250) 2023-03-03 07:40:02 -08:00
Earle F. Philhower, III 305e194993 Add setBattery to BLE HID devices (#1246) 2023-03-02 15:55:18 -08:00
Paint Your Dragon 719ab019a4 Add Adafruit Feather RP2040 DVI (#1245)
Includes option for QSPI/4 flash access on specific Adafruit boards for use when overclocking.
2023-03-02 15:54:19 -08:00
Earle F. Philhower, III e9df18f910 Update PicoBluetoothBLEHID.cpp 2023-03-02 08:18:02 -08:00
Earle F. Philhower, III 06a1fdac50 Update version 2023-03-01 16:59:38 -08:00
Earle F. Philhower, III 7308ef4117 Update bluetooth.rst 2023-03-01 16:44:35 -08:00
Earle F. Philhower, III 67c1db9957 JoystickBLE actually implements a gamepad, update appearance 2023-03-01 16:30:51 -08:00
Earle F. Philhower, III f5a621935d Add BLE HID libraries and examples (#1240) 2023-03-01 16:29:25 -08:00
Earle F. Philhower, III 354edb30d3 Move pico-sdk to RPI's original version (#1239)
No need to use my own fork, we're using the default upstream code.
2023-03-01 10:24:45 -08:00
Earle F. Philhower, III 96113fe848 Fix BLE enable definition (#1238)
BLE tested working with BTStack BLE hog-keyboard-demo.
2023-03-01 10:08:03 -08:00
Earle F. Philhower, III fd1596b6c9 Update keywords.txt 2023-02-28 12:41:22 -08:00
Earle F. Philhower, III 9760efbca3 Clean up the BT HID libraries a bit (#1236) 2023-02-28 10:10:39 -08:00
Earle F. Philhower, III d92c1025ba Update to SDK 1.5, add alpha-level BT support, use Pico-SDK CYW43 infrastructure (#1167)
* Update to Pico-SDK v1.5
* Hook in pico_rand, use ioctl to set ipv6 allmulti
* Move into PicoSDK LWIP mutex, hack timer sizes
* Utilize much of the PicoSDK infrastructure for WiFi
* Add WiFi::begin(ssid, pass, bssid)
* WiFiMulti to use BSSID, make more robust

WiFiMulti will now be more aggressive and try all matching SSIDs, in order
of RSSI, using the BSSID to identify individual APs in a mesh.

Before, if the highest RSSI AP didn't connect, it would fail immediately.
Now, it will go down the list, ordered by RSSI, to attempt to get a link.

* Add Bluetooth support from Pico-SDK
Able to build and run the HID Keyboard Demo from the Arduino IDE, almost
as-is.

Will probably need to make BT configurable.  Enabling BT on a plain WiFi
sketch uses 50KB of flash and 16KB of RAM even if no BT is used.

* Separate picow libs, BT through menus, example

Build normal Pico.a and 4 different options for PicoW IP/BT configuration.
Use IP=>IP/Bluetooth menu to select between options.

* CMakefile rationalization

* Move BT TLV(pairing) out of last 2 flash sectors

The pairing keys for BT are stored at the end of flash by default, but
we use the last sector of flash for EPROM and the penultimate one for
the filesystem.  Overwriting those in BT could cause some real exciting
crashes down the line.

Move the store to an app-build specific address using a dummy const
array to allocate space in the application image itself.

* PicoBluetoothHID with BT Mouse, Joystick, Keyboard

Add simple Bluetooth Classic HID helper function and port the existing
USB HID devices to it.  Port their examples.

* Protect BT key storage from multicore

* Add short-n-sweet Bluetooth documents

* Add Bluetooth Serial port library

* Turn off BT when the BT libraries exit
2023-02-27 20:09:02 -08:00
Earle F. Philhower, III de55db12f1 Update rp2040.rst 2023-02-26 18:54:32 -08:00
Earle F. Philhower, III 264b9efb36 Return custom USB product and manufacturer (#1223)
Return the pre-existing USB_PRODUCT/MANUFACTURER to the USB host in
the ID stage, allowing for reports like:

[1412958.589070] usb 1-6.3.4.1: New USB device found, idVendor=2e8a, idProduct=f00a, bcdDevice= 1.00
[1412958.589076] usb 1-6.3.4.1: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[1412958.589079] usb 1-6.3.4.1: Product: Pico W
[1412958.589080] usb 1-6.3.4.1: Manufacturer: Raspberry Pi
[1412958.589081] usb 1-6.3.4.1: SerialNumber: E6614C775B6C7F31

or

[1413190.272233] usb 1-6.3.4.1: New USB device found, idVendor=2e8a, idProduct=1037, bcdDevice= 1.00
[1413190.272239] usb 1-6.3.4.1: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[1413190.272242] usb 1-6.3.4.1: Product: HunterCat NFC RP2040
[1413190.272243] usb 1-6.3.4.1: Manufacturer: ElectronicCats
[1413190.272244] usb 1-6.3.4.1: SerialNumber: E6614C775B6C7F31
2023-02-23 17:13:12 -08:00
Earle F. Philhower, III 9fd5cdf1ba Move PicoW auto-reassignment of LED pin to code (#1208)
Many examples require that LED_BUILTIN be defined as a constant, so we
can't use a ternary operator to swap between Pico and PicoW LED pins.

Instead, do the check in the digitalWrite/digitalRead/pinMode calls
to cover most of the uses.
2023-02-22 16:13:24 -08:00
Earle F. Philhower, III 1b33cbe591 Always apply 5M speed to CMSIS_DAP TCL script (#1218)
Still need it on the command line in platform.txt for upload/etc., but make the
debug script in lib/picoprobe_cmsis_dap.tcl include the adapter speed setting.
2023-02-21 12:30:05 -08:00
MisterSilvereagleandEarle F. Philhower, III a97d5eab22 Fix spelling mistake (#1211)
Co-authored-by: Earle F. Philhower, III <earlephilhower@yahoo.com>
2023-02-20 09:58:50 -08:00
crp500 83e790851f Update PlayStereo.ino (#1210)
The PWMAudio lib is expecting an int16_t value but the example passes a sample cast to uint16_t 
So any values from the lookup table that are negative are recast to 0 i think.
So half the sine wave in the case of the example is lost.
2023-02-20 09:58:14 -08:00
Earle F. Philhower, III 11ac5ed33e Update version 2023-02-18 13:04:53 -08:00
Earle F. Philhower, III b7912f182b Add isPicoW call to RP2040 object (#1204)
Use the RPi code to get a best-guess as to whether the board is a Pico or
PicoW.

Fixes #849
2023-02-18 13:00:02 -08:00
Earle F. Philhower, III 6db0ac8471 Add release package fixups for picoprobe-cmsis-dap (#1205) 2023-02-18 12:14:23 -08:00
Ha Thach 060aa52c89 Add picoprobe CMSIS-DAP support (#1198) 2023-02-18 12:09:02 -08:00
Carter Nelson ba413bb7ad Remove extra SPI byte flip (#1202)
Fixes #1201
2023-02-17 12:42:31 -08:00
Earle F. Philhower, III 97e787e48a Reduce unintialized_ram overhead to 0 in most cases (#1200)
Use GNU LD MAX() to ensure the uninitialized RAM portions are after the
OTA region.  For most apps this already happens, so there will be no
overhead added.
2023-02-16 18:23:15 -08:00
Earle F. Philhower, III b473139758 Enable use of uninitialized_ram() macro (#1199)
The uninitted RAM macro would fail because the OTA code would clear out the
first 50KB or so of RAM to copy its code and global values.

Move all global values to the end of RAM in OTA, and then align any uninitted
vars to a 16KB unit to ensure it won't appear in the 1st part of RAM that is
still needed to copy the OTA executable.

In the normal case, without any uninit_ram vars, no additional space is used.
When uninit_ram is used, up to 16KB of space may be lost to get that alignment,
but it will work properly.

Fixes #1188
2023-02-16 17:59:15 -08:00
Earle F. Philhower, III 7afcec8edc Update picotool refs in JSON (#1197) 2023-02-15 18:49:40 -08:00
Earle F. Philhower, III d1a3009447 Upgrade to toolchain 1.5.0-b (#1196)
Includes fixes for ::printf/etc. using stdout/stderr
Fixes #1181
2023-02-15 18:20:18 -08:00
Earle F. Philhower, III 651d596246 Allow FreeRTOS to ::printf (#1195)
The stdin/stdout FILEs have an internal mutex which needs to be initted
to a FreeRTOS one, or any sketch with ::printf will hang.  Automatically
create and acquire/release the shadowed mutex.

Requires new build of pico-quick-toolchain to function properly.  Tested
on preliminary local build.
2023-02-15 15:58:45 -08:00
Earle F. Philhower, III 75bab41e39 Make uf2conf.py flush STDOUT for real-time updates (#1194)
Without flushing STDOUT, the upload script's output aften are buffered
and not displayed until it completes.  Add in flush commands to allow
the IDE to display status as it changes.
2023-02-15 12:13:55 -08:00
Earle F. Philhower, III 36e0b4a908 Unbreak FreeRTOS (#1193)
USB changes caused FreeRTOS to not be able to swap tasks when the Serial port
was connected.  Clear the "stop PendSV" flag after checking for reset signal.
2023-02-15 12:10:52 -08:00
Earle F. Philhower, III 974301eaaf Add rp2040.cpuid() call to get running core (#1190)
Per question received via email.
2023-02-14 16:22:04 -08:00
Earle F. Philhower, III 2acc161ad2 Update contrib.rst 2023-02-14 13:24:02 -08:00
Earle F. Philhower, III 7322bad830 Add docs on adding a new board to the core, too 2023-02-14 08:46:24 -08:00
Earle F. Philhower, III 6afd3260ef Update README.md 2023-02-13 14:56:46 -08:00
Earle F. Philhower, III 76e7cca821 Add contributing docs (#1183) 2023-02-13 14:54:52 -08:00
Earle F. Philhower, III 84206eb237 Fix SD.H FILE_WRITE mapping (#1178)
O_RDWR != O_READ|O_WRITE.  Posix is weird.  Thanks @mcspr
2023-02-12 17:46:50 -08:00
Earle F. Philhower, III 5e576c1a08 Update SD examples with working SPI configs (#1175)
Fixes #1172
2023-02-12 11:01:01 -08:00
Earle F. Philhower, III fc180041aa Implement WiFi::softAPgetStationNum (#1174) 2023-02-12 10:38:37 -08:00
Earle F. Philhower, III 1bfd07c19a Update version 2023-02-11 12:34:40 -08:00
Andrew KrollandEarle F. Philhower, III 5dafbf57e9 Optimize and improve upload experience (#1136)
Stop the IDE from reporting large "Serial port not fount"-type errors after
every upload by delaying a bit before the uploader exits to give the OS/Pico
time to renegotiate.

Fixes flashing problems on certain Linux distros by checking all possible mount
locations instead of only the first one to be found.

Make 1200bps reset tickle more robust

Co-authored-by: Earle F. Philhower, III <earlephilhower@yahoo.com>
2023-02-11 12:33:44 -08:00
Earle F. Philhower, III 09db2e6c37 Apply SD.h fix from ESP8266 (#1171)
Pull in the portion of the change correcting the flag setting from
https://github.com/esp8266/Arduino/pull/8833
2023-02-11 11:57:27 -08:00
Earle F. Philhower, III b6cb2e7edc Avoid race condition in I2S/PWMAudio delete (#1163)
Fixes #1162

Disable DMA interrupts while we're tearing down an AudioBufferManager
and explicitly clear any potential leftover IRQs to avoid hangs.
2023-02-09 13:29:45 -08:00
Earle F. Philhower, III bedcbf57c6 Add ESP8266/32 WiFi.isConnected wrapper (#1166)
Fixes #1165
2023-02-09 08:39:35 -08:00
TomKong666 7df080ee92 PDM library re-port (#1160)
See #1156
2023-02-07 08:10:24 -08:00
Earle F. Philhower, III b400897ca2 Avoid initial glitch on Serial1/2 when RX high (#1154)
Fixes #1153

Set up the GPIO redirects before the UART is pulled from reset to avoid
a possible bad byte at `Serial1/2.begin()`.
2023-02-01 19:15:58 -08:00
uPesy Electronics 7573500e59 Add uPesy Tutorials using Arduino Pico port. (#1151) 2023-02-01 06:52:25 -08:00
Vishnu Mohanan 8a1e03739a Fix SPI transfer16 return value (#1148)
The SPI transfer16() function returned wrongly oriented bytes. Replaced reverseByte() with reverse16Bit().

Fixes #1146
2023-01-31 08:09:53 -08:00
Earle F. Philhower, III a1af9698ac Fix USB VID/PID setting, rationalize boards.txt (#1144)
The USB VID was always being set to the Raspberry Pi foundation code,
causing other brand boards to show up incorrectly.

Remove redundant values from the boards.txt and define a consistent
USB VID/PID and use it in the setup code.

See #1129 for more info
2023-01-28 11:10:39 -08:00
Earle F. Philhower, III af01c3cc77 Add boot2_w25q128jv to generic Pico flash menu (#1142)
Add-on to #1126
2023-01-26 16:35:16 -08:00
Earle F. Philhower, III 4c8bdc2bfc Print useful uf2conv error if executable not found (#1141)
Fixes #1140

````
Converting to uf2, output size: 134144, start address: 0x2000
ERROR: Unable to execute powershell or wmic commands, can't continue.
ERROR: Please make sure either PowerShell or WMIC is installed and in
       your %PATH%.
````
2023-01-26 11:02:07 -08:00
Conor Burns c58f94a9ba Add correct boot source to helios (#1126) 2023-01-25 14:45:51 -08:00
Earle F. Philhower, III ecaa2bd778 Fix SerialUART::overflow reporting race condition (#1133)
Fixes #1132
2023-01-21 01:38:15 -08:00
Earle F. Philhower, III d619bf0bc1 More minor ESP8266 compatibility tweaks (#1131) 2023-01-20 17:06:40 -08:00
Gavin Hurlbut 9a241b0e43 Add Serial UART break reporting (#1130)
Added SerialUART::getBreakReceived()
2023-01-20 16:54:31 -08:00
Earle F. Philhower, III e3f2f87e2d Add more ESP8266 WiFi compatibility wrappers (#1128) 2023-01-19 12:44:05 -08:00
Earle F. Philhower, III a8238cb0d4 Add the YD-RP2040 support files
Oops!
2023-01-19 07:57:26 -08:00
Earle F. Philhower, III f212720484 Update version 2023-01-14 14:34:45 -08:00
Earle F. Philhower, III 1328f78099 Add VCC-GND YD-RP2040 board (#1120)
Fixes #1109
2023-01-14 14:33:52 -08:00
Earle F. Philhower, III 4c234310fd Add hook support to WebServer (#1119)
Implement the method used in the ESP8266 Web Server to allow user apps to hook into
the HTTP server (to support hooked WebSockets, etc._)

Add example of hook usage
2023-01-14 13:35:33 -08:00
Conor Burns f7ee4a868a Add 0xCB Helios (#1117) 2023-01-14 12:19:27 -08:00
Earle F. Philhower, III ae386d4308 Redo boards menu, separate out upload method, add picotool upload (#1112)
Instead of listing each board three times (normal upload, picoprobe,
and pico-debug uploads), list each board once and use a menu to select
the actual upload method.

Also add in picotool as an upload method for those folks who have trouble
with automounting.

Fix #1111
2023-01-13 13:04:24 -08:00
Earle F. Philhower, III ff9f5d3809 Update README.md 2023-01-09 09:55:27 -08:00
Earle F. Philhower, III ce17a6200b Update install.rst 2023-01-09 08:08:57 -08:00
AnachronisticPenguin 8289bbd27b Add additional instructions for Linux Flatpak users (#1105)
Provide instructions for users to override filesystem access restrictions imposed by Flatpak on some installations of the Arduino IDE
2023-01-09 08:03:30 -08:00
Earle F. Philhower, III aeb41f3e70 Handle slave mode I2C restarts (#1104)
Fixes #1100
2023-01-06 12:23:53 -08:00
Earle F. Philhower, III cefea28539 Stop the I2S PIO when I2S::end called (#1103) 2023-01-06 12:23:26 -08:00
Earle F. Philhower, III da26016edf DMA-based ADC input (microphone, analog sensor) (#1101)
Mimics the I2S/PWMAudio/Stream interface for ease of use.

* Fix non-32b DMA size transfer calculation in ABM
* Rename wasHolding to isHolding in the I2S/PWM
  It is the **current** number of bits left, not the past number.
* Add commented microphone example
* Add docs
2023-01-05 16:00:34 -08:00
Earle F. Philhower, III 6bef238772 Update to LittleFS 2.5.1 (only minor updates) (#1099) 2023-01-03 18:51:28 -08:00
Earle F. Philhower, III 02465b48b3 Allow on-the-fly changes to PWMAudio when possible (#1098)
Also fix crash on PWMAudio::end()
2023-01-03 16:02:43 -08:00
Earle F. Philhower, III 94abf9d19f Move analogReadTemp() to C++-only (#1097)
Now that we have a default parameter, need to only allow it in C++ since
default values are not part of C spec.  Should not affect any users since
only legacy code is in C.
2023-01-03 13:30:11 -08:00
Thomas Combriat 7a4244180b Set Right and Left correctly for lsbj format (#1096) 2023-01-03 13:15:08 -08:00
Earle F. Philhower, III 6fe6c474f7 Add LSBJ format support for I2S (#1095)
Fixes #1094
2023-01-03 11:47:55 -08:00
Earle F. Philhower, III be34ed1385 Reduce stack usage of several components (#1093)
Only 4K total stack, so allocating 400 bytes for a local C string
or 600 bytes for a DHCP response is dangerous.  Use static allocations
instead on the heap.
2023-01-02 11:40:51 -08:00
Earle F. Philhower, III 444bb24464 Remove debug printout warnings (#1091)
Exposed by #1090, remove ugly printf format warnings while in debug mode
2023-01-02 10:51:04 -08:00
NuclearPhoenix 0e6ca28316 Update wiring_analog.cpp (#1092) 2023-01-02 10:44:49 -08:00
Earle F. Philhower, III d718b143d2 Warn when Serial.printf() format is wrong (#1090)
Let GCC check the format string to Print::printf().  Will catch when
sketches use incorrect parameters to `Serial::printf()`.
2023-01-01 15:26:15 -08:00
Axotron 1e2f1a19ff Adding sei() and cli() as aliases for interrupts() and noInterrupts(). (#1089) 2023-01-01 14:18:06 -08:00
Earle F. Philhower, III 1228251bc3 Add stereo support, docs for PWM playback (#1084)
Limited to consecutive pins (i.e. GPIOs on the same PWM slice).
"For free" with PWM since no add'l DMA, buffers, or IRQs are needed.
2023-01-01 11:27:49 -08:00
Earle F. Philhower, III a781ec2fdd Add WString.h include redirect for broader compat (#1083)
See #1079
2022-12-31 11:03:28 -08:00
231 changed files with 28621 additions and 35382 deletions
+2
View File
@@ -217,3 +217,5 @@ jobs:
run: pio ci --board=rpipicow -O "platform_packages=framework-arduinopico@symlink:///home/runner/work/arduino-pico/arduino-pico" libraries/WiFi/examples/ScanNetworks/ScanNetworks.ino
- name: Build Signed OTA Example
run: pio ci --board=rpipicow -O "platform_packages=framework-arduinopico@symlink:///home/runner/work/arduino-pico/arduino-pico" libraries/ArduinoOTA/examples/SignedOTA/SignedOTA.ino
- name: Build Bluetooth Example
run: pio ci --board=rpipicow -O "platform_packages=framework-arduinopico@symlink:///home/runner/work/arduino-pico/arduino-pico" -O "build_flags=-DPIO_FRAMEWORK_ARDUINO_ENABLE_BLUETOOTH" libraries/MouseBLE/examples/BLECircle/BLECircle.ino
+7 -7
View File
@@ -3,7 +3,7 @@
url = https://github.com/earlephilhower/ArduinoCore-API.git
[submodule "pico-sdk"]
path = pico-sdk
url = https://github.com/earlephilhower/pico-sdk.git
url = https://github.com/raspberrypi/pico-sdk.git
[submodule "system/pyserial"]
path = tools/pyserial
url = https://github.com/pyserial/pyserial.git
@@ -14,14 +14,14 @@
path = libraries/ESP8266SdFat
url = https://github.com/earlephilhower/ESP8266SdFat.git
[submodule "libraries/Keyboard"]
path = libraries/Keyboard
url = https://github.com/earlephilhower/Keyboard
path = libraries/HID_Keyboard
url = https://github.com/earlephilhower/Keyboard.git
[submodule "libraries/Mouse"]
path = libraries/Mouse
url = https://github.com/earlephilhower/Mouse
path = libraries/HID_Mouse
url = https://github.com/earlephilhower/Mouse.git
[submodule "libraries/Joystick"]
path = libraries/Joystick
url = https://github.com/benjaminaigner/Joystick
path = libraries/HID_Joystick
url = https://github.com/earlephilhower/Joystick.git
[submodule "libraries/Adafruit_TinyUSB_Arduino"]
path = libraries/Adafruit_TinyUSB_Arduino
url = https://github.com/adafruit/Adafruit_TinyUSB_Arduino.git
+14 -1
View File
@@ -9,9 +9,13 @@ This is a port of the RP2040 (Raspberry Pi Pico processor) to the Arduino ecosys
# Documentation
See https://arduino-pico.readthedocs.io/en/latest/ along with the examples for more detailed usage information.
# Contributing
Read the [Contributing Guide](https://github.com/earlephilhower/arduino-pico/blob/master/docs/contrib.rst) for more information on submitting pull requests and porting libraries or sketches to this core.
# Supported Boards
* Raspberry Pi Pico
* Raspberry Pi Pico W
* 0xCB Helios
* Adafruit Feather RP2040
* Adafruit Feather RP2040 SCORPIO
* Adafruit ItsyBitsy RP2040
@@ -39,6 +43,7 @@ See https://arduino-pico.readthedocs.io/en/latest/ along with the examples for m
* Invector Labs RPICO32
* Melopero Cookie RP2040
* Melopero Shake RP2040
* Neko Systems BL2040 Mini
* nullbits Bit-C PRO
* Pimoroni PGA2040
* Seeed XIAO RP2040
@@ -46,6 +51,7 @@ See https://arduino-pico.readthedocs.io/en/latest/ along with the examples for m
* SparkFun ProMicro RP2040
* SparkFun Thing Plus RP2040
* uPesy RP2040 DevKit
* VCC-GND YD-RP2040
* Viyalab Mizu RP2040
* Waveshare RP2040 Zero
* Waveshare RP2040 One
@@ -158,7 +164,8 @@ The installed tools include a version of OpenOCD (in the pqt-openocd directory)
# Features
* Adafruit TinyUSB Arduino (USB mouse, keyboard, flash drive, generic HID, CDC Serial, MIDI, WebUSB, others)
* Generic Arduino USB Serial, Keyboard, and Mouse emulation
* Bluetooth on the PicoW (Classic and BLE) with Keyboard, Mouse, Joystick, and Virtual Serial
* Generic Arduino USB Serial, Keyboard, Joystick, and Mouse emulation
* WiFi (Pico W)
* HTTP client and server (WebServer)
* SSL/TLS/HTTPS
@@ -168,6 +175,9 @@ The installed tools include a version of OpenOCD (in the pqt-openocd directory)
* FreeRTOS SMP support
* Overclocking and underclocking from the menus
* digitalWrite/Read, shiftIn/Out, tone, analogWrite(PWM)/Read, temperature
* Analog stereo audio in using DMA and the built-in ADC
* Analog stereo audio out using PWM hardware
* USB drive mode for data loggers (SingleFileDrive)
* Peripherals: SPI master, Wire(I2C) master/slave, dual UART, emulated EEPROM, I2S audio input, I2S audio output, Servo
* printf (i.e. debug) output over USB serial
@@ -186,6 +196,9 @@ Here are some links to coverage and additional tutorials for using `arduino-pico
* Adafruit Feather RP2040 running LCD + TMP117 - https://www.youtube.com/watch?v=fKDeqZiIwHg
* Demonstration of Servos and I2C in Korean - https://cafe.naver.com/arduinoshield/1201
* Home Assistant Pico W integration starter project using Arduino - https://github.com/daniloc/PicoW_HomeAssistant_Starter
* Tutorials for the Raspberry Pi Pico / uPesy RP2040 DevKit board
- English version: https://www.upesy.com/blogs/tutorials/best-tutorials-for-rpi-pi-pico-with-arduino-code
- French version: https://www.upesy.fr/blogs/tutorials/best-tutorials-for-rpi-pi-pico-with-arduino-code
# Contributing
If you want to contribute or have bugfixes, drop me a note at <earlephilhower@yahoo.com> or open an issue/PR here.
+3288 -19157
View File
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,23 @@
// Padded and checksummed version of: generated\Winbond\W25Q128JVxQ\boot2.bin by @maxgerhardt
.cpu cortex-m0plus
.thumb
.section .boot2, "ax"
.byte 0xf7, 0xb5, 0x73, 0x46, 0x21, 0x22, 0x02, 0x26, 0x01, 0x93, 0x29, 0x4b, 0xc0, 0x24, 0x5a, 0x60
.byte 0x9a, 0x68, 0x00, 0x27, 0xb2, 0x43, 0xda, 0x60, 0x9a, 0x60, 0x1a, 0x61, 0x5a, 0x61, 0x04, 0x23
.byte 0x01, 0x25, 0x64, 0x05, 0xa7, 0x60, 0x63, 0x61, 0x22, 0x4b, 0x30, 0x00, 0x1d, 0x60, 0xe0, 0x23
.byte 0xdb, 0x02, 0x23, 0x60, 0x35, 0x23, 0xa5, 0x60, 0x23, 0x66, 0x23, 0x66, 0x00, 0xf0, 0x4a, 0xf8
.byte 0xc0, 0xb2, 0xb0, 0x42, 0x12, 0xd0, 0x06, 0x23, 0x28, 0x00, 0x23, 0x66, 0x00, 0xf0, 0x42, 0xf8
.byte 0x25, 0x66, 0x03, 0x20, 0x27, 0x66, 0x26, 0x66, 0x00, 0xf0, 0x3c, 0xf8, 0x03, 0x36, 0x26, 0x66
.byte 0x02, 0x20, 0x26, 0x66, 0x00, 0xf0, 0x36, 0xf8, 0x28, 0x42, 0xf8, 0xd1, 0x00, 0x25, 0x12, 0x4b
.byte 0xa5, 0x60, 0x12, 0x4f, 0x23, 0x60, 0x12, 0x4b, 0x65, 0x60, 0x01, 0x26, 0x3b, 0x60, 0xeb, 0x23
.byte 0xa6, 0x60, 0x23, 0x66, 0x4b, 0x3b, 0x23, 0x66, 0x02, 0x20, 0x00, 0xf0, 0x23, 0xf8, 0x0d, 0x4b
.byte 0xa5, 0x60, 0x3b, 0x60, 0xa6, 0x60, 0x01, 0x9b, 0xab, 0x42, 0x08, 0xd1, 0x0a, 0x4b, 0x0b, 0x4a
.byte 0x13, 0x60, 0x1b, 0x68, 0x83, 0xf3, 0x08, 0x88, 0x09, 0x4b, 0x1b, 0x68, 0x18, 0x47, 0xf7, 0xbd
.byte 0x00, 0x00, 0x02, 0x40, 0xf0, 0x00, 0x00, 0x18, 0x00, 0x03, 0x5f, 0x00, 0xf4, 0x00, 0x00, 0x18
.byte 0x21, 0x22, 0x00, 0x00, 0x22, 0x20, 0x00, 0xa0, 0x00, 0x01, 0x00, 0x10, 0x08, 0xed, 0x00, 0xe0
.byte 0x04, 0x01, 0x00, 0x10, 0xc0, 0x22, 0x03, 0x00, 0x04, 0x21, 0x52, 0x05, 0x90, 0x6a, 0x08, 0x42
.byte 0xfc, 0xd0, 0x01, 0x21, 0x90, 0x6a, 0x08, 0x42, 0xfc, 0xd1, 0x01, 0x3b, 0xdb, 0xb2, 0x10, 0x6e
.byte 0x00, 0x2b, 0xfa, 0xd1, 0x70, 0x47, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xaa, 0xa0, 0xf0, 0x2f
+7
View File
@@ -70,10 +70,14 @@ void noInterrupts();
#define portModeRegister(port) ((volatile uint32_t*) sio_hw->gpio_oe)
#define digitalWriteFast(pin, val) (val ? sio_hw->gpio_set = (1 << pin) : sio_hw->gpio_clr = (1 << pin))
#define digitalReadFast(pin) ((1 << pin) & sio_hw->gpio_in)
#define sei() interrupts()
#define cli() noInterrupts()
// ADC RP2040-specific calls
void analogReadResolution(int bits);
#ifdef __cplusplus
float analogReadTemp(float vref = 3.3); // Returns core temp in Centigrade
#endif
// PWM RP2040-specific calls
void analogWriteFreq(uint32_t freq);
@@ -103,6 +107,9 @@ extern bool __isFreeRTOS;
#ifdef __cplusplus
// emptyString is an ESP-ism, a constant string with ""
extern const String emptyString;
#ifdef USE_TINYUSB
// Needed for declaring Serial
#include "Adafruit_USBD_CDC.h"
+17 -19
View File
@@ -27,6 +27,7 @@
#include <hardware/structs/rosc.h>
#include <hardware/structs/systick.h>
#include <pico/multicore.h>
#include <pico/rand.h>
#include <pico/util/queue.h>
#include "CoreMutex.h"
#include "ccount.pio.h"
@@ -246,6 +247,11 @@ public:
return clock_get_hz(clk_sys);
}
// Get current CPU core number
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;
inline uint32_t getCycleCount() {
@@ -336,28 +342,20 @@ public:
_MFIFO fifo;
// TODO - Not so great HW random generator. 32-bits wide. Cryptographers somewhere are crying
uint32_t hwrand32() {
// Try and whiten the HW ROSC bit
uint32_t r = 0;
for (int k = 0; k < 32; k++) {
unsigned long int b;
do {
b = rosc_hw->randombit & 1;
if (b != (rosc_hw->randombit & 1)) {
break;
}
} while (true);
r <<= 1;
r |= b;
}
// Stir using the cycle count LSBs. In any WiFi use case this will be a random # since the connection time is not cycle-accurate
uint64_t rr = (((uint64_t)~r) << 32LL) | r;
rr >>= rp2040.getCycleCount() & 32LL;
return (uint32_t)rr;
return get_rand_32();
}
bool isPicoW() {
#if !defined(ARDUINO_RASPBERRY_PI_PICO_W)
return false;
#else
extern bool __isPicoW;
return __isPicoW;
#endif
}
private:
static void _SystickHandler() {
rp2040._epoch += 1LL << 24;
+113 -7
View File
@@ -33,6 +33,10 @@
#include "hardware/irq.h"
#include "pico/mutex.h"
#include "pico/unique_id.h"
#include "pico/usb_reset_interface.h"
#include "hardware/watchdog.h"
#include "pico/bootrom.h"
#include <device/usbd_pvt.h>
// Big, global USB mutex, shared with all USB devices to make sure we don't
// have multiple cores updating the TUSB state in parallel
@@ -42,12 +46,11 @@ mutex_t __usb_mutex;
#define USB_TASK_INTERVAL 1000
static int __usb_task_irq;
// USB VID/PID (note that PID can change depending on the add'l interfaces)
#ifndef USBD_VID
#define USBD_VID (0x2E8A) // Raspberry Pi
#endif
#ifdef SERIALUSB_PID
#define USBD_PID (SERIALUSB_PID)
#else
#ifndef USBD_PID
#define USBD_PID (0x000a) // Raspberry Pi Pico SDK CDC
#endif
@@ -67,6 +70,7 @@ static int __usb_task_irq;
#define USBD_STR_PRODUCT (0x02)
#define USBD_STR_SERIAL (0x03)
#define USBD_STR_CDC (0x04)
#define USBD_STR_RPI_RESET (0x05)
#define EPNUM_HID 0x83
@@ -74,6 +78,11 @@ static int __usb_task_irq;
#define USBD_MSC_EPIN 0x84
#define USBD_MSC_EPSIZE 64
#define TUD_RPI_RESET_DESCRIPTOR(_itfnum, _stridx) \
/* Interface */\
9, TUSB_DESC_INTERFACE, _itfnum, 0, 0, TUSB_CLASS_VENDOR_SPECIFIC, RESET_INTERFACE_SUBCLASS, RESET_INTERFACE_PROTOCOL, _stridx,
const uint8_t *tud_descriptor_device_cb(void) {
static tusb_desc_device_t usbd_desc_device = {
.bLength = sizeof(tusb_desc_device_t),
@@ -250,6 +259,14 @@ void __SetupUSBDescriptor() {
int usbd_desc_len = TUD_CONFIG_DESC_LEN + (__USBInstallSerial ? sizeof(cdc_desc) : 0) + (hasHID ? sizeof(hid_desc) : 0) + (__USBInstallMassStorage ? sizeof(msd_desc) : 0);
#ifdef ENABLE_PICOTOOL_USB
uint8_t picotool_itf = interface_count++;
uint8_t picotool_desc[] = {
TUD_RPI_RESET_DESCRIPTOR(picotool_itf, USBD_STR_RPI_RESET)
};
usbd_desc_len += sizeof(picotool_desc);
#endif
uint8_t tud_cfg_desc[TUD_CONFIG_DESC_LEN] = {
// Config number, interface count, string index, total length, attribute, power in mA
TUD_CONFIG_DESCRIPTOR(1, interface_count, USBD_STR_0, usbd_desc_len, TUSB_DESC_CONFIG_ATT_REMOTE_WAKEUP, USBD_MAX_POWER_MA)
@@ -274,23 +291,30 @@ void __SetupUSBDescriptor() {
memcpy(ptr, msd_desc, sizeof(msd_desc));
ptr += sizeof(msd_desc);
}
#ifdef ENABLE_PICOTOOL_USB
memcpy(ptr, picotool_desc, sizeof(picotool_desc));
ptr += sizeof(picotool_desc);
#endif
}
}
}
const uint16_t *tud_descriptor_string_cb(uint8_t index, uint16_t langid) {
(void) langid;
#define DESC_STR_MAX (20)
#define DESC_STR_MAX (32)
static uint16_t desc_str[DESC_STR_MAX];
static char idString[PICO_UNIQUE_BOARD_ID_SIZE_BYTES * 2 + 1];
static const char *const usbd_desc_str[] = {
[USBD_STR_0] = "",
[USBD_STR_MANUF] = "Raspberry Pi",
[USBD_STR_PRODUCT] = "PicoArduino",
[USBD_STR_MANUF] = USB_MANUFACTURER,
[USBD_STR_PRODUCT] = USB_PRODUCT,
[USBD_STR_SERIAL] = idString,
[USBD_STR_CDC] = "Board CDC",
#ifdef ENABLE_PICOTOOL_USB
[USBD_STR_RPI_RESET] = "Reset",
#endif
};
if (!idString[0]) {
@@ -359,6 +383,7 @@ void __USBStart() {
// Invoked when received GET_REPORT control request
// Application must fill buffer report's content and return its length.
// Return zero will cause the stack to STALL request
extern "C" uint16_t tud_hid_get_report_cb(uint8_t instance, uint8_t report_id, hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen) __attribute__((weak));
extern "C" uint16_t tud_hid_get_report_cb(uint8_t instance, uint8_t report_id, hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen) {
// TODO not implemented
(void) instance;
@@ -372,6 +397,7 @@ extern "C" uint16_t tud_hid_get_report_cb(uint8_t instance, uint8_t report_id, h
// Invoked when received SET_REPORT control request or
// received data on OUT endpoint ( Report ID = 0, Type = 0 )
extern "C" void tud_hid_set_report_cb(uint8_t instance, uint8_t report_id, hid_report_type_t report_type, uint8_t const* buffer, uint16_t bufsize) __attribute__((weak));
extern "C" void tud_hid_set_report_cb(uint8_t instance, uint8_t report_id, hid_report_type_t report_type, uint8_t const* buffer, uint16_t bufsize) {
// TODO set LED based on CAPLOCK, NUMLOCK etc...
(void) instance;
@@ -432,4 +458,84 @@ extern "C" void tud_msc_inquiry_cb(uint8_t lun, uint8_t vendor_id[8], uint8_t pr
}
#ifdef ENABLE_PICOTOOL_USB
static uint8_t _picotool_itf_num;
static void resetd_init() {
}
static void resetd_reset(uint8_t rhport) {
(void) rhport;
_picotool_itf_num = 0;
}
static uint16_t resetd_open(uint8_t rhport,
tusb_desc_interface_t const *itf_desc, uint16_t max_len) {
(void) rhport;
TU_VERIFY(TUSB_CLASS_VENDOR_SPECIFIC == itf_desc->bInterfaceClass &&
RESET_INTERFACE_SUBCLASS == itf_desc->bInterfaceSubClass &&
RESET_INTERFACE_PROTOCOL == itf_desc->bInterfaceProtocol, 0);
uint16_t const drv_len = sizeof(tusb_desc_interface_t);
TU_VERIFY(max_len >= drv_len, 0);
_picotool_itf_num = itf_desc->bInterfaceNumber;
return drv_len;
}
// Support for parameterized reset via vendor interface control request
static bool resetd_control_xfer_cb(uint8_t rhport, uint8_t stage,
tusb_control_request_t const *request) {
(void) rhport;
// nothing to do with DATA & ACK stage
if (stage != CONTROL_STAGE_SETUP) {
return true;
}
if (request->wIndex == _picotool_itf_num) {
if (request->bRequest == RESET_REQUEST_BOOTSEL) {
reset_usb_boot(0, (request->wValue & 0x7f));
// does not return, otherwise we'd return true
}
if (request->bRequest == RESET_REQUEST_FLASH) {
watchdog_reboot(0, 0, 100);
return true;
}
}
return false;
}
static bool resetd_xfer_cb(uint8_t rhport, uint8_t ep_addr,
xfer_result_t result, uint32_t xferred_bytes) {
(void) rhport;
(void) ep_addr;
(void) result;
(void) xferred_bytes;
return true;
}
static usbd_class_driver_t const _resetd_driver = {
#if CFG_TUSB_DEBUG >= 2
.name = "RESET",
#endif
.init = resetd_init,
.reset = resetd_reset,
.open = resetd_open,
.control_xfer_cb = resetd_control_xfer_cb,
.xfer_cb = resetd_xfer_cb,
.sof = NULL
};
// Implement callback to add our custom driver
usbd_class_driver_t const *usbd_app_driver_get_cb(uint8_t *driver_count) {
*driver_count = 1;
return &_resetd_driver;
}
#endif
#endif
+3 -3
View File
@@ -1,5 +1,5 @@
#pragma once
#define ARDUINO_PICO_MAJOR 2
#define ARDUINO_PICO_MINOR 7
#define ARDUINO_PICO_MAJOR 3
#define ARDUINO_PICO_MINOR 1
#define ARDUINO_PICO_REVISION 0
#define ARDUINO_PICO_VERSION_STR "2.7.0"
#define ARDUINO_PICO_VERSION_STR "3.1.0"
+53 -18
View File
@@ -134,6 +134,20 @@ void SerialUART::begin(unsigned long baud, uint16_t config) {
_overflow = false;
_queue = new uint8_t[_fifoSize];
_baud = baud;
_fcnTx = gpio_get_function(_tx);
_fcnRx = gpio_get_function(_rx);
gpio_set_function(_tx, GPIO_FUNC_UART);
gpio_set_function(_rx, GPIO_FUNC_UART);
if (_rts != UART_PIN_NOT_DEFINED) {
_fcnRts = gpio_get_function(_rts);
gpio_set_function(_rts, GPIO_FUNC_UART);
}
if (_cts != UART_PIN_NOT_DEFINED) {
_fcnCts = gpio_get_function(_cts);
gpio_set_function(_cts, GPIO_FUNC_UART);
}
uart_init(_uart, baud);
int bits, stop;
uart_parity_t parity;
@@ -171,18 +185,6 @@ void SerialUART::begin(unsigned long baud, uint16_t config) {
break;
}
uart_set_format(_uart, bits, stop, parity);
_fcnTx = gpio_get_function(_tx);
_fcnRx = gpio_get_function(_rx);
gpio_set_function(_tx, GPIO_FUNC_UART);
gpio_set_function(_rx, GPIO_FUNC_UART);
if (_rts != UART_PIN_NOT_DEFINED) {
_fcnRts = gpio_get_function(_rts);
gpio_set_function(_rts, GPIO_FUNC_UART);
}
if (_cts != UART_PIN_NOT_DEFINED) {
_fcnCts = gpio_get_function(_cts);
gpio_set_function(_cts, GPIO_FUNC_UART);
}
uart_set_hw_flow(_uart, _rts != UART_PIN_NOT_DEFINED, _cts != UART_PIN_NOT_DEFINED);
_writer = 0;
_reader = 0;
@@ -200,6 +202,7 @@ void SerialUART::begin(unsigned long baud, uint16_t config) {
} else {
// Polling mode has no IRQs used
}
_break = false;
_running = true;
}
@@ -288,13 +291,22 @@ int SerialUART::read() {
}
bool SerialUART::overflow() {
CoreMutex m(&_mutex);
if (!_running || !m) {
if (!_running) {
return false;
}
bool hold = _overflow;
if (_polling) {
_handleIRQ(false);
} else {
_pumpFIFO();
}
mutex_enter_blocking(&_fifoMutex);
bool ovf = _overflow;
_overflow = false;
return hold;
mutex_exit(&_fifoMutex);
return ovf;
}
int SerialUART::available() {
@@ -365,6 +377,25 @@ SerialUART::operator bool() {
return _running;
}
bool SerialUART::getBreakReceived() {
if (!_running) {
return false;
}
if (_polling) {
_handleIRQ(false);
} else {
_pumpFIFO();
}
mutex_enter_blocking(&_fifoMutex);
bool break_received = _break;
_break = false;
mutex_exit(&_fifoMutex);
return break_received;
}
void arduino::serialEvent1Run(void) {
if (serialEvent1 && Serial1.available()) {
serialEvent1();
@@ -391,8 +422,12 @@ void __not_in_flash_func(SerialUART::_handleIRQ)(bool inIRQ) {
uart_get_hw(_uart)->icr = UART_UARTICR_RTIC_BITS | UART_UARTICR_RXIC_BITS;
while (uart_is_readable(_uart)) {
uint32_t raw = uart_get_hw(_uart)->dr;
if (raw & 0x700) {
// Framing, Parity, or Break. Ignore this bad char
if (raw & 0x400) {
// break!
_break = true;
continue;
} else if (raw & 0x300) {
// Framing, Parity Error. Ignore this bad char
continue;
}
uint8_t val = raw & 0xff;
+10
View File
@@ -63,9 +63,18 @@ public:
bool overflow();
operator bool() override;
// ESP8266 compat
void setDebugOutput(bool unused) {
(void) unused;
}
// Not to be called by users, only from the IRQ handler. In public so that the C-language IQR callback can access it
void _handleIRQ(bool inIRQ = true);
// Allows the user to sleep until a break is received (self-clears the flag
// on read)
bool getBreakReceived();
private:
bool _running = false;
uart_inst_t *_uart;
@@ -76,6 +85,7 @@ private:
mutex_t _mutex;
bool _polling = false;
bool _overflow;
bool _break;
// Lockless, IRQ-handled circular queue
uint32_t _writer;
+13 -1
View File
@@ -33,6 +33,7 @@
#include "pico/mutex.h"
#include "hardware/watchdog.h"
#include "pico/unique_id.h"
#include "hardware/resets.h"
#ifndef DISABLE_USB_SERIAL
// Ensure we are installed in the USB chain
@@ -174,11 +175,22 @@ SerialUSB::operator bool() {
static bool _dtr = false;
static bool _rts = false;
static int _bps = 115200;
static bool _rebooting = false;
static void CheckSerialReset() {
if ((_bps == 1200) && (!_dtr)) {
__holdUpPendSV = 1; // Ensure we don't get swapped out by FreeRTOS
if (!_rebooting && (_bps == 1200) && (!_dtr)) {
_rebooting = true;
// Disable NVIC IRQ, so that we don't get bothered anymore
irq_set_enabled(USBCTRL_IRQ, false);
// Reset the whole USB hardware block
reset_block(RESETS_RESET_USBCTRL_BITS);
unreset_block(RESETS_RESET_USBCTRL_BITS);
// Delay a bit, so the PC can figure out that we have disconnected.
sleep_ms(3);
reset_usb_boot(0, 0);
while (1); // WDT will fire here
}
__holdUpPendSV = 0;
}
extern "C" void tud_cdc_line_state_cb(uint8_t itf, bool dtr, bool rts) {
+5
View File
@@ -44,6 +44,11 @@ public:
using Print::write;
operator bool() override;
// ESP8266 compat
void setDebugOutput(bool unused) {
(void) unused;
}
private:
bool _running = false;
};
+1 -1
View File
@@ -109,7 +109,7 @@ void tone(uint8_t pin, unsigned int frequency, unsigned long duration) {
if (ret > 0) {
newTone->alarm = ret;
} else {
DEBUGCORE("ERROR: Unable to allocate timer for tone(%d, %d, %d)\n",
DEBUGCORE("ERROR: Unable to allocate timer for tone(%d, %d, %lu)\n",
pin, frequency, duration);
}
}
+1
View File
@@ -0,0 +1 @@
#include "api/String.h"
+7 -2
View File
@@ -28,7 +28,7 @@ typedef struct {
} FMMap;
static FMMap *_map = nullptr;
extern "C" SemaphoreHandle_t __get_freertos_mutex_for_ptr(mutex_t *m) {
SemaphoreHandle_t __get_freertos_mutex_for_ptr(mutex_t *m, bool recursive) {
if (!_map) {
_map = (FMMap *)calloc(sizeof(FMMap), 16);
}
@@ -42,7 +42,12 @@ extern "C" SemaphoreHandle_t __get_freertos_mutex_for_ptr(mutex_t *m) {
for (int i = 0; i < 16; i++) {
if (_map[i].src == nullptr) {
// Make a new mutex
SemaphoreHandle_t fm = __freertos_mutex_create();
SemaphoreHandle_t fm;
if (recursive) {
fm = _freertos_recursive_mutex_create();
} else {
fm = __freertos_mutex_create();
}
if (fm == nullptr) {
return nullptr;
}
+1 -1
View File
@@ -59,8 +59,8 @@ extern "C" {
extern void vTaskPreemptionEnable(TaskHandle_t p) __attribute__((weak));
#endif
extern SemaphoreHandle_t __get_freertos_mutex_for_ptr(mutex_t *m);
}
extern SemaphoreHandle_t __get_freertos_mutex_for_ptr(mutex_t *m, bool recursive = false);
// Halt the FreeRTOS PendSV task switching magic
extern "C" int __holdUpPendSV;
+104
View File
@@ -0,0 +1,104 @@
/*
CYW43 TCP/Ethernet wrappers
Copyright (c) 2023 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
*/
#if defined(ARDUINO_RASPBERRY_PI_PICO_W)
#include "lwip/netif.h"
extern "C" {
#include "cyw43.h"
#include "cyw43_stats.h"
}
#include "pico/cyw43_arch.h"
#include <Arduino.h>
// From cyw43_ctrl.c
#define WIFI_JOIN_STATE_KIND_MASK (0x000f)
#define WIFI_JOIN_STATE_ACTIVE (0x0001)
#define WIFI_JOIN_STATE_FAIL (0x0002)
#define WIFI_JOIN_STATE_NONET (0x0003)
#define WIFI_JOIN_STATE_BADAUTH (0x0004)
#define WIFI_JOIN_STATE_AUTH (0x0200)
#define WIFI_JOIN_STATE_LINK (0x0400)
#define WIFI_JOIN_STATE_KEYED (0x0800)
#define WIFI_JOIN_STATE_ALL (0x0e01)
// The core can't directly call a library, so put in a dummy weak one to be overridden by one in lwip_cyw43 library
extern struct netif *__getCYW43Netif() __attribute__((weak));
struct netif *__getCYW43Netif() {
return nullptr;
}
// CB from the cyw43 driver
extern "C" void __wrap_cyw43_cb_process_ethernet(void *cb_data, int itf, size_t len, const uint8_t *buf) {
(void) cb_data;
(void) itf;
struct netif *netif = __getCYW43Netif();
if (netif && (netif->flags & NETIF_FLAG_LINK_UP)) {
struct pbuf *p = pbuf_alloc(PBUF_RAW, len, PBUF_POOL);
if (p != nullptr) {
pbuf_take(p, buf, len);
if ((netif->input(p, netif) != ERR_OK)) {
pbuf_free(p);
}
CYW43_STAT_INC(PACKET_IN_COUNT);
}
}
}
extern "C" void __wrap_cyw43_cb_tcpip_set_link_up(cyw43_t *self, int itf) {
(void) self;
(void) itf;
struct netif *netif = __getCYW43Netif();
if (netif) {
netif_set_link_up(netif);
}
}
extern "C" void __wrap_cyw43_cb_tcpip_set_link_down(cyw43_t *self, int itf) {
(void) self;
(void) itf;
struct netif *netif = __getCYW43Netif();
if (netif) {
netif_set_link_down(netif);
}
self->wifi_join_state &= ~WIFI_JOIN_STATE_ACTIVE;
}
extern "C" int __wrap_cyw43_tcpip_link_status(cyw43_t *self, int itf) {
struct netif *netif = __getCYW43Netif();
//if ((CYW43::_netif->flags & (NETIF_FLAG_UP | NETIF_FLAG_LINK_UP)) == (NETIF_FLAG_UP | NETIF_FLAG_LINK_UP))
// Fake this since it's only used in the SDK
if (netif && ((netif->flags & (NETIF_FLAG_LINK_UP)) == (NETIF_FLAG_LINK_UP))) {
return CYW43_LINK_UP;
} else {
return cyw43_wifi_link_status(self, itf);
}
}
// CBs from the SDK, not needed here as we do TCP later in the game
extern "C" void __wrap_cyw43_cb_tcpip_init(cyw43_t *self, int itf) {
(void) self;
(void) itf;
}
extern "C" void __wrap_cyw43_cb_tcpip_deinit(cyw43_t *self, int itf) {
(void) self;
(void) itf;
}
#endif
+6
View File
@@ -18,6 +18,8 @@
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#pragma once
#if !defined(DEBUG_RP2040_PORT)
#define DEBUGV(...) do { } while(0)
#define DEBUGCORE(...) do { } while(0)
@@ -44,3 +46,7 @@
#define DEBUGSPI(...) do { } while(0)
#endif
#endif
#ifdef __cplusplus
extern void hexdump(const void* mem, uint32_t len, uint8_t cols = 16);
#endif
+16 -4
View File
@@ -80,7 +80,7 @@ static SemaphoreHandle_t __getFreeRTOSMutex(_LOCK_T lock) {
} else if (l == &__lock___arc4random_mutex) {
return __lock___arc4random_mutex_freertos;
}
return nullptr;
return __get_freertos_mutex_for_ptr(l, false);
}
static SemaphoreHandle_t __getFreeRTOSRecursiveMutex(_LOCK_T lock) {
@@ -96,12 +96,18 @@ static SemaphoreHandle_t __getFreeRTOSRecursiveMutex(_LOCK_T lock) {
} else if (l == &__lock___env_recursive_mutex) {
return __lock___env_recursive_mutex_freertos;
}
return nullptr;
return __get_freertos_mutex_for_ptr((mutex_t *)l, true);
}
void __retarget_lock_init(_LOCK_T *lock) {
if (__freeRTOSinitted) {
/* Already done in initFreeRTOSMutexes() */
mutex_t *l = (mutex_t *)lock;
if ((l == &__lock___at_quick_exit_mutex) || (l == &__lock___tz_mutex) || (l == &__lock___dd_hash_mutex) || (l == &__lock___arc4random_mutex)) {
/* Already done in initFreeRTOSMutexes() */
} else {
// Will init the mutex as well
__get_freertos_mutex_for_ptr(l, false);
}
} else {
mutex_init((mutex_t*) lock);
}
@@ -109,7 +115,13 @@ void __retarget_lock_init(_LOCK_T *lock) {
void __retarget_lock_init_recursive(_LOCK_T *lock) {
if (__freeRTOSinitted) {
/* Already done in initFreeRTOSMutexes() */
recursive_mutex_t *l = (recursive_mutex_t *)lock;
if ((l == &__lock___sinit_recursive_mutex) || (l == &__lock___sfp_recursive_mutex) || (l == &__lock___atexit_recursive_mutex) || (l == &__lock___malloc_recursive_mutex) || (l == &__lock___env_recursive_mutex)) {
/* Already done in initFreeRTOSMutexes() */
} else {
// Will init the mutex as well
__get_freertos_mutex_for_ptr((mutex_t *)l, true);
}
} else {
recursive_mutex_init((recursive_mutex_t*) lock);
}
+12 -31
View File
@@ -18,45 +18,25 @@
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "pico/mutex.h"
#include "lwip/pbuf.h"
#include "lwip/udp.h"
#include "lwip/tcp.h"
#include "lwip/dns.h"
#include "lwip/raw.h"
#include "lwip/timeouts.h"
// Global indicator that we're inside an LWIP block
extern "C" {
volatile bool __inLWIP = false;
}
auto_init_recursive_mutex(__mtxLWIP);
#include <pico/mutex.h>
#include <lwip/pbuf.h>
#include <lwip/udp.h>
#include <lwip/tcp.h>
#include <lwip/dns.h>
#include <lwip/raw.h>
#include <lwip/timeouts.h>
#include <pico/cyw43_arch.h>
class LWIPMutex {
public:
LWIPMutex() {
noInterrupts();
recursive_mutex_enter_blocking(&__mtxLWIP);
__inLWIP = true;
_ref++;
interrupts();
cyw43_arch_lwip_begin();
}
~LWIPMutex() {
noInterrupts();
if (0 == --_ref) {
__inLWIP = false;
}
recursive_mutex_exit(&__mtxLWIP);
interrupts();
cyw43_arch_lwip_end();
}
private:
static int _ref;
};
int LWIPMutex::_ref = 0;
extern "C" {
@@ -275,7 +255,8 @@ extern "C" {
return __real_udp_sendto_if(pcb, p, dst_ip, dst_port, netif);
}
extern void __real_sys_check_timeouts(void);
// sys_check_timeouts is special case because the async process will call it. If we're already in a timeout check, just do a noop
extern void __real_sys_check_timeouts();
void __wrap_sys_check_timeouts(void) {
LWIPMutex m;
__real_sys_check_timeouts();
+27
View File
@@ -170,3 +170,30 @@ extern "C" struct _reent *__wrap___getreent() {
return _impure_ptr1;
}
}
// ESP8266 internal debug routine
extern void hexdump(const void* mem, uint32_t len, uint8_t cols) __attribute__((weak));
void hexdump(const void* mem, uint32_t len, uint8_t cols) {
const char* src = (const char*)mem;
printf("\n[HEXDUMP] Address: %p len: 0x%lX (%ld)", src, len, len);
while (len > 0) {
uint32_t linesize = cols > len ? len : cols;
printf("\n[%p] 0x%04x: ", src, (int)(src - (const char*)mem));
for (uint32_t i = 0; i < linesize; i++) {
printf("%02x ", *(src + i));
}
printf(" ");
for (uint32_t i = linesize; i < cols; i++) {
printf(" ");
}
for (uint32_t i = 0; i < linesize; i++) {
unsigned char c = *(src + i);
putc(isprint(c) ? c : '.', stdout);
}
src += linesize;
len -= linesize;
}
printf("\n");
}
const String emptyString = "";
@@ -0,0 +1,178 @@
/*
Copyright (c) 2023 Raspberry Pi (Trading) Ltd.
SPDX-License-Identifier: BSD-3-Clause
*/
#if defined(ARDUINO_RASPBERRY_PI_PICO_W)
#include <btstack.h>
#include <pico/btstack_flash_bank.h>
#include <hardware/flash.h>
#include <hardware/sync.h>
#include <string.h>
#include <Arduino.h>
const uint8_t __bluetooth_tlv[8192] __attribute__((aligned(4096))) = { 0 };
extern const uint8_t __flash_binary_start;
#undef PICO_FLASH_BANK_TOTAL_SIZE
#undef PICO_FLASH_BANK_STORAGE_OFFSET
#define PICO_FLASH_BANK_TOTAL_SIZE sizeof(__bluetooth_tlv)
#define PICO_FLASH_BANK_STORAGE_OFFSET ((unsigned int)(__bluetooth_tlv - &__flash_binary_start))
#if 0
// Check sizes
static_assert(PICO_FLASH_BANK_TOTAL_SIZE % (FLASH_SECTOR_SIZE * 2) == 0, "PICO_FLASH_BANK_TOTAL_SIZE invalid");
static_assert(PICO_FLASH_BANK_TOTAL_SIZE <= PICO_FLASH_SIZE_BYTES, "PICO_FLASH_BANK_TOTAL_SIZE too big");
static_assert(PICO_FLASH_BANK_STORAGE_OFFSET + PICO_FLASH_BANK_TOTAL_SIZE <= PICO_FLASH_SIZE_BYTES, "PICO_FLASH_BANK_TOTAL_SIZE too big");
#endif
// Size of one bank
#define PICO_FLASH_BANK_SIZE (PICO_FLASH_BANK_TOTAL_SIZE / 2)
#if 0
#define DEBUG_PRINT(format,args...) printf(format, ## args)
#else
#define DEBUG_PRINT(...)
#endif
static uint32_t pico_flash_bank_get_size(void * context) {
(void)(context);
return PICO_FLASH_BANK_SIZE;
}
static uint32_t pico_flash_bank_get_alignment(void * context) {
(void)(context);
return 1;
}
static void pico_flash_bank_erase(void * context, int bank) {
(void)(context);
DEBUG_PRINT("erase: bank %d\n", bank);
noInterrupts();
rp2040.idleOtherCore();
flash_range_erase(PICO_FLASH_BANK_STORAGE_OFFSET + (PICO_FLASH_BANK_SIZE * bank), PICO_FLASH_BANK_SIZE);
rp2040.resumeOtherCore();
interrupts();
}
static void pico_flash_bank_read(void *context, int bank, uint32_t offset, uint8_t *buffer, uint32_t size) {
(void)(context);
DEBUG_PRINT("read: bank %d offset %u size %u\n", bank, offset, size);
assert(bank <= 1);
if (bank > 1) {
return;
}
assert(offset < PICO_FLASH_BANK_SIZE);
if (offset >= PICO_FLASH_BANK_SIZE) {
return;
}
assert((offset + size) <= PICO_FLASH_BANK_SIZE);
if ((offset + size) > PICO_FLASH_BANK_SIZE) {
return;
}
// Flash is xip
memcpy(buffer, (void *)(XIP_BASE + PICO_FLASH_BANK_STORAGE_OFFSET + (PICO_FLASH_BANK_SIZE * bank) + offset), size);
}
static void pico_flash_bank_write(void * context, int bank, uint32_t offset, const uint8_t *data, uint32_t size) {
(void)(context);
DEBUG_PRINT("write: bank %d offset %u size %u\n", bank, offset, size);
assert(bank <= 1);
if (bank > 1) {
return;
}
assert(offset < PICO_FLASH_BANK_SIZE);
if (offset >= PICO_FLASH_BANK_SIZE) {
return;
}
assert((offset + size) <= PICO_FLASH_BANK_SIZE);
if ((offset + size) > PICO_FLASH_BANK_SIZE) {
return;
}
if (size == 0) {
return;
}
// calc bank start position
const uint32_t bank_start_pos = PICO_FLASH_BANK_STORAGE_OFFSET + (PICO_FLASH_BANK_SIZE * bank);
// Calculate first and last page in the bank
const uint32_t first_page = offset / FLASH_PAGE_SIZE;
const uint32_t last_page = (offset + size + FLASH_PAGE_SIZE - 1) / FLASH_PAGE_SIZE;
// Now we only care about the offset in the first page
offset %= FLASH_PAGE_SIZE;
// Amount of data we've copied
uint32_t data_pos = 0;
uint32_t size_left = size;
// Write all the pages required
for (uint32_t page = first_page; page < last_page; page++) {
uint8_t page_data[FLASH_PAGE_SIZE];
assert(data_pos < size && size_left <= size);
// Copy data we're not going to overwrite in the first page
if (page == first_page && offset > 0) {
memcpy(page_data,
(void *)(XIP_BASE + bank_start_pos + (page * FLASH_PAGE_SIZE)),
offset);
}
// Copy the data we're not going to overwrite in the last page
if (page == last_page - 1 && (offset + size_left) < FLASH_PAGE_SIZE) {
memcpy(page_data + offset + size_left,
(void *)(XIP_BASE + bank_start_pos + (page * FLASH_PAGE_SIZE) + offset + size_left),
FLASH_PAGE_SIZE - offset - size_left);
}
// Now copy the new data into the page
const uint32_t size_to_copy = MIN(size_left, FLASH_PAGE_SIZE - offset);
memcpy(page_data + offset, data + data_pos, size_to_copy);
data_pos += size_to_copy;
size_left -= size_to_copy;
// zero offset for the following pages
offset = 0;
// Now program the entire page
noInterrupts();
rp2040.idleOtherCore();
flash_range_program(bank_start_pos + (page * FLASH_PAGE_SIZE), page_data, FLASH_PAGE_SIZE);
rp2040.resumeOtherCore();
interrupts();
}
}
static const hal_flash_bank_t pico_flash_bank_instance_obj = {
/* uint32_t (*get_size)(..) */ &pico_flash_bank_get_size,
/* uint32_t (*get_alignment)(..); */ &pico_flash_bank_get_alignment,
/* void (*erase)(..); */ &pico_flash_bank_erase,
/* void (*read)(..); */ &pico_flash_bank_read,
/* void (*write)(..); */ &pico_flash_bank_write,
};
extern "C" {
const hal_flash_bank_t *pico_flash_bank_instance(void) {
#ifndef NDEBUG
// Check we're not overlapping the binary in flash
//extern char __flash_binary_end;
// assert((uintptr_t)&__flash_binary_end - XIP_BASE <= PICO_FLASH_BANK_STORAGE_OFFSET);
#endif
return &pico_flash_bank_instance_obj;
}
}
#endif
@@ -1,348 +0,0 @@
/*
Copyright (c) 2022 Raspberry Pi (Trading) Ltd.
SPDX-License-Identifier: BSD-3-Clause
*/
// Taken from the Pico-SDK v1.4.0 and hacked by EFP3 to allow overriding the LWIP setup
//#include <stdio.h>
#include "pico/cyw43_arch.h"
#include "pico/mutex.h"
#include "pico/sem.h"
#include "hardware/gpio.h"
#include "hardware/irq.h"
#include "cyw43_stats.h"
#include <lwip/init.h>
#include "lwip/timeouts.h"
#ifndef CYW43_PIN_WL_HOST_WAKE
#define CYW43_PIN_WL_HOST_WAKE 24
#endif
#ifndef CYW43_PIN_WL_REG_ON
#define CYW43_PIN_WL_REG_ON 23
#endif
#ifndef CYW43_WL_GPIO_COUNT
#define CYW43_WL_GPIO_COUNT 3
#endif
#ifndef CYW43_WL_GPIO_LED_PIN
#define CYW43_WL_GPIO_LED_PIN 0
#endif
extern volatile bool __inLWIP;
// note same code
#if PICO_CYW43_ARCH_THREADSAFE_BACKGROUND
#if PICO_CYW43_ARCH_THREADSAFE_BACKGROUND && CYW43_LWIP && !NO_SYS
#error PICO_CYW43_ARCH_THREADSAFE_BACKGROUND requires lwIP NO_SYS=1
#endif
#if PICO_CYW43_ARCH_THREADSAFE_BACKGROUND && CYW43_LWIP && MEM_LIBC_MALLOC
#error MEM_LIBC_MALLOC is incompatible with PICO_CYW43_ARCH_THREADSAFE_BACKGROUND
#endif
// todo right now we are now always doing a cyw43_dispatch along with a lwip one when hopping cores in low_prio_irq_schedule_dispatch
#ifndef CYW43_SLEEP_CHECK_MS
#define CYW43_SLEEP_CHECK_MS 50 // How often to run lwip callback
#endif
static alarm_id_t periodic_alarm = -1;
static inline uint recursive_mutex_enter_count(recursive_mutex_t *mutex) {
return mutex->enter_count;
}
static inline lock_owner_id_t recursive_mutex_owner(recursive_mutex_t *mutex) {
return mutex->owner;
}
#define CYW43_GPIO_IRQ_HANDLER_PRIORITY 0x40
enum {
CYW43_DISPATCH_SLOT_CYW43 = 0,
CYW43_DISPATCH_SLOT_ADAPTER,
CYW43_DISPATCH_SLOT_ENUM_COUNT
};
#ifndef CYW43_DISPATCH_SLOT_COUNT
#define CYW43_DISPATCH_SLOT_COUNT CYW43_DISPATCH_SLOT_ENUM_COUNT
#endif
typedef void (*low_prio_irq_dispatch_t)(void);
static void low_prio_irq_schedule_dispatch(size_t slot, low_prio_irq_dispatch_t f);
static uint8_t cyw43_core_num;
#ifndef NDEBUG
static bool in_low_priority_irq;
#endif
static uint8_t low_priority_irq_num;
static bool low_priority_irq_missed;
static low_prio_irq_dispatch_t low_priority_irq_dispatch_slots[CYW43_DISPATCH_SLOT_COUNT];
static recursive_mutex_t cyw43_mutex;
semaphore_t cyw43_irq_sem;
// Called in low priority pendsv interrupt only to do lwip processing and check cyw43 sleep
static void periodic_worker(void) {
#if CYW43_USE_STATS && LWIP_SYS_CHECK_MS
static uint32_t counter;
if (counter++ % (30000 / LWIP_SYS_CHECK_MS) == 0) {
cyw43_dump_stats();
}
#endif
CYW43_STAT_INC(LWIP_RUN_COUNT);
//#if CYW43_LWIP
if (!__inLWIP) {
sys_check_timeouts();
}
//#endif
if (cyw43_poll) {
if (cyw43_sleep > 0) {
if (--cyw43_sleep == 0) {
low_prio_irq_schedule_dispatch(CYW43_DISPATCH_SLOT_CYW43, cyw43_poll);
}
}
}
}
// Regular callback to get lwip to check for timeouts
static int64_t periodic_alarm_handler(__unused alarm_id_t id, __unused void *user_data) {
// Do lwip processing in low priority pendsv interrupt
low_prio_irq_schedule_dispatch(CYW43_DISPATCH_SLOT_ADAPTER, periodic_worker);
return CYW43_SLEEP_CHECK_MS * 1000;
}
void cyw43_await_background_or_timeout_us(uint32_t timeout_us) {
// if we are called from within an IRQ, then don't wait (we are only ever called in a polling loop)
if (!__get_current_exception()) {
sem_acquire_timeout_us(&cyw43_irq_sem, timeout_us);
}
}
// GPIO interrupt handler to tell us there's cyw43 has work to do
static void gpio_irq_handler(void) {
uint32_t events = gpio_get_irq_event_mask(CYW43_PIN_WL_HOST_WAKE);
if (events & GPIO_IRQ_LEVEL_HIGH) {
// As we use a high level interrupt, it will go off forever until it's serviced
// So disable the interrupt until this is done. It's re-enabled again by CYW43_POST_POLL_HOOK
// which is called at the end of cyw43_poll_func
gpio_set_irq_enabled(CYW43_PIN_WL_HOST_WAKE, GPIO_IRQ_LEVEL_HIGH, false);
// also clear the force bit which we use to progratically cause this handler to fire (on the right core)
io_irq_ctrl_hw_t *irq_ctrl_base = get_core_num() ?
&iobank0_hw->proc1_irq_ctrl : &iobank0_hw->proc0_irq_ctrl;
hw_clear_bits(&irq_ctrl_base->intf[CYW43_PIN_WL_HOST_WAKE / 8], GPIO_IRQ_LEVEL_HIGH << (4 * (CYW43_PIN_WL_HOST_WAKE & 7)));
low_prio_irq_schedule_dispatch(CYW43_DISPATCH_SLOT_CYW43, cyw43_poll);
CYW43_STAT_INC(IRQ_COUNT);
}
}
// Low priority interrupt handler to perform background processing
static void low_priority_irq_handler(void) {
assert(cyw43_core_num == get_core_num());
if (recursive_mutex_try_enter(&cyw43_mutex, NULL)) {
if (__inLWIP || (recursive_mutex_enter_count(&cyw43_mutex) != 1)) {
low_priority_irq_missed = true;
CYW43_STAT_INC(PENDSV_DISABLED_COUNT);
} else {
CYW43_STAT_INC(PENDSV_RUN_COUNT);
#ifndef NDEBUG
in_low_priority_irq = true;
#endif
for (size_t i = 0; i < count_of(low_priority_irq_dispatch_slots); i++) {
if (low_priority_irq_dispatch_slots[i] != NULL) {
low_prio_irq_dispatch_t f = low_priority_irq_dispatch_slots[i];
low_priority_irq_dispatch_slots[i] = NULL;
f();
}
}
#ifndef NDEBUG
in_low_priority_irq = false;
#endif
}
recursive_mutex_exit(&cyw43_mutex);
} else {
CYW43_STAT_INC(PENDSV_DISABLED_COUNT);
low_priority_irq_missed = true;
}
sem_release(&cyw43_irq_sem);
}
static bool low_prio_irq_init(uint8_t priority) {
assert(get_core_num() == cyw43_core_num);
int irq = user_irq_claim_unused(false);
if (irq < 0) {
return false;
}
low_priority_irq_num = (uint8_t) irq;
irq_set_exclusive_handler(low_priority_irq_num, low_priority_irq_handler);
irq_set_enabled(low_priority_irq_num, true);
irq_set_priority(low_priority_irq_num, priority);
return true;
}
static void low_prio_irq_deinit(void) {
if (low_priority_irq_num > 0) {
irq_set_enabled(low_priority_irq_num, false);
irq_remove_handler(low_priority_irq_num, low_priority_irq_handler);
user_irq_unclaim(low_priority_irq_num);
low_priority_irq_num = 0;
}
}
int cyw43_arch_init(void) {
cyw43_core_num = get_core_num();
recursive_mutex_init(&cyw43_mutex);
cyw43_init(&cyw43_state);
sem_init(&cyw43_irq_sem, 0, 1);
// Start regular lwip callback to handle timeouts
periodic_alarm = add_alarm_in_us(CYW43_SLEEP_CHECK_MS * 1000, periodic_alarm_handler, NULL, true);
if (periodic_alarm < 0) {
return PICO_ERROR_GENERIC;
}
gpio_add_raw_irq_handler_with_order_priority(IO_IRQ_BANK0, gpio_irq_handler, CYW43_GPIO_IRQ_HANDLER_PRIORITY);
gpio_set_irq_enabled(CYW43_PIN_WL_HOST_WAKE, GPIO_IRQ_LEVEL_HIGH, true);
irq_set_enabled(IO_IRQ_BANK0, true);
lwip_init();
// start low priority handler (no background work is done before this)
bool ok = low_prio_irq_init(PICO_LOWEST_IRQ_PRIORITY);
if (!ok) {
cyw43_arch_deinit();
return PICO_ERROR_GENERIC;
}
return PICO_OK;
}
void cyw43_arch_deinit(void) {
if (periodic_alarm >= 0) {
cancel_alarm(periodic_alarm);
periodic_alarm = -1;
}
gpio_set_irq_enabled(CYW43_PIN_WL_HOST_WAKE, GPIO_IRQ_LEVEL_HIGH, false);
gpio_remove_raw_irq_handler(IO_IRQ_BANK0, gpio_irq_handler);
low_prio_irq_deinit();
}
void cyw43_post_poll_hook(void) {
gpio_set_irq_enabled(CYW43_PIN_WL_HOST_WAKE, GPIO_IRQ_LEVEL_HIGH, true);
}
// This is called in the gpio and low_prio_irq interrupts and on either core
static void low_prio_irq_schedule_dispatch(size_t slot, low_prio_irq_dispatch_t f) {
assert(slot < count_of(low_priority_irq_dispatch_slots));
low_priority_irq_dispatch_slots[slot] = f;
if (cyw43_core_num == get_core_num()) {
//on same core, can dispatch directly
irq_set_pending(low_priority_irq_num);
} else {
// on wrong core, so force via GPIO IRQ which itself calls this method for the CYW43 slot.
// since the CYW43 slot always uses the same function, this is fine with the addition of an
// extra (but harmless) CYW43 slot call when another SLOT is invoked.
// We could do better, but would have to track why the IRQ was called.
io_irq_ctrl_hw_t *irq_ctrl_base = cyw43_core_num ?
&iobank0_hw->proc1_irq_ctrl : &iobank0_hw->proc0_irq_ctrl;
hw_set_bits(&irq_ctrl_base->intf[CYW43_PIN_WL_HOST_WAKE / 8], GPIO_IRQ_LEVEL_HIGH << (4 * (CYW43_PIN_WL_HOST_WAKE & 7)));
}
}
void cyw43_schedule_internal_poll_dispatch(void (*func)(void)) {
low_prio_irq_schedule_dispatch(CYW43_DISPATCH_SLOT_CYW43, func);
}
// Prevent background processing in pensv and access by the other core
// These methods are called in pensv context and on either core
// They can be called recursively
void cyw43_thread_enter(void) {
// Lock the other core and stop low_prio_irq running
recursive_mutex_enter_blocking(&cyw43_mutex);
}
#ifndef NDEBUG
void cyw43_thread_lock_check(void) {
// Lock the other core and stop low_prio_irq running
if (recursive_mutex_enter_count(&cyw43_mutex) < 1 || recursive_mutex_owner(&cyw43_mutex) != lock_get_caller_owner_id()) {
panic("cyw43_thread_lock_check failed");
}
}
#endif
// Re-enable background processing
void cyw43_thread_exit(void) {
// Run low_prio_irq if needed
if (1 == recursive_mutex_enter_count(&cyw43_mutex)) {
// note the outer release of the mutex is not via cyw43_exit in the low_priority_irq case (it is a direct mutex exit)
assert(!in_low_priority_irq);
// if (low_priority_irq_missed) {
// low_priority_irq_missed = false;
if (low_priority_irq_dispatch_slots[CYW43_DISPATCH_SLOT_CYW43]) {
low_prio_irq_schedule_dispatch(CYW43_DISPATCH_SLOT_CYW43, cyw43_poll);
}
// }
}
recursive_mutex_exit(&cyw43_mutex);
}
static void cyw43_delay_until(absolute_time_t until) {
// sleep can be called in IRQs, so there's not much we can do there
if (__get_current_exception()) {
busy_wait_until(until);
} else {
sleep_until(until);
}
}
void cyw43_delay_ms(uint32_t ms) {
cyw43_delay_until(make_timeout_time_ms(ms));
}
void cyw43_delay_us(uint32_t us) {
cyw43_delay_until(make_timeout_time_us(us));
}
void cyw43_arch_poll() {
// should not be necessary
// if (cyw43_poll) {
// low_prio_irq_schedule_dispatch(CYW43_DISPATCH_SLOT_CYW43, cyw43_poll);
// }
}
#ifdef ARDUINO_RASPBERRY_PI_PICO_W
void __attribute__((weak)) cyw43_cb_tcpip_init(cyw43_t *self, int itf);
void cyw43_cb_tcpip_init(cyw43_t *self, int itf) {
(void) self;
(void) itf;
}
void __attribute__((weak)) cyw43_cb_tcpip_deinit(cyw43_t *self, int itf);
void cyw43_cb_tcpip_deinit(cyw43_t *self, int itf) {
(void) self;
(void) itf;
}
void __attribute__((weak)) cyw43_cb_tcpip_set_link_up(cyw43_t *self, int itf);
void cyw43_cb_tcpip_set_link_up(cyw43_t *self, int itf) {
(void) self;
(void) itf;
}
void __attribute__((weak)) cyw43_cb_tcpip_set_link_down(cyw43_t *self, int itf);
void cyw43_cb_tcpip_set_link_down(cyw43_t *self, int itf) {
(void) self;
(void) itf;
}
void __attribute__((weak)) cyw43_cb_process_ethernet(void *cb_data, int itf, size_t len, const uint8_t *buf);
void cyw43_cb_process_ethernet(void *cb_data, int itf, size_t len, const uint8_t *buf) {
(void) cb_data;
(void) itf;
(void) len;
(void) buf;
}
#endif
#endif
+6 -6
View File
@@ -43,10 +43,10 @@ extern "C" void analogWriteFreq(uint32_t freq) {
return;
}
if (freq < 100) {
DEBUGCORE("ERROR: analogWriteFreq too low (%d)\n", freq);
DEBUGCORE("ERROR: analogWriteFreq too low (%lu)\n", freq);
analogFreq = 100;
} else if (freq > 10'000'000) {
DEBUGCORE("ERROR: analogWriteFreq too high (%d)\n", freq);
DEBUGCORE("ERROR: analogWriteFreq too high (%lu)\n", freq);
analogFreq = 10'000'000;
} else {
analogFreq = freq;
@@ -64,7 +64,7 @@ extern "C" void analogWriteRange(uint32_t range) {
pwmInitted = 0;
scaleInitted = false;
} else {
DEBUGCORE("ERROR: analogWriteRange out of range (%d)\n", range);
DEBUGCORE("ERROR: analogWriteRange out of range (%lu)\n", range);
}
}
@@ -90,14 +90,14 @@ extern "C" void analogWrite(pin_size_t pin, int val) {
while (((clock_get_hz(clk_sys) / ((float)analogScale * analogFreq)) > 255.0) && (analogScale < 32678)) {
analogWritePseudoScale++;
analogScale *= 2;
DEBUGCORE("Adjusting analogWrite values PS=%d, scale=%d\n", analogWritePseudoScale, analogScale);
DEBUGCORE("Adjusting analogWrite values PS=%d, scale=%lu\n", analogWritePseudoScale, analogScale);
}
// For high frequencies, we need to scale the output max value down to actually hit the frequency target
analogWriteSlowScale = 1;
while (((clock_get_hz(clk_sys) / ((float)analogScale * analogFreq)) < 1.0) && (analogScale >= 6)) {
analogWriteSlowScale++;
analogScale /= 2;
DEBUGCORE("Adjusting analogWrite values SS=%d, scale=%d\n", analogWriteSlowScale, analogScale);
DEBUGCORE("Adjusting analogWrite values SS=%d, scale=%lu\n", analogWriteSlowScale, analogScale);
}
scaleInitted = true;
}
@@ -172,7 +172,7 @@ extern "C" float analogReadTemp(float vref) {
adc_select_input(4); // Temperature sensor
int v = adc_read();
adc_set_temp_sensor_enabled(false);
float t = 27.0f - ((v * vref / pow(2, _readBits)) - 0.706f) / 0.001721f; // From the datasheet
float t = 27.0f - ((v * vref / 4096.0f) - 0.706f) / 0.001721f; // From the datasheet
return t;
}
+87
View File
@@ -0,0 +1,87 @@
ADC Input Library
=================
The ADC pins can be sampled and recorded by an application using the same
interface as the I2S or PWM Audio libraries. This allows analog devices which
need to be periodically sampled to be read by applications, easily, such as:
* Analog electret microphones
* Potentiometers
* Light dependent resistors (LDR), etc.
Up to 4 analog samples can be recorded by the hardware (``A0`` ... ``A4``), 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``
object in lieu of an ``I2S`` input object and choosing the pins to record.
Since this uses the ADC hardware, no ``analogRead`` or ``analogReadTemp`` calls are
allowed while in use.
ADC Input API
-------------
ADCInput(pin0 [, pin1, pin2, pin3])
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Creates an ADC input object which will record the pins specified in the code.
Only pins ``A0`` ... ``A4`` 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)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Set the number of DMA buffers and their size in 32-bit words. Call before
``ADCInput::begin()``.
When running at high sample rates, it is recommended to increase the
``bufferWords`` to 32 or higher (i.e. ``adcinput.setBuffers(4, 32);`` ).
bool setPins(pin_size_t pin [, pin1, pin2, pin3])
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Adjusts the pin to record. Only legal before ``ADCInput::begin()``.
bool setFrequency(long sampleRate)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sets the ADC sampling frequency, but does not start recording (however if the
device was already running, it will continue to run at the new frequency). Note
that every pin requested will be sampled at this frequency, one after the other.
That is, if you have code like this:
.. code:: cpp
ADCInput adc(A0, A1);
adc.setFrequency(1000);
``A0`` will be sampled at 0ms, 1ms, 2ms, etc. and ``A1`` will be sampled at 0.5ms
1.5ms, 2.5ms, etc. Each input is sampled at the proper frequency but offset in time
since there is only one active ADC at a time.
bool begin()/begin(long sampleRate)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Start the ADC input up with the given sample rate, or with the value set
using the prior ``setFrequency`` call.
void end()
~~~~~~~~~~
Stops the ADC Input device.
int read()
~~~~~~~~~~
Reads a single sample of recorded ADC data, as a 16-bit value. When multiple pins are
recorded the first read will be pin 0, the second will be pin 1, etc. Applications need
to keep track of which pin is being returned (normally by always reading out all pins
at once). Will not return until data is available.
int available()
~~~~~~~~~~~~~~~
Returns the number of samples that can be read without potentially blocking.
void onReceive(void (\*fn)(void))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sets a callback to be called when a ADC input DMA buffer is fully filled.
Will be in an interrupt context so the specified function must operate
quickly and not use blocking calls like delay().
+2 -2
View File
@@ -14,12 +14,12 @@ Returns a value from 0...4095 correspionding to the ADC reading
of the specific pin.
void analogReadResolution(int bits)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Determines the resolution (in bits) of the value returned by the analogRead() function.
Default resolution is 10bit.
float analogReadTemp(float vref = 3.3f)
~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Returns the temperature, in Celsius, of the onboard thermal sensor.
If you have a custom Vref for the ADC on your RP2040 board, you can pass it in as a parameter. Calling with no parameters assumes the normal, 3.3V Vref.
This reading is not exceedingly accurate and of relatively low
+49
View File
@@ -0,0 +1,49 @@
Bluetooth on PicoW Support
==========================
As of the Pico-SDK version 1.5.0, the PicoW has **BETA** Bluetooth support.
So, since this core builds off the SDK the best that can be suggested it
that we have **ALPHA** Bluetooth support. As such, bug reports are welcome,
but Pull Requests fixing problems you find are seriously appreciated.
Enabling Bluetooth
------------------
To enable Bluetooth (BT), use the ``Tools->IP/Bluetooth Stack`` menu. It
requires around 80KB of flash and 20KB of RAM when enabled.
Both Bluetooth Classic and BluetoothBLE are enabled in ``btstack_config.h``.
Included Bluetooth Libraries
----------------------------
You may use the ``KeyboardBT``, ``MouseBT``, or ``JoystickBT`` to emulate a
Bluetooth Classic HID device using the same API as their USB versions.
You may use the ``KeyboardBLE``, ``MouseBLE``, or ``JoystickBLE`` to emulate a
Bluetooth Low Energy (BLE) HID device using the same API as their USB versions.
The ``SerialBT`` library implements a very simple SPP (Serial Port Profile)
Serial-compatible port.
Writing Custom Bluetooth Applications
-------------------------------------
You may also write full applications using the ``BTStack`` standard callback
method, but please be aware that the Raspberry Pi team has built an
interrupt-driven version of the BT execute loop, so there is no need
to actually call ``btstack_run_loop_execute`` because the ``async_context``
handler will do it for you.
There is no need to call ``cyw43_arch_init`` in your code, either, as that
is part of the PicoW variant booting process.
For many BTStack examples, you simply need call the included
``btstack_main()`` and make sure that ``hci_power_control(HCI_POWER_ON);`` is
called afterwards to start processing (in the background).
You will also need to acquire the BT ``async_context`` system lock before
calling any BTStack APIs. See the ``libraries/PicoBluetoothHID`` helper
class for an example of how to do this.
Note that if you need to modify the system ``btstack_config.h`` file, do so
in the ``tools/libpico`` directory and rebuild the Pico SDK static library.
Otherwise the change will not take effect in the precompiled code, leading
to really bad behavior.
+2 -2
View File
@@ -54,9 +54,9 @@ author = u'Earle F. Philhower, III'
# built documents.
#
# The short X.Y version.
version = u'2.7.0'
version = u'3.1.0'
# The full version, including alpha/beta/rc tags.
release = u'2.7.0'
release = u'3.1.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
+99
View File
@@ -0,0 +1,99 @@
Contributing and Porting to the Core
====================================
First of all, thank you for contributing to the project. It's a lot of work
keeping up with all the different uses of the RP2040, so the more people
working on the code, the better. Your assistance can help the project
succeed.
Contributing to the Core (Pull Requests)
----------------------------------------
We use the standard GitHub Pull Request model. If you're unfamiliar with it,
this `guide <https://www.freecodecamp.org/news/how-to-make-your-first-pull-request-on-github-3/>` gives a simple overview of the process.
All pull requests have to pass a set of Continuous Integration (CI) checks
which help make sure the code compiles under different configurations and has
no spelling or style errors.
Tips for a Good Pull Request (PR)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All code in the core and libraries, except for INO sketches, uses a 4-space
indent with cuddled brackets. When in doubt, copy your formatting from the
surrounding code. You should install ``astyle`` and run ``tests/restyle.sh``
on your machine before committing and pushing any pull requests to ensure
the formatting is correct.
Describe the change you're proposing and why it's important in your
``git commit`` message. If it fixes an open issue, place ``Fixes #xxxx``
(where xxxx is the issue number) in the message to link the two.
Try and only change one thing per pull request. That makes it easier to
review and prioritize. Opening up a separate PR per change also helps keep
track of them when release messages are generated.
Adding a New Board
------------------
Adding a new board requires:
* Updated ``tools/makeboards.py`` script
* Updated ``boards.txt`` file, generated by ``makeboard.py``
* Updated ``package_pico_index.template.json`` file, generated by ``makeboard.py``
* New ``tools/json/BOARD_NAME.json`` board file for Platform.IO
* New ``variants/BOARD_NAME/pins_arduino.h`` header defining the I/O pins
To add a new RP2040 board you will need to update the ``tools/makeboards.py``
script. Do *NOT* manually edit ``boards.txt``, that file is machine generated.
You will need to add a ``MakeBoard`` call at the end of the file. Please be sure
to add your board so that it sorts alphabetically, starting with the company name
and then the board name. Otherwise it is hard to find a specific board in the menu.
Run ``python3 tools/makeboards.py`` to update the ``boards.txt`` file and generate
a Platform.IO JSON file in the ``tools/json`` directory.
Create a folder called ``variants/BOARD_NAME`` and place in a ``pins_arduino.h``
file in it that contains your default pin name mapping (i.e. SPI0/1 pins, UART
pins, LED_DEFAULT, etc.). Copying one of the existing ones as a template can
make this task much simpler.
In your ``git commit`` be sure to add the newly generated ``tools/json/XXX.json``
file as well as the modified ``makeboards`` script and ``boards.txt``, the new
``pins_arduino.h`` header you generated, and the Arduino packaging JSON
``package/package_pico_index.template.json``. You should also add a note in
the ``README.md`` file listing your new board.
Submit the updated commit as a PR and, if all goes well, your board will be in
on the next core release.
Porting Libraries and Applications to the Core
----------------------------------------------
We try and follow Arduino standards so, with luck, porting to this core should
be relatively straightforward. The ``WiFi`` library and associates support
libraries like ``WebServer`` are modeled after the ESP32 and ESP8266 versions
of those libraries, combined with the "standard" Arduino ``WiFi`` one.
Compiler Defines for Porting
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If you are adding RP2040 support to an existing library and need to isolate
code that only runs on this core, use the following define.
.. code:: cpp
#if defined(ARDUINO_ARCH_RP2040)
~~~ your changes ~~~
#endif
Library Architectures
~~~~~~~~~~~~~~~~~~~~~
After adding support in the code, libraries need their ``library.properties``
and ``library.json`` files updated to indicate support, or the IDE will
not know your new code is compatible here.
Add ``rp2040`` to ``architectures`` (in ``library.properties``) and
``"rp2040"`` to ``platforms[]`` (in ``library.json``) to let the tools know.
+2 -2
View File
@@ -1,5 +1,5 @@
Getting Help and Contributing
=============================
Getting Help
============
This is a community supported project and has multiple ways to get assistance.
Posting complete details, in a polite and organized way will get the best
+6
View File
@@ -58,6 +58,12 @@ Sets the word clock frequency, but does not start the I2S device if not
already running. May be called after ``I2S::begin()`` to change the
sample rate on-the-fly.
bool setLSBJFormat()
~~~~~~~~~~~~~~~~~~~~
Enables LSB-J format for I2S output. In this mode the MSB comes out at the
same time as the LRCLK changes, and not the normal 1-cycle delay. Useful for
DAC chips like the PT8211.
bool begin()/begin(long sampleRate)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Start the I2S device up with the given sample rate, or with the value set
+7 -1
View File
@@ -16,7 +16,9 @@ For the latest version, always check https://github.com/earlephilhower/arduino-p
:maxdepth: 2
:caption: Contents:
Getting Help and Contributing <help>
Getting Help <help>
Contributing <contrib>
Installation <install>
IDE Menus <ide>
@@ -30,6 +32,8 @@ For the latest version, always check https://github.com/earlephilhower/arduino-p
Digital I/O <digital>
EEPROM <eeprom>
I2S Audio <i2s>
PWM Audio <pwm>
Microphone (and Analog Sensor) Input <adc>
Serial USB and UARTs <serial>
"Software Serial" PIO UART <piouart>
Servo <servo>
@@ -39,6 +43,8 @@ For the latest version, always check https://github.com/earlephilhower/arduino-p
USB (Arduino and Adafruit_TinyUSB) <usb>
Multicore Processing <multicore>
Bluetooth (Alpha/Beta) <bluetooth>
Single File USB Drive <singlefile>
FreeRTOS SMP (multicore) <freertos>
+34 -8
View File
@@ -9,14 +9,6 @@ installation.
Installing via Arduino Boards Manager
-------------------------------------
**Note for Windows Users**: Please do not use the Windows Store version of
the actual Arduino application because it has issues detecting attached Pico
boards. Use the "Windows ZIP" or plain "Windows" executable (EXE) download
direct from https://arduino.cc. and allow it to install any device drivers
it suggests. Otherwise the Pico board may not be detected. Also, if trying
out the 2.0 beta Arduino please install the release 1.8 version beforehand
to ensure needed device drivers are present.
1. Open up the Arduino IDE and go to File->Preferences.
2. In the dialog that pops up, enter the following URL in the "Additional Boards Manager URLs" field: https://github.com/earlephilhower/arduino-pico/releases/download/global/package_rp2040_index.json
@@ -28,6 +20,24 @@ to ensure needed device drivers are present.
.. image:: images/install2.png
Arduino IDE Installation Warning
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
**Note for Windows Users**: Please do not use the Windows Store version of
the actual Arduino application because it has issues detecting attached Pico
boards. Use the "Windows ZIP" or plain "Windows" executable (EXE) download
direct from https://arduino.cc. and allow it to install any device drivers
it suggests. Otherwise the Pico board may not be detected. Also, if trying
out the 2.0 beta Arduino please install the release 1.8 version beforehand
to ensure needed device drivers are present.
**Note for Linux Users**: If you installed the Arduino IDE using Flatpak, which
is common in Pop!_OS, Fedora, and Mint, among others, you may need to configure
Flatpak to allow the IDE access to files outside your home folder. The RP2040
device is sometimes mounted as a folder in /opt or /media, which Flatpak will
prevent the Arduino IDE from accessing. For Arduino IDE V2, override the filesystem
restriction using ``flatpak override --user --filesystem=host cc.arduino.IDE2`` . For
For Arduino IDE < V2, use ``flatpak override --user --filesystem=host cc.arduino.arduinoide``.
Installing via GIT
------------------
To install via GIT (for latest and greatest versions):
@@ -125,6 +135,22 @@ For detailed usage information, please check the repo documentation available at
* https://arduino-pico.readthedocs.io/en/latest/fs.html
Uploading Sketches with Picotool
--------------------------------
Because the Picotool uses a custom device driver in the Pico to handle upload, when using the ``Upload Method->Picotool`` mode custom code needs to be run on the Pico which is not included by default for compatibility and code savings.
So for the first sketch you will need to rebuild (with the ``Upload Method->Picotool`` selected in them menus) and then manually hold down BOOTSEL and insert the Pico USB cable to enter the ROM bootloader.
After the initial upload, as long as the running binary was built using the ``Picotool`` upload method, then the normal upload process should work.
Note that for Ubuntu and other Linux operating systems you may need to add the following lines to a new `udev` config file(``99-picotool.rules``) to allow normal users to access the special USB device the Pico exports:
.. code::
echo 'SUBSYSTEM=="usb", ATTRS{idVendor}=="2e8a", ATTRS{idProduct}=="0003", MODE="660", GROUP="plugdev"' | sudo tee -a /etc/udev/rules.d/98-Picotool.rules
echo 'SUBSYSTEM=="usb", ATTRS{idVendor}=="2e8a", ATTRS{idProduct}=="000a", MODE="660", GROUP="plugdev"' | sudo tee -a /etc/udev/rules.d/98-Picotool.rules
sudo udevadm control --reload
Uploading Sketches with Picoprobe
---------------------------------
If you have built a Raspberry Pi Picoprobe, you can use OpenOCD to handle your sketch uploads and for debugging with GDB.
+97
View File
@@ -0,0 +1,97 @@
PWM Audio Library
=================
Relatively good quality analog audio out can be generated by using the
RP2040 onboard PWM hardware. It can drive an amplifier for speaker output,
or be decoupled using a capacitor to drive a headphone-level signal. Mono
and stereo signals can be generated.
All samples are sent to the ``PWMAudio`` library as **signed 16 bits per sample**.
Due to frequency limitations of the PWM hardware, at higher bit rates
these 16-bits will automatically be reduced to the maximum the hardware
can handle.
Multiple ``PWMAudio`` devices are supported, depending on availability of
DMA channels.
The interface for the ``PWMAudio`` device is very similar to the ``I2S``
device, and most code can be ported simply by instantiating a ``PWMAudio``
object in lieu of an ``I2S`` object.
PWM Class API
-------------
PWMAudio(pin)
~~~~~~~~~~~~~
Creates a mono PWM output port. Any pin can be used, but no ``analogWrite``
calls are allowed to any other pins using that pin's PWM slice hardware.
See the RP2040 datasheet for more details about PWM slices.
PWMAudio(pin, true)
~~~~~~~~~~~~~~~~~~~
Creates a stereo PWM output port. Only even pins (left signal) can be used, the next odd
pin will automatically be assigned to the right channel (i.e. ``PWMAudio pwm(0, true);``
will make GP0 as the left channel, GP1 as the right channel). The same restriction as
in mono mode applies.
bool setBuffers(size_t buffers, size_t bufferWords)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Set the number of DMA buffers and their size in 32-bit words.
Call before ``PWMAudio::begin()``.
When running at high sample rates, it is recommended to increase the
``bufferWords`` to 32 or higher (i.e. ``pwm.setBuffers(4, 32);`` ).
bool setPin(pin_size_t pin)
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Adjusts the pin to connect to the PWM audio output. Only legal before
``PWMAudio::begin()``.
bool setStereo(bool stereo)
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Adjusts the mono/stereo setting of the PWM audio output. Only legal before
``PWMAudio::begin()``.
bool setFrequency(long sampleRate)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sets the sample frequency, but does not start the PWM device (however if the
device was already running, it will wontinue to run at the new frequency).
bool begin()/begin(long sampleRate)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Start the PWM Audio device up with the given sample rate, or with the value set
using the prior ``setFrequency`` call.
void end()
~~~~~~~~~~
Stops the PWMAudio device.
void flush()
~~~~~~~~~~~~
Waits until all the PWM Audio buffers have been output.
size_t write(int16_t sample, bool sync = true)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Writes a single 16-bit sample to the buffer. It is up to the user to keep track
of left/right channels when in stereo mode. In mono mode, one sample is written
per timestep while in stereo mode two ``write()`` calls are required.
This call will block (wait) until space is available to actually write
the data if ``sync`` is not specified or set to ``true``.
size_t write(const uint8_t \*buffer, size_t size)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Transfers number of bytes from an application buffer to the PWM Audio 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.
int availableForWrite()
~~~~~~~~~~~~~~~~~~~~~~~
Returns the number of samples that can be written without potentially blocking.
void onTransmit(void (\*fn)(void))
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sets a callback to be called when a PWM Audio DMA buffer is fully transmitted.
Will be in an interrupt context so the specified function must operate
quickly and not use blocking calls like delay() or write to the PWM Audio.
+18 -2
View File
@@ -13,6 +13,10 @@ Returns the current frequency of the core clock. This is read at runtime,
versus the constant ``F_CPU`` macro that is also available. This is useful
in cases where your code changes the core clock (i.e. low power modes, etc.)
int rp2040.cpuid()
~~~~~~~~~~~~~~~~~~
Returns the current core ID (0 or 1) of the executing task.
uint32_t rp2040.getCycleCount()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Returns a 32-bit cycle count from then the core started running. Because it
@@ -41,13 +45,16 @@ Hardware Watchdog
-----------------
void rp2040.wdt_begin(uint32_t delay_ms)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enables the hardware watchdog timer with a delay value of delay_ms
milliseconds. Note that on the RP2040, once this function has called, the
hardware watchdog can _not_ be disabled.
The maximum ``delay_ms`` allowed in this call is ``8300``, corresponding
to 8.3 seconds. Any higher values will be truncated by the hardware.
void rp2040.wdt_reset()
~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~
Reloads the watchdog's counter with the amount of time set by wdt_begin.
@@ -71,6 +78,15 @@ Returns the total heap that was available to this program at compile time (i.e.
the Pico RAM size minus things like the ``.data`` and ``.bss`` sections and other
overhead).
Hardware Identification
-----------------------
bool isPicoW()
~~~~~~~~~~~~~~
Returns the core's best guess if this code is running on a Raspberry Pi Pico W.
This would let you, possibly, use the same UF2 for Pico and PicoW by simply not
doing any WiFi calls.
Bootloader
----------
+74
View File
@@ -0,0 +1,74 @@
#pragma once
// BTstack features that can be enabled
#define ENABLE_LOG_INFO
#define ENABLE_LOG_ERROR
#define ENABLE_PRINTF_HEXDUMP
#define ENABLE_SCO_OVER_HCI
#ifdef ENABLE_CLASSIC
#define ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
#endif
#ifdef ENABLE_BLE
#define ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
#define ENABLE_LE_PERIPHERAL
#define ENABLE_LE_CENTRAL
#endif
// BTstack configuration. buffers, sizes, ...
#define HCI_OUTGOING_PRE_BUFFER_SIZE 4
#define HCI_ACL_PAYLOAD_SIZE (1691 + 4)
#define HCI_ACL_CHUNK_SIZE_ALIGNMENT 4
#define MAX_NR_AVDTP_CONNECTIONS 1
#define MAX_NR_AVDTP_STREAM_ENDPOINTS 1
#define MAX_NR_AVRCP_CONNECTIONS 2
#define MAX_NR_BNEP_CHANNELS 1
#define MAX_NR_BNEP_SERVICES 1
#define MAX_NR_BTSTACK_LINK_KEY_DB_MEMORY_ENTRIES 2
#define MAX_NR_GATT_CLIENTS 1
#define MAX_NR_HCI_CONNECTIONS 2
#define MAX_NR_HID_HOST_CONNECTIONS 1
#define MAX_NR_HIDS_CLIENTS 1
#define MAX_NR_HFP_CONNECTIONS 1
#define MAX_NR_L2CAP_CHANNELS 4
#define MAX_NR_L2CAP_SERVICES 3
#define MAX_NR_RFCOMM_CHANNELS 1
#define MAX_NR_RFCOMM_MULTIPLEXERS 1
#define MAX_NR_RFCOMM_SERVICES 1
#define MAX_NR_SERVICE_RECORD_ITEMS 4
#define MAX_NR_SM_LOOKUP_ENTRIES 3
#define MAX_NR_WHITELIST_ENTRIES 16
#define MAX_NR_LE_DEVICE_DB_ENTRIES 16
// Limit number of ACL/SCO Buffer to use by stack to avoid cyw43 shared bus overrun
#define MAX_NR_CONTROLLER_ACL_BUFFERS 3
#define MAX_NR_CONTROLLER_SCO_PACKETS 3
// Enable and configure HCI Controller to Host Flow Control to avoid cyw43 shared bus overrun
#define ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
#define HCI_HOST_ACL_PACKET_LEN 1024
#define HCI_HOST_ACL_PACKET_NUM 3
#define HCI_HOST_SCO_PACKET_LEN 120
#define HCI_HOST_SCO_PACKET_NUM 3
// Link Key DB and LE Device DB using TLV on top of Flash Sector interface
#define NVM_NUM_DEVICE_DB_ENTRIES 16
#define NVM_NUM_LINK_KEYS 16
// We don't give btstack a malloc, so use a fixed-size ATT DB.
#define MAX_ATT_DB_SIZE 512
// BTstack HAL configuration
#define HAVE_EMBEDDED_TIME_MS
// map btstack_assert onto Pico SDK assert()
#define HAVE_ASSERT
// Some USB dongles take longer to respond to HCI reset (e.g. BCM20702A).
#define HCI_RESET_RESEND_TIMEOUT_MS 1000
#define ENABLE_SOFTWARE_AES128
#define ENABLE_MICRO_ECC_FOR_LE_SECURE_CONNECTIONS
#undef HAVE_BTSTACK_STDIN
+4 -1
View File
@@ -13,6 +13,9 @@ extern void interrupts();
#define SYS_ARCH_PROTECT(lev) noInterrupts
#define SYS_ARCH_UNPROTECT(lev) interrupts
extern unsigned long get_rand_32(void);
#define LWIP_RAND() get_rand_32()
// Common settings used in most of the pico_w examples
// (see https://www.nongnu.org/lwip/2_1_x/group__lwip__opts.html for details)
@@ -25,7 +28,7 @@ extern void interrupts();
#define MEMP_NUM_TCP_SEG 32
#define MEMP_NUM_ARP_QUEUE 10
#define PBUF_POOL_SIZE 24
#define LWIP_ARP 1
#define LWIP_ARP 2
#define LWIP_ETHERNET 1
#define LWIP_ICMP 1
#define LWIP_RAW 1
+2 -2
View File
@@ -12,8 +12,8 @@
#define _PICO_VERSION_H
#define PICO_SDK_VERSION_MAJOR 1
#define PICO_SDK_VERSION_MINOR 4
#define PICO_SDK_VERSION_MINOR 5
#define PICO_SDK_VERSION_REVISION 0
#define PICO_SDK_VERSION_STRING "1.4.0"
#define PICO_SDK_VERSION_STRING "1.5.0"
#endif
+2
View File
@@ -44,6 +44,8 @@ restartCore1 KEYWORD2
reboot KEYWORD2
restart KEYWORD2
isPicoW KEYWORD2
getChipID KEYWORD2
hwrand32 KEYWORD2
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+10 -6
View File
@@ -191,11 +191,6 @@ SECTIONS
__data_end__ = .;
} > RAM AT> FLASH
.uninitialized_data (COPY): {
. = ALIGN(4);
*(.uninitialized_data*)
} > RAM
/* Start and end symbols must be word-aligned */
.scratch_x : {
__scratch_x_start__ = .;
@@ -213,7 +208,7 @@ SECTIONS
} > SCRATCH_Y AT > FLASH
__scratch_y_source__ = LOADADDR(.scratch_y);
.bss : {
.bss : {
. = ALIGN(4);
__bss_start__ = .;
*(SORT_BY_ALIGNMENT(SORT_BY_NAME(.bss*)))
@@ -222,6 +217,15 @@ SECTIONS
__bss_end__ = .;
} > RAM
/* At most one of the following two will be engaged, depending on the SDK version */
.uninitialized_ram MAX(0x20003000, .) (NOLOAD) : {
*(.uninitialized_ram*)
} > RAM
.uninitialized_data MAX(0x20003000, .) (NOLOAD) : {
*(.uninitialized_data*)
} > RAM
.heap (COPY):
{
__end__ = .;
BIN
View File
Binary file not shown.
+3
View File
@@ -0,0 +1,3 @@
source [find interface/cmsis-dap.cfg]
adapter speed 5000
source [find target/rp2040.cfg]
+7
View File
@@ -9,6 +9,7 @@
-iwithprefixbefore/pico-sdk/src/common/pico_stdlib/include
-iwithprefixbefore/pico-sdk/src/common/pico_sync/include
-iwithprefixbefore/pico-sdk/src/common/pico_time/include
-iwithprefixbefore/pico-sdk/src/common/pico_usb_reset_interface/include
-iwithprefixbefore/pico-sdk/src/common/pico_util/include
-iwithprefixbefore/pico-sdk/src/rp2040/hardware_regs/include
-iwithprefixbefore/pico-sdk/src/rp2040/hardware_structs/include
@@ -39,8 +40,11 @@
-iwithprefixbefore/pico-sdk/src/rp2_common/hardware_vreg/include
-iwithprefixbefore/pico-sdk/src/rp2_common/hardware_watchdog/include
-iwithprefixbefore/pico-sdk/src/rp2_common/hardware_xosc/include
-iwithprefixbefore/pico-sdk/src/rp2_common/pico_async_context/include
-iwithprefixbefore/pico-sdk/src/rp2_common/pico_bootrom/include
-iwithprefixbefore/pico-sdk/src/rp2_common/pico_btstack/include
-iwithprefixbefore/pico-sdk/src/rp2_common/pico_cyw43_arch/include
-iwithprefixbefore/pico-sdk/src/rp2_common/pico_cyw43_driver/include
-iwithprefixbefore/pico-sdk/src/rp2_common/pico_double/include
-iwithprefixbefore/pico-sdk/src/rp2_common/pico_float/include
-iwithprefixbefore/pico-sdk/src/rp2_common/pico_int64_ops/include
@@ -49,8 +53,11 @@
-iwithprefixbefore/pico-sdk/src/rp2_common/pico_platform/include
-iwithprefixbefore/pico-sdk/src/rp2_common/pico_printf/include
-iwithprefixbefore/pico-sdk/src/rp2_common/pico_runtime/include
-iwithprefixbefore/pico-sdk/src/rp2_common/pico_rand/include
-iwithprefixbefore/pico-sdk/src/rp2_common/pico_stdio/include
-iwithprefixbefore/pico-sdk/src/rp2_common/pico_stdio_uart/include
-iwithprefixbefore/pico-sdk/src/rp2_common/pico_unique_id/include
-iwithprefixbefore/pico-sdk/lib/cyw43-driver/src
-iwithprefixbefore/pico-sdk/lib/lwip/src/include
-iwithprefixbefore/pico-sdk/lib/btstack/src
-iwithprefixbefore/pico-sdk/lib/btstack/platform/embedded
+7
View File
@@ -200,3 +200,10 @@
-Wl,--wrap=raw_bind
-Wl,--wrap=raw_sendto
-Wl,--wrap=raw_remove
-Wl,--wrap=cyw43_cb_process_ethernet
-Wl,--wrap=cyw43_cb_tcpip_set_link_up
-Wl,--wrap=cyw43_cb_tcpip_set_link_down
-Wl,--wrap=cyw43_tcpip_link_status
-Wl,--wrap=cyw43_cb_tcpip_init
-Wl,--wrap=cyw43_cb_tcpip_deinit
@@ -0,0 +1,30 @@
/*
Mono analog microphone example using electret mike on A0
Run using the Arduino Serial Plotter to see waveform.
Released to the Public Domain by Earle F. Philhower, III
Wire the mike's VCC to 3.3V on the Pico, connect the mike's
GND to a convenient Pico GND, and then connect mike OUT to A0
*/
#include <ADCInput.h>
ADCInput mike(A0);
// For stereo/dual mikes, could use this line instead
// ADCInput(A0, A1);
void setup() {
Serial.begin(115200);
mike.begin(8000);
while (1) {
Serial.printf("%d\n", mike.read());
// For stereo/dual mikes, use this line instead
// Serial.printf("%d %d\n", mike.read(), mike.read());
}
}
void loop() {
/* Nothing here */
}
+25
View File
@@ -0,0 +1,25 @@
#######################################
# Syntax Coloring Map
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
ADCInput KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
begin KEYWORD2
end KEYWORD2
setPins KEYWORD2
setFrequency KEYWORD2
setBuffers KEYWORD2
onReceive KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################
+10
View File
@@ -0,0 +1,10 @@
name=ADCInput
version=1.0
author=Earle F. Philhower, III <earlephilhower@yahoo.com>
maintainer=Earle F. Philhower, III <earlephilhower@yahoo.com>
sentence=Records ADC values (i.e. microphone, sensors) and presents an I2S-like callback/immediate read interface
paragraph=Records ADC values (i.e. microphone, sensors) and presents an I2S-like callback/immediate read interface
category=Communication
url=http://github.com/earlephilhower/arduino-pico
architectures=rp2040
dot_a_linkage=true
+172
View File
@@ -0,0 +1,172 @@
/*
ADCInput
Records ADC values (i.e. microphone, sensors) and presents an I2S-like
callback/immediate read interface
Copyright (c) 2023 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 "ADCInput.h"
#include <hardware/adc.h>
ADCInput::ADCInput(pin_size_t p0, pin_size_t p1, pin_size_t p2, pin_size_t p3) {
_running = false;
setPins(p0, p1, p2, p3);
_freq = 48000;
_arb = nullptr;
_cb = nullptr;
_buffers = 8;
_bufferWords = 0;
}
ADCInput::~ADCInput() {
end();
}
bool ADCInput::setBuffers(size_t buffers, size_t bufferWords) {
if (_running || (buffers < 3) || (bufferWords < 8)) {
return false;
}
_buffers = buffers;
_bufferWords = bufferWords;
return true;
}
int ADCInput::_mask(pin_size_t p) {
switch (p) {
case 26: return 1;
case 27: return 2;
case 28: return 4;
case 29: return 8;
default: return 0;
}
}
bool ADCInput::setPins(pin_size_t pin0, pin_size_t pin1, pin_size_t pin2, pin_size_t pin3) {
if (_running) {
return false;
}
_pinMask = _mask(pin0) | _mask(pin1) | _mask(pin2) | _mask(pin3);
return true;
}
bool ADCInput::setFrequency(int newFreq) {
_freq = newFreq * __builtin_popcount(_pinMask); // Want to sample all channels at given frequency
adc_set_clkdiv(48000000.0f / _freq - 1.0f);
return true;
}
void ADCInput::onReceive(void(*fn)(void)) {
_cb = fn;
if (_running) {
_arb->setCallback(_cb);
}
}
bool ADCInput::begin() {
_running = true;
_isHolding = 0;
if (!_bufferWords) {
_bufferWords = 16;
}
// Set up the GPIOs to go to ADC
adc_init();
int cnt = 0;
for (int mask = 1, pin = 26; pin <= 29; mask <<= 1, pin++) {
if (_pinMask & mask) {
if (!cnt) {
adc_select_input(pin - 26);
}
cnt++;
adc_gpio_init(pin);
}
}
adc_set_round_robin(_pinMask);
adc_fifo_setup(true, true, 1, false, false);
setFrequency(_freq);
_arb = new AudioBufferManager(_buffers, _bufferWords, 0, INPUT, DMA_SIZE_16);
_arb->begin(DREQ_ADC, (volatile void*)&adc_hw->fifo);
_arb->setCallback(_cb);
adc_fifo_drain();
adc_run(true);
return true;
}
void ADCInput::end() {
if (_running) {
_running = false;
delete _arb;
_arb = nullptr;
}
adc_run(false);
adc_fifo_drain();
}
int ADCInput::available() {
if (!_running) {
return 0;
} else {
return _arb->available();
}
}
int ADCInput::read() {
if (!_running) {
return -1;
}
if (_hasPeeked) {
_hasPeeked = false;
return _peekSaved;
}
if (_isHolding <= 0) {
_arb->read(&_holdWord, true);
_isHolding = 32;
}
int ret = _holdWord & 0x0fff;
_holdWord >>= 16;
_isHolding -= 16;
return ret;
}
int ADCInput::peek() {
if (!_running) {
return -1;
}
if (!_hasPeeked) {
_peekSaved = read();
_hasPeeked = true;
}
return _peekSaved;
}
void ADCInput::flush() {
if (_running) {
_arb->flush();
}
}
+87
View File
@@ -0,0 +1,87 @@
/*
ADCInput
Records ADC values (i.e. microphone, sensors) and presents an I2S-like
callback/immediate read interface
Copyright (c) 2023 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 "AudioBufferManager.h"
class ADCInput : public Stream {
public:
ADCInput(pin_size_t pin0, pin_size_t pin1 = 255, pin_size_t pin2 = 255, pin_size_t pin3 = 255);
virtual ~ADCInput();
bool setBuffers(size_t buffers, size_t bufferWords);
bool setFrequency(int newFreq);
bool setPins(pin_size_t pin0, pin_size_t pin1 = 255, pin_size_t pin2 = 255, pin_size_t pin3 = 255);
bool begin(long sampleRate) {
setFrequency(sampleRate);
return begin();
}
bool begin();
void end();
// from Stream
virtual int available() override;
virtual int read() override;
virtual int peek() override;
virtual void flush() override;
// from Print, not supported
virtual size_t write(const uint8_t *buffer, size_t size) override {
(void) buffer;
(void) size;
return -1;
}
virtual size_t write(uint8_t x) override {
(void) x;
return -1;
}
virtual int availableForWrite() override {
return 0;
}
// Note that these callback are called from **INTERRUPT CONTEXT** and hence
// should be in RAM, not FLASH, and should be quick to execute.
void onReceive(void(*)(void));
private:
uint32_t _pinMask;
int _freq;
size_t _buffers;
size_t _bufferWords;
bool _running;
void (*_cb)();
bool _hasPeeked;
uint32_t _peekSaved;
uint32_t _holdWord = 0;
int _isHolding = 0;
int _mask(pin_size_t pin);
AudioBufferManager *_arb;
};
@@ -59,6 +59,7 @@ AudioBufferManager::AudioBufferManager(size_t bufferCount, size_t bufferWords, i
for (size_t i = 0; i < bufferCount; i++) {
auto ab = new AudioBuffer;
ab->buff = new uint32_t[_wordsPerBuffer];
bzero(ab->buff, _wordsPerBuffer * 4);
ab->next = nullptr;
_addToList(&_empty, ab);
}
@@ -68,11 +69,15 @@ AudioBufferManager::AudioBufferManager(size_t bufferCount, size_t bufferWords, i
}
AudioBufferManager::~AudioBufferManager() {
noInterrupts();
if (_running) {
_running = false;
for (auto i = 0; i < 2; i++) {
dma_channel_set_irq0_enabled(_channelDMA[i], false);
dma_channel_unclaim(_channelDMA[i]);
__channelMap[_channelDMA[i]] = nullptr;
dma_channel_abort(_channelDMA[i]);
dma_channel_unclaim(_channelDMA[i]);
dma_channel_acknowledge_irq0(_channelDMA[i]);
}
__channelCount--;
if (!__channelCount) {
@@ -81,6 +86,7 @@ AudioBufferManager::~AudioBufferManager() {
irq_remove_handler(DMA_IRQ_0, _irq);
}
}
interrupts();
for (int i = 0; i < 2; i++) {
if (_active[i] != _silence) {
_deleteAudioBuffer(_active[i]);
@@ -133,10 +139,10 @@ bool AudioBufferManager::begin(int dreq, volatile void *pioFIFOAddr) {
channel_config_set_irq_quiet(&c, false); // Need IRQs
if (_isOutput) {
dma_channel_configure(_channelDMA[i], &c, pioFIFOAddr, _silence->buff, _wordsPerBuffer, false);
dma_channel_configure(_channelDMA[i], &c, pioFIFOAddr, _silence->buff, _wordsPerBuffer * (_dmaSize == DMA_SIZE_16 ? 2 : 1), false);
} else {
_active[i] = _takeFromList(&_empty);
dma_channel_configure(_channelDMA[i], &c, _active[i]->buff, pioFIFOAddr, _wordsPerBuffer, false);
dma_channel_configure(_channelDMA[i], &c, _active[i]->buff, pioFIFOAddr, _wordsPerBuffer * (_dmaSize == DMA_SIZE_16 ? 2 : 1), false);
}
dma_channel_set_irq0_enabled(_channelDMA[i], true);
__channelMap[_channelDMA[i]] = this;
@@ -237,6 +243,9 @@ void AudioBufferManager::flush() {
}
void __not_in_flash_func(AudioBufferManager::_dmaIRQ)(int channel) {
if (!_running) {
return;
}
if (_isOutput) {
if (_active[0] != _silence) {
_addToList(&_empty, _active[0]);
@@ -259,7 +268,7 @@ void __not_in_flash_func(AudioBufferManager::_dmaIRQ)(int channel) {
}
dma_channel_set_write_addr(channel, _active[0]->buff, false);
}
dma_channel_set_trans_count(channel, _wordsPerBuffer, false);
dma_channel_set_trans_count(channel, _wordsPerBuffer * (_dmaSize == DMA_SIZE_16 ? 2 : 1), false);
dma_channel_acknowledge_irq0(channel);
if (_callback) {
_callback();
@@ -30,7 +30,7 @@ void ps() {
Serial.printf("# Tasks: %d\n", tasks);
Serial.println("ID, NAME, STATE, PRIO, CYCLES");
for (int i=0; i < tasks; i++) {
Serial.printf("%d: %-16s %-10s %d %lu\n", i, pxTaskStatusArray[i].pcTaskName, eTaskStateName[pxTaskStatusArray[i].eCurrentState], pxTaskStatusArray[i].uxCurrentPriority, pxTaskStatusArray[i].ulRunTimeCounter);
Serial.printf("%d: %-16s %-10s %d %lu\n", i, pxTaskStatusArray[i].pcTaskName, eTaskStateName[pxTaskStatusArray[i].eCurrentState], (int)pxTaskStatusArray[i].uxCurrentPriority, pxTaskStatusArray[i].ulRunTimeCounter);
}
delete[] pxTaskStatusArray;
}
+30
View File
@@ -0,0 +1,30 @@
#######################################
# Syntax Coloring Map
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
PicoBluetoothHID KEYWORD1
PicoBluetoothBLEHID KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
setOpenedCB KEYWORD2
setClosedCB KEYWORD2
setCanSendNowCB KEYWORD2
startHID KEYWORD2
connected KEYWORD2
send KEYWORD2
lockBluetooth KEYWORD2
unlockBluetooth KEYWORD2
getCID KEYWORD2
setBattery KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################
@@ -0,0 +1,9 @@
name=HID_Bluetooth
version=1.0.0
author=Earle F. Philhower, III <earlephilhower@yahoo.com>
maintainer=Earle F. Philhower, III <earlephilhower@yahoo.com>
sentence=Implements a HID device base class for PicoW Bluetooth
paragraph=Implements a HID device base class for PicoW Bluetooth
category=Device Control
url=https://github.com/earlephilhower/arduino-pico
architectures=rp2040
@@ -0,0 +1,7 @@
#ifdef ENABLE_CLASSIC
#include "PicoBluetoothHID.h"
#endif
#ifdef ENABLE_BLE
#include "PicoBluetoothBLEHID.h"
#endif
@@ -0,0 +1,23 @@
/*
PicoBluetoothBLEHID.h - Simple wrapper for BT-HID objects like
keyboards, mice, gamepads.
Copyright (c) 2023 Earle F. Philhower, III. All rights reserved.
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 "PicoBluetoothBLEHID.h"
PicoBluetoothBLEHID_ PicoBluetoothBLEHID;
@@ -0,0 +1,484 @@
/*
PicoBluetoothBLEHID.h - Simple wrapper for BT-HID objects like
keyboards, mice, gamepads using Bluetooth LE mode
Based off of the BTStack HID main loop
Copyright (c) 2023 Earle F. Philhower, III. All rights reserved.
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 <functional>
#include <pico/cyw43_arch.h>
#include <class/hid/hid_device.h>
// The BTStack has redefinitions of this USB enum (same values, just redefined), so hide it to allow easy compilation
#define HID_REPORT_TYPE_INPUT HID_REPORT_TYPE_INPUT_BT
#define HID_REPORT_TYPE_OUTPUT HID_REPORT_TYPE_OUTPUT_BT
#define HID_REPORT_TYPE_FEATURE HID_REPORT_TYPE_FEATURE_BT
#define hid_report_type_t hid_report_type_t_bt
#include <btstack.h>
#undef hid_report_type_t
#undef HID_REPORT_TYPE_FEATURE
#undef HID_REPORT_TYPE_OUTPUT
#undef HID_REPORT_TYPE_INPUT
#include <ble/sm.h>
#include <ble/att_server.h>
#include <btstack_event.h>
#include <ble/gatt-service/battery_service_server.h>
#include <ble/gatt-service/device_information_service_server.h>
#include <ble/gatt-service/hids_device.h>
class PicoBluetoothBLEHID_;
extern PicoBluetoothBLEHID_ PicoBluetoothBLEHID;
class PicoBluetoothBLEHID_ {
public:
PicoBluetoothBLEHID_() {
}
~PicoBluetoothBLEHID_() {
}
// Optional callback, not used presently
// Usage: PicoBluetoothHID.setCanSendNowCB(std::bind(&kbd::onCanSendNow, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4));
typedef std::function<void(uint8_t type, uint16_t channel, uint8_t *packet, uint16_t size)> BTCallback;
void setOpenedCB(BTCallback cb) {
_onOpened = cb;
}
void setClosedCB(BTCallback cb) {
_onClosed = cb;
}
void setCanSendNowCB(BTCallback cb) {
_onCanSendNow = cb;
}
bool startHID(const char *localName, const char *hidName, uint16_t appearance, const uint8_t *hidDescriptor, uint16_t hidDescriptorSize, int battery = 100) {
if (_running) {
return false;
}
_running = true;
_buildAdvData(localName, appearance);
_buildAttdb(hidName);
_battery = battery;
// Setup L2CAP
l2cap_init();
// Setup SM
sm_init();
sm_set_io_capabilities(IO_CAPABILITY_NO_INPUT_NO_OUTPUT);
sm_set_authentication_requirements(SM_AUTHREQ_SECURE_CONNECTION | SM_AUTHREQ_BONDING);
// Setup ATT server
att_server_init(_attdb, NULL, NULL);
// Setup battery service
battery_service_server_init(battery);
// Setup device information service
device_information_service_server_init();
// Setup HID Device service
hids_device_init(0, hidDescriptor, hidDescriptorSize);
// Setup advertisements
uint16_t adv_int_min = 0x0030;
uint16_t adv_int_max = 0x0030;
uint8_t adv_type = 0;
bd_addr_t null_addr;
memset(null_addr, 0, 6);
gap_advertisements_set_params(adv_int_min, adv_int_max, adv_type, 0, null_addr, 0x07, 0x00);
gap_advertisements_set_data(_advDataLen, _advData);
gap_advertisements_enable(1);
// Register for HCI events
_hci_event_callback_registration.callback = PacketHandlerWrapper;
hci_add_event_handler(&_hci_event_callback_registration);
// Register for SM events
_sm_event_callback_registration.callback = PacketHandlerWrapper;
sm_add_event_handler(&_sm_event_callback_registration);
// Register for HIDS events
hids_device_register_packet_handler(PacketHandlerWrapper);
// GO!
hci_power_control(HCI_POWER_ON);
return true;
}
static void PacketHandlerWrapper(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t packet_size) {
PicoBluetoothBLEHID.packetHandler(packet_type, channel, packet, packet_size);
}
void packetHandler(uint8_t type, uint16_t channel, uint8_t *packet, uint16_t size) {
if (type != HCI_EVENT_PACKET) {
return;
}
switch (hci_event_packet_get_type(packet)) {
case HCI_EVENT_DISCONNECTION_COMPLETE:
_con_handle = HCI_CON_HANDLE_INVALID;
if (_onClosed) {
_onClosed(type, channel, packet, size);
}
break;
case SM_EVENT_JUST_WORKS_REQUEST:
sm_just_works_confirm(sm_event_just_works_request_get_handle(packet));
break;
case SM_EVENT_NUMERIC_COMPARISON_REQUEST:
// printf("Confirming numeric comparison: %"PRIu32"\n", sm_event_numeric_comparison_request_get_passkey(packet));
sm_numeric_comparison_confirm(sm_event_passkey_display_number_get_handle(packet));
break;
case SM_EVENT_PASSKEY_DISPLAY_NUMBER:
//printf("Display Passkey: %"PRIu32"\n", sm_event_passkey_display_number_get_passkey(packet));
break;
case HCI_EVENT_HIDS_META:
switch (hci_event_hids_meta_get_subevent_code(packet)) {
case HIDS_SUBEVENT_INPUT_REPORT_ENABLE:
_con_handle = hids_subevent_input_report_enable_get_con_handle(packet);
if (_onOpened) {
_onOpened(type, channel, packet, size);
}
break;
case HIDS_SUBEVENT_BOOT_KEYBOARD_INPUT_REPORT_ENABLE:
_con_handle = hids_subevent_boot_keyboard_input_report_enable_get_con_handle(packet);
if (_onOpened) {
_onOpened(type, channel, packet, size);
}
break;
case HIDS_SUBEVENT_PROTOCOL_MODE:
_protocol_mode = hids_subevent_protocol_mode_get_protocol_mode(packet);
break;
case HIDS_SUBEVENT_CAN_SEND_NOW:
switch (_protocol_mode) {
case 0:
hids_device_send_boot_keyboard_input_report(_con_handle, (const uint8_t *)_sendReport, _sendReportLen);
break;
case 1:
hids_device_send_input_report(_con_handle, (const uint8_t *)_sendReport, _sendReportLen);
break;
default:
break;
}
_needToSend = false;
if (_onCanSendNow) {
_onCanSendNow(type, channel, packet, size);
}
break;
}
break;
default:
break;
}
}
bool end() {
if (_running) {
hci_power_control(HCI_POWER_OFF);
}
_running = false;
_needToSend = false;
return true;
}
bool connected() {
return _con_handle != HCI_CON_HANDLE_INVALID;
}
bool send(void *rpt, int len) {
_needToSend = true;
_sendReport = rpt;
_sendReportLen = len;
lockBluetooth();
hids_device_request_can_send_now_event(_con_handle);
unlockBluetooth();
while (connected() && _needToSend) {
/* noop busy wait */
}
return connected();
}
bool setBattery(int level) {
if (!_running || (level < 0) || (level > 100)) {
return false;
}
battery_service_server_set_battery_value(level);
return true;
}
static void lockBluetooth() {
async_context_acquire_lock_blocking(cyw43_arch_async_context());
}
static void unlockBluetooth() {
async_context_release_lock(cyw43_arch_async_context());
}
private:
bool _running = false;
BTCallback _onOpened = nullptr;
BTCallback _onClosed = nullptr;
BTCallback _onCanSendNow = nullptr;
btstack_packet_callback_registration_t _hci_event_callback_registration;
btstack_packet_callback_registration_t _sm_event_callback_registration;
uint8_t _battery = 100;
hci_con_handle_t _con_handle = HCI_CON_HANDLE_INVALID;
uint8_t _protocol_mode = 1;
void _buildAdvData(const char *completeLocalName, uint16_t appearance) {
free(_advData);
_advDataLen = 13 + strlen(completeLocalName);
_advData = (uint8_t*) malloc(_advDataLen);
int i = 0;
// Flags general discoverable, BR/EDR not supported
// 0x02, BLUETOOTH_DATA_TYPE_FLAGS, 0x06,
_advData[i++] = 0x02;
_advData[i++] = BLUETOOTH_DATA_TYPE_FLAGS;
_advData[i++] = 0x06;
// Name
// 0x0d, BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME,
_advData[i++] = 1 + strlen(completeLocalName);
_advData[i++] = BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME;
memcpy(_advData + i, completeLocalName, strlen(completeLocalName));
i += strlen(completeLocalName);
// 16-bit Service UUIDs
// 0x03, BLUETOOTH_DATA_TYPE_COMPLETE_LIST_OF_16_BIT_SERVICE_CLASS_UUIDS, ORG_BLUETOOTH_SERVICE_HUMAN_INTERFACE_DEVICE & 0xff, ORG_BLUETOOTH_SERVICE_HUMAN_INTERFACE_DEVICE >> 8,
_advData[i++] = 0x03;
_advData[i++] = BLUETOOTH_DATA_TYPE_COMPLETE_LIST_OF_16_BIT_SERVICE_CLASS_UUIDS;
_advData[i++] = ORG_BLUETOOTH_SERVICE_HUMAN_INTERFACE_DEVICE & 0xff;
_advData[i++] = ORG_BLUETOOTH_SERVICE_HUMAN_INTERFACE_DEVICE >> 8;
// Appearance HID - Keyboard (Category 15, Sub-Category 1)
// 0x03, BLUETOOTH_DATA_TYPE_APPEARANCE, 0xC1, 0x03,
_advData[i++] = 0x03;
_advData[i++] = BLUETOOTH_DATA_TYPE_APPEARANCE;
_advData[i++] = appearance & 0xff;
_advData[i++] = appearance >> 8;
}
uint8_t *_advData = nullptr;
uint8_t _advDataLen = 0;
void _buildAttdb(const char *hidName) {
free(_attdb);
_attdbLen = sizeof(_attdb_head) + 8 + strlen(hidName) + sizeof(_attdb_tail);
_attdb = (uint8_t *) malloc(_attdbLen);
memcpy(_attdb, _attdb_head, sizeof(_attdb_head));
// 0x0003 VALUE CHARACTERISTIC-GAP_DEVICE_NAME - READ -'HID Mouse'
// READ_ANYBODY
// 0x11, 0x00, 0x02, 0x00, 0x03, 0x00, 0x00, 0x2a, 0x48, 0x49, 0x44, 0x20, 0x4d, 0x6f, 0x75, 0x73, 0x65,
int i = sizeof(_attdb_head);
_attdb[i++] = 8 + strlen(hidName);
_attdb[i++] = 0x00;
_attdb[i++] = 0x02;
_attdb[i++] = 0x00;
_attdb[i++] = 0x03;
_attdb[i++] = 0x00;
_attdb[i++] = 0x00;
_attdb[i++] = 0x2a;
memcpy(_attdb + i, hidName, strlen(hidName));
i += strlen(hidName);
memcpy(_attdb + i, _attdb_tail, sizeof(_attdb_tail));
}
uint8_t *_attdb = nullptr;
int _attdbLen = 0;
static constexpr const uint8_t _attdb_head[] = {
// ATT DB Version
1,
// 0x0001 PRIMARY_SERVICE-GAP_SERVICE
0x0a, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x28, 0x00, 0x18,
// 0x0002 CHARACTERISTIC-GAP_DEVICE_NAME - READ
0x0d, 0x00, 0x02, 0x00, 0x02, 0x00, 0x03, 0x28, 0x02, 0x03, 0x00, 0x00, 0x2a,
};
static constexpr const uint8_t _attdb_tail[] = {
// #import <battery_service.gatt> -- BEGIN
// Specification Type org.bluetooth.service.battery_service
// https://www.bluetooth.com/api/gatt/xmlfile?xmlFileName=org.bluetooth.service.battery_service.xml
// Battery Service 180F
// 0x0004 PRIMARY_SERVICE-ORG_BLUETOOTH_SERVICE_BATTERY_SERVICE
0x0a, 0x00, 0x02, 0x00, 0x04, 0x00, 0x00, 0x28, 0x0f, 0x18,
// 0x0005 CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_BATTERY_LEVEL - DYNAMIC | READ | NOTIFY
0x0d, 0x00, 0x02, 0x00, 0x05, 0x00, 0x03, 0x28, 0x12, 0x06, 0x00, 0x19, 0x2a,
// 0x0006 VALUE CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_BATTERY_LEVEL - DYNAMIC | READ | NOTIFY
// READ_ANYBODY
0x08, 0x00, 0x02, 0x01, 0x06, 0x00, 0x19, 0x2a,
// 0x0007 CLIENT_CHARACTERISTIC_CONFIGURATION
// READ_ANYBODY, WRITE_ANYBODY
0x0a, 0x00, 0x0e, 0x01, 0x07, 0x00, 0x02, 0x29, 0x00, 0x00,
// #import <battery_service.gatt> -- END
// add Device ID Service
// #import <device_information_service.gatt> -- BEGIN
// Specification Type org.bluetooth.service.device_information
// https://www.bluetooth.com/api/gatt/xmlfile?xmlFileName=org.bluetooth.service.device_information.xml
// Device Information 180A
// 0x0008 PRIMARY_SERVICE-ORG_BLUETOOTH_SERVICE_DEVICE_INFORMATION
0x0a, 0x00, 0x02, 0x00, 0x08, 0x00, 0x00, 0x28, 0x0a, 0x18,
// 0x0009 CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_MANUFACTURER_NAME_STRING - DYNAMIC | READ
0x0d, 0x00, 0x02, 0x00, 0x09, 0x00, 0x03, 0x28, 0x02, 0x0a, 0x00, 0x29, 0x2a,
// 0x000a VALUE CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_MANUFACTURER_NAME_STRING - DYNAMIC | READ
// READ_ANYBODY
0x08, 0x00, 0x02, 0x01, 0x0a, 0x00, 0x29, 0x2a,
// 0x000b CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_MODEL_NUMBER_STRING - DYNAMIC | READ
0x0d, 0x00, 0x02, 0x00, 0x0b, 0x00, 0x03, 0x28, 0x02, 0x0c, 0x00, 0x24, 0x2a,
// 0x000c VALUE CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_MODEL_NUMBER_STRING - DYNAMIC | READ
// READ_ANYBODY
0x08, 0x00, 0x02, 0x01, 0x0c, 0x00, 0x24, 0x2a,
// 0x000d CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_SERIAL_NUMBER_STRING - DYNAMIC | READ
0x0d, 0x00, 0x02, 0x00, 0x0d, 0x00, 0x03, 0x28, 0x02, 0x0e, 0x00, 0x25, 0x2a,
// 0x000e VALUE CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_SERIAL_NUMBER_STRING - DYNAMIC | READ
// READ_ANYBODY
0x08, 0x00, 0x02, 0x01, 0x0e, 0x00, 0x25, 0x2a,
// 0x000f CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_HARDWARE_REVISION_STRING - DYNAMIC | READ
0x0d, 0x00, 0x02, 0x00, 0x0f, 0x00, 0x03, 0x28, 0x02, 0x10, 0x00, 0x27, 0x2a,
// 0x0010 VALUE CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_HARDWARE_REVISION_STRING - DYNAMIC | READ
// READ_ANYBODY
0x08, 0x00, 0x02, 0x01, 0x10, 0x00, 0x27, 0x2a,
// 0x0011 CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_FIRMWARE_REVISION_STRING - DYNAMIC | READ
0x0d, 0x00, 0x02, 0x00, 0x11, 0x00, 0x03, 0x28, 0x02, 0x12, 0x00, 0x26, 0x2a,
// 0x0012 VALUE CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_FIRMWARE_REVISION_STRING - DYNAMIC | READ
// READ_ANYBODY
0x08, 0x00, 0x02, 0x01, 0x12, 0x00, 0x26, 0x2a,
// 0x0013 CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_SOFTWARE_REVISION_STRING - DYNAMIC | READ
0x0d, 0x00, 0x02, 0x00, 0x13, 0x00, 0x03, 0x28, 0x02, 0x14, 0x00, 0x28, 0x2a,
// 0x0014 VALUE CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_SOFTWARE_REVISION_STRING - DYNAMIC | READ
// READ_ANYBODY
0x08, 0x00, 0x02, 0x01, 0x14, 0x00, 0x28, 0x2a,
// 0x0015 CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_SYSTEM_ID - DYNAMIC | READ
0x0d, 0x00, 0x02, 0x00, 0x15, 0x00, 0x03, 0x28, 0x02, 0x16, 0x00, 0x23, 0x2a,
// 0x0016 VALUE CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_SYSTEM_ID - DYNAMIC | READ
// READ_ANYBODY
0x08, 0x00, 0x02, 0x01, 0x16, 0x00, 0x23, 0x2a,
// 0x0017 CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_IEEE_11073_20601_REGULATORY_CERTIFICATION_DATA_LIST - DYNAMIC | READ
0x0d, 0x00, 0x02, 0x00, 0x17, 0x00, 0x03, 0x28, 0x02, 0x18, 0x00, 0x2a, 0x2a,
// 0x0018 VALUE CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_IEEE_11073_20601_REGULATORY_CERTIFICATION_DATA_LIST - DYNAMIC | READ
// READ_ANYBODY
0x08, 0x00, 0x02, 0x01, 0x18, 0x00, 0x2a, 0x2a,
// 0x0019 CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_PNP_ID - DYNAMIC | READ
0x0d, 0x00, 0x02, 0x00, 0x19, 0x00, 0x03, 0x28, 0x02, 0x1a, 0x00, 0x50, 0x2a,
// 0x001a VALUE CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_PNP_ID - DYNAMIC | READ
// READ_ANYBODY
0x08, 0x00, 0x02, 0x01, 0x1a, 0x00, 0x50, 0x2a,
// #import <device_information_service.gatt> -- END
// #import <hids.gatt> -- BEGIN
// Specification Type org.bluetooth.service.human_interface_device
// https://www.bluetooth.com/api/gatt/xmlfile?xmlFileName=org.bluetooth.service.human_interface_device.xml
// Human Interface Device 1812
// 0x001b PRIMARY_SERVICE-ORG_BLUETOOTH_SERVICE_HUMAN_INTERFACE_DEVICE
0x0a, 0x00, 0x02, 0x00, 0x1b, 0x00, 0x00, 0x28, 0x12, 0x18,
// 0x001c CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_PROTOCOL_MODE - DYNAMIC | READ | WRITE_WITHOUT_RESPONSE
0x0d, 0x00, 0x02, 0x00, 0x1c, 0x00, 0x03, 0x28, 0x06, 0x1d, 0x00, 0x4e, 0x2a,
// 0x001d VALUE CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_PROTOCOL_MODE - DYNAMIC | READ | WRITE_WITHOUT_RESPONSE
// READ_ANYBODY, WRITE_ANYBODY
0x08, 0x00, 0x06, 0x01, 0x1d, 0x00, 0x4e, 0x2a,
// 0x001e CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_REPORT - DYNAMIC | READ | WRITE | NOTIFY | ENCRYPTION_KEY_SIZE_16
0x0d, 0x00, 0x02, 0x00, 0x1e, 0x00, 0x03, 0x28, 0x1a, 0x1f, 0x00, 0x4d, 0x2a,
// 0x001f VALUE CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_REPORT - DYNAMIC | READ | WRITE | NOTIFY | ENCRYPTION_KEY_SIZE_16
// READ_ENCRYPTED, WRITE_ENCRYPTED, ENCRYPTION_KEY_SIZE=16
0x08, 0x00, 0x0b, 0xf5, 0x1f, 0x00, 0x4d, 0x2a,
// 0x0020 CLIENT_CHARACTERISTIC_CONFIGURATION
// READ_ANYBODY, WRITE_ENCRYPTED, ENCRYPTION_KEY_SIZE=16
0x0a, 0x00, 0x0f, 0xf1, 0x20, 0x00, 0x02, 0x29, 0x00, 0x00,
// fixed report id = 1, type = Input (1)
// 0x0021 REPORT_REFERENCE-READ-1-1
0x0a, 0x00, 0x02, 0x00, 0x21, 0x00, 0x08, 0x29, 0x1, 0x1,
// 0x0022 CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_REPORT - DYNAMIC | READ | WRITE | NOTIFY | ENCRYPTION_KEY_SIZE_16
0x0d, 0x00, 0x02, 0x00, 0x22, 0x00, 0x03, 0x28, 0x1a, 0x23, 0x00, 0x4d, 0x2a,
// 0x0023 VALUE CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_REPORT - DYNAMIC | READ | WRITE | NOTIFY | ENCRYPTION_KEY_SIZE_16
// READ_ENCRYPTED, WRITE_ENCRYPTED, ENCRYPTION_KEY_SIZE=16
0x08, 0x00, 0x0b, 0xf5, 0x23, 0x00, 0x4d, 0x2a,
// 0x0024 CLIENT_CHARACTERISTIC_CONFIGURATION
// READ_ANYBODY, WRITE_ENCRYPTED, ENCRYPTION_KEY_SIZE=16
0x0a, 0x00, 0x0f, 0xf1, 0x24, 0x00, 0x02, 0x29, 0x00, 0x00,
// fixed report id = 2, type = Output (2)
// 0x0025 REPORT_REFERENCE-READ-2-2
0x0a, 0x00, 0x02, 0x00, 0x25, 0x00, 0x08, 0x29, 0x2, 0x2,
// 0x0026 CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_REPORT - DYNAMIC | READ | WRITE | NOTIFY | ENCRYPTION_KEY_SIZE_16
0x0d, 0x00, 0x02, 0x00, 0x26, 0x00, 0x03, 0x28, 0x1a, 0x27, 0x00, 0x4d, 0x2a,
// 0x0027 VALUE CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_REPORT - DYNAMIC | READ | WRITE | NOTIFY | ENCRYPTION_KEY_SIZE_16
// READ_ENCRYPTED, WRITE_ENCRYPTED, ENCRYPTION_KEY_SIZE=16
0x08, 0x00, 0x0b, 0xf5, 0x27, 0x00, 0x4d, 0x2a,
// 0x0028 CLIENT_CHARACTERISTIC_CONFIGURATION
// READ_ANYBODY, WRITE_ENCRYPTED, ENCRYPTION_KEY_SIZE=16
0x0a, 0x00, 0x0f, 0xf1, 0x28, 0x00, 0x02, 0x29, 0x00, 0x00,
// fixed report id = 3, type = Feature (3)
// 0x0029 REPORT_REFERENCE-READ-3-3
0x0a, 0x00, 0x02, 0x00, 0x29, 0x00, 0x08, 0x29, 0x3, 0x3,
// 0x002a CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_REPORT_MAP - DYNAMIC | READ
0x0d, 0x00, 0x02, 0x00, 0x2a, 0x00, 0x03, 0x28, 0x02, 0x2b, 0x00, 0x4b, 0x2a,
// 0x002b VALUE CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_REPORT_MAP - DYNAMIC | READ
// READ_ANYBODY
0x08, 0x00, 0x02, 0x01, 0x2b, 0x00, 0x4b, 0x2a,
// 0x002c CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_BOOT_KEYBOARD_INPUT_REPORT - DYNAMIC | READ | WRITE | NOTIFY
0x0d, 0x00, 0x02, 0x00, 0x2c, 0x00, 0x03, 0x28, 0x1a, 0x2d, 0x00, 0x22, 0x2a,
// 0x002d VALUE CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_BOOT_KEYBOARD_INPUT_REPORT - DYNAMIC | READ | WRITE | NOTIFY
// READ_ANYBODY, WRITE_ANYBODY
0x08, 0x00, 0x0a, 0x01, 0x2d, 0x00, 0x22, 0x2a,
// 0x002e CLIENT_CHARACTERISTIC_CONFIGURATION
// READ_ANYBODY, WRITE_ANYBODY
0x0a, 0x00, 0x0e, 0x01, 0x2e, 0x00, 0x02, 0x29, 0x00, 0x00,
// 0x002f CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_BOOT_KEYBOARD_OUTPUT_REPORT - DYNAMIC | READ | WRITE | WRITE_WITHOUT_RESPONSE
0x0d, 0x00, 0x02, 0x00, 0x2f, 0x00, 0x03, 0x28, 0x0e, 0x30, 0x00, 0x32, 0x2a,
// 0x0030 VALUE CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_BOOT_KEYBOARD_OUTPUT_REPORT - DYNAMIC | READ | WRITE | WRITE_WITHOUT_RESPONSE
// READ_ANYBODY, WRITE_ANYBODY
0x08, 0x00, 0x0e, 0x01, 0x30, 0x00, 0x32, 0x2a,
// 0x0031 CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_BOOT_MOUSE_INPUT_REPORT - DYNAMIC | READ | WRITE | NOTIFY
0x0d, 0x00, 0x02, 0x00, 0x31, 0x00, 0x03, 0x28, 0x1a, 0x32, 0x00, 0x33, 0x2a,
// 0x0032 VALUE CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_BOOT_MOUSE_INPUT_REPORT - DYNAMIC | READ | WRITE | NOTIFY
// READ_ANYBODY, WRITE_ANYBODY
0x08, 0x00, 0x0a, 0x01, 0x32, 0x00, 0x33, 0x2a,
// 0x0033 CLIENT_CHARACTERISTIC_CONFIGURATION
// READ_ANYBODY, WRITE_ANYBODY
0x0a, 0x00, 0x0e, 0x01, 0x33, 0x00, 0x02, 0x29, 0x00, 0x00,
// bcdHID = 0x101 (v1.0.1), bCountryCode 0, remote wakeable = 0 | normally connectable 2
// 0x0034 CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_HID_INFORMATION - READ
0x0d, 0x00, 0x02, 0x00, 0x34, 0x00, 0x03, 0x28, 0x02, 0x35, 0x00, 0x4a, 0x2a,
// 0x0035 VALUE CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_HID_INFORMATION - READ -'01 01 00 02'
// READ_ANYBODY
0x0c, 0x00, 0x02, 0x00, 0x35, 0x00, 0x4a, 0x2a, 0x01, 0x01, 0x00, 0x02,
// 0x0036 CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_HID_CONTROL_POINT - DYNAMIC | WRITE_WITHOUT_RESPONSE
0x0d, 0x00, 0x02, 0x00, 0x36, 0x00, 0x03, 0x28, 0x04, 0x37, 0x00, 0x4c, 0x2a,
// 0x0037 VALUE CHARACTERISTIC-ORG_BLUETOOTH_CHARACTERISTIC_HID_CONTROL_POINT - DYNAMIC | WRITE_WITHOUT_RESPONSE
// WRITE_ANYBODY
0x08, 0x00, 0x04, 0x01, 0x37, 0x00, 0x4c, 0x2a,
// #import <hids.gatt> -- END
// 0x0038 PRIMARY_SERVICE-GATT_SERVICE
0x0a, 0x00, 0x02, 0x00, 0x38, 0x00, 0x00, 0x28, 0x01, 0x18,
// 0x0039 CHARACTERISTIC-GATT_DATABASE_HASH - READ
0x0d, 0x00, 0x02, 0x00, 0x39, 0x00, 0x03, 0x28, 0x02, 0x3a, 0x00, 0x2a, 0x2b,
// 0x003a VALUE CHARACTERISTIC-GATT_DATABASE_HASH - READ -''
// READ_ANYBODY
0x18, 0x00, 0x02, 0x00, 0x3a, 0x00, 0x2a, 0x2b, 0xc2, 0x10, 0xf5, 0x75, 0xf3, 0x9f, 0x50, 0xb6, 0x83, 0xc7, 0xfa, 0xac, 0xa6, 0x1b, 0x7d, 0x32,
// END
0x00, 0x00
};
volatile bool _needToSend = false;
void *_sendReport;
int _sendReportLen;
};
@@ -0,0 +1,23 @@
/*
PicoBluetoothHID.h - Simple wrapper for BT-HID objects like
keyboards, mice, gamepads.
Copyright (c) 2023 Earle F. Philhower, III. All rights reserved.
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 "PicoBluetoothHID.h"
PicoBluetoothHID_ PicoBluetoothHID;
@@ -0,0 +1,255 @@
/*
PicoBluetoothHID.h - Simple wrapper for BT-HID objects like
keyboards, mice, gamepads.
Based off of the BTStack HID main loop
Copyright (c) 2023 Earle F. Philhower, III. All rights reserved.
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 <functional>
#include <pico/cyw43_arch.h>
#include <class/hid/hid_device.h>
// The BTStack has redefinitions of this USB enum (same values, just redefined), so hide it to allow easy compilation
#define HID_REPORT_TYPE_INPUT HID_REPORT_TYPE_INPUT_BT
#define HID_REPORT_TYPE_OUTPUT HID_REPORT_TYPE_OUTPUT_BT
#define HID_REPORT_TYPE_FEATURE HID_REPORT_TYPE_FEATURE_BT
#define hid_report_type_t hid_report_type_t_bt
#include <btstack.h>
#undef hid_report_type_t
#undef HID_REPORT_TYPE_FEATURE
#undef HID_REPORT_TYPE_OUTPUT
#undef HID_REPORT_TYPE_INPUT
class PicoBluetoothHID_;
extern PicoBluetoothHID_ PicoBluetoothHID;
class PicoBluetoothHID_ {
public:
PicoBluetoothHID_() {
}
~PicoBluetoothHID_() {
}
// Optional callback, not used presently
// Usage: PicoBluetoothHID.setCanSendNowCB(std::bind(&kbd::onCanSendNow, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4));
typedef std::function<void(uint8_t type, uint16_t channel, uint8_t *packet, uint16_t size)> BTCallback;
void setOpenedCB(BTCallback cb) {
_onOpened = cb;
}
void setClosedCB(BTCallback cb) {
_onClosed = cb;
}
void setCanSendNowCB(BTCallback cb) {
_onCanSendNow = cb;
}
bool startHID(const char *localName, const char *hidName, uint16_t hidClass, uint8_t hidSubclass, const uint8_t *hidDescriptor, uint16_t hidDescriptorSize) {
if (_running) {
return false;
}
_running = true;
// Allow finding via inquiry
gap_discoverable_control(1);
// Use Limited Discoverable Mode; Peripheral; Keyboard as CoD
gap_set_class_of_device(hidClass);
// Set local name to be identified - zeroes will be replaced by actual BD ADDR
gap_set_local_name(localName);
// Allow for role switch in general and sniff mode
gap_set_default_link_policy_settings(LM_LINK_POLICY_ENABLE_ROLE_SWITCH | LM_LINK_POLICY_ENABLE_SNIFF_MODE);
// Allow for role switch on outgoing connections - this allow HID Host to become master when we re-connect to it
gap_set_allow_role_switch(true);
// L2CAP
l2cap_init();
#ifdef ENABLE_BLE
// Initialize LE Security Manager. Needed for cross-transport key derivation
sm_init();
#endif
// SDP Server
sdp_init();
bzero(_hid_service_buffer, sizeof(_hid_service_buffer));
const uint8_t hid_boot_device = 0;
const uint8_t hid_virtual_cable = 0;
const uint8_t hid_remote_wake = 1;
const uint8_t hid_reconnect_initiate = 1;
const uint8_t hid_normally_connectable = 1;
// When not set to 0xffff, sniff and sniff subrating are enabled
const uint16_t host_max_latency = 1600;
const uint16_t host_min_timeout = 3200;
hid_sdp_record_t hid_params = {
hidClass, hidSubclass,
hid_virtual_cable, hid_remote_wake,
hid_reconnect_initiate, (bool)hid_normally_connectable,
(bool)hid_boot_device,
host_max_latency, host_min_timeout,
3200,
hidDescriptor,
hidDescriptorSize,
hidName
};
hid_create_sdp_record(_hid_service_buffer, 0x10001, &hid_params);
sdp_register_service(_hid_service_buffer);
// See https://www.bluetooth.com/specifications/assigned-numbers/company-identifiers if you don't have a USB Vendor ID and need a Bluetooth Vendor ID
// device info: BlueKitchen GmbH, product 1, version 1
device_id_create_sdp_record(_device_id_sdp_service_buffer, 0x10003, DEVICE_ID_VENDOR_ID_SOURCE_BLUETOOTH, BLUETOOTH_COMPANY_ID_BLUEKITCHEN_GMBH, 1, 1);
sdp_register_service(_device_id_sdp_service_buffer);
// HID Device
hid_device_init(hid_boot_device, hidDescriptorSize, hidDescriptor);
// register for HCI events
_hci_event_callback_registration.callback = PacketHandlerWrapper;
hci_add_event_handler(&_hci_event_callback_registration);
// register for HID events
hid_device_register_packet_handler(PacketHandlerWrapper);
hci_power_control(HCI_POWER_ON);
return true;
}
static void PacketHandlerWrapper(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t packet_size) {
PicoBluetoothHID.packetHandler(packet_type, channel, packet, packet_size);
}
void packetHandler(uint8_t type, uint16_t channel, uint8_t *packet, uint16_t size) {
uint8_t status;
if (type != HCI_EVENT_PACKET) {
return;
}
switch (hci_event_packet_get_type(packet)) {
case BTSTACK_EVENT_STATE:
if (btstack_event_state_get_state(packet) != HCI_STATE_WORKING) {
return;
}
_appState = APP_NOT_CONNECTED;
break;
case HCI_EVENT_USER_CONFIRMATION_REQUEST:
// ssp: inform about user confirmation request
//log_info("SSP User Confirmation Request with numeric value '%06" PRIu32 "'\n", hci_event_user_confirmation_request_get_numeric_value(packet));
//log_info("SSP User Confirmation Auto accept\n");
break;
case HCI_EVENT_HID_META:
switch (hci_event_hid_meta_get_subevent_code(packet)) {
case HID_SUBEVENT_CONNECTION_OPENED:
status = hid_subevent_connection_opened_get_status(packet);
if (status != ERROR_CODE_SUCCESS) {
// outgoing connection failed
_appState = APP_NOT_CONNECTED;
_hid_cid = 0;
return;
}
_appState = APP_CONNECTED;
_hid_cid = hid_subevent_connection_opened_get_hid_cid(packet);
if (_onOpened) {
_onOpened(type, channel, packet, size);
}
break;
case HID_SUBEVENT_CONNECTION_CLOSED:
_appState = APP_NOT_CONNECTED;
_hid_cid = 0;
if (_onClosed) {
_onClosed(type, channel, packet, size);
}
break;
case HID_SUBEVENT_CAN_SEND_NOW:
uint8_t report[2 + _sendReportLen];
report[0] = 0xa1;
report[1] = _sendReportID;
memcpy(report + 2, _sendReport, _sendReportLen);
hid_device_send_interrupt_message(getCID(), report, sizeof(report));
_needToSend = false;
if (_onCanSendNow) {
_onCanSendNow(type, channel, packet, size);
}
break;
}
}
}
bool end() {
if (_running) {
hci_power_control(HCI_POWER_OFF);
}
_running = false;
_needToSend = false;
return true;
}
bool connected() {
return _appState == APP_CONNECTED;
}
bool send(int id, void *rpt, int len) {
_needToSend = true;
_sendReportID = id;
_sendReport = rpt;
_sendReportLen = len;
lockBluetooth();
hid_device_request_can_send_now_event(getCID());
unlockBluetooth();
while (connected() && _needToSend) {
/* noop busy wait */
}
return connected();
}
static void lockBluetooth() {
async_context_acquire_lock_blocking(cyw43_arch_async_context());
}
static void unlockBluetooth() {
async_context_release_lock(cyw43_arch_async_context());
}
uint16_t getCID() {
return _hid_cid;
}
private:
bool _running = false;
enum {APP_BOOTING, APP_NOT_CONNECTED, APP_CONNECTING, APP_CONNECTED} _appState = APP_BOOTING;
BTCallback _onOpened = nullptr;
BTCallback _onClosed = nullptr;
BTCallback _onCanSendNow = nullptr;
uint8_t _hid_service_buffer[300];
uint8_t _device_id_sdp_service_buffer[100];
btstack_packet_callback_registration_t _hci_event_callback_registration;
uint16_t _hid_cid;
volatile bool _needToSend = false;
int _sendReportID;
void *_sendReport;
int _sendReportLen;
};
Submodule libraries/HID_Mouse added at 2aa06d1615
+29
View File
@@ -0,0 +1,29 @@
/**
simple demo to show sha1 calculation
*/
#include <Arduino.h>
#include <Hash.h>
void setup() {
Serial.begin(115200);
}
void loop() {
// usage as String
// SHA1:a9993e364706816aba3e25717850c26c9cd0d89d
Serial.print("SHA1:");
Serial.println(sha1("abc"));
// usage as ptr
// SHA1:a94a8fe5ccb19ba61c4c0873d391e987982fbbd3
uint8_t hash[20];
sha1("test", &hash[0]);
Serial.print("SHA1:");
for (uint16_t i = 0; i < 20; i++) { Serial.printf("%02x", hash[i]); }
Serial.println();
delay(1000);
}
+23
View File
@@ -0,0 +1,23 @@
#######################################
# Syntax Coloring Map For Hash
#######################################
#######################################
# Library (KEYWORD3)
#######################################
Hash KEYWORD3 RESERVED_WORD
#######################################
# Datatypes (KEYWORD1)
#######################################
#######################################
# Methods and Functions (KEYWORD2)
#######################################
sha1 KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################
+10
View File
@@ -0,0 +1,10 @@
name=Hash
version=1.0
author=Markus Sattler
maintainer=Markus Sattler
sentence=Generate Hash from data
paragraph=
category=Data Processing
url=
architectures=rp2040
dot_a_linkage=true
+96
View File
@@ -0,0 +1,96 @@
/**
* @file Hash.cpp
* @date 20.05.2015
* @author Markus Sattler
*
* Copyright (c) 2015 Markus Sattler. All rights reserved.
* This file is part of the esp8266 core for Arduino environment.
*
* 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 <bearssl/bearssl_hash.h>
#include "Hash.h"
/**
* create a sha1 hash from data
* @param data uint8_t *
* @param size uint32_t
* @param hash uint8_t[20]
*/
void sha1(const uint8_t* data, uint32_t size, uint8_t hash[20]) {
br_sha1_context ctx;
#ifdef DEBUG_SHA1
os_printf("DATA:");
for(uint16_t i = 0; i < size; i++) {
os_printf("%02X", data[i]);
}
os_printf("\n");
os_printf("DATA:");
for(uint16_t i = 0; i < size; i++) {
os_printf("%c", data[i]);
}
os_printf("\n");
#endif
br_sha1_init(&ctx);
br_sha1_update(&ctx, data, size);
br_sha1_out(&ctx, hash);
#ifdef DEBUG_SHA1
os_printf("SHA1:");
for(uint16_t i = 0; i < 20; i++) {
os_printf("%02X", hash[i]);
}
os_printf("\n\n");
#endif
}
void sha1(const char* data, uint32_t size, uint8_t hash[20]) {
sha1((const uint8_t *) data, size, hash);
}
void sha1(const String& data, uint8_t hash[20]) {
sha1(data.c_str(), data.length(), hash);
}
String sha1(const uint8_t* data, uint32_t size) {
uint8_t hash[20];
String hashStr((const char*)nullptr);
hashStr.reserve(20 * 2 + 1);
sha1(&data[0], size, &hash[0]);
for(uint16_t i = 0; i < 20; i++) {
char hex[3];
snprintf(hex, sizeof(hex), "%02x", hash[i]);
hashStr += hex;
}
return hashStr;
}
String sha1(const char* data, uint32_t size) {
return sha1((const uint8_t*) data, size);
}
String sha1(const String& data) {
return sha1(data.c_str(), data.length());
}
+38
View File
@@ -0,0 +1,38 @@
/**
* @file Hash.h
* @date 20.05.2015
* @author Markus Sattler
*
* Copyright (c) 2015 Markus Sattler. All rights reserved.
* This file is part of the esp8266 core for Arduino environment.
*
* 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
*
*/
#ifndef HASH_H_
#define HASH_H_
//#define DEBUG_SHA1
void sha1(const uint8_t* data, uint32_t size, uint8_t hash[20]);
void sha1(const char* data, uint32_t size, uint8_t hash[20]);
void sha1(const String& data, uint8_t hash[20]);
String sha1(const uint8_t* data, uint32_t size);
String sha1(const char* data, uint32_t size);
String sha1(const String& data);
#endif /* HASH_H_ */
+21 -2
View File
@@ -10,6 +10,19 @@
+-- ------------------------------------ --+
left RPI | (1) GND (2) DIN (3) BCLK (4) LRCLK (5) 3.3V | AIY right
logo +---------------------------------------------+ logo
For an Adfruit I2S MEMS microphone (https://www.adafruit.com/product/3421),
connect the pins as follows:
DOUT -> GPIO0
BCLK <- GPIO1
LRCL <- GPIO2 # LRCLK = BCLK + 1
GND <-> GND
3V <-> 3V3OUT
The other idiosyncrasy of most modern MEMS microphones is that they
require a minimum clock rate to wake up. For example, the SPH0645
microphone needs at least 1MHz.
*/
#include <I2S.h>
@@ -20,15 +33,21 @@ void setup() {
Serial.begin(115200);
i2s.setDATA(0);
i2s.setBCLK(1); // LRCLK = GP2
i2s.setBCLK(1); // 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);
Serial.printf("%d %d\n", l, r);
// NOTE: Adafruit microphone word size needs to match the BPS above.
// int32_t l, r;
// i2s.read32(&l, &r);
Serial.printf("%d %d\r\n", l, r);
}
}
+1
View File
@@ -19,6 +19,7 @@ setDATA KEYWORD2
setBitsPerSample KEYWORD2
setFrequency KEYWORD2
setBuffers KEYWORD2
setLSBJFormat KEYWORD2
read8 KEYWORD2
read16 KEYWORD2
+37 -21
View File
@@ -51,6 +51,7 @@ I2S::I2S(PinMode direction) {
_buffers = 8;
_bufferWords = 0;
_silenceSample = 0;
_isLSBJ = false;
}
I2S::~I2S() {
@@ -99,6 +100,14 @@ bool I2S::setFrequency(int newFreq) {
return true;
}
bool I2S::setLSBJFormat() {
if (_running || !_isOutput) {
return false;
}
_isLSBJ = true;
return true;
}
void I2S::onTransmit(void(*fn)(void)) {
if (_isOutput) {
_cb = fn;
@@ -121,10 +130,14 @@ bool I2S::begin() {
_running = true;
_hasPeeked = false;
int off = 0;
_i2s = new PIOProgram(_isOutput ? &pio_i2s_out_program : &pio_i2s_in_program);
_i2s = new PIOProgram(_isOutput ? (_isLSBJ ? &pio_lsbj_out_program : &pio_i2s_out_program) : &pio_i2s_in_program);
_i2s->prepare(&_pio, &_sm, &off);
if (_isOutput) {
pio_i2s_out_program_init(_pio, _sm, off, _pinDOUT, _pinBCLK, _bps);
if (_isLSBJ) {
pio_lsbj_out_program_init(_pio, _sm, off, _pinDOUT, _pinBCLK, _bps);
} else {
pio_i2s_out_program_init(_pio, _sm, off, _pinDOUT, _pinBCLK, _bps);
}
} else {
pio_i2s_in_program_init(_pio, _sm, off, _pinDOUT, _pinBCLK, _bps);
}
@@ -148,11 +161,14 @@ bool I2S::begin() {
}
void I2S::end() {
_running = false;
delete _arb;
_arb = nullptr;
delete _i2s;
_i2s = nullptr;
if (_running) {
pio_sm_set_enabled(_pio, _sm, false);
_running = false;
delete _arb;
_arb = nullptr;
delete _i2s;
_i2s = nullptr;
}
}
int I2S::available() {
@@ -175,9 +191,9 @@ int I2S::read() {
return _peekSaved;
}
if (_wasHolding <= 0) {
if (_isHolding <= 0) {
read(&_holdWord, true);
_wasHolding = 32;
_isHolding = 32;
}
int ret;
@@ -185,18 +201,18 @@ int I2S::read() {
case 8:
ret = _holdWord >> 24;
_holdWord <<= 8;
_wasHolding -= 8;
_isHolding -= 8;
return ret;
case 16:
ret = _holdWord >> 16;
_holdWord <<= 16;
_wasHolding -= 32;
_isHolding -= 32;
return ret;
case 24:
case 32:
default:
ret = _holdWord;
_wasHolding = 0;
_isHolding = 0;
return ret;
}
}
@@ -225,26 +241,26 @@ size_t I2S::_writeNatural(int32_t s) {
switch (_bps) {
case 8:
_holdWord |= s & 0xff;
if (_wasHolding >= 24) {
if (_isHolding >= 24) {
auto ret = write(_holdWord, true);
_holdWord = 0;
_wasHolding = 0;
_isHolding = 0;
return ret;
} else {
_holdWord <<= 8;
_wasHolding += 8;
_isHolding += 8;
return 1;
}
case 16:
_holdWord |= s & 0xffff;
if (_wasHolding) {
if (_isHolding) {
auto ret = write(_holdWord, true);
_holdWord = 0;
_wasHolding = 0;
_isHolding = 0;
return ret;
} else {
_holdWord <<= 16;
_wasHolding = 16;
_isHolding = 16;
return 1;
}
case 24:
@@ -301,13 +317,13 @@ bool I2S::read8(int8_t *l, int8_t *r) {
if (!_running || _isOutput) {
return false;
}
if (_wasHolding) {
if (_isHolding) {
*l = (_holdWord >> 8) & 0xff;
*r = (_holdWord >> 0) & 0xff;
_wasHolding = 0;
_isHolding = 0;
} else {
read(&_holdWord, true);
_wasHolding = 16;
_isHolding = 16;
*l = (_holdWord >> 24) & 0xff;
*r = (_holdWord >> 16) & 0xff;
}
+3 -1
View File
@@ -33,6 +33,7 @@ public:
bool setBitsPerSample(int bps);
bool setBuffers(size_t buffers, size_t bufferWords, int32_t silenceSample = 0);
bool setFrequency(int newFreq);
bool setLSBJFormat();
bool begin(long sampleRate) {
setFrequency(sampleRate);
@@ -104,6 +105,7 @@ private:
size_t _buffers;
size_t _bufferWords;
int32_t _silenceSample;
bool _isLSBJ;
bool _isOutput;
bool _running;
@@ -116,7 +118,7 @@ private:
bool _writtenHalf;
int32_t _holdWord = 0;
int _wasHolding = 0;
int _isHolding = 0;
void (*_cb)();
+45 -1
View File
@@ -41,6 +41,29 @@ right:
out pins, 1 side 0b00 ; Last bit of right also has WCLK change
; Loop back to beginning...
.program pio_lsbj_out
.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 0b01
left:
out pins, 1 side 0b10
jmp x--, left side 0b11
out pins, 1 side 0b10
mov x, y side 0b11
right:
out pins, 1 side 0b00
jmp x--, right side 0b01
out pins, 1 side 0b00
; Loop back to beginning...
.program pio_i2s_in ; Note this is the same as _out, just "in" and not "out"
.side_set 2 ; 0 = bclk, 1=wclk
@@ -73,7 +96,28 @@ static inline void pio_i2s_out_program_init(PIO pio, uint sm, uint offset, uint
pio_gpio_init(pio, clock_pin_base + 1);
pio_sm_config sm_config = pio_i2s_out_program_get_default_config(offset);
sm_config_set_out_pins(&sm_config, data_pin, 1);
sm_config_set_sideset_pins(&sm_config, clock_pin_base);
sm_config_set_out_shift(&sm_config, false, true, (bits <= 16) ? 2 * bits : bits);
sm_config_set_fifo_join(&sm_config, PIO_FIFO_JOIN_TX);
pio_sm_init(pio, sm, offset, &sm_config);
uint pin_mask = (1u << data_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_exec(pio, sm, pio_encode_set(pio_y, bits - 2));
}
static inline void pio_lsbj_out_program_init(PIO pio, uint sm, uint offset, uint data_pin, uint clock_pin_base, uint bits) {
pio_gpio_init(pio, data_pin);
pio_gpio_init(pio, clock_pin_base);
pio_gpio_init(pio, clock_pin_base + 1);
pio_sm_config sm_config = pio_lsbj_out_program_get_default_config(offset);
sm_config_set_out_pins(&sm_config, data_pin, 1);
sm_config_set_sideset_pins(&sm_config, clock_pin_base);
sm_config_set_out_shift(&sm_config, false, true, (bits <= 16) ? 2 * bits : bits);
+50 -1
View File
@@ -43,6 +43,41 @@ static inline pio_sm_config pio_i2s_out_program_get_default_config(uint offset)
}
#endif
// ------------ //
// pio_lsbj_out //
// ------------ //
#define pio_lsbj_out_wrap_target 0
#define pio_lsbj_out_wrap 7
static const uint16_t pio_lsbj_out_program_instructions[] = {
// .wrap_target
0xa822, // 0: mov x, y side 1
0x7001, // 1: out pins, 1 side 2
0x1841, // 2: jmp x--, 1 side 3
0x7001, // 3: out pins, 1 side 2
0xb822, // 4: mov x, y side 3
0x6001, // 5: out pins, 1 side 0
0x0845, // 6: jmp x--, 5 side 1
0x6001, // 7: out pins, 1 side 0
// .wrap
};
#if !PICO_NO_HARDWARE
static const struct pio_program pio_lsbj_out_program = {
.instructions = pio_lsbj_out_program_instructions,
.length = 8,
.origin = -1,
};
static inline pio_sm_config pio_lsbj_out_program_get_default_config(uint offset) {
pio_sm_config c = pio_get_default_sm_config();
sm_config_set_wrap(&c, offset + pio_lsbj_out_wrap_target, offset + pio_lsbj_out_wrap);
sm_config_set_sideset(&c, 2, false, false);
return c;
}
#endif
// ---------- //
// pio_i2s_in //
// ---------- //
@@ -92,6 +127,21 @@ static inline void pio_i2s_out_program_init(PIO pio, uint sm, uint offset, uint
pio_sm_set_pins(pio, sm, 0); // clear pins
pio_sm_exec(pio, sm, pio_encode_set(pio_y, bits - 2));
}
static inline void pio_lsbj_out_program_init(PIO pio, uint sm, uint offset, uint data_pin, uint clock_pin_base, uint bits) {
pio_gpio_init(pio, data_pin);
pio_gpio_init(pio, clock_pin_base);
pio_gpio_init(pio, clock_pin_base + 1);
pio_sm_config sm_config = pio_lsbj_out_program_get_default_config(offset);
sm_config_set_out_pins(&sm_config, data_pin, 1);
sm_config_set_sideset_pins(&sm_config, clock_pin_base);
sm_config_set_out_shift(&sm_config, false, true, (bits <= 16) ? 2 * bits : bits);
sm_config_set_fifo_join(&sm_config, PIO_FIFO_JOIN_TX);
pio_sm_init(pio, sm, offset, &sm_config);
uint pin_mask = (1u << data_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_exec(pio, sm, pio_encode_set(pio_y, bits - 2));
}
static inline void pio_i2s_in_program_init(PIO pio, uint sm, uint offset, uint data_pin, uint clock_pin_base, uint bits) {
pio_gpio_init(pio, data_pin);
pio_gpio_init(pio, clock_pin_base);
@@ -109,4 +159,3 @@ static inline void pio_i2s_in_program_init(PIO pio, uint sm, uint offset, uint d
}
#endif
+32
View File
@@ -0,0 +1,32 @@
:repository-owner: arduino-libraries
:repository-name: Joystick
= {repository-name} Library for Arduino (RP2040 based boards) =
This library allows an RaspberryPi RP2040 board to act as a Joystick when
Earle F. Philhower`s [arduino-pico](https://github.com/earlephilhower/arduino-pico)
Core is used.
== Acknowledgements / Credits ==
* [arduino-pico](https://github.com/earlephilhower/arduino-pico) Earle F. Philhower providing the Arduino Core, on which this library is based on, available under LGPL.
* [tinyUSB] (https://github.com/hathach/tinyusb) Ha Thach for providing tinyUSB under MIT license, which covers most of the USB functionality.
== License ==
Copyright (c) Benjamin Aigner <beni@asterics-foundation.org> All right reserved.
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
+435
View File
@@ -0,0 +1,435 @@
# Joystick library
## Methods
### `Joystick.begin()`
Must be called before starting using the Joystick emulation. To end control, use `Joystick.end()`.
#### Syntax
```
Joystick.begin()
```
#### Parameters
None.
#### Returns
None.
#### Example
```
#include <Joystick.h>
void setup() {
pinMode(2, INPUT_PULLUP);
}
void loop() {
// Initialize the Joystick library when button is pressed
if (digitalRead(2) == LOW) {
Joystick.begin();
}
}
```
#### See also
* [Joystick.button()](#joystickbutton)
* [Joystick.end()](#joystickend)
* [Joystick.send_now()](#joysticksend_now)
* [Joystick.position()](#joystickposition)
* [Joystick.X()](#joystickx)
* [Joystick.hat()](#joystickhat)
* [Joystick.use8bit()](#joystickuse8bit)
* [Joystick.useManualSend()](#joystickuseManualSend)
### `Joystick.button()`
Updates a button of the USB joystick.
#### Syntax
```
Joystick.button(1,true);
delay(250);
Joystick.button(1,false);
```
#### Parameters
* `button`: number of Joystick button, which status should be changed
* `val`: state of button, `true` for pressed, `false` for released
#### Returns
None.
#### Example
```
#include <Joystick.h>
void setup() {
pinMode(2, INPUT_PULLUP);
Joystick.begin();
}
void loop() {
uint8_t i = 1; //counter for the button number 1-32
if (digitalRead(2) == LOW) { //if button is pressed
Joystick.button(i,true); //"press" the Joystick button
delay(250); //wait for 0.25s
Joystick.button(i,false); //"release" the Joystick button
i = i + 1; //increment & use next Joystick button number
if(i > 32) i = 1; //we have 32 buttons available, wrap-around
}
}
```
#### Notes
* Up to 32 buttons are available, numbered as button 1 to button 32.
* If manual_send is active, call `Joystick.send_now()` to send an update to the host.
#### See also
* [Joystick.send_now()](#joysticksend_now)
* [Joystick.useManualSend()](#joystickuseManualSend)
* [Joystick.X()](#joystickx)
* [Joystick.hat()](#joystickhat)
### `Joystick.end()`
Stops emulating the Joystick connected to a computer. To start control, use `Joystick.begin()`.
#### Syntax
```
Joystick.end()
```
#### Parameters
None.
#### Returns
None.
#### Example
```
#include <Joystick.h>
void setup() {
pinMode(2, INPUT_PULLUP);
// Initiate the Joystick library
Joystick.begin();
}
void loop() {
// If the button is pressed, send a button 1 press / release
if (digitalRead(2) == LOW) {
Joystick.button(1,true);
delay(250);
Joystick.button(1,false);
// Then end the Joystick emulation
Joystick.end();
}
}
```
#### See also
* [Joystick.begin()](#joystickbegin)
### `Joystick.use8bit()`
Switch axis value range between 10bit and 8bit.
* Default: 10bit, range for an axis from 0 to 1023
* 8bit mode: range from -127 to 127.
__Note:__ due to the gamepad descriptor of tinyUSB, the maximum range is -127/127. 10bit mode enables mapping, not a higher resolution.
#### Syntax
```
Joystick.use8bit(true)
```
#### Parameters
* `mode`: true, if values from -127/127 are used. False to use a range from 0 to 1023.
#### Returns
None.
#### Example
```
#include <Joystick.h>
void setup() {
pinMode(2, INPUT_PULLUP);
Joystick.begin();
}
void loop() {
//send middle position in default 10bit mode
Joystick.position(512,512);
delay(250);
//enable 8bit mode
Joystick.use8bit(true);
//send middle position in 8bit mode
Joystick.position(0,0);
delay(250);
//send maximum left in 10bit mode
Joystick.use8bit(false);
Joystick.position(0,0);
delay(250);
//enable 8bit mode
Joystick.use8bit(true);
//send left position in 8bit mode
Joystick.position(-127,-127);
}
```
#### See also
* [Joystick.position()](#joystickposition)
* [Joystick.X()](#joystickx)
* [Joystick.Y()](#joysticky)
* [Joystick.Z()](#joystickz)
* [Joystick.Zrotate()](#joystickrotate)
* [Joystick.slider()](#joystickslider)
* [Joystick.sliderLeft()](#joysticksliderleft)
* [Joystick.sliderRight()](#joysticksliderright)
### `Joystick.useManualSend()`
To fully control transmitting the USB-HID reports, enable manual sending.
If disabled, each call to a function updating the Joystick status (buttons, all axis, hat)
will send a HID report. If you update in a loop, the time between updates (at least 1ms) is too short and something might be not transmitted correctly.
If enabled, update all your axis values, buttons, hat and then send one report via `Joystick.send_now()`.
#### Syntax
```
Joystick.useManualSend(true)
```
#### Parameters
* `mode`: false is sending report each Joystick update, true enables manual sending via send_now().
#### Returns
None.
#### Example
```
#include <Joystick.h>
void setup() {
pinMode(2, INPUT_PULLUP);
Joystick.begin();
}
void loop() {
if (digitalRead(2) == LOW) {
// send data in 4 different reports
Joystick.button(1,true);
Joystick.button(2,true);
Joystick.button(3,true);
Joystick.button(4,true);
//enable manual send
Joystick.useManualSend(true);
//send same data in one report
Joystick.button(1,false);
Joystick.button(2,false);
Joystick.button(3,false);
Joystick.button(4,false);
Joystick.send_now();
}
}
```
#### See also
* [Joystick.send_now()](#joysticksend_now)
### `Joystick.send_now()`
Send a HID report now. Used together with manual sending, see `Joystick.useManualSend()`.
#### Syntax
```
Joystick.send_now()
```
#### Parameters
None.
#### Returns
None.
#### Example
```
#include <Joystick.h>
void setup() {
pinMode(2, INPUT_PULLUP);
Joystick.begin();
//enable manual sending in setup
Joystick.useManualSend(true);
}
void loop() {
if (digitalRead(2) == LOW) {
// update all buttons, but nothing is sent to the host
for(uint8_t i = 1; i<=32; i++) Joystick.button(i,true);
Joystick.X(256);
Joystick.sliderLeft(0);
//now send in one HID report
Joystick.send_now();
}
}
```
#### See also
* [Joystick.useManualSend()](#joystickusemanualsend)
### `Joystick.X()`
Update X axis.
__Note:__ If [manual send](#joystickusemanualsend) is active, the value is sent to the host only after calling [send_now](#joysticksend_now).
__Note:__ If in 10bit mode (default), the parameter is interpreted from 0 to 1023.
In 8bit mode from -127 to 127. The internal resolution is always 8bit. Change setting with [use8bit](#joystickuse8bit).
#### Syntax
```
Joystick.X(0)
```
#### Parameters
* `val`: value from 0 to 1023 (default) or -127 to 127 (8bit mode)
#### Returns
None.
#### Example
```
#include <Joystick.h>
void setup() {
pinMode(2, INPUT_PULLUP);
Joystick.begin();
}
void loop() {
if (digitalRead(2) == LOW) {
Joystick.X(256);
delay(500);
Joystick.X(512);
}
}
```
#### See also
* [Joystick.Y()](#joysticky)
* [Joystick.Z()](#joystickz)
* [Joystick.Zrotate()](#joystickrotate)
* [Joystick.slider()](#joystickslider)
* [Joystick.sliderLeft()](#joysticksliderleft)
* [Joystick.sliderRight()](#joysticksliderright)
* [Joystick.send_now()](#joysticksend_now)
* [Joystick.position()](#joystickposition)
* [Joystick.hat()](#joystickhat)
* [Joystick.use8bit()](#joystickuse8bit)
* [Joystick.useManualSend()](#joystickuseManualSend)
### `Joystick.Y()`
Update Y axis. Please refer to [Joystick.X()](#joystickx).
### `Joystick.Z()`
Update Z axis. Please refer to [Joystick.X()](#joystickx).
### `Joystick.Zrotate()`
Update Z rotate axis. Please refer to [Joystick.X()](#joystickx).
### `Joystick.sliderLeft()`
Left slider value. Please refer to [Joystick.X()](#joystickx).
### `Joystick.sliderRight()`
Right slider value. Please refer to [Joystick.X()](#joystickx).
### `Joystick.slider()`
Same as [Joystick.sliderLeft()](#joysticksliderleft).
### `Joystick.position()`
Sets X and Y axis in one call. If autosending is active, one report is generated. Please refer to [Joystick.X()](#joystickx).
#### Syntax
```
Joystick.position(512,512)
```
#### Parameters
* `X`: value from 0 to 1023 (default) or -127 to 127 (8bit mode); for X axis
* `Y`: value from 0 to 1023 (default) or -127 to 127 (8bit mode); for Y axis
#### See also
* [Joystick.X()](#joystickx)
* [Joystick.Y()](#joysticky)
### `Joystick.hat()`
Set the hat value to selection angle or rest position.
#### Syntax
```
Joystick.hat(-1), // released/rest position
```
#### Parameters
* `angle` Angle value from 0-360 degrees or -1 for released resting position. Mapped to 8 different directions.
+14
View File
@@ -0,0 +1,14 @@
# Joystick library
The Joystick functions enable a RP2040 board to act as a HID game controller.
To use this library:
```
#include <Joystick.h>
```
## Examples
* [Joystick-AllFunctions] Includes example calls for each Joystick function
@@ -0,0 +1,110 @@
/* Benjamin Aigner, 2022 <beni@asterics-foundation.org> */
/* Public domain / CC 0 */
/** example code using all possibilities of the Joystick class
for the RP2040.
*/
#include <Joystick.h>
void setup() {
Serial.begin(115200);
Serial.println("Use BOOTSEL to start the Joystick demo.");
Joystick.begin();
}
void loop() {
if (BOOTSEL) {
Serial.println("Joystick buttons");
for (uint8_t i = 1; i <= 32; i++) {
Joystick.button(i, true);
delay(250);
Joystick.button(i, false);
delay(10); //we need a short delay here, sending packets with less than 1ms leads to packet loss!
}
//alternativ with manual send:
Joystick.useManualSend(true);
Serial.println("Joystick buttons - manual send");
for (uint8_t i = 1; i <= 32; i++) {
Joystick.button(i, true);
Joystick.send_now();
delay(250);
Joystick.button(i, false);
}
Joystick.useManualSend(false);
//iterate all joystick axis
//Note: although you can use 0-1023 here (10bit), internally 8bits are used (-127 to 127)
Serial.println("Joystick X");
for (uint16_t i = 0; i < 1023; i++) {
Joystick.X(i);
delay(2);
} Joystick.X(512);
Serial.println("Joystick Y");
for (uint16_t i = 0; i < 1023; i++) {
Joystick.Y(i);
delay(2);
} Joystick.Y(512);
Serial.println("Joystick Z");
for (uint16_t i = 0; i < 1023; i++) {
Joystick.Z(i);
delay(2);
} Joystick.Z(512);
Serial.println("Joystick Zrotate");
for (uint16_t i = 0; i < 1023; i++) {
Joystick.Zrotate(i);
delay(2);
} Joystick.Zrotate(512);
Serial.println("Joystick sliderLeft");
for (uint16_t i = 0; i < 1023; i++) {
Joystick.sliderLeft(i);
delay(2);
} Joystick.sliderLeft(0);
Serial.println("Joystick sliderRight");
for (uint16_t i = 0; i < 1023; i++) {
Joystick.sliderRight(i);
delay(2);
} Joystick.sliderRight(0);
Serial.println("Joystick hat");
for (uint16_t i = 0; i < 360; i++) {
Joystick.hat(i);
delay(20);
} Joystick.hat(-1);
//use int8 mode for the axis.
//Note: hat is not used differently.
Serial.println("Now all axis in 8bit mode, -127 to 127");
Joystick.use8bit(true);
Serial.println("Joystick X");
for (int16_t i = -127; i < 128; i++) {
Joystick.X(i);
delay(2);
} Joystick.X(0);
Serial.println("Joystick Y");
for (int16_t i = -127; i < 128; i++) {
Joystick.Y(i);
delay(2);
} Joystick.Y(0);
Serial.println("Joystick Z");
for (int16_t i = -127; i < 128; i++) {
Joystick.Z(i);
delay(2);
} Joystick.Z(0);
Serial.println("Joystick Zrotate");
for (int16_t i = -127; i < 128; i++) {
Joystick.Zrotate(i);
delay(2);
} Joystick.Zrotate(0);
Serial.println("Joystick sliderLeft");
for (int16_t i = -127; i < 128; i++) {
Joystick.sliderLeft(i);
delay(2);
} Joystick.sliderLeft(0);
Serial.println("Joystick sliderRight");
for (int16_t i = -127; i < 128; i++) {
Joystick.sliderRight(i);
delay(2);
} Joystick.sliderRight(0);
Joystick.use8bit(false);
}
}
+33
View File
@@ -0,0 +1,33 @@
#######################################
# Syntax Coloring Map For Joystick
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
Joystick KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
begin KEYWORD2
end KEYWORD2
use8bit KEYWORD2
X KEYWORD2
Y KEYWORD2
button KEYWORD2
position KEYWORD2
Z KEYWORD2
Zrotate KEYWORD2
sliderLeft KEYWORD2
slider KEYWORD2
sliderRight KEYWORD2
hat KEYWORD2
useManualSend KEYWORD2
send_now KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################
+9
View File
@@ -0,0 +1,9 @@
name=Joystick
version=1.0.1
author=Benjamin Aigner
maintainer=Benjamin Aigner <beni@asterics-foundation.org>
sentence=Allows any RP2040 board to act as a joystick/gamepad
paragraph=Allows the RP2040 to emulate a USB Joystick
category=Device Control
url=https://github.com/benjaminaigner/Joystick
architectures=rp2040
+49
View File
@@ -0,0 +1,49 @@
/*
Joystick.cpp
Copyright (c) 2022, Benjamin Aigner <beni@asterics-foundation.org>
Implementation loosely based on:
Mouse library from https://github.com/earlephilhower/arduino-pico
Joystick functions from Teensyduino https://github.com/PaulStoffregen
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 "Joystick.h"
#include "Arduino.h"
#include <RP2040USB.h>
#include "tusb.h"
#include "class/hid/hid_device.h"
// Weak function override to add our descriptor to the TinyUSB list
void __USBInstallJoystick() { /* noop */ }
Joystick_::Joystick_(void) {
// Everything set up in HID_Joystick constructor
}
//immediately send an HID report
void Joystick_::send_now(void) {
CoreMutex m(&__usb_mutex);
tud_task();
if (tud_hid_ready()) {
tud_hid_n_report(0, __USBGetJoystickReportID(), &data, sizeof(data));
}
tud_task();
}
Joystick_ Joystick;
+35
View File
@@ -0,0 +1,35 @@
/*
Joystick.h
Copyright (c) 2022, Benjamin Aigner <beni@asterics-foundation.org>
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
*/
#ifndef _JOYSTICK_h
#define _JOYSTICK_h
#include <HID_Joystick.h>
#include "class/hid/hid.h"
//======================================================================
class Joystick_ : public HID_Joystick {
public:
Joystick_(void);
virtual void send_now(void) override;
};
extern Joystick_ Joystick;
#endif /* _JOYSTICK_h */
+34
View File
@@ -0,0 +1,34 @@
:repository-owner: arduino-libraries
:repository-name: Joystick
= {repository-name} Library for Arduino (RP2040 based boards) =
This library allows an RaspberryPi RP2040 board to act as a Joystick when
Earle F. Philhower`s [arduino-pico](https://github.com/earlephilhower/arduino-pico)
Core is used.
It was forked from the original upstream USB Joystick library by Benjamin Aigner
== Acknowledgements / Credits ==
* [arduino-pico](https://github.com/earlephilhower/arduino-pico) Earle F. Philhower providing the Arduino Core, on which this library is based on, available under LGPL.
* [tinyUSB] (https://github.com/hathach/tinyusb) Ha Thach for providing tinyUSB under MIT license, which covers most of the USB functionality.
== License ==
Copyright (c) Benjamin Aigner <beni@asterics-foundation.org> All right reserved.
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
+435
View File
@@ -0,0 +1,435 @@
# Joystick library
## Methods
### `Joystick.begin()`
Must be called before starting using the Joystick emulation. To end control, use `Joystick.end()`.
#### Syntax
```
Joystick.begin()
```
#### Parameters
None.
#### Returns
None.
#### Example
```
#include <Joystick.h>
void setup() {
pinMode(2, INPUT_PULLUP);
}
void loop() {
// Initialize the Joystick library when button is pressed
if (digitalRead(2) == LOW) {
Joystick.begin();
}
}
```
#### See also
* [Joystick.button()](#joystickbutton)
* [Joystick.end()](#joystickend)
* [Joystick.send_now()](#joysticksend_now)
* [Joystick.position()](#joystickposition)
* [Joystick.X()](#joystickx)
* [Joystick.hat()](#joystickhat)
* [Joystick.use8bit()](#joystickuse8bit)
* [Joystick.useManualSend()](#joystickuseManualSend)
### `Joystick.button()`
Updates a button of the USB joystick.
#### Syntax
```
Joystick.button(1,true);
delay(250);
Joystick.button(1,false);
```
#### Parameters
* `button`: number of Joystick button, which status should be changed
* `val`: state of button, `true` for pressed, `false` for released
#### Returns
None.
#### Example
```
#include <Joystick.h>
void setup() {
pinMode(2, INPUT_PULLUP);
Joystick.begin();
}
void loop() {
uint8_t i = 1; //counter for the button number 1-32
if (digitalRead(2) == LOW) { //if button is pressed
Joystick.button(i,true); //"press" the Joystick button
delay(250); //wait for 0.25s
Joystick.button(i,false); //"release" the Joystick button
i = i + 1; //increment & use next Joystick button number
if(i > 32) i = 1; //we have 32 buttons available, wrap-around
}
}
```
#### Notes
* Up to 32 buttons are available, numbered as button 1 to button 32.
* If manual_send is active, call `Joystick.send_now()` to send an update to the host.
#### See also
* [Joystick.send_now()](#joysticksend_now)
* [Joystick.useManualSend()](#joystickuseManualSend)
* [Joystick.X()](#joystickx)
* [Joystick.hat()](#joystickhat)
### `Joystick.end()`
Stops emulating the Joystick connected to a computer. To start control, use `Joystick.begin()`.
#### Syntax
```
Joystick.end()
```
#### Parameters
None.
#### Returns
None.
#### Example
```
#include <Joystick.h>
void setup() {
pinMode(2, INPUT_PULLUP);
// Initiate the Joystick library
Joystick.begin();
}
void loop() {
// If the button is pressed, send a button 1 press / release
if (digitalRead(2) == LOW) {
Joystick.button(1,true);
delay(250);
Joystick.button(1,false);
// Then end the Joystick emulation
Joystick.end();
}
}
```
#### See also
* [Joystick.begin()](#joystickbegin)
### `Joystick.use8bit()`
Switch axis value range between 10bit and 8bit.
* Default: 10bit, range for an axis from 0 to 1023
* 8bit mode: range from -127 to 127.
__Note:__ due to the gamepad descriptor of tinyUSB, the maximum range is -127/127. 10bit mode enables mapping, not a higher resolution.
#### Syntax
```
Joystick.use8bit(true)
```
#### Parameters
* `mode`: true, if values from -127/127 are used. False to use a range from 0 to 1023.
#### Returns
None.
#### Example
```
#include <Joystick.h>
void setup() {
pinMode(2, INPUT_PULLUP);
Joystick.begin();
}
void loop() {
//send middle position in default 10bit mode
Joystick.position(512,512);
delay(250);
//enable 8bit mode
Joystick.use8bit(true);
//send middle position in 8bit mode
Joystick.position(0,0);
delay(250);
//send maximum left in 10bit mode
Joystick.use8bit(false);
Joystick.position(0,0);
delay(250);
//enable 8bit mode
Joystick.use8bit(true);
//send left position in 8bit mode
Joystick.position(-127,-127);
}
```
#### See also
* [Joystick.position()](#joystickposition)
* [Joystick.X()](#joystickx)
* [Joystick.Y()](#joysticky)
* [Joystick.Z()](#joystickz)
* [Joystick.Zrotate()](#joystickrotate)
* [Joystick.slider()](#joystickslider)
* [Joystick.sliderLeft()](#joysticksliderleft)
* [Joystick.sliderRight()](#joysticksliderright)
### `Joystick.useManualSend()`
To fully control transmitting the USB-HID reports, enable manual sending.
If disabled, each call to a function updating the Joystick status (buttons, all axis, hat)
will send a HID report. If you update in a loop, the time between updates (at least 1ms) is too short and something might be not transmitted correctly.
If enabled, update all your axis values, buttons, hat and then send one report via `Joystick.send_now()`.
#### Syntax
```
Joystick.useManualSend(true)
```
#### Parameters
* `mode`: false is sending report each Joystick update, true enables manual sending via send_now().
#### Returns
None.
#### Example
```
#include <Joystick.h>
void setup() {
pinMode(2, INPUT_PULLUP);
Joystick.begin();
}
void loop() {
if (digitalRead(2) == LOW) {
// send data in 4 different reports
Joystick.button(1,true);
Joystick.button(2,true);
Joystick.button(3,true);
Joystick.button(4,true);
//enable manual send
Joystick.useManualSend(true);
//send same data in one report
Joystick.button(1,false);
Joystick.button(2,false);
Joystick.button(3,false);
Joystick.button(4,false);
Joystick.send_now();
}
}
```
#### See also
* [Joystick.send_now()](#joysticksend_now)
### `Joystick.send_now()`
Send a HID report now. Used together with manual sending, see `Joystick.useManualSend()`.
#### Syntax
```
Joystick.send_now()
```
#### Parameters
None.
#### Returns
None.
#### Example
```
#include <Joystick.h>
void setup() {
pinMode(2, INPUT_PULLUP);
Joystick.begin();
//enable manual sending in setup
Joystick.useManualSend(true);
}
void loop() {
if (digitalRead(2) == LOW) {
// update all buttons, but nothing is sent to the host
for(uint8_t i = 1; i<=32; i++) Joystick.button(i,true);
Joystick.X(256);
Joystick.sliderLeft(0);
//now send in one HID report
Joystick.send_now();
}
}
```
#### See also
* [Joystick.useManualSend()](#joystickusemanualsend)
### `Joystick.X()`
Update X axis.
__Note:__ If [manual send](#joystickusemanualsend) is active, the value is sent to the host only after calling [send_now](#joysticksend_now).
__Note:__ If in 10bit mode (default), the parameter is interpreted from 0 to 1023.
In 8bit mode from -127 to 127. The internal resolution is always 8bit. Change setting with [use8bit](#joystickuse8bit).
#### Syntax
```
Joystick.X(0)
```
#### Parameters
* `val`: value from 0 to 1023 (default) or -127 to 127 (8bit mode)
#### Returns
None.
#### Example
```
#include <Joystick.h>
void setup() {
pinMode(2, INPUT_PULLUP);
Joystick.begin();
}
void loop() {
if (digitalRead(2) == LOW) {
Joystick.X(256);
delay(500);
Joystick.X(512);
}
}
```
#### See also
* [Joystick.Y()](#joysticky)
* [Joystick.Z()](#joystickz)
* [Joystick.Zrotate()](#joystickrotate)
* [Joystick.slider()](#joystickslider)
* [Joystick.sliderLeft()](#joysticksliderleft)
* [Joystick.sliderRight()](#joysticksliderright)
* [Joystick.send_now()](#joysticksend_now)
* [Joystick.position()](#joystickposition)
* [Joystick.hat()](#joystickhat)
* [Joystick.use8bit()](#joystickuse8bit)
* [Joystick.useManualSend()](#joystickuseManualSend)
### `Joystick.Y()`
Update Y axis. Please refer to [Joystick.X()](#joystickx).
### `Joystick.Z()`
Update Z axis. Please refer to [Joystick.X()](#joystickx).
### `Joystick.Zrotate()`
Update Z rotate axis. Please refer to [Joystick.X()](#joystickx).
### `Joystick.sliderLeft()`
Left slider value. Please refer to [Joystick.X()](#joystickx).
### `Joystick.sliderRight()`
Right slider value. Please refer to [Joystick.X()](#joystickx).
### `Joystick.slider()`
Same as [Joystick.sliderLeft()](#joysticksliderleft).
### `Joystick.position()`
Sets X and Y axis in one call. If autosending is active, one report is generated. Please refer to [Joystick.X()](#joystickx).
#### Syntax
```
Joystick.position(512,512)
```
#### Parameters
* `X`: value from 0 to 1023 (default) or -127 to 127 (8bit mode); for X axis
* `Y`: value from 0 to 1023 (default) or -127 to 127 (8bit mode); for Y axis
#### See also
* [Joystick.X()](#joystickx)
* [Joystick.Y()](#joysticky)
### `Joystick.hat()`
Set the hat value to selection angle or rest position.
#### Syntax
```
Joystick.hat(-1), // released/rest position
```
#### Parameters
* `angle` Angle value from 0-360 degrees or -1 for released resting position. Mapped to 8 different directions.
+14
View File
@@ -0,0 +1,14 @@
# Joystick library
The Joystick functions enable a RP2040 board to act as a HID game controller.
To use this library:
```
#include <Joystick.h>
```
## Examples
* [Joystick-AllFunctions] Includes example calls for each Joystick function
@@ -0,0 +1,110 @@
/* Benjamin Aigner, 2022 <beni@asterics-foundation.org> */
/* Public domain / CC 0 */
/** example code using all possibilities of the Joystick class
for the RP2040.
*/
#include <JoystickBLE.h>
void setup() {
Serial.begin(115200);
Serial.println("Use BOOTSEL to start the Joystick demo.");
JoystickBLE.begin();
}
void loop() {
if (BOOTSEL) {
Serial.println("Joystick buttons");
for (uint8_t i = 1; i <= 32; i++) {
JoystickBLE.button(i, true);
delay(250);
JoystickBLE.button(i, false);
delay(10); //we need a short delay here, sending packets with less than 1ms leads to packet loss!
}
//alternativ with manual send:
JoystickBLE.useManualSend(true);
Serial.println("Joystick buttons - manual send");
for (uint8_t i = 1; i <= 32; i++) {
JoystickBLE.button(i, true);
JoystickBLE.send_now();
delay(250);
JoystickBLE.button(i, false);
}
JoystickBLE.useManualSend(false);
//iterate all joystick axis
//Note: although you can use 0-1023 here (10bit), internally 8bits are used (-127 to 127)
Serial.println("Joystick X");
for (uint16_t i = 0; i < 1023; i++) {
JoystickBLE.X(i);
delay(2);
} JoystickBLE.X(512);
Serial.println("Joystick Y");
for (uint16_t i = 0; i < 1023; i++) {
JoystickBLE.Y(i);
delay(2);
} JoystickBLE.Y(512);
Serial.println("Joystick Z");
for (uint16_t i = 0; i < 1023; i++) {
JoystickBLE.Z(i);
delay(2);
} JoystickBLE.Z(512);
Serial.println("Joystick Zrotate");
for (uint16_t i = 0; i < 1023; i++) {
JoystickBLE.Zrotate(i);
delay(2);
} JoystickBLE.Zrotate(512);
Serial.println("Joystick sliderLeft");
for (uint16_t i = 0; i < 1023; i++) {
JoystickBLE.sliderLeft(i);
delay(2);
} JoystickBLE.sliderLeft(0);
Serial.println("Joystick sliderRight");
for (uint16_t i = 0; i < 1023; i++) {
JoystickBLE.sliderRight(i);
delay(2);
} JoystickBLE.sliderRight(0);
Serial.println("Joystick hat");
for (uint16_t i = 0; i < 360; i++) {
JoystickBLE.hat(i);
delay(20);
} JoystickBLE.hat(-1);
//use int8 mode for the axis.
//Note: hat is not used differently.
Serial.println("Now all axis in 8bit mode, -127 to 127");
JoystickBLE.use8bit(true);
Serial.println("Joystick X");
for (int16_t i = -127; i < 128; i++) {
JoystickBLE.X(i);
delay(2);
} JoystickBLE.X(0);
Serial.println("Joystick Y");
for (int16_t i = -127; i < 128; i++) {
JoystickBLE.Y(i);
delay(2);
} JoystickBLE.Y(0);
Serial.println("Joystick Z");
for (int16_t i = -127; i < 128; i++) {
JoystickBLE.Z(i);
delay(2);
} JoystickBLE.Z(0);
Serial.println("Joystick Zrotate");
for (int16_t i = -127; i < 128; i++) {
JoystickBLE.Zrotate(i);
delay(2);
} JoystickBLE.Zrotate(0);
Serial.println("Joystick sliderLeft");
for (int16_t i = -127; i < 128; i++) {
JoystickBLE.sliderLeft(i);
delay(2);
} JoystickBLE.sliderLeft(0);
Serial.println("Joystick sliderRight");
for (int16_t i = -127; i < 128; i++) {
JoystickBLE.sliderRight(i);
delay(2);
} JoystickBLE.sliderRight(0);
JoystickBLE.use8bit(false);
}
}
+34
View File
@@ -0,0 +1,34 @@
#######################################
# Syntax Coloring Map
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
JoystickBLE KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
begin KEYWORD2
end KEYWORD2
use8bit KEYWORD2
X KEYWORD2
Y KEYWORD2
button KEYWORD2
position KEYWORD2
Z KEYWORD2
Zrotate KEYWORD2
sliderLeft KEYWORD2
slider KEYWORD2
sliderRight KEYWORD2
hat KEYWORD2
useManualSend KEYWORD2
send_now KEYWORD2
setBattery KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################
+9
View File
@@ -0,0 +1,9 @@
name=JoystickBLE
version=1.0.1
author=Benjamin Aigner
maintainer=Earle F. Philhower, III <earlephilhower@yahoo.com>
sentence=Allows any PicoW board to act as a BLE joystick/gamepad
paragraph=Allows any PicoW board to act as a BLE joystick/gamepad
category=Device Control
url=https://github.com/earlephilhower/arduino-pico
architectures=rp2040
+63
View File
@@ -0,0 +1,63 @@
/*
JoystickBLE.cpp
Copyright (c) 2022, Benjamin Aigner <beni@asterics-foundation.org>
Modified for BLE 2023 by Earle F. Philhower, III <earlephilhower@yahoo.com>
Implementation loosely based on:
Mouse library from https://github.com/earlephilhower/arduino-pico
Joystick functions from Teensyduino https://github.com/PaulStoffregen
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 "JoystickBLE.h"
#include <Arduino.h>
#include <PicoBluetoothBLEHID.h>
//================================================================================
//================================================================================
// Joystick/Gamepad
JoystickBLE_::JoystickBLE_(void) {
// Member vars set in base constructor
}
#define REPORT_ID 0x01
static const uint8_t desc_joystick[] = {TUD_HID_REPORT_DESC_GAMEPAD(HID_REPORT_ID(REPORT_ID))};
void JoystickBLE_::begin(const char *localName, const char *hidName) {
if (!localName) {
localName = "PicoW BLE Joystick";
}
if (!hidName) {
hidName = localName;
}
PicoBluetoothBLEHID.startHID(localName, hidName, 0x03c4, desc_joystick, sizeof(desc_joystick));
}
void JoystickBLE_::end() {
PicoBluetoothBLEHID.end();
}
void JoystickBLE_::setBattery(int lvl) {
PicoBluetoothBLEHID.setBattery(lvl);
}
void JoystickBLE_::send_now() {
PicoBluetoothBLEHID.send(&data, sizeof(data));
}
JoystickBLE_ JoystickBLE;
+36
View File
@@ -0,0 +1,36 @@
/*
JoystickBLE.h
Copyright (c) 2022, Benjamin Aigner <beni@asterics-foundation.org>
Modified for BT 2023 by 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 <HID_Joystick.h>
#include "class/hid/hid.h"
//======================================================================
class JoystickBLE_ : public HID_Joystick {
public:
JoystickBLE_();
void begin(const char *localName = nullptr, const char *hidName = nullptr);
void end();
virtual void send_now() override;
void setBattery(int lvl);
};
extern JoystickBLE_ JoystickBLE;
+34
View File
@@ -0,0 +1,34 @@
:repository-owner: arduino-libraries
:repository-name: Joystick
= {repository-name} Library for Arduino (RP2040 based boards) =
This library allows an RaspberryPi RP2040 board to act as a Joystick when
Earle F. Philhower`s [arduino-pico](https://github.com/earlephilhower/arduino-pico)
Core is used.
It was forked from the original upstream USB Joystick library by Benjamin Aigner
== Acknowledgements / Credits ==
* [arduino-pico](https://github.com/earlephilhower/arduino-pico) Earle F. Philhower providing the Arduino Core, on which this library is based on, available under LGPL.
* [tinyUSB] (https://github.com/hathach/tinyusb) Ha Thach for providing tinyUSB under MIT license, which covers most of the USB functionality.
== License ==
Copyright (c) Benjamin Aigner <beni@asterics-foundation.org> All right reserved.
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
+435
View File
@@ -0,0 +1,435 @@
# Joystick library
## Methods
### `Joystick.begin()`
Must be called before starting using the Joystick emulation. To end control, use `Joystick.end()`.
#### Syntax
```
Joystick.begin()
```
#### Parameters
None.
#### Returns
None.
#### Example
```
#include <Joystick.h>
void setup() {
pinMode(2, INPUT_PULLUP);
}
void loop() {
// Initialize the Joystick library when button is pressed
if (digitalRead(2) == LOW) {
Joystick.begin();
}
}
```
#### See also
* [Joystick.button()](#joystickbutton)
* [Joystick.end()](#joystickend)
* [Joystick.send_now()](#joysticksend_now)
* [Joystick.position()](#joystickposition)
* [Joystick.X()](#joystickx)
* [Joystick.hat()](#joystickhat)
* [Joystick.use8bit()](#joystickuse8bit)
* [Joystick.useManualSend()](#joystickuseManualSend)
### `Joystick.button()`
Updates a button of the USB joystick.
#### Syntax
```
Joystick.button(1,true);
delay(250);
Joystick.button(1,false);
```
#### Parameters
* `button`: number of Joystick button, which status should be changed
* `val`: state of button, `true` for pressed, `false` for released
#### Returns
None.
#### Example
```
#include <Joystick.h>
void setup() {
pinMode(2, INPUT_PULLUP);
Joystick.begin();
}
void loop() {
uint8_t i = 1; //counter for the button number 1-32
if (digitalRead(2) == LOW) { //if button is pressed
Joystick.button(i,true); //"press" the Joystick button
delay(250); //wait for 0.25s
Joystick.button(i,false); //"release" the Joystick button
i = i + 1; //increment & use next Joystick button number
if(i > 32) i = 1; //we have 32 buttons available, wrap-around
}
}
```
#### Notes
* Up to 32 buttons are available, numbered as button 1 to button 32.
* If manual_send is active, call `Joystick.send_now()` to send an update to the host.
#### See also
* [Joystick.send_now()](#joysticksend_now)
* [Joystick.useManualSend()](#joystickuseManualSend)
* [Joystick.X()](#joystickx)
* [Joystick.hat()](#joystickhat)
### `Joystick.end()`
Stops emulating the Joystick connected to a computer. To start control, use `Joystick.begin()`.
#### Syntax
```
Joystick.end()
```
#### Parameters
None.
#### Returns
None.
#### Example
```
#include <Joystick.h>
void setup() {
pinMode(2, INPUT_PULLUP);
// Initiate the Joystick library
Joystick.begin();
}
void loop() {
// If the button is pressed, send a button 1 press / release
if (digitalRead(2) == LOW) {
Joystick.button(1,true);
delay(250);
Joystick.button(1,false);
// Then end the Joystick emulation
Joystick.end();
}
}
```
#### See also
* [Joystick.begin()](#joystickbegin)
### `Joystick.use8bit()`
Switch axis value range between 10bit and 8bit.
* Default: 10bit, range for an axis from 0 to 1023
* 8bit mode: range from -127 to 127.
__Note:__ due to the gamepad descriptor of tinyUSB, the maximum range is -127/127. 10bit mode enables mapping, not a higher resolution.
#### Syntax
```
Joystick.use8bit(true)
```
#### Parameters
* `mode`: true, if values from -127/127 are used. False to use a range from 0 to 1023.
#### Returns
None.
#### Example
```
#include <Joystick.h>
void setup() {
pinMode(2, INPUT_PULLUP);
Joystick.begin();
}
void loop() {
//send middle position in default 10bit mode
Joystick.position(512,512);
delay(250);
//enable 8bit mode
Joystick.use8bit(true);
//send middle position in 8bit mode
Joystick.position(0,0);
delay(250);
//send maximum left in 10bit mode
Joystick.use8bit(false);
Joystick.position(0,0);
delay(250);
//enable 8bit mode
Joystick.use8bit(true);
//send left position in 8bit mode
Joystick.position(-127,-127);
}
```
#### See also
* [Joystick.position()](#joystickposition)
* [Joystick.X()](#joystickx)
* [Joystick.Y()](#joysticky)
* [Joystick.Z()](#joystickz)
* [Joystick.Zrotate()](#joystickrotate)
* [Joystick.slider()](#joystickslider)
* [Joystick.sliderLeft()](#joysticksliderleft)
* [Joystick.sliderRight()](#joysticksliderright)
### `Joystick.useManualSend()`
To fully control transmitting the USB-HID reports, enable manual sending.
If disabled, each call to a function updating the Joystick status (buttons, all axis, hat)
will send a HID report. If you update in a loop, the time between updates (at least 1ms) is too short and something might be not transmitted correctly.
If enabled, update all your axis values, buttons, hat and then send one report via `Joystick.send_now()`.
#### Syntax
```
Joystick.useManualSend(true)
```
#### Parameters
* `mode`: false is sending report each Joystick update, true enables manual sending via send_now().
#### Returns
None.
#### Example
```
#include <Joystick.h>
void setup() {
pinMode(2, INPUT_PULLUP);
Joystick.begin();
}
void loop() {
if (digitalRead(2) == LOW) {
// send data in 4 different reports
Joystick.button(1,true);
Joystick.button(2,true);
Joystick.button(3,true);
Joystick.button(4,true);
//enable manual send
Joystick.useManualSend(true);
//send same data in one report
Joystick.button(1,false);
Joystick.button(2,false);
Joystick.button(3,false);
Joystick.button(4,false);
Joystick.send_now();
}
}
```
#### See also
* [Joystick.send_now()](#joysticksend_now)
### `Joystick.send_now()`
Send a HID report now. Used together with manual sending, see `Joystick.useManualSend()`.
#### Syntax
```
Joystick.send_now()
```
#### Parameters
None.
#### Returns
None.
#### Example
```
#include <Joystick.h>
void setup() {
pinMode(2, INPUT_PULLUP);
Joystick.begin();
//enable manual sending in setup
Joystick.useManualSend(true);
}
void loop() {
if (digitalRead(2) == LOW) {
// update all buttons, but nothing is sent to the host
for(uint8_t i = 1; i<=32; i++) Joystick.button(i,true);
Joystick.X(256);
Joystick.sliderLeft(0);
//now send in one HID report
Joystick.send_now();
}
}
```
#### See also
* [Joystick.useManualSend()](#joystickusemanualsend)
### `Joystick.X()`
Update X axis.
__Note:__ If [manual send](#joystickusemanualsend) is active, the value is sent to the host only after calling [send_now](#joysticksend_now).
__Note:__ If in 10bit mode (default), the parameter is interpreted from 0 to 1023.
In 8bit mode from -127 to 127. The internal resolution is always 8bit. Change setting with [use8bit](#joystickuse8bit).
#### Syntax
```
Joystick.X(0)
```
#### Parameters
* `val`: value from 0 to 1023 (default) or -127 to 127 (8bit mode)
#### Returns
None.
#### Example
```
#include <Joystick.h>
void setup() {
pinMode(2, INPUT_PULLUP);
Joystick.begin();
}
void loop() {
if (digitalRead(2) == LOW) {
Joystick.X(256);
delay(500);
Joystick.X(512);
}
}
```
#### See also
* [Joystick.Y()](#joysticky)
* [Joystick.Z()](#joystickz)
* [Joystick.Zrotate()](#joystickrotate)
* [Joystick.slider()](#joystickslider)
* [Joystick.sliderLeft()](#joysticksliderleft)
* [Joystick.sliderRight()](#joysticksliderright)
* [Joystick.send_now()](#joysticksend_now)
* [Joystick.position()](#joystickposition)
* [Joystick.hat()](#joystickhat)
* [Joystick.use8bit()](#joystickuse8bit)
* [Joystick.useManualSend()](#joystickuseManualSend)
### `Joystick.Y()`
Update Y axis. Please refer to [Joystick.X()](#joystickx).
### `Joystick.Z()`
Update Z axis. Please refer to [Joystick.X()](#joystickx).
### `Joystick.Zrotate()`
Update Z rotate axis. Please refer to [Joystick.X()](#joystickx).
### `Joystick.sliderLeft()`
Left slider value. Please refer to [Joystick.X()](#joystickx).
### `Joystick.sliderRight()`
Right slider value. Please refer to [Joystick.X()](#joystickx).
### `Joystick.slider()`
Same as [Joystick.sliderLeft()](#joysticksliderleft).
### `Joystick.position()`
Sets X and Y axis in one call. If autosending is active, one report is generated. Please refer to [Joystick.X()](#joystickx).
#### Syntax
```
Joystick.position(512,512)
```
#### Parameters
* `X`: value from 0 to 1023 (default) or -127 to 127 (8bit mode); for X axis
* `Y`: value from 0 to 1023 (default) or -127 to 127 (8bit mode); for Y axis
#### See also
* [Joystick.X()](#joystickx)
* [Joystick.Y()](#joysticky)
### `Joystick.hat()`
Set the hat value to selection angle or rest position.
#### Syntax
```
Joystick.hat(-1), // released/rest position
```
#### Parameters
* `angle` Angle value from 0-360 degrees or -1 for released resting position. Mapped to 8 different directions.
+14
View File
@@ -0,0 +1,14 @@
# Joystick library
The Joystick functions enable a RP2040 board to act as a HID game controller.
To use this library:
```
#include <Joystick.h>
```
## Examples
* [Joystick-AllFunctions] Includes example calls for each Joystick function

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