Compare commits

...

213 Commits

Author SHA1 Message Date
3b7fec6efc wip 2023-10-03 17:59:49 -05:00
731df8be49 wip 2023-10-03 17:58:44 -05:00
2849bfcc6b wip 2023-10-03 17:57:12 -05:00
a4b20fc943 wip 2023-10-03 17:49:18 -05:00
8bb48f3083 wip 2023-10-03 17:47:41 -05:00
d7ce823d79 wpan: fix ipcc delay 2023-10-03 17:47:29 -05:00
e7ab044935 ci: remove wpan tests again 2023-10-03 16:59:18 -05:00
0c4cddfafb Merge branch 'main' of github.com:embassy-rs/embassy into opamp 2023-10-03 16:44:44 -05:00
e561e673c2 stm32: add opamp mod and update pac 2023-10-03 16:34:13 -05:00
09dfcd6b66 Merge pull request #2008 from xoviat/wpan
wpan: re-enable HIL tests
2023-10-03 21:02:48 +00:00
bb8a1b7f1f wpan: re-enable HIL tests 2023-10-03 15:53:22 -05:00
b012a67df7 Merge pull request #2007 from embassy-rs/unverbose
Remove a few ultra-verbose logs.
2023-10-03 20:28:44 +00:00
40f30fa4cd Remove a few ultra-verbose logs.
They're heavily spamming logs for HIL tests, and I don't believe
they're valuable now that the thing they helped debug in their young
age is now solid and mature.
2023-10-03 22:22:16 +02:00
f197aa9419 Merge pull request #2005 from embassy-rs/minor-doc-improvs
docs: minor doc improvements and cleanup
2023-10-03 19:37:39 +00:00
80a740bc72 docs: minor doc improvements and cleanup 2023-10-03 21:35:31 +02:00
ad524373ed Merge pull request #1926 from m5p3nc3r/async_dtr
Add a signal for when the CDC control state changes
2023-10-03 02:13:12 +00:00
9badf740d8 Merge pull request #2001 from embassy-rs/stm32-more-hil
stm32/hil: add f2, f3, f7, l49
2023-10-03 02:07:00 +00:00
6e901846df Merge pull request #1995 from JuliDi/quadspi
[STM32] QUADSPI support bank 2
2023-10-03 01:55:27 +00:00
c0a6c78a14 stm32/hil: add f2, f3, f7, l49 2023-10-03 02:11:58 +02:00
58280048e3 Merge pull request #2002 from embassy-rs/fix-stop
stm32: fix stop
2023-10-02 23:56:33 +00:00
00824af82b ci: remove wpan tests 2023-10-02 18:55:31 -05:00
adf9ffb109 tests/stm32: use default clock config 2023-10-02 18:51:59 -05:00
bc203ebe4b Merge branch 'main' of github.com:embassy-rs/embassy into fix-stop 2023-10-02 18:30:41 -05:00
e042b3056d stm32: fix stop 2023-10-02 18:11:03 -05:00
9dc927250c Merge pull request #1959 from embassy-rs/test-eth
stm32: add eth tests
2023-10-02 20:41:31 +00:00
b856d760f4 stm32/rcc: reset backup domain before enabling LSE. 2023-10-02 22:12:50 +02:00
a742a80171 Merge pull request #1999 from KingCol13/rp-wifi-examples-fixes
cyw43: Update examples
2023-10-02 20:07:45 +00:00
90ade1b311 Add wait for DHCP in rp wifi_tcp_server 2023-10-02 20:10:52 +01:00
a931dfd9ad Update firmware size in rp wifi examples 2023-10-02 20:10:45 +01:00
eff61648fe tests/stm32: add eth test. 2023-10-02 20:40:11 +02:00
9228a6334b Merge pull request #1996 from embassy-rs/update-nightly
Update Nightly.
2023-10-02 17:29:21 +00:00
3c9dfbbc9d enable wifi_esp_hosted_perf test, disable stm32f4 stop test. 2023-10-02 19:05:41 +02:00
ce0add61f8 Merge pull request #1997 from dzamlo/main
stm32: avoid useless endian conversion in rng
2023-10-02 15:31:13 +00:00
bf6e06060b stm32: avoid useless endian conversion in rng 2023-10-02 17:20:58 +02:00
eb12114345 Remove impl_trait_projections. 2023-10-02 14:00:49 +02:00
4b252586e5 Update Nightly. 2023-10-02 13:51:13 +02:00
5f6a915a32 Merge pull request #1994 from jcdickinson/pin_params
feat (rp2040): allow schmitt, slew, and drive strength be set from Flex, Input, Output
2023-10-02 10:44:19 +00:00
923f1851ee remove debug logging in build.rs 2023-10-02 09:36:11 +02:00
bd267a6479 move stm32h7 specific import 2023-10-02 09:34:59 +02:00
f3aa0cfe5a remove debug code, add some comments 2023-10-02 09:33:10 +02:00
6ea5aa347d feature-gate errata workaround for h7 2023-10-02 09:30:58 +02:00
8c13126cff make push/pull settings for pins explicit 2023-10-02 09:30:58 +02:00
81da9ca621 Bump stm32-metapac, add flash selection 2023-10-02 09:30:58 +02:00
729338875c support QSPI BK2 2023-10-02 09:30:57 +02:00
f98c8886b2 feat: allow schmitt, slew, and drive strength be set from Flex, Input, Output
Allows the schmitt, slew and drive strength to be set from Flex. Input and Output[OpenDrain] also expose the appropriate setters.
2023-10-01 21:49:14 -04:00
a1036e111e Merge pull request #1990 from embassy-rs/stm32f4-rcc-fix
stm32f4: fix rcc build on stm32f446
2023-10-01 21:16:09 +00:00
2af97e7595 rcc/f4: fix build on stm32f446
fixes #1989
2023-10-01 23:01:58 +02:00
2008030a8b ci: add all stm32f4 2023-10-01 23:01:35 +02:00
480328d07e Merge pull request #1984 from xoviat/set-config
stm32: require use of setconfig to set config
2023-10-01 14:41:52 +00:00
05218a52e6 stm32: update set_config 2023-10-01 09:39:10 -05:00
d2a2734752 nrf, rp: update set_config 2023-10-01 09:37:42 -05:00
5ad34404af eh: update set_config and add get_config 2023-10-01 09:37:20 -05:00
a7b1e51650 Merge pull request #1987 from tyler-gilbert/issue-1986-add-sai-receiver-driver
Issue 1986 add sai receiver driver
2023-10-01 14:06:25 +00:00
70005c3956 Merge pull request #1988 from JuliDi/expose-analog-switch-pins-rebased
[STM32] Handle STM32H7 "_C" pins (rebased)
2023-10-01 12:36:21 +00:00
93adbb9922 update stm32-metapac 2023-10-01 12:41:08 +02:00
e80df91e02 update stm32-metapac revision 2023-10-01 12:34:26 +02:00
5cb58754d4 skip _C pins for pin impls if split_feature not enabled. 2023-10-01 12:32:47 +02:00
5c83179071 change split_features from array to Vec 2023-10-01 12:32:47 +02:00
49608714aa cleanup, fix pushing to pins_table 2023-10-01 12:32:47 +02:00
f116ca83e0 check whether split-feature is valid 2023-10-01 12:32:47 +02:00
6e5f3f9515 update to testing pr #1889 2023-10-01 12:32:46 +02:00
5924cc8b49 handle _C pins 2023-10-01 12:30:34 +02:00
0d49aaf8ca Issue #1986 fix ci build errors 2023-09-30 22:51:23 -05:00
5dd9e9b3b7 issue #1986 separate blocks to prevent unsafe user code 2023-09-30 22:48:49 -05:00
d42cfda2db Issue #1986 add PartialEq to SyncEnable to fix build error on sai_v4 2023-09-30 19:51:00 -05:00
d1f4511cd1 Issue #1986 update the SAI driver with receiver capability 2023-09-30 19:43:44 -05:00
fa8d5da4a5 Merge pull request #5 from embassy-rs/main
Merge latest including SAI driver
2023-09-30 16:06:11 -06:00
7bc57ca3f7 Merge pull request #1975 from tyler-gilbert/issue-1974-add-sai-driver
Issue 1974 add sai driver
2023-09-30 20:04:26 +00:00
7ad102695d Merge pull request #1981 from xoviat/fix-traits
Fix traits
2023-09-30 17:57:22 +00:00
4999de6f82 rustfmt 2023-09-30 12:53:17 -05:00
9b8bdad403 Fix clippy error exposed by moving out of macros 2023-09-30 13:07:11 -04:00
3c3fb0a529 Remove unused imports 2023-09-30 12:20:31 -04:00
dc4c27aead Move one more method out of macros 2023-09-30 12:16:47 -04:00
74eb519810 Move trait impls out of macros 2023-09-30 12:14:20 -04:00
61dc36b1f2 Fix small formatting issue 2023-09-30 11:36:32 -04:00
55a0a15be2 Fix trait inconsistency between sealed traits and implementations 2023-09-30 11:19:09 -04:00
fc8f96fea5 Merge pull request #1976 from elasticdotventures/feature/examples
fix typo / update wasm example
2023-09-30 10:55:08 +00:00
08175f191a bump wasm-pack version 2023-09-30 05:42:59 +00:00
8da987cfbb typo 2023-09-30 05:34:22 +00:00
1be5f193c3 #Issue 1974 more whitespace fixes 2023-09-29 21:53:01 -05:00
4a632e08b7 #Issue 1974 fix extra whitespace 2023-09-29 21:46:19 -05:00
6cdee93934 #Issue 1974 fix more warnings treated as errors 2023-09-29 21:27:15 -05:00
5c8c1b2146 #Issue 1974 fix warnings 2023-09-29 21:16:20 -05:00
2addfc4b86 Merge branch 'issue-1974-add-sai-driver' of https://github.com/tyler-gilbert/embassy into issue-1974-add-sai-driver 2023-09-29 21:08:21 -05:00
92df87781d Issue 1974 add sai/mod file 2023-09-29 21:08:07 -05:00
a35d149cb1 Revert metapac change in Cargo.toml 2023-09-29 21:07:09 -05:00
c52320f467 Merge pull request #4 from embassy-rs/main
Pull latest from embassy main
2023-09-29 20:03:31 -06:00
2f9b59c5cf Merge branch 'main' into issue-1974-add-sai-driver 2023-09-29 20:02:24 -06:00
ce91fb2bfc Issue #1974 add SAI driver 2023-09-29 20:57:59 -05:00
95b3d9eb3b Merge pull request #1972 from embassy-rs/rtc-lse-fix
stm32/rtc: enable lse in examples.
2023-09-29 22:23:42 +00:00
f1e7205055 stm32/rtc: enable lse in examples. 2023-09-30 00:18:30 +02:00
6627824c02 Merge pull request #1970 from dberlin/revert-1969-main
Revert "Forgot set_count_direction and set_clock_division in 32 bit instance"
2023-09-29 17:32:37 +00:00
d62533879c Merge pull request #1971 from oro-os/enc28j60-mac-addr
enc28j60: expose a the MAC address via `address()` getter
2023-09-29 15:49:07 +00:00
e1a8caffa4 enc28j60: expose a the MAC address via address() getter 2023-09-29 17:23:39 +02:00
dffdb9268b Revert "Forgot set_count_direction and set_clock_division in 32 bit instance" 2023-09-28 21:56:18 -04:00
22e820b743 Merge pull request #1969 from dberlin/main
Forgot set_count_direction and set_clock_division in 32 bit instance
2023-09-29 00:38:45 +00:00
aa14f18d3f Merge pull request #1968 from xoviat/sbs
update metapac and rename sbs
2023-09-29 00:25:55 +00:00
39f1b26a39 stm32: update metapac and remove sbs 2023-09-28 19:21:02 -05:00
e70143ef8f Forgot set_count_direction and set_clock_division in 32 bit instance 2023-09-28 20:01:04 -04:00
d6654bf8b5 Merge pull request #1966 from xoviat/hrtim
stm32/hrtim: move traits out of macro def'n
2023-09-28 20:53:55 +00:00
322a4a8401 stm32/hrtim: move traits out of macro def'n 2023-09-28 15:48:46 -05:00
ee5591017b Merge pull request #1964 from dberlin/main
Add support for STM32 input capture filter
2023-09-28 20:37:48 +00:00
b1b32f079b Merge pull request #1962 from bugadani/esp32s2
Add 80MHz tick rate
2023-09-28 17:07:26 +00:00
e8a462768e Add more tick rates 2023-09-28 19:06:38 +02:00
ce0d787781 Merge pull request #1965 from oro-os/return-len-receive-enc28j60
enc28j60: return packet length from receive() instead of mut slice
2023-09-28 16:32:22 +00:00
fa2e63f74b enc28j60: return packet length from receive() instead of mut slice 2023-09-28 18:28:46 +02:00
23f3889167 Add support for STM32 input capture filter 2023-09-28 09:35:43 -04:00
a72a91ab06 Merge pull request #1963 from Mirror0/restore-f7-rtc
Restore RTC configuration for `STM32F7` boards
2023-09-28 11:32:50 +00:00
b9ef831ff7 Add 80MHz tick rate 2023-09-28 09:41:35 +02:00
e538aeacc8 Merge pull request #1960 from embassy-rs/test-eth-2
Net fixes
2023-09-28 03:39:10 +00:00
6b3745fc47 temporarily disable wifi_esp_hosted_perf test. 2023-09-28 05:34:19 +02:00
6200d22438 stm32/eth: fix receiving large frames on v2. 2023-09-28 05:12:35 +02:00
901d31e8f8 Merge pull request #1933 from xoviat/adc
stm32: more adc cleanup
2023-09-28 01:59:51 +00:00
79146c4bd5 stm32/adc: cleanup f1, f3, v1, and v2 2023-09-27 20:58:46 -05:00
d9eae79f3e test: deduplicate net perf test code. 2023-09-28 03:47:14 +02:00
3d1b4116ec test: set DEFMT_LOG not too verbose so net perf tests pass with cargo run. 2023-09-28 03:47:14 +02:00
901f0257bd net: allow non-'static drivers. 2023-09-28 03:47:14 +02:00
fec4194ae6 Merge pull request #1958 from dberlin/main
Add support for input capture function
2023-09-28 01:00:36 +00:00
f866735802 Add support for input capture function 2023-09-27 20:15:57 -04:00
20ea76c19c Merge pull request #1953 from embassy-rs/stm32l-tests
tests/stm32: add L0, L1, L4, L4+, L5
2023-09-27 19:37:04 +00:00
e1951f3ddf feat(stm32f7): restore rtc configuration for stm32f7 series 2023-09-27 16:08:05 +02:00
8b5fb254c0 tests/stm32: add L0, L1, L4, L4+, L5 2023-09-26 05:30:50 +02:00
624f786203 Merge pull request #1952 from embassy-rs/stm32-test-cleanup
stm32 rcc fixes.
2023-09-26 03:24:53 +00:00
a57e48459e stm32/rcc: remove bad limits on l5. 2023-09-26 05:15:09 +02:00
c604d8a8f1 stm32/rcc: add voltage_scale, flash waitstates. 2023-09-26 05:15:09 +02:00
be0c52bf5e Merge pull request #1951 from embassy-rs/stm32-test-cleanup
stm32/usart: enable fifo mode on usartv4.
2023-09-26 02:42:11 +00:00
44bb405683 stm32/usart: enable fifo mode on usartv4. 2023-09-26 04:38:53 +02:00
e8587e2fba Merge pull request #1950 from embassy-rs/stm32-test-cleanup
stm32/usart: return error instead of panicking on bad baudrate.
2023-09-25 22:21:29 +00:00
5d8817d109 stm32/usart: return error instead of panicking on bad baudrate. 2023-09-26 00:19:27 +02:00
c79a84a98a Merge pull request #1949 from xoviat/rtc
stm32/rtc: cleanup and fixes
2023-09-25 21:40:05 +00:00
96edbd84fb rtc: use enable on known working chips only 2023-09-25 16:38:30 -05:00
dc400a0539 stm32/rtc: always set wakeup alarm 2023-09-25 16:27:08 -05:00
04b09a2acb stm32/rtc: use rccperi enable 2023-09-25 16:26:29 -05:00
481d2998ef Merge pull request #1948 from embassy-rs/stm32-test-cleanup
tests/stm32: centralize pin configuration.
2023-09-25 20:44:57 +00:00
4b695120fc tests/stm32: centralize pin configuration. 2023-09-25 22:41:22 +02:00
bd9021ca1d Make irq token Copy+Clone 2023-09-25 22:35:31 +02:00
6e63c8d4bf Merge pull request #1947 from ceekdee/rust-lorawan-lora-phy-v2
Update rust-lorawan and embassy to use lora-phy version 2
2023-09-25 16:20:50 +00:00
70acc093dd Update rust-lorawan crate versions. 2023-09-25 10:45:53 -05:00
f7c2db245f Merge branch 'embassy-rs:main' into rust-lorawan-lora-phy-v2 2023-09-24 19:09:04 -05:00
2543bcafaf Merge pull request #1945 from xoviat/bd-2
stm32: fix bd lsi
2023-09-24 23:41:04 +00:00
9f2fc04caa stm32: fix bd lsi 2023-09-24 18:37:09 -05:00
f32bfafa61 Merge pull request #1943 from embassy-rs/centralize-pwr-syscfg
stm32: centralize enabling pwr, syscfg, flash.
2023-09-24 23:15:25 +00:00
e03239e88d stm32: centralize enabling pwr, syscfg, flash. 2023-09-25 01:07:55 +02:00
7d5e62d4a7 Update for rust-lorawan and lora-phy version 2. 2023-09-24 10:33:03 -05:00
65d36f9f99 Merge pull request #1940 from luveti/patch-1
stm32: fix rtc example
2023-09-24 09:30:08 +00:00
347ff18644 stm32: fix rtc example
lsi must be enabled otherwise a assertion fails
2023-09-24 01:11:58 -04:00
1e80fd81f7 Merge pull request #1939 from nilfit/spim-anomaly-109
spim: Fix nRF52832 SPIM with polling executors
2023-09-23 11:14:16 +00:00
52e269edbb Merge pull request #1938 from xoviat/low-power
stm32/lp: clamp requested_duration
2023-09-22 20:39:54 +00:00
c849620cd6 stm32/lp: clamp requested_duration to avoid overflow 2023-09-22 15:35:20 -05:00
6f83acc010 Add separate work-around specific flag for DMA errata on NRF52832 2023-09-22 17:02:21 +02:00
2b7b7a917d spim: Fix SPIM with polling executors
Co-authored-by: Priit Laes <plaes@plaes.org>
2023-09-22 17:02:21 +02:00
f1488864eb Merge pull request #1937 from xoviat/low-power
stm32/low-power: create one critical-section for all time ops
2023-09-22 00:36:21 +00:00
7cf327130e stm32/low-power: create one critical-section for all time ops 2023-09-21 19:32:48 -05:00
02b0523199 Merge pull request #1935 from embassy-rs/stm32-update-metapacgc
stm32: update metapac.
2023-09-21 22:26:53 +00:00
47175198c0 stm32: update metapac. 2023-09-22 00:13:57 +02:00
4b20e6c258 Merge pull request #1927 from embassy-rs/stm32-rcc-unify-h
stm32/rcc: unify h5 and h7.
2023-09-21 22:05:01 +00:00
83b4c01273 stm32/rcc: unify h5 and h7. 2023-09-21 23:47:56 +02:00
e313ca4ae8 Merge pull request #1934 from chrenderle/low-power-l0
fix low-power: APB1 needed for LSE
2023-09-21 17:40:11 +00:00
ad64d7b20b fix low-power: APB1 needed for LSE 2023-09-21 17:17:58 +02:00
5626a28af2 Merge pull request #1930 from xoviat/adc
stm32/adc: make v1 async
2023-09-20 22:45:51 +00:00
766ae724cb Merge pull request #1932 from embassy-rs/h7fix
stm32/h7: fix bad PWR reg versions.
2023-09-20 22:28:09 +00:00
00b9f9acef stm32/h7: fix bad PWR reg versions. 2023-09-21 00:23:56 +02:00
d46920dce6 stm32/adc: make v1 async and leave en 2023-09-20 16:07:35 -05:00
e1ed492577 Merge pull request #1929 from sgoll/exti-level
stm32/exti: Add get_level() to ExtiInput
2023-09-19 22:44:19 +00:00
2405aff11f Add get_level() to ExtiInput 2023-09-20 00:03:39 +02:00
a402aed3d1 Add async interface for CDC control changes
Signed-off-by: Matt Spencer <matthew@thespencers.me.uk>
2023-09-19 15:42:26 +01:00
c573959a95 Merge pull request #1928 from sgoll/fix-r2-voltage-range
stm32/f2: Fix typo in RCC voltage range docs
2023-09-19 12:03:40 +00:00
561696dfad Fix typo in F2 RCC voltage ranges 2023-09-19 10:20:25 +02:00
b1abaa380f Merge pull request #1919 from xoviat/adc
adc/f3: add async conversion
2023-09-18 21:32:59 +00:00
e640933e2f stm32/adc: add async conversion 2023-09-18 16:31:20 -05:00
183824fbdd Merge pull request #1924 from embassy-rs/rp-remove-paste
rp: remove paste macro.
2023-09-18 01:33:55 +00:00
5d0c40f61d rp: remove paste macro. 2023-09-18 03:30:17 +02:00
fdfe12fe1c Merge pull request #1923 from embassy-rs/pac-vos
stm32: use PAC enums for VOS.
2023-09-18 01:23:40 +00:00
4bfbcd6c72 stm32: use PAC enums for VOS. 2023-09-18 03:15:15 +02:00
0da793e5de Merge pull request #1921 from xoviat/rtc
stm32: update configure_ls and misc cleanup
2023-09-18 00:04:32 +00:00
0dcb34fc7d ci: fix tests 2023-09-17 19:03:45 -05:00
feaeee1e83 stm32: misc. cleanup 2023-09-17 18:47:22 -05:00
a6ef314be1 stm32: update configure_ls as agreed 2023-09-17 18:41:45 -05:00
daeb497045 Merge pull request #1917 from MabezDev/set-config-uart
stm32: Implement `set_config` for Uart structs
2023-09-17 21:33:18 +00:00
88eb5cca71 stm32: Implement set_config for Uart structs 2023-09-17 18:38:03 +01:00
cd128c20fa Merge pull request #1920 from MabezDev/rtc-time-provider
stm32: Add RtcTimeProvider struct to Rtc module
2023-09-17 17:32:56 +00:00
087ef918bf stm32: Add RtcTimeProvider struct to Rtc module
This struct allows users to acquire the current time without putting `Rtc`
in a mutex and passing that around. This is allowed because reading from the
rtc registers is atomic.
2023-09-17 18:04:05 +01:00
75cae09e79 Merge pull request #1918 from embassy-rs/stm32wba
stm32/rcc: use AHBPrescaler div impls in stm32wba
2023-09-17 00:39:26 +00:00
bbe1d96045 stm32/rcc: use AHBPrescaler div impls in stm32wba 2023-09-17 02:30:50 +02:00
3ddc9cd110 Merge pull request #1915 from xoviat/rcc
stm32/rcc: convert bus prescalers to pac enums
2023-09-16 22:59:26 +00:00
de2773afdd stm32/rcc: convert bus prescalers to pac enums 2023-09-16 17:41:11 -05:00
2930be5e17 Merge pull request #1916 from wkf/main
Update stm32wb examples to use ble/mac firmware.
2023-09-16 20:43:02 +00:00
09f087e53e Update stm32wb examples to use ble/mac firmware. 2023-09-16 16:32:25 -04:00
044b837caa Merge pull request #1914 from xoviat/fix-wpan
stm32: fix  wpan_ble test
2023-09-16 15:20:55 +00:00
ad0a306ea5 stm32: fix wpan_ble test 2023-09-16 10:19:09 -05:00
b5fffbf66f Merge pull request #1913 from xoviat/doc
update docs
2023-09-16 13:20:39 +00:00
537e2f3b44 update docs 2023-09-16 08:19:49 -05:00
80d7193b5b Merge pull request #1911 from embassy-rs/stm32wba
stm32: add stm32wba support.
2023-09-16 02:06:22 +00:00
8315cf064e stm32: add stm32wba support. 2023-09-16 04:04:45 +02:00
a2a26f489b ci: set net.git-fetch-with-cli=true 2023-09-16 02:16:33 +02:00
f27620cc0b Merge pull request #1909 from xoviat/adc
stm32: generate adc_common and misc.
2023-09-15 23:49:41 +00:00
2911774849 Merge pull request #1910 from xoviat/rtc
stm32: rtc/low-power cleanup
2023-09-15 23:49:36 +00:00
6da75ea285 stm32: rtc/low-power cleanup 2023-09-15 18:41:33 -05:00
aa2fa29b89 stm32: fix adc f3 startup time
closes #1888.
2023-09-15 17:36:21 -05:00
c28a6bdd0b stm32: generate adc_common 2023-09-15 17:35:53 -05:00
5a158b94bd Merge pull request #1896 from haileys/inline-never-for-rvo
Write to TaskStorage::future via never-inlined fn to encourage RVO
2023-09-15 18:45:21 +00:00
c091ed2f63 Merge pull request #1908 from chrenderle/low-power-l0
Fix low-power feature for STM32L0
2023-09-15 14:50:19 +00:00
45e9e51bdc Fix low-power feature for STM32L0 2023-09-15 16:36:51 +02:00
7c77d2bd94 ci: reenable stm32 docs. 2023-09-15 03:43:46 +02:00
f76d94098d Merge pull request #1906 from xoviat/pwr-l0
update metapac and add low-power for l0
2023-09-15 00:21:24 +00:00
07233ca5b4 ci: build low-power on l0 2023-09-14 19:09:35 -05:00
9fb14379c3 stm32: add lp to l0 2023-09-14 18:53:27 -05:00
309c3d6b47 update metapac 2023-09-14 18:36:03 -05:00
b9d4b18f14 update UninitCell::write call in arch::wasm too 2023-09-14 13:59:24 +10:00
3a1ed823f8 write to TaskStorage::future via inline(never) fn to encourage RVO 2023-09-14 13:42:11 +10:00
f033089625 Merge pull request #3 from embassy-rs/main
Update to embassy head
2023-08-24 17:38:04 -06:00
6d8a5c6c20 Merge pull request #2 from embassy-rs/main
Pull changes from base embassy repo
2023-07-16 19:08:01 -05:00
3aedbce5c2 Merge pull request #1 from embassy-rs/main
Pull changes from embassy main
2023-07-01 15:41:11 -05:00
212 changed files with 6184 additions and 4288 deletions

View File

@ -8,6 +8,10 @@ export RUSTUP_HOME=/ci/cache/rustup
export CARGO_HOME=/ci/cache/cargo
export CARGO_TARGET_DIR=/ci/cache/target
# needed for "dumb HTTP" transport support
# used when pointing stm32-metapac to a CI-built one.
export CARGO_NET_GIT_FETCH_WITH_CLI=true
hashtime restore /ci/cache/filetime.json || true
hashtime save /ci/cache/filetime.json

4
.github/ci/build.sh vendored
View File

@ -14,6 +14,10 @@ if [ -f /ci/secrets/teleprobe-token.txt ]; then
export TELEPROBE_CACHE=/ci/cache/teleprobe_cache.json
fi
# needed for "dumb HTTP" transport support
# used when pointing stm32-metapac to a CI-built one.
export CARGO_NET_GIT_FETCH_WITH_CLI=true
hashtime restore /ci/cache/filetime.json || true
hashtime save /ci/cache/filetime.json

9
.github/ci/doc.sh vendored
View File

@ -49,8 +49,7 @@ kubectl cp webroot/static $POD:/data
# build and upload stm32 last
# so that it doesn't prevent other crates from getting docs updates when it breaks.
# temporarily disabled because it's bringing CI down.
#rm -rf webroot
#docserver-builder -i ./embassy-stm32 -o webroot/crates/embassy-stm32/git.zup
#POD=$(kubectl -n embassy get po -l app=docserver -o jsonpath={.items[0].metadata.name})
#kubectl cp webroot/crates $POD:/data
rm -rf webroot
docserver-builder -i ./embassy-stm32 -o webroot/crates/embassy-stm32/git.zup
POD=$(kubectl -n embassy get po -l app=docserver -o jsonpath={.items[0].metadata.name})
kubectl cp webroot/crates $POD:/data

4
.github/ci/test.sh vendored
View File

@ -8,6 +8,10 @@ export RUSTUP_HOME=/ci/cache/rustup
export CARGO_HOME=/ci/cache/cargo
export CARGO_TARGET_DIR=/ci/cache/target
# needed for "dumb HTTP" transport support
# used when pointing stm32-metapac to a CI-built one.
export CARGO_NET_GIT_FETCH_WITH_CLI=true
hashtime restore /ci/cache/filetime.json || true
hashtime save /ci/cache/filetime.json

347
ci.sh
View File

@ -15,171 +15,198 @@ fi
find . -name '*.rs' -not -path '*target*' | xargs rustfmt --check --skip-children --unstable-features --edition 2021
cargo batch \
--- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features nightly \
--- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features nightly,log \
--- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features nightly,defmt \
--- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv6m-none-eabi --features nightly,defmt \
--- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv6m-none-eabi --features nightly,defmt,arch-cortex-m,executor-thread,executor-interrupt,integrated-timers \
--- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features nightly,arch-cortex-m \
--- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features nightly,arch-cortex-m,integrated-timers \
--- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features nightly,arch-cortex-m,executor-thread \
--- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features nightly,arch-cortex-m,executor-thread,integrated-timers \
--- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features nightly,arch-cortex-m,executor-interrupt \
--- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features nightly,arch-cortex-m,executor-interrupt,integrated-timers \
--- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features nightly,arch-cortex-m,executor-thread,executor-interrupt \
--- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features nightly,arch-cortex-m,executor-thread,executor-interrupt,integrated-timers \
--- build --release --manifest-path embassy-executor/Cargo.toml --target riscv32imac-unknown-none-elf --features nightly,arch-riscv32 \
--- build --release --manifest-path embassy-executor/Cargo.toml --target riscv32imac-unknown-none-elf --features nightly,arch-riscv32,integrated-timers \
--- build --release --manifest-path embassy-executor/Cargo.toml --target riscv32imac-unknown-none-elf --features nightly,arch-riscv32,executor-thread \
--- build --release --manifest-path embassy-executor/Cargo.toml --target riscv32imac-unknown-none-elf --features nightly,arch-riscv32,executor-thread,integrated-timers \
--- build --release --manifest-path embassy-sync/Cargo.toml --target thumbv6m-none-eabi --features nightly,defmt \
--- build --release --manifest-path embassy-time/Cargo.toml --target thumbv6m-none-eabi --features nightly,defmt,defmt-timestamp-uptime,tick-hz-32_768,generic-queue-8 \
--- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,proto-ipv4,medium-ethernet \
--- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,dhcpv4,medium-ethernet \
--- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,dhcpv4,medium-ethernet,nightly \
--- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,proto-ipv6,medium-ethernet \
--- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,proto-ipv6,medium-ieee802154 \
--- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,proto-ipv6,medium-ethernet,medium-ieee802154 \
--- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,proto-ipv6,medium-ethernet,nightly \
--- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,proto-ipv4,proto-ipv6,medium-ethernet \
--- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,proto-ipv4,proto-ipv6,medium-ethernet,nightly \
--- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,proto-ipv4,proto-ipv6,medium-ip,nightly \
--- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,proto-ipv4,proto-ipv6,medium-ip,medium-ethernet,nightly \
--- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,proto-ipv4,proto-ipv6,medium-ip,medium-ethernet,medium-ieee802154,nightly \
--- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv7em-none-eabi --features nightly,nrf52805,gpiote,time-driver-rtc1 \
--- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv7em-none-eabi --features nightly,nrf52810,gpiote,time-driver-rtc1 \
--- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv7em-none-eabi --features nightly,nrf52811,gpiote,time-driver-rtc1 \
--- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv7em-none-eabi --features nightly,nrf52820,gpiote,time-driver-rtc1 \
--- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv7em-none-eabi --features nightly,nrf52832,gpiote,time-driver-rtc1,reset-pin-as-gpio \
--- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv7em-none-eabi --features nightly,nrf52833,gpiote,time-driver-rtc1,unstable-traits,nfc-pins-as-gpio \
--- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv8m.main-none-eabihf --features nightly,nrf9160-s,gpiote,time-driver-rtc1 \
--- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv8m.main-none-eabihf --features nightly,nrf9160-ns,gpiote,time-driver-rtc1,unstable-traits \
--- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv8m.main-none-eabihf --features nightly,nrf5340-app-s,gpiote,time-driver-rtc1,unstable-traits \
--- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv8m.main-none-eabihf --features nightly,nrf5340-app-ns,gpiote,time-driver-rtc1 \
--- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv8m.main-none-eabihf --features nightly,nrf5340-net,gpiote,time-driver-rtc1,unstable-traits \
--- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv7em-none-eabi --features nightly,nrf52840,gpiote,time-driver-rtc1 \
--- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv7em-none-eabi --features nightly,nrf52840,log,gpiote,time-driver-rtc1 \
--- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv7em-none-eabi --features nightly,nrf52840,defmt,gpiote,time-driver-rtc1,unstable-traits \
--- build --release --manifest-path embassy-rp/Cargo.toml --target thumbv6m-none-eabi --features nightly,unstable-traits,defmt \
--- build --release --manifest-path embassy-rp/Cargo.toml --target thumbv6m-none-eabi --features nightly,unstable-traits,log \
--- build --release --manifest-path embassy-rp/Cargo.toml --target thumbv6m-none-eabi --features nightly,unstable-traits \
--- build --release --manifest-path embassy-rp/Cargo.toml --target thumbv6m-none-eabi --features nightly \
--- build --release --manifest-path embassy-rp/Cargo.toml --target thumbv6m-none-eabi --features nightly,intrinsics \
--- build --release --manifest-path embassy-rp/Cargo.toml --target thumbv6m-none-eabi --features nightly,qspi-as-gpio \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt,exti,time-driver-any \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt,time-driver-any \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt,exti \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt,exti,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,nightly,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,nightly,defmt,exti,time-driver-any \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,nightly,defmt,time-driver-any \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,nightly,defmt,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,nightly,defmt,exti \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,nightly,defmt,exti,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,nightly,defmt \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f410tb,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f411ce,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f413vh,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f429zi,log,exti,time-driver-any,unstable-traits,embedded-sdmmc \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f730i8,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32h755zi-cm7,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32h7b3ai,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32l476vg,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32l422cb,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32wb15cc,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features nightly,stm32l072cz,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features nightly,stm32l041f6,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32l151cb-a,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32f398ve,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32f378cc,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features nightly,stm32g0c1ve,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32f217zg,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features nightly,stm32l552ze,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features nightly,stm32wl54jc-cm0p,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32wle5jb,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32g474pe,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32f107vc,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32f103re,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32f100c4,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32h503rb,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32h562ag,defmt,exti,time-driver-any,unstable-traits \
--- build --release --manifest-path cyw43/Cargo.toml --target thumbv6m-none-eabi --features ''\
--- build --release --manifest-path cyw43/Cargo.toml --target thumbv6m-none-eabi --features 'log' \
--- build --release --manifest-path cyw43/Cargo.toml --target thumbv6m-none-eabi --features 'defmt' \
--- build --release --manifest-path cyw43/Cargo.toml --target thumbv6m-none-eabi --features 'log,firmware-logs' \
--- build --release --manifest-path cyw43/Cargo.toml --target thumbv6m-none-eabi --features 'defmt,firmware-logs' \
--- build --release --manifest-path cyw43-pio/Cargo.toml --target thumbv6m-none-eabi --features '' \
--- build --release --manifest-path cyw43-pio/Cargo.toml --target thumbv6m-none-eabi --features 'overclock' \
--- build --release --manifest-path embassy-boot/nrf/Cargo.toml --target thumbv7em-none-eabi --features embassy-nrf/nrf52840,nightly \
--- build --release --manifest-path embassy-boot/nrf/Cargo.toml --target thumbv8m.main-none-eabihf --features embassy-nrf/nrf9160-ns,nightly \
--- build --release --manifest-path embassy-boot/rp/Cargo.toml --target thumbv6m-none-eabi --features nightly \
--- build --release --manifest-path embassy-boot/stm32/Cargo.toml --target thumbv7em-none-eabi --features embassy-stm32/stm32wl55jc-cm4,nightly \
--- build --release --manifest-path docs/modules/ROOT/examples/basic/Cargo.toml --target thumbv7em-none-eabi \
--- build --release --manifest-path docs/modules/ROOT/examples/layer-by-layer/blinky-pac/Cargo.toml --target thumbv7em-none-eabi \
--- build --release --manifest-path docs/modules/ROOT/examples/layer-by-layer/blinky-hal/Cargo.toml --target thumbv7em-none-eabi \
--- build --release --manifest-path docs/modules/ROOT/examples/layer-by-layer/blinky-irq/Cargo.toml --target thumbv7em-none-eabi \
--- build --release --manifest-path docs/modules/ROOT/examples/layer-by-layer/blinky-async/Cargo.toml --target thumbv7em-none-eabi \
--- build --release --manifest-path examples/nrf52840/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/nrf52840 \
--- build --release --manifest-path examples/nrf52840-rtic/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/nrf52840-rtic \
--- build --release --manifest-path examples/nrf5340/Cargo.toml --target thumbv8m.main-none-eabihf --out-dir out/examples/nrf5340 \
--- build --release --manifest-path examples/rp/Cargo.toml --target thumbv6m-none-eabi --out-dir out/examples/rp \
--- build --release --manifest-path examples/stm32f0/Cargo.toml --target thumbv6m-none-eabi --out-dir out/examples/stm32f0 \
--- build --release --manifest-path examples/stm32f1/Cargo.toml --target thumbv7m-none-eabi --out-dir out/examples/stm32f1 \
--- build --release --manifest-path examples/stm32f2/Cargo.toml --target thumbv7m-none-eabi --out-dir out/examples/stm32f2 \
--- build --release --manifest-path examples/stm32f3/Cargo.toml --target thumbv7em-none-eabihf --out-dir out/examples/stm32f3 \
--- build --release --manifest-path examples/stm32f334/Cargo.toml --target thumbv7em-none-eabihf --out-dir out/examples/stm32f334 \
--- build --release --manifest-path examples/stm32f4/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/stm32f4 \
--- build --release --manifest-path examples/stm32f7/Cargo.toml --target thumbv7em-none-eabihf --out-dir out/examples/stm32f7 \
--- build --release --manifest-path examples/stm32c0/Cargo.toml --target thumbv6m-none-eabi --out-dir out/examples/stm32c0 \
--- build --release --manifest-path examples/stm32g0/Cargo.toml --target thumbv6m-none-eabi --out-dir out/examples/stm32g0 \
--- build --release --manifest-path examples/stm32g4/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/stm32g4 \
--- build --release --manifest-path examples/stm32h5/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/stm32h5 \
--- build --release --manifest-path examples/stm32h7/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/stm32h7 \
--- build --release --manifest-path examples/stm32l0/Cargo.toml --target thumbv6m-none-eabi --out-dir out/examples/stm32l0 \
--- build --release --manifest-path examples/stm32l1/Cargo.toml --target thumbv7m-none-eabi --out-dir out/examples/stm32l1 \
--- build --release --manifest-path examples/stm32l4/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/stm32l4 \
--- build --release --manifest-path examples/stm32l5/Cargo.toml --target thumbv8m.main-none-eabihf --out-dir out/examples/stm32l5 \
--- build --release --manifest-path examples/stm32u5/Cargo.toml --target thumbv8m.main-none-eabihf --out-dir out/examples/stm32u5 \
--- build --release --manifest-path examples/stm32wb/Cargo.toml --target thumbv7em-none-eabihf --out-dir out/examples/stm32wb \
--- build --release --manifest-path examples/stm32wl/Cargo.toml --target thumbv7em-none-eabihf --out-dir out/examples/stm32wl \
--- build --release --manifest-path examples/boot/application/nrf/Cargo.toml --target thumbv7em-none-eabi --features embassy-nrf/nrf52840,skip-include --out-dir out/examples/boot/nrf52840 \
--- build --release --manifest-path examples/boot/application/nrf/Cargo.toml --target thumbv8m.main-none-eabihf --features embassy-nrf/nrf9160-ns,skip-include --out-dir out/examples/boot/nrf9160 \
--- build --release --manifest-path examples/boot/application/rp/Cargo.toml --target thumbv6m-none-eabi --features skip-include --out-dir out/examples/boot/rp \
--- build --release --manifest-path examples/boot/application/stm32f3/Cargo.toml --target thumbv7em-none-eabi --features skip-include --out-dir out/examples/boot/stm32f3 \
--- build --release --manifest-path examples/boot/application/stm32f7/Cargo.toml --target thumbv7em-none-eabi --features skip-include --out-dir out/examples/boot/stm32f7 \
--- build --release --manifest-path examples/boot/application/stm32h7/Cargo.toml --target thumbv7em-none-eabi --features skip-include --out-dir out/examples/boot/stm32h7 \
--- build --release --manifest-path examples/boot/application/stm32l0/Cargo.toml --target thumbv6m-none-eabi --features skip-include --out-dir out/examples/boot/stm32l0 \
--- build --release --manifest-path examples/boot/application/stm32l1/Cargo.toml --target thumbv7m-none-eabi --features skip-include --out-dir out/examples/boot/stm32l1 \
--- build --release --manifest-path examples/boot/application/stm32l4/Cargo.toml --target thumbv7em-none-eabi --features skip-include --out-dir out/examples/boot/stm32l4 \
--- build --release --manifest-path examples/boot/application/stm32wl/Cargo.toml --target thumbv7em-none-eabihf --features skip-include --out-dir out/examples/boot/stm32wl \
--- build --release --manifest-path examples/boot/bootloader/nrf/Cargo.toml --target thumbv7em-none-eabi --features embassy-nrf/nrf52840 \
--- build --release --manifest-path examples/boot/bootloader/nrf/Cargo.toml --target thumbv8m.main-none-eabihf --features embassy-nrf/nrf9160-ns \
--- build --release --manifest-path examples/boot/bootloader/rp/Cargo.toml --target thumbv6m-none-eabi \
--- build --release --manifest-path examples/boot/bootloader/stm32/Cargo.toml --target thumbv7em-none-eabi --features embassy-stm32/stm32wl55jc-cm4 \
--- build --release --manifest-path examples/wasm/Cargo.toml --target wasm32-unknown-unknown --out-dir out/examples/wasm \
--- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32f103c8 --out-dir out/tests/stm32f103c8 \
--- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f429zi --out-dir out/tests/stm32f429zi \
--- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32g491re --out-dir out/tests/stm32g491re \
--- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32g071rb --out-dir out/tests/stm32g071rb \
--- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32c031c6 --out-dir out/tests/stm32c031c6 \
--- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32h755zi --out-dir out/tests/stm32h755zi \
--- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32wb55rg --out-dir out/tests/stm32wb55rg \
--- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32h563zi --out-dir out/tests/stm32h563zi \
--- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32u585ai --out-dir out/tests/stm32u585ai \
--- build --release --manifest-path tests/rp/Cargo.toml --target thumbv6m-none-eabi --out-dir out/tests/rpi-pico \
--- build --release --manifest-path tests/nrf/Cargo.toml --target thumbv7em-none-eabi --out-dir out/tests/nrf52840-dk \
--- build --release --manifest-path tests/riscv32/Cargo.toml --target riscv32imac-unknown-none-elf \
$BUILD_EXTRA
--- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32wb55rg --out-dir out/tests/stm32wb55rg # \
# --- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features nightly \
# --- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features nightly,log \
# --- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features nightly,defmt \
# --- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv6m-none-eabi --features nightly,defmt \
# --- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv6m-none-eabi --features nightly,defmt,arch-cortex-m,executor-thread,executor-interrupt,integrated-timers \
# --- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features nightly,arch-cortex-m \
# --- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features nightly,arch-cortex-m,integrated-timers \
# --- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features nightly,arch-cortex-m,executor-thread \
# --- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features nightly,arch-cortex-m,executor-thread,integrated-timers \
# --- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features nightly,arch-cortex-m,executor-interrupt \
# --- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features nightly,arch-cortex-m,executor-interrupt,integrated-timers \
# --- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features nightly,arch-cortex-m,executor-thread,executor-interrupt \
# --- build --release --manifest-path embassy-executor/Cargo.toml --target thumbv7em-none-eabi --features nightly,arch-cortex-m,executor-thread,executor-interrupt,integrated-timers \
# --- build --release --manifest-path embassy-executor/Cargo.toml --target riscv32imac-unknown-none-elf --features nightly,arch-riscv32 \
# --- build --release --manifest-path embassy-executor/Cargo.toml --target riscv32imac-unknown-none-elf --features nightly,arch-riscv32,integrated-timers \
# --- build --release --manifest-path embassy-executor/Cargo.toml --target riscv32imac-unknown-none-elf --features nightly,arch-riscv32,executor-thread \
# --- build --release --manifest-path embassy-executor/Cargo.toml --target riscv32imac-unknown-none-elf --features nightly,arch-riscv32,executor-thread,integrated-timers \
# --- build --release --manifest-path embassy-sync/Cargo.toml --target thumbv6m-none-eabi --features nightly,defmt \
# --- build --release --manifest-path embassy-time/Cargo.toml --target thumbv6m-none-eabi --features nightly,defmt,defmt-timestamp-uptime,tick-hz-32_768,generic-queue-8 \
# --- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,proto-ipv4,medium-ethernet \
# --- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,dhcpv4,medium-ethernet \
# --- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,dhcpv4,medium-ethernet,nightly \
# --- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,proto-ipv6,medium-ethernet \
# --- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,proto-ipv6,medium-ieee802154 \
# --- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,proto-ipv6,medium-ethernet,medium-ieee802154 \
# --- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,proto-ipv6,medium-ethernet,nightly \
# --- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,proto-ipv4,proto-ipv6,medium-ethernet \
# --- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,proto-ipv4,proto-ipv6,medium-ethernet,nightly \
# --- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,proto-ipv4,proto-ipv6,medium-ip,nightly \
# --- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,proto-ipv4,proto-ipv6,medium-ip,medium-ethernet,nightly \
# --- build --release --manifest-path embassy-net/Cargo.toml --target thumbv7em-none-eabi --features defmt,tcp,udp,dns,proto-ipv4,proto-ipv6,medium-ip,medium-ethernet,medium-ieee802154,nightly \
# --- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv7em-none-eabi --features nightly,nrf52805,gpiote,time-driver-rtc1 \
# --- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv7em-none-eabi --features nightly,nrf52810,gpiote,time-driver-rtc1 \
# --- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv7em-none-eabi --features nightly,nrf52811,gpiote,time-driver-rtc1 \
# --- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv7em-none-eabi --features nightly,nrf52820,gpiote,time-driver-rtc1 \
# --- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv7em-none-eabi --features nightly,nrf52832,gpiote,time-driver-rtc1,reset-pin-as-gpio \
# --- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv7em-none-eabi --features nightly,nrf52833,gpiote,time-driver-rtc1,unstable-traits,nfc-pins-as-gpio \
# --- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv8m.main-none-eabihf --features nightly,nrf9160-s,gpiote,time-driver-rtc1 \
# --- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv8m.main-none-eabihf --features nightly,nrf9160-ns,gpiote,time-driver-rtc1,unstable-traits \
# --- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv8m.main-none-eabihf --features nightly,nrf5340-app-s,gpiote,time-driver-rtc1,unstable-traits \
# --- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv8m.main-none-eabihf --features nightly,nrf5340-app-ns,gpiote,time-driver-rtc1 \
# --- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv8m.main-none-eabihf --features nightly,nrf5340-net,gpiote,time-driver-rtc1,unstable-traits \
# --- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv7em-none-eabi --features nightly,nrf52840,gpiote,time-driver-rtc1 \
# --- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv7em-none-eabi --features nightly,nrf52840,log,gpiote,time-driver-rtc1 \
# --- build --release --manifest-path embassy-nrf/Cargo.toml --target thumbv7em-none-eabi --features nightly,nrf52840,defmt,gpiote,time-driver-rtc1,unstable-traits \
# --- build --release --manifest-path embassy-rp/Cargo.toml --target thumbv6m-none-eabi --features nightly,unstable-traits,defmt \
# --- build --release --manifest-path embassy-rp/Cargo.toml --target thumbv6m-none-eabi --features nightly,unstable-traits,log \
# --- build --release --manifest-path embassy-rp/Cargo.toml --target thumbv6m-none-eabi --features nightly,unstable-traits \
# --- build --release --manifest-path embassy-rp/Cargo.toml --target thumbv6m-none-eabi --features nightly \
# --- build --release --manifest-path embassy-rp/Cargo.toml --target thumbv6m-none-eabi --features nightly,intrinsics \
# --- build --release --manifest-path embassy-rp/Cargo.toml --target thumbv6m-none-eabi --features nightly,qspi-as-gpio \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt,exti,time-driver-any \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt,time-driver-any \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt,exti \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt,exti,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,defmt \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,nightly,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,nightly,defmt,exti,time-driver-any \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,nightly,defmt,time-driver-any \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,nightly,defmt,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,nightly,defmt,exti \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,nightly,defmt,exti,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze,nightly,defmt \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f401ve,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f405zg,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f407zg,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f410tb,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f411ce,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f412zg,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f413vh,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f415zg,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f417zg,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f423zh,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f427zi,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f429zi,log,exti,time-driver-any,unstable-traits,embedded-sdmmc \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f437zi,log,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f439zi,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f446ze,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f469zi,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f479zi,defmt,exti,time-driver-any,unstable-traits,embedded-sdmmc \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32f730i8,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32h753zi,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32h735zg,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32h755zi-cm7,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32h7b3ai,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32l476vg,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32l422cb,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32wb15cc,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features nightly,stm32l072cz,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features nightly,stm32l041f6,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features nightly,stm32l073cz,defmt,exti,time-driver-any,unstable-traits,low-power \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32l151cb-a,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32f398ve,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32f378cc,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features nightly,stm32g0c1ve,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32f217zg,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features nightly,stm32l552ze,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv6m-none-eabi --features nightly,stm32wl54jc-cm0p,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32wle5jb,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7em-none-eabi --features nightly,stm32g474pe,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32f107vc,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32f103re,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32f100c4,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32h503rb,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path embassy-stm32/Cargo.toml --target thumbv7m-none-eabi --features nightly,stm32h562ag,defmt,exti,time-driver-any,unstable-traits \
# --- build --release --manifest-path cyw43/Cargo.toml --target thumbv6m-none-eabi --features ''\
# --- build --release --manifest-path cyw43/Cargo.toml --target thumbv6m-none-eabi --features 'log' \
# --- build --release --manifest-path cyw43/Cargo.toml --target thumbv6m-none-eabi --features 'defmt' \
# --- build --release --manifest-path cyw43/Cargo.toml --target thumbv6m-none-eabi --features 'log,firmware-logs' \
# --- build --release --manifest-path cyw43/Cargo.toml --target thumbv6m-none-eabi --features 'defmt,firmware-logs' \
# --- build --release --manifest-path cyw43-pio/Cargo.toml --target thumbv6m-none-eabi --features '' \
# --- build --release --manifest-path cyw43-pio/Cargo.toml --target thumbv6m-none-eabi --features 'overclock' \
# --- build --release --manifest-path embassy-boot/nrf/Cargo.toml --target thumbv7em-none-eabi --features embassy-nrf/nrf52840,nightly \
# --- build --release --manifest-path embassy-boot/nrf/Cargo.toml --target thumbv8m.main-none-eabihf --features embassy-nrf/nrf9160-ns,nightly \
# --- build --release --manifest-path embassy-boot/rp/Cargo.toml --target thumbv6m-none-eabi --features nightly \
# --- build --release --manifest-path embassy-boot/stm32/Cargo.toml --target thumbv7em-none-eabi --features embassy-stm32/stm32wl55jc-cm4,nightly \
# --- build --release --manifest-path docs/modules/ROOT/examples/basic/Cargo.toml --target thumbv7em-none-eabi \
# --- build --release --manifest-path docs/modules/ROOT/examples/layer-by-layer/blinky-pac/Cargo.toml --target thumbv7em-none-eabi \
# --- build --release --manifest-path docs/modules/ROOT/examples/layer-by-layer/blinky-hal/Cargo.toml --target thumbv7em-none-eabi \
# --- build --release --manifest-path docs/modules/ROOT/examples/layer-by-layer/blinky-irq/Cargo.toml --target thumbv7em-none-eabi \
# --- build --release --manifest-path docs/modules/ROOT/examples/layer-by-layer/blinky-async/Cargo.toml --target thumbv7em-none-eabi \
# --- build --release --manifest-path examples/nrf52840/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/nrf52840 \
# --- build --release --manifest-path examples/nrf52840-rtic/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/nrf52840-rtic \
# --- build --release --manifest-path examples/nrf5340/Cargo.toml --target thumbv8m.main-none-eabihf --out-dir out/examples/nrf5340 \
# --- build --release --manifest-path examples/rp/Cargo.toml --target thumbv6m-none-eabi --out-dir out/examples/rp \
# --- build --release --manifest-path examples/stm32f0/Cargo.toml --target thumbv6m-none-eabi --out-dir out/examples/stm32f0 \
# --- build --release --manifest-path examples/stm32f1/Cargo.toml --target thumbv7m-none-eabi --out-dir out/examples/stm32f1 \
# --- build --release --manifest-path examples/stm32f2/Cargo.toml --target thumbv7m-none-eabi --out-dir out/examples/stm32f2 \
# --- build --release --manifest-path examples/stm32f3/Cargo.toml --target thumbv7em-none-eabihf --out-dir out/examples/stm32f3 \
# --- build --release --manifest-path examples/stm32f334/Cargo.toml --target thumbv7em-none-eabihf --out-dir out/examples/stm32f334 \
# --- build --release --manifest-path examples/stm32f4/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/stm32f4 \
# --- build --release --manifest-path examples/stm32f7/Cargo.toml --target thumbv7em-none-eabihf --out-dir out/examples/stm32f7 \
# --- build --release --manifest-path examples/stm32c0/Cargo.toml --target thumbv6m-none-eabi --out-dir out/examples/stm32c0 \
# --- build --release --manifest-path examples/stm32g0/Cargo.toml --target thumbv6m-none-eabi --out-dir out/examples/stm32g0 \
# --- build --release --manifest-path examples/stm32g4/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/stm32g4 \
# --- build --release --manifest-path examples/stm32h5/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/stm32h5 \
# --- build --release --manifest-path examples/stm32h7/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/stm32h7 \
# --- build --release --manifest-path examples/stm32l0/Cargo.toml --target thumbv6m-none-eabi --out-dir out/examples/stm32l0 \
# --- build --release --manifest-path examples/stm32l1/Cargo.toml --target thumbv7m-none-eabi --out-dir out/examples/stm32l1 \
# --- build --release --manifest-path examples/stm32l4/Cargo.toml --target thumbv7em-none-eabi --out-dir out/examples/stm32l4 \
# --- build --release --manifest-path examples/stm32l5/Cargo.toml --target thumbv8m.main-none-eabihf --out-dir out/examples/stm32l5 \
# --- build --release --manifest-path examples/stm32u5/Cargo.toml --target thumbv8m.main-none-eabihf --out-dir out/examples/stm32u5 \
# --- build --release --manifest-path examples/stm32wb/Cargo.toml --target thumbv7em-none-eabihf --out-dir out/examples/stm32wb \
# --- build --release --manifest-path examples/stm32wba/Cargo.toml --target thumbv8m.main-none-eabihf --out-dir out/examples/stm32wba \
# --- build --release --manifest-path examples/stm32wl/Cargo.toml --target thumbv7em-none-eabihf --out-dir out/examples/stm32wl \
# --- build --release --manifest-path examples/boot/application/nrf/Cargo.toml --target thumbv7em-none-eabi --features embassy-nrf/nrf52840,skip-include --out-dir out/examples/boot/nrf52840 \
# --- build --release --manifest-path examples/boot/application/nrf/Cargo.toml --target thumbv8m.main-none-eabihf --features embassy-nrf/nrf9160-ns,skip-include --out-dir out/examples/boot/nrf9160 \
# --- build --release --manifest-path examples/boot/application/rp/Cargo.toml --target thumbv6m-none-eabi --features skip-include --out-dir out/examples/boot/rp \
# --- build --release --manifest-path examples/boot/application/stm32f3/Cargo.toml --target thumbv7em-none-eabi --features skip-include --out-dir out/examples/boot/stm32f3 \
# --- build --release --manifest-path examples/boot/application/stm32f7/Cargo.toml --target thumbv7em-none-eabi --features skip-include --out-dir out/examples/boot/stm32f7 \
# --- build --release --manifest-path examples/boot/application/stm32h7/Cargo.toml --target thumbv7em-none-eabi --features skip-include --out-dir out/examples/boot/stm32h7 \
# --- build --release --manifest-path examples/boot/application/stm32l0/Cargo.toml --target thumbv6m-none-eabi --features skip-include --out-dir out/examples/boot/stm32l0 \
# --- build --release --manifest-path examples/boot/application/stm32l1/Cargo.toml --target thumbv7m-none-eabi --features skip-include --out-dir out/examples/boot/stm32l1 \
# --- build --release --manifest-path examples/boot/application/stm32l4/Cargo.toml --target thumbv7em-none-eabi --features skip-include --out-dir out/examples/boot/stm32l4 \
# --- build --release --manifest-path examples/boot/application/stm32wl/Cargo.toml --target thumbv7em-none-eabihf --features skip-include --out-dir out/examples/boot/stm32wl \
# --- build --release --manifest-path examples/boot/bootloader/nrf/Cargo.toml --target thumbv7em-none-eabi --features embassy-nrf/nrf52840 \
# --- build --release --manifest-path examples/boot/bootloader/nrf/Cargo.toml --target thumbv8m.main-none-eabihf --features embassy-nrf/nrf9160-ns \
# --- build --release --manifest-path examples/boot/bootloader/rp/Cargo.toml --target thumbv6m-none-eabi \
# --- build --release --manifest-path examples/boot/bootloader/stm32/Cargo.toml --target thumbv7em-none-eabi --features embassy-stm32/stm32wl55jc-cm4 \
# --- build --release --manifest-path examples/wasm/Cargo.toml --target wasm32-unknown-unknown --out-dir out/examples/wasm \
# --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32f103c8 --out-dir out/tests/stm32f103c8 \
# --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f429zi --out-dir out/tests/stm32f429zi \
# --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32g491re --out-dir out/tests/stm32g491re \
# --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32g071rb --out-dir out/tests/stm32g071rb \
# --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32c031c6 --out-dir out/tests/stm32c031c6 \
# --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32h755zi --out-dir out/tests/stm32h755zi \
#
# --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32h563zi --out-dir out/tests/stm32h563zi \
# --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32u585ai --out-dir out/tests/stm32u585ai \
# --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv6m-none-eabi --features stm32l073rz --out-dir out/tests/stm32l073rz \
# --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32l152re --out-dir out/tests/stm32l152re \
# --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32l4a6zg --out-dir out/tests/stm32l4a6zg \
# --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32l4r5zi --out-dir out/tests/stm32l4r5zi \
# --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv8m.main-none-eabihf --features stm32l552ze --out-dir out/tests/stm32l552ze \
# --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f767zi --out-dir out/tests/stm32f767zi \
# --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32f207zg --out-dir out/tests/stm32f207zg \
# --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32f303ze --out-dir out/tests/stm32f303ze \
# --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7em-none-eabi --features stm32l496zg --out-dir out/tests/stm32l496zg \
# --- build --release --manifest-path tests/rp/Cargo.toml --target thumbv6m-none-eabi --out-dir out/tests/rpi-pico \
# --- build --release --manifest-path tests/nrf/Cargo.toml --target thumbv7em-none-eabi --out-dir out/tests/nrf52840-dk \
# --- build --release --manifest-path tests/riscv32/Cargo.toml --target riscv32imac-unknown-none-elf \
# $BUILD_EXTRA
rm /ci/cache/teleprobe_cache.json
if [[ -z "${TELEPROBE_TOKEN-}" ]]; then
echo No teleprobe token found, skipping running HIL tests
exit
fi
rm out/tests/stm32wb55rg/wpan_ble
teleprobe client run -r out/tests

View File

@ -1,6 +1,6 @@
* xref:getting_started.adoc[Getting started]
** xref:basic_application.adoc[Basic application]
** xref:layer_by_layer.adoc[Layer by Layer]
* xref:layer_by_layer.adoc[Bare metal to async]
* xref:runtime.adoc[Executor]
* xref:hal.adoc[HAL]
** xref:nrf.adoc[nRF]
@ -8,3 +8,5 @@
* xref:bootloader.adoc[Bootloader]
* xref:examples.adoc[Examples]
* xref:developer.adoc[Developer]
** xref:developer_stm32.adoc[Developer: STM32]

View File

@ -0,0 +1 @@
= Developer Documentation

View File

@ -0,0 +1,79 @@
= Developer Documentation: STM32
== Understanding metapac
When a project that imports `embassy-stm32` is compiled, that project selects the feature corresponding to the chip that project is using. Based on that feature, `embassy-stm32` selects supported link:https://anysilicon.com/ip-intellectual-property-core-semiconductors/[IP] for the chip, and enables the corresponding HAL implementations. But how does `embassy-stm32` know what IP the chip contains, out of the hundreds of chips that we support? It's a long story that starts with `stm32-data-sources`.
== `stm32-data-sources`
link:https://github.com/embassy-rs/stm32-data-sources[`stm32-data-sources`] is as mostly barren repository. It has no README, no documentation, and few watchers. But it's the core of what makes `embassy-stm32` possible. The data for every chip that we support is taken in part from a corresponding XML file like link:https://github.com/embassy-rs/stm32-data-sources/blob/b8b85202e22a954d6c59d4a43d9795d34cff05cf/cubedb/mcu/STM32F051K4Ux.xml[`STM32F051K4Ux.xml`]. In that file, you'll see lines like the following:
[source,xml]
----
<IP InstanceName="I2C1" Name="I2C" Version="i2c2_v1_1_Cube"/>
<!-- snip -->
<IP ConfigFile="TIM-STM32F0xx" InstanceName="TIM1" Name="TIM1_8F0" Version="gptimer2_v2_x_Cube"/>
----
These lines indicate that this chip has an i2c, and that it's version is "v1_1". It also indicates that it has a general purpose timer that with a version of "v2_x". From this data, it's possible to determine which implementations should be included in `embassy-stm32`. But actually doing that is another matter.
== `stm32-data`
While all users of this project are familiar with `embassy-stm32`, fewer are familiar with the project that powers it: `stm32-data`. This project doesn't just aim to generate data for `embassy-stm32`, but for machine consumption in general. To acheive this, information from multiple files from the `stm32-data-sources` project are combined and parsed to assign register block implementations for each supported IP. The core of this matching resides in `chips.rs`:
[source,rust]
----
(".*:I2C:i2c2_v1_1", ("i2c", "v2", "I2C")),
// snip
(r".*TIM\d.*:gptimer.*", ("timer", "v1", "TIM_GP16")),
----
In this case, the i2c version corresponds to our "v2" and the general purpose timer version corresponds to our "v1". Therefore, the `i2c_v2.yaml` and `timer_v1.yaml` register block implementations are assigned to those IP, respectively. The result is that these lines arr generated in `STM32F051K4.json`:
[source,json]
----
{
"name": "I2C1",
"address": 1073763328,
"registers": {
"kind": "i2c",
"version": "v2",
"block": "I2C"
},
// snip
}
// snip
{
"name": "TIM1",
"address": 1073818624,
"registers": {
"kind": "timer",
"version": "v1",
"block": "TIM_ADV"
},
// snip
}
----
In addition to register blocks, data for pin and RCC mapping is also generated and consumed by `embassy-stm32`. `stm32-metapac-gen` is used to package and publish the data as a crate.
== `embassy-stm32`
In the `lib.rs` file located in the root of `embassy-stm32`, you'll see this line:
[source,rust]
----
#[cfg(i2c)]
pub mod i2c;
----
And in the `mod.rs` of the i2c mod, you'll see this:
[source,rust]
----
#[cfg_attr(i2c_v2, path = "v2.rs")]
----
Because i2c is supported for STM32F051K4 and its version corresponds to our "v2", the `i2c` and `i2c_v2`, configuration directives will be present, and `embassy-stm32` will include these files, respectively. This and other configuration directives and tables are generated from the data for chip, allowing `embassy-stm32` to expressively and clearly adapt logic and implementations to what is required for each chip. Compared to other projects across the embedded ecosystem, `embassy-stm32` is the only project that can re-use code across the entire stm32 lineup and remove difficult-to-implement unsafe logic to the HAL.

View File

@ -3,7 +3,7 @@
So you want to try Embassy, great! To get started, there are a few tools you need to install:
* link:https://rustup.rs/[rustup] - the Rust toolchain is needed to compile Rust code.
* link:https://crates.io/crates/probe-run[probe-run] - to flash the firmware on your device. If you already have other tools like `OpenOCD` setup, you can use that as well.
* link:https://crates.io/crates/probe-rs[probe-rs] - to flash the firmware on your device. If you already have other tools like `OpenOCD` setup, you can use that as well.
If you don't have any supported board, don't worry: you can also run embassy on your PC using the `std` examples.
@ -30,6 +30,10 @@ Embassy supports many microcontroller families, but the easiest ways to get star
* link:https://www.raspberrypi.com/products/raspberry-pi-pico/[Raspberry Pi Pico]
=== ESP32
* link:https://github.com/esp-rs/esp-rust-board[ESP32C3]
== Running an example
First you need to clone the [github repository];
@ -38,7 +42,6 @@ First you need to clone the [github repository];
----
git clone https://github.com/embassy-rs/embassy.git
cd embassy
git submodule update --init
----
You can run an example by opening a terminal and entering the following commands:

View File

@ -7,4 +7,6 @@ Embassy provides HALs for several microcontroller families:
* `embassy-rp` for the Raspberry Pi RP2040 microcontrollers
These HALs implement async/await functionality for most peripherals while also implementing the
async traits in `embedded-hal-async`. You can also use these HALs with another executor.
async traits in `embedded-hal` and `embedded-hal-async`. You can also use these HALs with another executor.
For the ESP32 series, there is an link:https://github.com/esp-rs/esp-hal[esp-hal] which you can use.

View File

@ -4,14 +4,9 @@ Embassy is a project to make async/await a first-class option for embedded devel
== What is async?
Software written without async may block on I/O operations. In an std environment, such as a PC, software can handle this either by using threads or non-blocking operations.
When handling I/O, software must call functions that block program execution until the I/O operation completes. When running inside of an OS such as Linux, such functions generally transfer control to the kernel so that another task, known as a thread, can be executed if available, or the CPU can be put to sleep until another such task is ready to perform more work. Because an OS cannot presume that threads will behave cooperatively, threads are relatively resource-intensive, and may be forcibly interrupted they do not transfer control back to the kernel within an allotted time. But if tasks could be presumed to behave cooperatively, or at least not maliciously, it would be possible to create tasks that appear to be almost free when compared to a traditional OS thread. In Rust, these lightweight tasks, known as 'coroutines' or 'goroutines' in other languages, are implemented with async.
With threads, one thread blocks on an I/O operation, another is able to take its place. However, even on a PC, threads are relatively heavy, and therefore some programming languages, such as Go, have implemented a concept called coroutines or 'goroutines' that are much lighter and less-intensive than threads.
The other way to handle blocking I/O operations is to support polling the state of the underlying peripherals to check whether it is available to perform the requested operation. In programming languages without builtin async support,
this requires building a complex loop checking for events.
In Rust, non-blocking operations can be implemented using async-await. Async-await works by transforming each async function into an object called a future. When a future blocks on I/O the future yields, and the scheduler, called an executor, can select a different future to execute. Compared to alternatives such as an RTOS, async can yield better performance and lower power consumption because the executor doesn't have to guess when a future is ready to execute. However, program size may be higher than other alternatives, which may be a problem for certain space-constrained devices with very low memory. On the devices Embassy supports, such as stm32 and nrf, memory is generally large enough to accommodate the modestly-increased program size.
Async-await works by transforming each async function into an object called a future. When a future blocks on I/O the future yields, and the scheduler, called an executor, can select a different future to execute. Compared to alternatives such as an RTOS, async can yield better performance and lower power consumption because the executor doesn't have to guess when a future is ready to execute. However, program size may be higher than other alternatives, which may be a problem for certain space-constrained devices with very low memory. On the devices Embassy supports, such as stm32 and nrf, memory is generally large enough to accommodate the modestly-increased program size.
== What is Embassy?
@ -22,13 +17,26 @@ The Embassy project consists of several crates that you can use together or inde
* **Hardware Abstraction Layers** - HALs implement safe, idiomatic Rust APIs to use the hardware capabilities, so raw register manipulation is not needed. The Embassy project maintains HALs for select hardware, but you can still use HALs from other projects with Embassy.
** link:https://docs.embassy.dev/embassy-stm32/[embassy-stm32], for all STM32 microcontroller families.
** link:https://docs.embassy.dev/embassy-nrf/[embassy-nrf], for the Nordic Semiconductor nRF52, nRF53, nRF91 series.
** link:https://docs.embassy.dev/embassy-rp/[embassy-rp], for the Raspberry Pi RP2040 microcontroller.
** link:https://github.com/esp-rs[esp-rs], for the Espressif Systems ESP32 series of chips.
+
NOTE: A common question is if one can use the Embassy HALs standalone. Yes, it is possible! There are no dependency on the executor within the HALs. You can even use them without async,
as they implement both the link:https://github.com/rust-embedded/embedded-hal[Embedded HAL] blocking and async traits.
* **Networking** - The link:https://docs.embassy.dev/embassy-net/[embassy-net] network stack implements extensive networking functionality, including Ethernet, IP, TCP, UDP, ICMP and DHCP. Async drastically simplifies managing timeouts and serving multiple connections concurrently.
* **Networking** - The link:https://docs.embassy.dev/embassy-net/[embassy-net] network stack implements extensive networking functionality, including Ethernet, IP, TCP, UDP, ICMP and DHCP. Async drastically simplifies managing timeouts and serving multiple connections concurrently. Several drivers for WiFi and Ethernet chips can be found.
* **Bluetooth** - The link:https://github.com/embassy-rs/nrf-softdevice[nrf-softdevice] crate provides Bluetooth Low Energy 4.x and 5.x support for nRF52 microcontrollers.
* **LoRa** - link:https://docs.embassy.dev/embassy-lora/[embassy-lora] supports LoRa networking on STM32WL wireless microcontrollers and Semtech SX127x transceivers.
* **LoRa** - link:https://github.com/embassy-rs/lora-phy[lora-phy] and link:https://docs.embassy.dev/embassy-lora/[embassy-lora] supports LoRa networking on a wide range of LoRa radios, fully integrated with a Rust link:https://github.com/ivajloip/rust-lorawan[LoRaWAN] implementation.
* **USB** - link:https://docs.embassy.dev/embassy-usb/[embassy-usb] implements a device-side USB stack. Implementations for common classes such as USB serial (CDC ACM) and USB HID are available, and a rich builder API allows building your own.
* **Bootloader and DFU** - link:https://github.com/embassy-rs/embassy/tree/master/embassy-boot[embassy-boot] is a lightweight bootloader supporting firmware application upgrades in a power-fail-safe way, with trial boots and rollbacks.
== Resources
For more reading material on async Rust and Embassy:
* link:https://tweedegolf.nl/en/blog/65/async-rust-vs-rtos-showdown[Comparsion of FreeRTOS and Embassy]
* link:https://dev.to/apollolabsbin/series/20707[Tutorials]
* link:https://blog.drogue.io/firmware-updates-part-1/[Firmware Updates with Embassy]

View File

@ -1,4 +1,4 @@
= Embassy layer by layer
= From bare metal to async Rust
If you're new to Embassy, it can be overwhelming to grasp all the terminology and concepts. This guide aims to clarify the different layers in Embassy, which problem each layer solves for the application writer.
@ -8,8 +8,7 @@ The application we'll write is a simple 'push button, blink led' application, wh
== PAC version
The PAC is the lowest API for accessing peripherals and registers, if you don't count reading/writing directly to memory addresses. It provides distinct types
to make accessing peripheral registers easier, but it does not prevent you from writing unsafe code.
The PAC is the lowest API for accessing peripherals and registers, if you don't count reading/writing directly to memory addresses. It provides distinct types to make accessing peripheral registers easier, but it does not prevent you from writing unsafe code.
Writing an application using the PAC directly is therefore not recommended, but if the functionality you want to use is not exposed in the upper layers, that's what you need to use.

View File

@ -8,7 +8,7 @@ The nRF timer driver operates at 32768 Hz by default.
== Peripherals
The following peripherals have a HAL implementation at present:
The following peripherals have a HAL implementation at present
* PWM
* SPIM
@ -23,3 +23,7 @@ The following peripherals have a HAL implementation at present:
* UARTE
* TWIM
* SAADC
== Bluetooth
For bluetooth, you can use the link:https://github.com/embassy-rs/nrf-softdevice[nrf-softdevice] crate.

View File

@ -10,7 +10,7 @@ The Embassy executor is an async/await executor designed for embedded usage alon
* No busy-loop polling: CPU sleeps when there's no work to do, using interrupts or `WFE/SEV`.
* Efficient polling: a wake will only poll the woken task, not all of them.
* Fair: a task can't monopolize CPU time even if it's constantly being woken. All other tasks get a chance to run before a given task gets polled for the second time.
* Creating multiple executor instances is supported, to run tasks with multiple priority levels. This allows higher-priority tasks to preempt lower-priority tasks.
* Creating multiple executor instances is supported, to run tasks at different priority levels. This allows higher-priority tasks to preempt lower-priority tasks.
== Executor

View File

@ -1,5 +1,5 @@
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(feature = "nightly", feature(async_fn_in_trait, impl_trait_projections, try_blocks))]
#![cfg_attr(feature = "nightly", feature(async_fn_in_trait, try_blocks))]
#![warn(missing_docs)]
//! Utilities to use `embedded-hal` traits with Embassy.
@ -26,6 +26,18 @@ pub trait SetConfig {
/// The configuration type used by this driver.
type Config;
/// The error type that can occur if `set_config` fails.
type ConfigError;
/// Set the configuration of the driver.
fn set_config(&mut self, config: &Self::Config);
fn set_config(&mut self, config: &Self::Config) -> Result<(), Self::ConfigError>;
}
/// Get the configuration of a peripheral driver.
pub trait GetConfig {
/// The configuration type used by this driver.
type Config;
/// Get the configuration of the driver.
fn get_config(&self) -> Self::Config;
}

View File

@ -125,14 +125,14 @@ where
{
async fn read(&mut self, address: u8, buffer: &mut [u8]) -> Result<(), I2cDeviceError<BUS::Error>> {
let mut bus = self.bus.lock().await;
bus.set_config(&self.config);
bus.set_config(&self.config).map_err(|_| I2cDeviceError::Config)?;
bus.read(address, buffer).await.map_err(I2cDeviceError::I2c)?;
Ok(())
}
async fn write(&mut self, address: u8, bytes: &[u8]) -> Result<(), I2cDeviceError<BUS::Error>> {
let mut bus = self.bus.lock().await;
bus.set_config(&self.config);
bus.set_config(&self.config).map_err(|_| I2cDeviceError::Config)?;
bus.write(address, bytes).await.map_err(I2cDeviceError::I2c)?;
Ok(())
}
@ -144,7 +144,7 @@ where
rd_buffer: &mut [u8],
) -> Result<(), I2cDeviceError<BUS::Error>> {
let mut bus = self.bus.lock().await;
bus.set_config(&self.config);
bus.set_config(&self.config).map_err(|_| I2cDeviceError::Config)?;
bus.write_read(address, wr_buffer, rd_buffer)
.await
.map_err(I2cDeviceError::I2c)?;
@ -153,7 +153,7 @@ where
async fn transaction(&mut self, address: u8, operations: &mut [i2c::Operation<'_>]) -> Result<(), Self::Error> {
let mut bus = self.bus.lock().await;
bus.set_config(&self.config);
bus.set_config(&self.config).map_err(|_| I2cDeviceError::Config)?;
bus.transaction(address, operations)
.await
.map_err(I2cDeviceError::I2c)?;

View File

@ -130,7 +130,7 @@ where
{
async fn transaction(&mut self, operations: &mut [spi::Operation<'_, u8>]) -> Result<(), Self::Error> {
let mut bus = self.bus.lock().await;
bus.set_config(&self.config);
bus.set_config(&self.config).map_err(|_| SpiDeviceError::Config)?;
self.cs.set_low().map_err(SpiDeviceError::Cs)?;
let op_res: Result<(), BUS::Error> = try {

View File

@ -148,7 +148,7 @@ where
fn read(&mut self, address: u8, buffer: &mut [u8]) -> Result<(), Self::Error> {
self.bus.lock(|bus| {
let mut bus = bus.borrow_mut();
bus.set_config(&self.config);
bus.set_config(&self.config).map_err(|_| I2cDeviceError::Config)?;
bus.read(address, buffer).map_err(I2cDeviceError::I2c)
})
}
@ -156,7 +156,7 @@ where
fn write(&mut self, address: u8, bytes: &[u8]) -> Result<(), Self::Error> {
self.bus.lock(|bus| {
let mut bus = bus.borrow_mut();
bus.set_config(&self.config);
bus.set_config(&self.config).map_err(|_| I2cDeviceError::Config)?;
bus.write(address, bytes).map_err(I2cDeviceError::I2c)
})
}
@ -164,7 +164,7 @@ where
fn write_read(&mut self, address: u8, wr_buffer: &[u8], rd_buffer: &mut [u8]) -> Result<(), Self::Error> {
self.bus.lock(|bus| {
let mut bus = bus.borrow_mut();
bus.set_config(&self.config);
bus.set_config(&self.config).map_err(|_| I2cDeviceError::Config)?;
bus.write_read(address, wr_buffer, rd_buffer)
.map_err(I2cDeviceError::I2c)
})

View File

@ -163,7 +163,7 @@ where
fn transaction(&mut self, operations: &mut [Operation<'_, u8>]) -> Result<(), Self::Error> {
self.bus.lock(|bus| {
let mut bus = bus.borrow_mut();
bus.set_config(&self.config);
bus.set_config(&self.config).map_err(|_| SpiDeviceError::Config)?;
self.cs.set_low().map_err(SpiDeviceError::Cs)?;
let op_res = operations.iter_mut().try_for_each(|op| match op {

View File

@ -14,6 +14,8 @@ pub mod blocking;
pub enum I2cDeviceError<BUS> {
/// An operation on the inner I2C bus failed.
I2c(BUS),
/// Configuration of the inner I2C bus failed.
Config,
}
impl<BUS> i2c::Error for I2cDeviceError<BUS>
@ -23,6 +25,7 @@ where
fn kind(&self) -> i2c::ErrorKind {
match self {
Self::I2c(e) => e.kind(),
Self::Config => i2c::ErrorKind::Other,
}
}
}
@ -38,6 +41,8 @@ pub enum SpiDeviceError<BUS, CS> {
Cs(CS),
/// DelayUs operations are not supported when the `time` Cargo feature is not enabled.
DelayUsNotSupported,
/// The SPI bus could not be configured.
Config,
}
impl<BUS, CS> spi::Error for SpiDeviceError<BUS, CS>
@ -50,6 +55,7 @@ where
Self::Spi(e) => e.kind(),
Self::Cs(_) => spi::ErrorKind::Other,
Self::DelayUsNotSupported => spi::ErrorKind::Other,
Self::Config => spi::ErrorKind::Other,
}
}
}

View File

@ -73,9 +73,10 @@ mod thread {
pub fn start(&'static mut self, init: impl FnOnce(Spawner)) {
unsafe {
let executor = &self.inner;
self.ctx.closure.write(Closure::new(move |_| {
let future = Closure::new(move |_| {
executor.poll();
}));
});
self.ctx.closure.write_in_place(|| future);
init(self.inner.spawner());
}
}

View File

@ -203,7 +203,7 @@ impl<F: Future + 'static> AvailableTask<F> {
fn initialize_impl<S>(self, future: impl FnOnce() -> F) -> SpawnToken<S> {
unsafe {
self.task.raw.poll_fn.set(Some(TaskStorage::<F>::poll));
self.task.future.write(future());
self.task.future.write_in_place(future);
let task = TaskRef::new(self.task);

View File

@ -17,8 +17,9 @@ impl<T> UninitCell<T> {
&mut *self.as_mut_ptr()
}
pub unsafe fn write(&self, val: T) {
ptr::write(self.as_mut_ptr(), val)
#[inline(never)]
pub unsafe fn write_in_place(&self, func: impl FnOnce() -> T) {
ptr::write(self.as_mut_ptr(), func())
}
pub unsafe fn drop_in_place(&self) {

View File

@ -27,8 +27,5 @@ embedded-hal-async = { version = "=1.0.0-rc.1" }
embedded-hal = { version = "0.2", features = ["unproven"] }
futures = { version = "0.3.17", default-features = false, features = [ "async-await" ] }
lora-phy = { version = "1" }
lorawan-device = { version = "0.10.0", default-features = false, features = ["async"], optional = true }
[patch.crates-io]
lora-phy = { git = "https://github.com/embassy-rs/lora-phy", rev = "1323eccc1c470d4259f95f4f315d1be830d572a3"}
lora-phy = { version = "2" }
lorawan-device = { version = "0.11.0", default-features = false, features = ["async"], optional = true }

View File

@ -67,24 +67,20 @@ where
self.board_type = board_type;
}
async fn set_nss_low(&mut self) -> Result<(), RadioError> {
let pwr = pac::PWR;
pwr.subghzspicr().modify(|w| w.set_nss(pac::pwr::vals::Nss::LOW));
pac::PWR.subghzspicr().modify(|w| w.set_nss(false));
Ok(())
}
async fn set_nss_high(&mut self) -> Result<(), RadioError> {
let pwr = pac::PWR;
pwr.subghzspicr().modify(|w| w.set_nss(pac::pwr::vals::Nss::HIGH));
pac::PWR.subghzspicr().modify(|w| w.set_nss(true));
Ok(())
}
async fn reset(&mut self, _delay: &mut impl DelayUs) -> Result<(), RadioError> {
let rcc = pac::RCC;
rcc.csr().modify(|w| w.set_rfrst(true));
rcc.csr().modify(|w| w.set_rfrst(false));
pac::RCC.csr().modify(|w| w.set_rfrst(true));
pac::RCC.csr().modify(|w| w.set_rfrst(false));
Ok(())
}
async fn wait_on_busy(&mut self) -> Result<(), RadioError> {
let pwr = pac::PWR;
while pwr.sr2().read().rfbusys() == pac::pwr::vals::Rfbusys::BUSY {}
while pac::PWR.sr2().read().rfbusys() {}
Ok(())
}

View File

@ -1,5 +1,5 @@
#![no_std]
#![feature(async_fn_in_trait, impl_trait_projections)]
#![feature(async_fn_in_trait)]
//! embassy-lora holds LoRa-specific functionality.
pub(crate) mod fmt;

View File

@ -194,10 +194,15 @@ where
self.bit_field_set(common::Register::ECON1, common::ECON1::mask().rxen());
}
/// Returns the device's MAC address
pub fn address(&self) -> [u8; 6] {
self.mac_addr
}
/// Flushes the transmit buffer, ensuring all pending transmissions have completed
/// NOTE: The returned packet *must* be `read` or `ignore`-d, otherwise this method will always
/// return `None` on subsequent invocations
pub fn receive<'a>(&mut self, buf: &'a mut [u8]) -> Option<&'a mut [u8]> {
pub fn receive(&mut self, buf: &mut [u8]) -> Option<usize> {
if self.pending_packets() == 0 {
// Errata #6: we can't rely on PKTIF so we check PKTCNT
return None;
@ -241,7 +246,7 @@ where
self.next_packet = next_packet;
Some(&mut buf[..len as usize])
Some(len as usize)
}
fn wait_tx_ready(&mut self) {
@ -642,9 +647,8 @@ where
fn receive(&mut self, cx: &mut core::task::Context) -> Option<(Self::RxToken<'_>, Self::TxToken<'_>)> {
let rx_buf = unsafe { &mut RX_BUF };
let tx_buf = unsafe { &mut TX_BUF };
if let Some(pkt) = self.receive(rx_buf) {
let n = pkt.len();
Some((RxToken { buf: &mut pkt[..n] }, TxToken { buf: tx_buf, eth: self }))
if let Some(n) = self.receive(rx_buf) {
Some((RxToken { buf: &mut rx_buf[..n] }, TxToken { buf: tx_buf, eth: self }))
} else {
cx.waker().wake_by_ref();
None

View File

@ -1,5 +1,5 @@
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(feature = "nightly", feature(async_fn_in_trait, impl_trait_projections))]
#![cfg_attr(feature = "nightly", feature(async_fn_in_trait))]
#![warn(missing_docs)]
#![doc = include_str!("../README.md")]
@ -258,7 +258,7 @@ fn to_smoltcp_hardware_address(addr: driver::HardwareAddress) -> HardwareAddress
}
}
impl<D: Driver + 'static> Stack<D> {
impl<D: Driver> Stack<D> {
/// Create a new network stack.
pub fn new<const SOCK: usize>(
mut device: D,
@ -555,7 +555,7 @@ impl<D: Driver + 'static> Stack<D> {
}
#[cfg(feature = "igmp")]
impl<D: Driver + 'static> Stack<D> {
impl<D: Driver> Stack<D> {
/// Join a multicast group.
pub async fn join_multicast_group<T>(&self, addr: T) -> Result<bool, MulticastError>
where
@ -645,7 +645,7 @@ impl SocketStack {
}
}
impl<D: Driver + 'static> Inner<D> {
impl<D: Driver> Inner<D> {
#[cfg(feature = "proto-ipv4")]
pub fn set_config_v4(&mut self, _s: &mut SocketStack, config: ConfigV4) {
// Handle static config.

View File

@ -51,7 +51,7 @@ nrf52805 = ["nrf52805-pac", "_nrf52"]
nrf52810 = ["nrf52810-pac", "_nrf52"]
nrf52811 = ["nrf52811-pac", "_nrf52"]
nrf52820 = ["nrf52820-pac", "_nrf52"]
nrf52832 = ["nrf52832-pac", "_nrf52"]
nrf52832 = ["nrf52832-pac", "_nrf52", "_nrf52832_anomaly_109"]
nrf52833 = ["nrf52833-pac", "_nrf52", "_gpio-p1"]
nrf52840 = ["nrf52840-pac", "_nrf52", "_gpio-p1"]
nrf5340-app-s = ["_nrf5340-app", "_s"]
@ -90,6 +90,9 @@ _ppi = []
_dppi = []
_gpio-p1 = []
# Errata workarounds
_nrf52832_anomaly_109 = []
[dependencies]
embassy-time = { version = "0.1.3", path = "../embassy-time", optional = true }
embassy-sync = { version = "0.3.0", path = "../embassy-sync" }

View File

@ -1,5 +1,5 @@
#![no_std]
#![cfg_attr(feature = "nightly", feature(async_fn_in_trait, impl_trait_projections))]
#![cfg_attr(feature = "nightly", feature(async_fn_in_trait))]
#![doc = include_str!("../README.md")]
#![warn(missing_docs)]
@ -102,6 +102,7 @@ mod chip;
#[macro_export]
macro_rules! bind_interrupts {
($vis:vis struct $name:ident { $($irq:ident => $($handler:ty),*;)* }) => {
#[derive(Copy, Clone)]
$vis struct $name;
$(

View File

@ -68,30 +68,14 @@ impl<T: Instance> interrupt::typelevel::Handler<T::Interrupt> for InterruptHandl
let r = T::regs();
let s = T::state();
#[cfg(feature = "nrf52832")]
// NRF32 Anomaly 109 workaround... NRF52832
if r.intenset.read().started().is_enabled() && r.events_started.read().bits() != 0 {
// Handle the first "fake" transmission
r.events_started.reset();
r.events_end.reset();
// Update DMA registers with correct rx/tx buffer sizes
r.rxd
.maxcnt
.write(|w| unsafe { w.maxcnt().bits(s.rx.load(Ordering::Relaxed)) });
r.txd
.maxcnt
.write(|w| unsafe { w.maxcnt().bits(s.tx.load(Ordering::Relaxed)) });
// Disable interrupt for STARTED event...
#[cfg(feature = "_nrf52832_anomaly_109")]
if r.events_started.read().bits() != 0 {
s.waker.wake();
r.intenclr.write(|w| w.started().clear());
// ... and start actual, hopefully glitch-free transmission
r.tasks_start.write(|w| unsafe { w.bits(1) });
return;
}
if r.events_end.read().bits() != 0 {
s.end_waker.wake();
s.waker.wake();
r.intenclr.write(|w| w.end().clear());
}
}
@ -192,7 +176,7 @@ impl<'d, T: Instance> Spim<'d, T> {
let mut spim = Self { _p: spim };
// Apply runtime peripheral configuration
Self::set_config(&mut spim, &config);
Self::set_config(&mut spim, &config).unwrap();
// Disable all events interrupts
r.intenclr.write(|w| unsafe { w.bits(0xFFFF_FFFF) });
@ -222,8 +206,7 @@ impl<'d, T: Instance> Spim<'d, T> {
r.rxd.ptr.write(|w| unsafe { w.ptr().bits(ptr as _) });
r.rxd.maxcnt.write(|w| unsafe { w.maxcnt().bits(rx_len as _) });
// ANOMALY 109 workaround
#[cfg(feature = "nrf52832")]
#[cfg(feature = "_nrf52832_anomaly_109")]
{
let s = T::state();
@ -254,6 +237,9 @@ impl<'d, T: Instance> Spim<'d, T> {
fn blocking_inner_from_ram(&mut self, rx: *mut [u8], tx: *const [u8]) -> Result<(), Error> {
self.prepare(rx, tx)?;
#[cfg(feature = "_nrf52832_anomaly_109")]
while let Poll::Pending = self.nrf52832_dma_workaround_status() {}
// Wait for 'end' event.
while T::regs().events_end.read().bits() == 0 {}
@ -278,9 +264,19 @@ impl<'d, T: Instance> Spim<'d, T> {
async fn async_inner_from_ram(&mut self, rx: *mut [u8], tx: *const [u8]) -> Result<(), Error> {
self.prepare(rx, tx)?;
#[cfg(feature = "_nrf52832_anomaly_109")]
poll_fn(|cx| {
let s = T::state();
s.waker.register(cx.waker());
self.nrf52832_dma_workaround_status()
})
.await;
// Wait for 'end' event.
poll_fn(|cx| {
T::state().end_waker.register(cx.waker());
T::state().waker.register(cx.waker());
if T::regs().events_end.read().bits() != 0 {
return Poll::Ready(());
}
@ -371,6 +367,32 @@ impl<'d, T: Instance> Spim<'d, T> {
pub async fn write_from_ram(&mut self, data: &[u8]) -> Result<(), Error> {
self.async_inner_from_ram(&mut [], data).await
}
#[cfg(feature = "_nrf52832_anomaly_109")]
fn nrf52832_dma_workaround_status(&mut self) -> Poll<()> {
let r = T::regs();
if r.events_started.read().bits() != 0 {
let s = T::state();
// Handle the first "fake" transmission
r.events_started.reset();
r.events_end.reset();
// Update DMA registers with correct rx/tx buffer sizes
r.rxd
.maxcnt
.write(|w| unsafe { w.maxcnt().bits(s.rx.load(Ordering::Relaxed)) });
r.txd
.maxcnt
.write(|w| unsafe { w.maxcnt().bits(s.tx.load(Ordering::Relaxed)) });
r.intenset.write(|w| w.end().set());
// ... and start actual, hopefully glitch-free transmission
r.tasks_start.write(|w| unsafe { w.bits(1) });
return Poll::Ready(());
}
Poll::Pending
}
}
impl<'d, T: Instance> Drop for Spim<'d, T> {
@ -395,7 +417,7 @@ impl<'d, T: Instance> Drop for Spim<'d, T> {
}
pub(crate) mod sealed {
#[cfg(feature = "nrf52832")]
#[cfg(feature = "_nrf52832_anomaly_109")]
use core::sync::atomic::AtomicU8;
use embassy_sync::waitqueue::AtomicWaker;
@ -403,20 +425,20 @@ pub(crate) mod sealed {
use super::*;
pub struct State {
pub end_waker: AtomicWaker,
#[cfg(feature = "nrf52832")]
pub waker: AtomicWaker,
#[cfg(feature = "_nrf52832_anomaly_109")]
pub rx: AtomicU8,
#[cfg(feature = "nrf52832")]
#[cfg(feature = "_nrf52832_anomaly_109")]
pub tx: AtomicU8,
}
impl State {
pub const fn new() -> Self {
Self {
end_waker: AtomicWaker::new(),
#[cfg(feature = "nrf52832")]
waker: AtomicWaker::new(),
#[cfg(feature = "_nrf52832_anomaly_109")]
rx: AtomicU8::new(0),
#[cfg(feature = "nrf52832")]
#[cfg(feature = "_nrf52832_anomaly_109")]
tx: AtomicU8::new(0),
}
}
@ -544,7 +566,8 @@ mod eha {
impl<'d, T: Instance> SetConfig for Spim<'d, T> {
type Config = Config;
fn set_config(&mut self, config: &Self::Config) {
type ConfigError = ();
fn set_config(&mut self, config: &Self::Config) -> Result<(), Self::ConfigError> {
let r = T::regs();
// Configure mode.
let mode = config.mode;
@ -582,5 +605,7 @@ impl<'d, T: Instance> SetConfig for Spim<'d, T> {
// Set over-read character
let orc = config.orc;
r.orc.write(|w| unsafe { w.orc().bits(orc) });
Ok(())
}
}

View File

@ -172,7 +172,7 @@ impl<'d, T: Instance> Spis<'d, T> {
let mut spis = Self { _p: spis };
// Apply runtime peripheral configuration
Self::set_config(&mut spis, &config);
Self::set_config(&mut spis, &config).unwrap();
// Disable all events interrupts.
r.intenclr.write(|w| unsafe { w.bits(0xFFFF_FFFF) });
@ -467,7 +467,8 @@ macro_rules! impl_spis {
impl<'d, T: Instance> SetConfig for Spis<'d, T> {
type Config = Config;
fn set_config(&mut self, config: &Self::Config) {
type ConfigError = ();
fn set_config(&mut self, config: &Self::Config) -> Result<(), Self::ConfigError> {
let r = T::regs();
// Configure mode.
let mode = config.mode;
@ -509,5 +510,7 @@ impl<'d, T: Instance> SetConfig for Spis<'d, T> {
// Configure auto-acquire on 'transfer end' event.
let auto_acquire = config.auto_acquire;
r.shorts.write(|w| w.end_acquire().bit(auto_acquire));
Ok(())
}
}

View File

@ -170,7 +170,7 @@ impl<'d, T: Instance> Twim<'d, T> {
let mut twim = Self { _p: twim };
// Apply runtime peripheral configuration
Self::set_config(&mut twim, &config);
Self::set_config(&mut twim, &config).unwrap();
// Disable all events interrupts
r.intenclr.write(|w| unsafe { w.bits(0xFFFF_FFFF) });
@ -890,9 +890,12 @@ mod eha {
impl<'d, T: Instance> SetConfig for Twim<'d, T> {
type Config = Config;
fn set_config(&mut self, config: &Self::Config) {
type ConfigError = ();
fn set_config(&mut self, config: &Self::Config) -> Result<(), Self::ConfigError> {
let r = T::regs();
r.frequency
.write(|w| unsafe { w.frequency().bits(config.frequency as u32) });
Ok(())
}
}

View File

@ -89,7 +89,6 @@ embedded-hal-1 = { package = "embedded-hal", version = "=1.0.0-rc.1", optional =
embedded-hal-async = { version = "=1.0.0-rc.1", optional = true}
embedded-hal-nb = { version = "=1.0.0-rc.1", optional = true}
paste = "1.0"
pio-proc = {version= "0.2" }
pio = {version= "0.2.1" }
rp2040-boot2 = "0.3"

View File

@ -97,6 +97,12 @@ impl<'d, T: Pin> Input<'d, T> {
Self { pin }
}
/// Set the pin's Schmitt trigger.
#[inline]
pub fn set_schmitt(&mut self, enable: bool) {
self.pin.set_schmitt(enable)
}
#[inline]
pub fn is_high(&self) -> bool {
self.pin.is_high()
@ -216,7 +222,6 @@ fn IO_IRQ_QSPI() {
#[must_use = "futures do nothing unless you `.await` or poll them"]
struct InputFuture<'a, T: Pin> {
pin: PeripheralRef<'a, T>,
level: InterruptTrigger,
}
impl<'d, T: Pin> InputFuture<'d, T> {
@ -243,7 +248,6 @@ impl<'d, T: Pin> InputFuture<'d, T> {
.inte((pin.pin() / 8) as usize)
.write_set(|w| match level {
InterruptTrigger::LevelHigh => {
trace!("InputFuture::new enable LevelHigh for pin {}", pin.pin());
w.set_level_high(pin_group, true);
}
InterruptTrigger::LevelLow => {
@ -261,7 +265,7 @@ impl<'d, T: Pin> InputFuture<'d, T> {
}
});
Self { pin, level }
Self { pin }
}
}
@ -297,14 +301,8 @@ impl<'d, T: Pin> Future for InputFuture<'d, T> {
&& !inte.level_high(pin_group)
&& !inte.level_low(pin_group)
{
trace!(
"{:?} for pin {} was cleared, return Poll::Ready",
self.level,
self.pin.pin()
);
return Poll::Ready(());
}
trace!("InputFuture::poll return Poll::Pending");
Poll::Pending
}
}
@ -326,6 +324,18 @@ impl<'d, T: Pin> Output<'d, T> {
Self { pin }
}
/// Set the pin's drive strength.
#[inline]
pub fn set_drive_strength(&mut self, strength: Drive) {
self.pin.set_drive_strength(strength)
}
// Set the pin's slew rate.
#[inline]
pub fn set_slew_rate(&mut self, slew_rate: SlewRate) {
self.pin.set_slew_rate(slew_rate)
}
/// Set the output as high.
#[inline]
pub fn set_high(&mut self) {
@ -386,6 +396,18 @@ impl<'d, T: Pin> OutputOpenDrain<'d, T> {
Self { pin }
}
/// Set the pin's drive strength.
#[inline]
pub fn set_drive_strength(&mut self, strength: Drive) {
self.pin.set_drive_strength(strength)
}
// Set the pin's slew rate.
#[inline]
pub fn set_slew_rate(&mut self, slew_rate: SlewRate) {
self.pin.set_slew_rate(slew_rate)
}
/// Set the output as high.
#[inline]
pub fn set_high(&mut self) {
@ -541,6 +563,14 @@ impl<'d, T: Pin> Flex<'d, T> {
});
}
/// Set the pin's Schmitt trigger.
#[inline]
pub fn set_schmitt(&mut self, enable: bool) {
self.pin.pad_ctrl().modify(|w| {
w.set_schmitt(enable);
});
}
/// Put the pin into input mode.
///
/// The pull setting is left unchanged.

View File

@ -1,5 +1,5 @@
#![no_std]
#![cfg_attr(feature = "nightly", feature(async_fn_in_trait, impl_trait_projections))]
#![cfg_attr(feature = "nightly", feature(async_fn_in_trait))]
// This mod MUST go first, so that the others see its macros.
pub(crate) mod fmt;
@ -90,7 +90,8 @@ embassy_hal_internal::interrupt_mod!(
#[macro_export]
macro_rules! bind_interrupts {
($vis:vis struct $name:ident { $($irq:ident => $($handler:ty),*;)* }) => {
$vis struct $name;
#[derive(Copy, Clone)]
$vis struct $name;
$(
#[allow(non_snake_case)]

View File

@ -1079,18 +1079,43 @@ impl_pio!(PIO1, 1, PIO1, PIO1_0, PIO1_IRQ_0);
pub trait PioPin: sealed::PioPin + gpio::Pin {}
macro_rules! impl_pio_pin {
($( $num:tt )*) => {
($( $pin:ident, )*) => {
$(
paste::paste!{
impl sealed::PioPin for peripherals::[< PIN_ $num >] {}
impl PioPin for peripherals::[< PIN_ $num >] {}
}
impl sealed::PioPin for peripherals::$pin {}
impl PioPin for peripherals::$pin {}
)*
};
}
impl_pio_pin! {
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
PIN_0,
PIN_1,
PIN_2,
PIN_3,
PIN_4,
PIN_5,
PIN_6,
PIN_7,
PIN_8,
PIN_9,
PIN_10,
PIN_11,
PIN_12,
PIN_13,
PIN_14,
PIN_15,
PIN_16,
PIN_17,
PIN_18,
PIN_19,
PIN_20,
PIN_21,
PIN_22,
PIN_23,
PIN_24,
PIN_25,
PIN_26,
PIN_27,
PIN_28,
PIN_29,
}

View File

@ -597,7 +597,8 @@ mod eha {
impl<'d, T: Instance, M: Mode> SetConfig for Spi<'d, T, M> {
type Config = Config;
fn set_config(&mut self, config: &Self::Config) {
type ConfigError = ();
fn set_config(&mut self, config: &Self::Config) -> Result<(), ()> {
let p = self.inner.regs();
let (presc, postdiv) = calc_prescs(config.frequency);
p.cpsr().write(|w| w.set_cpsdvsr(presc));
@ -607,5 +608,7 @@ impl<'d, T: Instance, M: Mode> SetConfig for Spi<'d, T, M> {
w.set_sph(config.phase == Phase::CaptureOnSecondTransition);
w.set_scr(postdiv);
});
Ok(())
}
}

View File

@ -490,8 +490,6 @@ impl<T: Instance> interrupt::typelevel::Handler<T::Interrupt> for BufferedInterr
w.set_oeic(ris.oeris());
});
trace!("on_interrupt ris={:#X}", ris.0);
// Errors
if ris.feris() {
warn!("Framing error");

View File

@ -1,4 +1,3 @@
use core::marker::PhantomData;
use core::ptr;
use embassy_stm32::ipcc::Ipcc;
@ -13,7 +12,7 @@ use crate::unsafe_linked_list::LinkedListNode;
use crate::{channels, evt};
pub struct Ble {
phantom: PhantomData<Ble>,
_private: (),
}
impl Ble {
@ -29,7 +28,7 @@ impl Ble {
});
}
Self { phantom: PhantomData }
Self { _private: () }
}
/// `HW_IPCC_BLE_EvtNot`
pub async fn tl_read(&self) -> EvtBox<Self> {

View File

@ -1,5 +1,4 @@
use core::future::poll_fn;
use core::marker::PhantomData;
use core::ptr;
use core::sync::atomic::{AtomicBool, Ordering};
use core::task::Poll;
@ -21,12 +20,12 @@ static MAC_WAKER: AtomicWaker = AtomicWaker::new();
static MAC_EVT_OUT: AtomicBool = AtomicBool::new(false);
pub struct Mac {
phantom: PhantomData<Mac>,
_private: (),
}
impl Mac {
pub(crate) fn new() -> Self {
Self { phantom: PhantomData }
Self { _private: () }
}
/// `HW_IPCC_MAC_802_15_4_EvtNot`

View File

@ -1,6 +1,5 @@
//! Memory manager routines
use core::future::poll_fn;
use core::marker::PhantomData;
use core::mem::MaybeUninit;
use core::task::Poll;
@ -21,7 +20,7 @@ static MM_WAKER: AtomicWaker = AtomicWaker::new();
static mut LOCAL_FREE_BUF_QUEUE: Aligned<A4, MaybeUninit<LinkedListNode>> = Aligned(MaybeUninit::uninit());
pub struct MemoryManager {
phantom: PhantomData<MemoryManager>,
_private: (),
}
impl MemoryManager {
@ -44,7 +43,7 @@ impl MemoryManager {
});
}
Self { phantom: PhantomData }
Self { _private: () }
}
pub async fn run_queue(&self) {

View File

@ -1,4 +1,3 @@
use core::marker::PhantomData;
use core::ptr;
use crate::cmd::CmdPacket;
@ -12,7 +11,7 @@ use crate::unsafe_linked_list::LinkedListNode;
use crate::{channels, Ipcc, SYSTEM_EVT_QUEUE, SYS_CMD_BUF, TL_DEVICE_INFO_TABLE, TL_SYS_TABLE};
pub struct Sys {
phantom: PhantomData<Sys>,
_private: (),
}
impl Sys {
@ -27,7 +26,7 @@ impl Sys {
});
}
Self { phantom: PhantomData }
Self { _private: () }
}
/// Returns CPU2 wireless firmware information (if present).

View File

@ -21,12 +21,13 @@ flavors = [
{ regex_feature = "stm32g4.*", target = "thumbv7em-none-eabi" },
{ regex_feature = "stm32h5.*", target = "thumbv8m.main-none-eabihf" },
{ regex_feature = "stm32h7.*", target = "thumbv7em-none-eabi" },
{ regex_feature = "stm32l0.*", target = "thumbv6m-none-eabi" },
{ regex_feature = "stm32l0.*", target = "thumbv6m-none-eabi", features = ["low-power"] },
{ regex_feature = "stm32l1.*", target = "thumbv7m-none-eabi" },
{ regex_feature = "stm32l4.*", target = "thumbv7em-none-eabi" },
{ regex_feature = "stm32l5.*", target = "thumbv8m.main-none-eabihf" },
{ regex_feature = "stm32u5.*", target = "thumbv8m.main-none-eabihf" },
{ regex_feature = "stm32wb.*", target = "thumbv7em-none-eabi" },
{ regex_feature = "stm32wba.*", target = "thumbv8m.main-none-eabihf" },
{ regex_feature = "stm32wl.*", target = "thumbv7em-none-eabi" },
]
@ -58,7 +59,7 @@ sdio-host = "0.5.0"
embedded-sdmmc = { git = "https://github.com/embassy-rs/embedded-sdmmc-rs", rev = "a4f293d3a6f72158385f79c98634cb8a14d0d2fc", optional = true }
critical-section = "1.1"
atomic-polyfill = "1.0.1"
stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-4e6a74f69c4bc5d2d4872ba50d805e75bfe55cad" }
stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-06d13dfd245cc9bf86fd88c35b401bdb84c079c4" }
vcell = "0.1.3"
bxcan = "0.7.0"
nb = "1.0.0"
@ -77,7 +78,8 @@ critical-section = { version = "1.1", features = ["std"] }
[build-dependencies]
proc-macro2 = "1.0.36"
quote = "1.0.15"
stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-4e6a74f69c4bc5d2d4872ba50d805e75bfe55cad", default-features = false, features = ["metadata"]}
stm32-metapac = { git = "https://github.com/embassy-rs/stm32-data-generated", tag = "stm32-data-06d13dfd245cc9bf86fd88c35b401bdb84c079c4", default-features = false, features = ["metadata"]}
[features]
default = ["rt"]
@ -133,6 +135,22 @@ time-driver-tim12 = ["_time-driver"]
time-driver-tim15 = ["_time-driver"]
#! ## Analog Switch Pins (Pxy_C) on STM32H7 series
#! Get `PXY` and `PXY_C` singletons. Digital impls are on `PXY`, Analog impls are on `PXY_C`
#! If disabled, you get only the `PXY` singleton. It has both digital and analog impls.
## Split PA0
split-pa0 = ["_split-pins-enabled"]
## Split PA1
split-pa1 = ["_split-pins-enabled"]
## Split PC2
split-pc2 = ["_split-pins-enabled"]
## Split PC3
split-pc3 = ["_split-pins-enabled"]
## internal use only
_split-pins-enabled = []
#! ## Chip-selection features
#! Select your chip by specifying the model as a feature, e.g. `stm32c011d6`.
#! Check the `Cargo.toml` for the latest list of supported chips.
@ -1454,6 +1472,10 @@ stm32wb55vc = [ "stm32-metapac/stm32wb55vc" ]
stm32wb55ve = [ "stm32-metapac/stm32wb55ve" ]
stm32wb55vg = [ "stm32-metapac/stm32wb55vg" ]
stm32wb55vy = [ "stm32-metapac/stm32wb55vy" ]
stm32wba52ce = [ "stm32-metapac/stm32wba52ce" ]
stm32wba52cg = [ "stm32-metapac/stm32wba52cg" ]
stm32wba52ke = [ "stm32-metapac/stm32wba52ke" ]
stm32wba52kg = [ "stm32-metapac/stm32wba52kg" ]
stm32wl54cc-cm4 = [ "stm32-metapac/stm32wl54cc-cm4" ]
stm32wl54cc-cm0p = [ "stm32-metapac/stm32wl54cc-cm0p" ]
stm32wl54jc-cm4 = [ "stm32-metapac/stm32wl54jc-cm4" ]

View File

@ -81,6 +81,60 @@ fn main() {
singletons.push(c.name.to_string());
}
let mut pin_set = std::collections::HashSet::new();
for p in METADATA.peripherals {
for pin in p.pins {
pin_set.insert(pin.pin);
}
}
struct SplitFeature {
feature_name: String,
pin_name_with_c: String,
#[cfg(feature = "_split-pins-enabled")]
pin_name_without_c: String,
}
// Extra analog switch pins available on most H7 chips
let split_features: Vec<SplitFeature> = vec![
#[cfg(feature = "split-pa0")]
SplitFeature {
feature_name: "split-pa0".to_string(),
pin_name_with_c: "PA0_C".to_string(),
pin_name_without_c: "PA0".to_string(),
},
#[cfg(feature = "split-pa1")]
SplitFeature {
feature_name: "split-pa1".to_string(),
pin_name_with_c: "PA1_C".to_string(),
pin_name_without_c: "PA1".to_string(),
},
#[cfg(feature = "split-pc2")]
SplitFeature {
feature_name: "split-pc2".to_string(),
pin_name_with_c: "PC2_C".to_string(),
pin_name_without_c: "PC2".to_string(),
},
#[cfg(feature = "split-pc3")]
SplitFeature {
feature_name: "split-pc3".to_string(),
pin_name_with_c: "PC3_C".to_string(),
pin_name_without_c: "PC3".to_string(),
},
];
for split_feature in &split_features {
if pin_set.contains(split_feature.pin_name_with_c.as_str()) {
singletons.push(split_feature.pin_name_with_c.clone());
} else {
panic!(
"'{}' feature invalid for this chip! No pin '{}' found.\n
Found pins: {:#?}",
split_feature.feature_name, split_feature.pin_name_with_c, pin_set
)
}
}
// ========
// Handle time-driver-XXXX features.
@ -463,6 +517,15 @@ fn main() {
(("lpuart", "RTS"), quote!(crate::usart::RtsPin)),
(("lpuart", "CK"), quote!(crate::usart::CkPin)),
(("lpuart", "DE"), quote!(crate::usart::DePin)),
(("sai", "SCK_A"), quote!(crate::sai::SckAPin)),
(("sai", "SCK_B"), quote!(crate::sai::SckBPin)),
(("sai", "FS_A"), quote!(crate::sai::FsAPin)),
(("sai", "FS_B"), quote!(crate::sai::FsBPin)),
(("sai", "SD_A"), quote!(crate::sai::SdAPin)),
(("sai", "SD_B"), quote!(crate::sai::SdBPin)),
(("sai", "MCLK_A"), quote!(crate::sai::MclkAPin)),
(("sai", "MCLK_B"), quote!(crate::sai::MclkBPin)),
(("sai", "WS"), quote!(crate::sai::WsPin)),
(("spi", "SCK"), quote!(crate::spi::SckPin)),
(("spi", "MOSI"), quote!(crate::spi::MosiPin)),
(("spi", "MISO"), quote!(crate::spi::MisoPin)),
@ -656,12 +719,17 @@ fn main() {
(("sdmmc", "D6"), quote!(crate::sdmmc::D6Pin)),
(("sdmmc", "D6"), quote!(crate::sdmmc::D7Pin)),
(("sdmmc", "D8"), quote!(crate::sdmmc::D8Pin)),
(("quadspi", "BK1_IO0"), quote!(crate::qspi::D0Pin)),
(("quadspi", "BK1_IO1"), quote!(crate::qspi::D1Pin)),
(("quadspi", "BK1_IO2"), quote!(crate::qspi::D2Pin)),
(("quadspi", "BK1_IO3"), quote!(crate::qspi::D3Pin)),
(("quadspi", "BK1_IO0"), quote!(crate::qspi::BK1D0Pin)),
(("quadspi", "BK1_IO1"), quote!(crate::qspi::BK1D1Pin)),
(("quadspi", "BK1_IO2"), quote!(crate::qspi::BK1D2Pin)),
(("quadspi", "BK1_IO3"), quote!(crate::qspi::BK1D3Pin)),
(("quadspi", "BK1_NCS"), quote!(crate::qspi::BK1NSSPin)),
(("quadspi", "BK2_IO0"), quote!(crate::qspi::BK2D0Pin)),
(("quadspi", "BK2_IO1"), quote!(crate::qspi::BK2D1Pin)),
(("quadspi", "BK2_IO2"), quote!(crate::qspi::BK2D2Pin)),
(("quadspi", "BK2_IO3"), quote!(crate::qspi::BK2D3Pin)),
(("quadspi", "BK2_NCS"), quote!(crate::qspi::BK2NSSPin)),
(("quadspi", "CLK"), quote!(crate::qspi::SckPin)),
(("quadspi", "BK1_NCS"), quote!(crate::qspi::NSSPin)),
].into();
for p in METADATA.peripherals {
@ -670,7 +738,16 @@ fn main() {
let key = (regs.kind, pin.signal);
if let Some(tr) = signals.get(&key) {
let mut peri = format_ident!("{}", p.name);
let pin_name = format_ident!("{}", pin.pin);
let pin_name = {
// If we encounter a _C pin but the split_feature for this pin is not enabled, skip it
if pin.pin.ends_with("_C") && !split_features.iter().any(|x| x.pin_name_with_c == pin.pin) {
continue;
}
format_ident!("{}", pin.pin)
};
let af = pin.af.unwrap_or(0);
// MCO is special
@ -707,7 +784,13 @@ fn main() {
}
let peri = format_ident!("{}", p.name);
let pin_name = format_ident!("{}", pin.pin);
let pin_name = {
// If we encounter a _C pin but the split_feature for this pin is not enabled, skip it
if pin.pin.ends_with("_C") && !split_features.iter().any(|x| x.pin_name_with_c == pin.pin) {
continue;
}
format_ident!("{}", pin.pin)
};
// H7 has differential voltage measurements
let ch: Option<u8> = if pin.signal.starts_with("INP") {
@ -727,6 +810,20 @@ fn main() {
}
}
if regs.kind == "opamp" {
if !pin.signal.starts_with("VP") {
continue;
}
let peri = format_ident!("{}", p.name);
let pin_name = format_ident!("{}", pin.pin);
let ch: u8 = pin.signal.strip_prefix("VP").unwrap().parse().unwrap();
g.extend(quote! {
impl_opamp_pin!( #peri, #pin_name, #ch);
})
}
// DAC is special
if regs.kind == "dac" {
let peri = format_ident!("{}", p.name);
@ -750,6 +847,8 @@ fn main() {
(("usart", "TX"), quote!(crate::usart::TxDma)),
(("lpuart", "RX"), quote!(crate::usart::RxDma)),
(("lpuart", "TX"), quote!(crate::usart::TxDma)),
(("sai", "A"), quote!(crate::sai::DmaA)),
(("sai", "B"), quote!(crate::sai::DmaB)),
(("spi", "RX"), quote!(crate::spi::RxDma)),
(("spi", "TX"), quote!(crate::spi::TxDma)),
(("i2c", "RX"), quote!(crate::i2c::RxDma)),
@ -817,6 +916,17 @@ fn main() {
let mut peripherals_table: Vec<Vec<String>> = Vec::new();
let mut pins_table: Vec<Vec<String>> = Vec::new();
let mut dma_channels_table: Vec<Vec<String>> = Vec::new();
let mut adc_common_table: Vec<Vec<String>> = Vec::new();
/*
If ADC3_COMMON exists, ADC3 and higher are assigned to it
All other ADCs are assigned to ADC_COMMON
ADC3 and higher are assigned to the adc34 clock in the table
The adc3_common cfg directive is added if ADC3_COMMON exists
*/
let has_adc3 = METADATA.peripherals.iter().find(|p| p.name == "ADC3_COMMON").is_some();
let set_adc345 = HashSet::from(["ADC3", "ADC4", "ADC5"]);
for m in METADATA
.memory
@ -844,16 +954,45 @@ fn main() {
for pin_num in 0u32..16 {
let pin_name = format!("P{}{}", port_letter, pin_num);
pins_table.push(vec![
pin_name,
pin_name.clone(),
p.name.to_string(),
port_num.to_string(),
pin_num.to_string(),
format!("EXTI{}", pin_num),
]);
// If we have the split pins, we need to do a little extra work:
// Add the "_C" variant to the table. The solution is not optimal, though.
// Adding them only when the corresponding GPIOx also appears.
// This should avoid unintended side-effects as much as possible.
#[cfg(feature = "_split-pins-enabled")]
for split_feature in &split_features {
if split_feature.pin_name_without_c == pin_name {
pins_table.push(vec![
split_feature.pin_name_with_c.to_string(),
p.name.to_string(),
port_num.to_string(),
pin_num.to_string(),
format!("EXTI{}", pin_num),
]);
}
}
}
}
if regs.kind == "adc" {
let (adc_common, adc_clock) = if set_adc345.contains(p.name) && has_adc3 {
("ADC3_COMMON", "adc34")
} else {
("ADC_COMMON", "adc")
};
let row = vec![p.name.to_string(), adc_common.to_string(), adc_clock.to_string()];
adc_common_table.push(row);
}
for irq in p.interrupts {
let row = vec![
p.name.to_string(),
@ -932,6 +1071,7 @@ fn main() {
make_table(&mut m, "foreach_peripheral", &peripherals_table);
make_table(&mut m, "foreach_pin", &pins_table);
make_table(&mut m, "foreach_dma_channel", &dma_channels_table);
make_table(&mut m, "foreach_adc", &adc_common_table);
let out_dir = &PathBuf::from(env::var_os("OUT_DIR").unwrap());
let out_file = out_dir.join("_macros.rs").to_string_lossy().to_string();
@ -973,13 +1113,24 @@ fn main() {
println!("cargo:rustc-cfg={}x{}", &chip_name[..9], &chip_name[10..11]);
}
// =======
// ADC3_COMMON is present
if has_adc3 {
println!("cargo:rustc-cfg={}", "adc3_common");
}
// =======
// Features for targeting groups of chips
println!("cargo:rustc-cfg={}", &chip_name[..7]); // stm32f4
println!("cargo:rustc-cfg={}", &chip_name[..9]); // stm32f429
println!("cargo:rustc-cfg={}x", &chip_name[..8]); // stm32f42x
println!("cargo:rustc-cfg={}x{}", &chip_name[..7], &chip_name[8..9]); // stm32f4x9
if &chip_name[..8] == "stm32wba" {
println!("cargo:rustc-cfg={}", &chip_name[..8]); // stm32wba
println!("cargo:rustc-cfg={}", &chip_name[..10]); // stm32wba52
} else {
println!("cargo:rustc-cfg={}", &chip_name[..7]); // stm32f4
println!("cargo:rustc-cfg={}", &chip_name[..9]); // stm32f429
println!("cargo:rustc-cfg={}x", &chip_name[..8]); // stm32f42x
println!("cargo:rustc-cfg={}x{}", &chip_name[..7], &chip_name[8..9]); // stm32f4x9
}
// Handle time-driver-XXXX features.
if env::var("CARGO_FEATURE_TIME_DRIVER_ANY").is_ok() {}

View File

@ -1,16 +1,37 @@
use core::future::poll_fn;
use core::marker::PhantomData;
use core::task::Poll;
use embassy_hal_internal::into_ref;
use embedded_hal_02::blocking::delay::DelayUs;
use crate::adc::{Adc, AdcPin, Instance, SampleTime};
use crate::rcc::get_freqs;
use crate::time::Hertz;
use crate::Peripheral;
use crate::{interrupt, Peripheral};
pub const VDDA_CALIB_MV: u32 = 3300;
pub const ADC_MAX: u32 = (1 << 12) - 1;
// No calibration data for F103, voltage should be 1.2v
pub const VREF_INT: u32 = 1200;
/// Interrupt handler.
pub struct InterruptHandler<T: Instance> {
_phantom: PhantomData<T>,
}
impl<T: Instance> interrupt::typelevel::Handler<T::Interrupt> for InterruptHandler<T> {
unsafe fn on_interrupt() {
if T::regs().sr().read().eoc() {
T::regs().cr1().modify(|w| w.set_eocie(false));
} else {
return;
}
T::state().waker.wake();
}
}
pub struct Vref;
impl<T: Instance> AdcPin<T> for Vref {}
impl<T: Instance> super::sealed::AdcPin<T> for Vref {
@ -95,18 +116,28 @@ impl<'d, T: Instance> Adc<'d, T> {
}
/// Perform a single conversion.
fn convert(&mut self) -> u16 {
async fn convert(&mut self) -> u16 {
T::regs().cr2().modify(|reg| {
reg.set_adon(true);
reg.set_swstart(true);
});
while T::regs().cr2().read().swstart() {}
while !T::regs().sr().read().eoc() {}
T::regs().cr1().modify(|w| w.set_eocie(true));
poll_fn(|cx| {
T::state().waker.register(cx.waker());
if !T::regs().cr2().read().swstart() && T::regs().sr().read().eoc() {
Poll::Ready(())
} else {
Poll::Pending
}
})
.await;
T::regs().dr().read().0 as u16
}
pub fn read(&mut self, pin: &mut impl AdcPin<T>) -> u16 {
pub async fn read(&mut self, pin: &mut impl AdcPin<T>) -> u16 {
Self::set_channel_sample_time(pin.channel(), self.sample_time);
T::regs().cr1().modify(|reg| {
reg.set_scan(false);
@ -123,7 +154,7 @@ impl<'d, T: Instance> Adc<'d, T> {
// Configure the channel to sample
T::regs().sqr3().write(|reg| reg.set_sq(0, pin.channel()));
self.convert()
self.convert().await
}
fn set_channel_sample_time(ch: u8, sample_time: SampleTime) {
@ -135,3 +166,11 @@ impl<'d, T: Instance> Adc<'d, T> {
}
}
}
impl<'d, T: Instance> Drop for Adc<'d, T> {
fn drop(&mut self) {
T::regs().cr2().modify(|reg| reg.set_adon(false));
T::disable();
}
}

View File

@ -1,14 +1,36 @@
use core::future::poll_fn;
use core::marker::PhantomData;
use core::task::Poll;
use embassy_hal_internal::into_ref;
use embedded_hal_02::blocking::delay::DelayUs;
use crate::adc::{Adc, AdcPin, Instance, SampleTime};
use crate::interrupt::typelevel::Interrupt;
use crate::time::Hertz;
use crate::Peripheral;
use crate::{interrupt, Peripheral};
pub const VDDA_CALIB_MV: u32 = 3300;
pub const ADC_MAX: u32 = (1 << 12) - 1;
pub const VREF_INT: u32 = 1230;
/// Interrupt handler.
pub struct InterruptHandler<T: Instance> {
_phantom: PhantomData<T>,
}
impl<T: Instance> interrupt::typelevel::Handler<T::Interrupt> for InterruptHandler<T> {
unsafe fn on_interrupt() {
if T::regs().isr().read().eoc() {
T::regs().ier().modify(|w| w.set_eocie(false));
} else {
return;
}
T::state().waker.wake();
}
}
pub struct Vref;
impl<T: Instance> AdcPin<T> for Vref {}
impl<T: Instance> super::sealed::AdcPin<T> for Vref {
@ -17,6 +39,13 @@ impl<T: Instance> super::sealed::AdcPin<T> for Vref {
}
}
impl Vref {
/// The value that vref would be if vdda was at 3300mv
pub fn value(&self) -> u16 {
crate::pac::VREFINTCAL.data().read().value()
}
}
pub struct Temperature;
impl<T: Instance> AdcPin<T> for Temperature {}
impl<T: Instance> super::sealed::AdcPin<T> for Temperature {
@ -26,7 +55,11 @@ impl<T: Instance> super::sealed::AdcPin<T> for Temperature {
}
impl<'d, T: Instance> Adc<'d, T> {
pub fn new(adc: impl Peripheral<P = T> + 'd, delay: &mut impl DelayUs<u32>) -> Self {
pub fn new(
adc: impl Peripheral<P = T> + 'd,
_irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
delay: &mut impl DelayUs<u32>,
) -> Self {
use crate::pac::adc::vals;
into_ref!(adc);
@ -50,7 +83,7 @@ impl<'d, T: Instance> Adc<'d, T> {
while T::regs().cr().read().adcal() {}
// Wait more than 4 clock cycles after adcal is cleared (RM0364 p. 223)
delay.delay_us(6 * 1_000_000 / Self::freq().0);
delay.delay_us(1 + (6 * 1_000_000 / Self::freq().0));
// Enable the adc
T::regs().cr().modify(|w| w.set_aden(true));
@ -58,6 +91,11 @@ impl<'d, T: Instance> Adc<'d, T> {
// Wait until the adc is ready
while !T::regs().isr().read().adrdy() {}
T::Interrupt::unpend();
unsafe {
T::Interrupt::enable();
}
Self {
adc,
sample_time: Default::default(),
@ -97,30 +135,61 @@ impl<'d, T: Instance> Adc<'d, T> {
}
/// Perform a single conversion.
fn convert(&mut self) -> u16 {
async fn convert(&mut self) -> u16 {
T::regs().isr().write(|_| {});
T::regs().ier().modify(|w| w.set_eocie(true));
T::regs().cr().modify(|w| w.set_adstart(true));
while !T::regs().isr().read().eoc() && !T::regs().isr().read().eos() {}
poll_fn(|cx| {
T::state().waker.register(cx.waker());
if T::regs().isr().read().eoc() {
Poll::Ready(())
} else {
Poll::Pending
}
})
.await;
T::regs().isr().write(|_| {});
T::regs().dr().read().rdata()
}
pub fn read(&mut self, pin: &mut impl AdcPin<T>) -> u16 {
pub async fn read(&mut self, pin: &mut impl AdcPin<T>) -> u16 {
Self::set_channel_sample_time(pin.channel(), self.sample_time);
// Configure the channel to sample
T::regs().sqr1().write(|w| w.set_sq(0, pin.channel()));
self.convert()
self.convert().await
}
fn set_channel_sample_time(ch: u8, sample_time: SampleTime) {
let sample_time = sample_time.into();
if ch <= 9 {
T::regs().smpr2().modify(|reg| reg.set_smp(ch as _, sample_time));
T::regs().smpr1().modify(|reg| reg.set_smp(ch as _, sample_time));
} else {
T::regs().smpr1().modify(|reg| reg.set_smp((ch - 10) as _, sample_time));
T::regs().smpr2().modify(|reg| reg.set_smp((ch - 10) as _, sample_time));
}
}
}
impl<'d, T: Instance> Drop for Adc<'d, T> {
fn drop(&mut self) {
use crate::pac::adc::vals;
T::regs().cr().modify(|w| w.set_adstp(true));
while T::regs().cr().read().adstp() {}
T::regs().cr().modify(|w| w.set_addis(true));
while T::regs().cr().read().aden() {}
// Disable the adc regulator
T::regs().cr().modify(|w| w.set_advregen(vals::Advregen::INTERMEDIATE));
T::regs().cr().modify(|w| w.set_advregen(vals::Advregen::DISABLED));
T::disable();
}
}

View File

@ -31,15 +31,41 @@ pub struct Adc<'d, T: Instance> {
}
pub(crate) mod sealed {
pub trait Instance {
#[cfg(any(adc_f1, adc_f3, adc_v1))]
use embassy_sync::waitqueue::AtomicWaker;
#[cfg(any(adc_f1, adc_f3, adc_v1))]
pub struct State {
pub waker: AtomicWaker,
}
#[cfg(any(adc_f1, adc_f3, adc_v1))]
impl State {
pub const fn new() -> Self {
Self {
waker: AtomicWaker::new(),
}
}
}
pub trait InterruptableInstance {
type Interrupt: crate::interrupt::typelevel::Interrupt;
}
pub trait Instance: InterruptableInstance {
fn regs() -> crate::pac::adc::Adc;
#[cfg(not(any(adc_f1, adc_v1, adc_f3_v2, adc_g0)))]
fn common_regs() -> crate::pac::adccommon::AdcCommon;
#[cfg(adc_f3)]
fn frequency() -> crate::time::Hertz;
#[cfg(any(adc_f1, adc_f3, adc_v1))]
fn state() -> &'static State;
}
pub trait AdcPin<T: Instance> {
#[cfg(any(adc_v1, adc_v2))]
fn set_as_analog(&mut self) {}
fn channel(&self) -> u8;
}
@ -56,129 +82,37 @@ pub trait Instance: sealed::Instance + crate::Peripheral<P = Self> + crate::rcc:
pub trait AdcPin<T: Instance>: sealed::AdcPin<T> {}
pub trait InternalChannel<T>: sealed::InternalChannel<T> {}
#[cfg(not(any(stm32h7, adc_f3, adc_v4)))]
foreach_peripheral!(
(adc, $inst:ident) => {
foreach_adc!(
($inst:ident, $common_inst:ident, $clock:ident) => {
impl crate::adc::sealed::Instance for peripherals::$inst {
fn regs() -> crate::pac::adc::Adc {
crate::pac::$inst
}
#[cfg(not(any(adc_f1, adc_v1, adc_f3_v2, adc_g0)))]
fn common_regs() -> crate::pac::adccommon::AdcCommon {
foreach_peripheral!{
(adccommon, $common_inst:ident) => {
return crate::pac::$common_inst
};
}
}
}
impl crate::adc::Instance for peripherals::$inst {}
};
);
#[cfg(any(stm32h7, adc_f3, adc_v4))]
foreach_peripheral!(
(adc, ADC3) => {
impl crate::adc::sealed::Instance for peripherals::ADC3 {
fn regs() -> crate::pac::adc::Adc {
crate::pac::ADC3
}
#[cfg(all(not(adc_f1), not(adc_v1)))]
#[allow(unreachable_code)]
fn common_regs() -> crate::pac::adccommon::AdcCommon {
foreach_peripheral!{
(adccommon, ADC3_COMMON) => {
return crate::pac::ADC3_COMMON
};
// Fall back to ADC_COMMON if ADC3_COMMON does not exist
(adccommon, ADC_COMMON) => {
return crate::pac::ADC_COMMON
};
}
return crate::pac::$common_inst
}
#[cfg(adc_f3)]
fn frequency() -> crate::time::Hertz {
unsafe { crate::rcc::get_freqs() }.adc34.unwrap()
unsafe { crate::rcc::get_freqs() }.$clock.unwrap()
}
#[cfg(any(adc_f1, adc_f3, adc_v1))]
fn state() -> &'static sealed::State {
static STATE: sealed::State = sealed::State::new();
&STATE
}
}
impl crate::adc::Instance for peripherals::ADC3 {}
};
(adc, ADC4) => {
impl crate::adc::sealed::Instance for peripherals::ADC4 {
fn regs() -> crate::pac::adc::Adc {
crate::pac::ADC4
}
#[cfg(not(any(adc_f1, adc_v1)))]
#[allow(unreachable_code)]
fn common_regs() -> crate::pac::adccommon::AdcCommon {
foreach_peripheral!{
(adccommon, ADC3_COMMON) => {
return crate::pac::ADC3_COMMON
};
// Fall back to ADC_COMMON if ADC3_COMMON does not exist
(adccommon, ADC_COMMON) => {
return crate::pac::ADC_COMMON
};
foreach_interrupt!(
($inst,adc,ADC,GLOBAL,$irq:ident) => {
impl sealed::InterruptableInstance for peripherals::$inst {
type Interrupt = crate::interrupt::typelevel::$irq;
}
}
#[cfg(adc_f3)]
fn frequency() -> crate::time::Hertz {
unsafe { crate::rcc::get_freqs() }.adc34.unwrap()
}
}
impl crate::adc::Instance for peripherals::ADC4 {}
};
(adc, ADC5) => {
impl crate::adc::sealed::Instance for peripherals::ADC5 {
fn regs() -> crate::pac::adc::Adc {
crate::pac::ADC5
}
#[cfg(not(any(adc_f1, adc_v1)))]
#[allow(unreachable_code)]
fn common_regs() -> crate::pac::adccommon::AdcCommon {
foreach_peripheral!{
(adccommon, ADC3_COMMON) => {
return crate::pac::ADC3_COMMON
};
// Fall back to ADC_COMMON if ADC3_COMMON does not exist
(adccommon, ADC_COMMON) => {
return crate::pac::ADC_COMMON
};
}
}
#[cfg(adc_f3)]
fn frequency() -> crate::time::Hertz {
unsafe { crate::rcc::get_freqs() }.adc34.unwrap()
}
}
impl crate::adc::Instance for peripherals::ADC5 {}
};
(adc, $inst:ident) => {
impl crate::adc::sealed::Instance for peripherals::$inst {
fn regs() -> crate::pac::adc::Adc {
crate::pac::$inst
}
#[cfg(not(any(adc_f1, adc_v1)))]
fn common_regs() -> crate::pac::adccommon::AdcCommon {
foreach_peripheral!{
(adccommon, ADC_COMMON) => {
return crate::pac::ADC_COMMON
};
}
}
#[cfg(adc_f3)]
fn frequency() -> crate::time::Hertz {
unsafe { crate::rcc::get_freqs() }.adc.unwrap()
}
}
};
);
impl crate::adc::Instance for peripherals::$inst {}
};
@ -189,6 +123,11 @@ macro_rules! impl_adc_pin {
impl crate::adc::AdcPin<peripherals::$inst> for crate::peripherals::$pin {}
impl crate::adc::sealed::AdcPin<peripherals::$inst> for crate::peripherals::$pin {
#[cfg(any(adc_v1, adc_v2))]
fn set_as_analog(&mut self) {
<Self as crate::gpio::sealed::Pin>::set_as_analog(self);
}
fn channel(&self) -> u8 {
$ch
}

View File

@ -1,39 +1,65 @@
use core::future::poll_fn;
use core::marker::PhantomData;
use core::task::Poll;
use embassy_hal_internal::into_ref;
use embedded_hal_02::blocking::delay::DelayUs;
use crate::adc::{Adc, AdcPin, Instance, InternalChannel, Resolution, SampleTime};
use crate::adc::{Adc, AdcPin, Instance, Resolution, SampleTime};
use crate::interrupt::typelevel::Interrupt;
use crate::peripherals::ADC;
use crate::Peripheral;
use crate::{interrupt, Peripheral};
pub const VDDA_CALIB_MV: u32 = 3300;
pub const VREF_INT: u32 = 1230;
/// Interrupt handler.
pub struct InterruptHandler<T: Instance> {
_phantom: PhantomData<T>,
}
impl<T: Instance> interrupt::typelevel::Handler<T::Interrupt> for InterruptHandler<T> {
unsafe fn on_interrupt() {
if T::regs().isr().read().eoc() {
T::regs().ier().modify(|w| w.set_eocie(false));
} else {
return;
}
T::state().waker.wake();
}
}
pub struct Vbat;
impl InternalChannel<ADC> for Vbat {}
impl super::sealed::InternalChannel<ADC> for Vbat {
impl AdcPin<ADC> for Vbat {}
impl super::sealed::AdcPin<ADC> for Vbat {
fn channel(&self) -> u8 {
18
}
}
pub struct Vref;
impl InternalChannel<ADC> for Vref {}
impl super::sealed::InternalChannel<ADC> for Vref {
impl AdcPin<ADC> for Vref {}
impl super::sealed::AdcPin<ADC> for Vref {
fn channel(&self) -> u8 {
17
}
}
pub struct Temperature;
impl InternalChannel<ADC> for Temperature {}
impl super::sealed::InternalChannel<ADC> for Temperature {
impl AdcPin<ADC> for Temperature {}
impl super::sealed::AdcPin<ADC> for Temperature {
fn channel(&self) -> u8 {
16
}
}
impl<'d, T: Instance> Adc<'d, T> {
pub fn new(adc: impl Peripheral<P = T> + 'd, delay: &mut impl DelayUs<u32>) -> Self {
pub fn new(
adc: impl Peripheral<P = T> + 'd,
_irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
delay: &mut impl DelayUs<u32>,
) -> Self {
into_ref!(adc);
T::enable();
T::reset();
@ -44,12 +70,32 @@ impl<'d, T: Instance> Adc<'d, T> {
// tstab = 14 * 1/fadc
delay.delay_us(1);
let s = Self {
// A.7.1 ADC calibration code example
T::regs().cfgr1().modify(|reg| reg.set_dmaen(false));
T::regs().cr().modify(|reg| reg.set_adcal(true));
while T::regs().cr().read().adcal() {}
// A.7.2 ADC enable sequence code example
if T::regs().isr().read().adrdy() {
T::regs().isr().modify(|reg| reg.set_adrdy(true));
}
T::regs().cr().modify(|reg| reg.set_aden(true));
while !T::regs().isr().read().adrdy() {
// ES0233, 2.4.3 ADEN bit cannot be set immediately after the ADC calibration
// Workaround: When the ADC calibration is complete (ADCAL = 0), keep setting the
// ADEN bit until the ADRDY flag goes high.
T::regs().cr().modify(|reg| reg.set_aden(true));
}
T::Interrupt::unpend();
unsafe {
T::Interrupt::enable();
}
Self {
adc,
sample_time: Default::default(),
};
s.calibrate();
s
}
}
pub fn enable_vbat(&self, _delay: &mut impl DelayUs<u32>) -> Vbat {
@ -80,21 +126,6 @@ impl<'d, T: Instance> Adc<'d, T> {
Temperature
}
fn calibrate(&self) {
// A.7.1 ADC calibration code example
if T::regs().cr().read().aden() {
T::regs().cr().modify(|reg| reg.set_addis(true));
}
while T::regs().cr().read().aden() {
// spin
}
T::regs().cfgr1().modify(|reg| reg.set_dmaen(false));
T::regs().cr().modify(|reg| reg.set_adcal(true));
while T::regs().cr().read().adcal() {
// spin
}
}
pub fn set_sample_time(&mut self, sample_time: SampleTime) {
self.sample_time = sample_time;
}
@ -103,57 +134,50 @@ impl<'d, T: Instance> Adc<'d, T> {
T::regs().cfgr1().modify(|reg| reg.set_res(resolution.into()));
}
pub fn read<P>(&mut self, pin: &mut P) -> u16
where
P: AdcPin<T> + crate::gpio::sealed::Pin,
{
pub async fn read(&mut self, pin: &mut impl AdcPin<T>) -> u16 {
let channel = pin.channel();
pin.set_as_analog();
self.read_channel(channel)
// A.7.5 Single conversion sequence code example - Software trigger
T::regs().chselr().write(|reg| reg.set_chselx(channel as usize, true));
self.convert().await
}
pub fn read_internal(&mut self, channel: &mut impl InternalChannel<T>) -> u16 {
let channel = channel.channel();
self.read_channel(channel)
}
fn read_channel(&mut self, channel: u8) -> u16 {
// A.7.2 ADC enable sequence code example
if T::regs().isr().read().adrdy() {
T::regs().isr().modify(|reg| reg.set_adrdy(true));
}
T::regs().cr().modify(|reg| reg.set_aden(true));
while !T::regs().isr().read().adrdy() {
// ES0233, 2.4.3 ADEN bit cannot be set immediately after the ADC calibration
// Workaround: When the ADC calibration is complete (ADCAL = 0), keep setting the
// ADEN bit until the ADRDY flag goes high.
T::regs().cr().modify(|reg| reg.set_aden(true));
}
async fn convert(&mut self) -> u16 {
T::regs().isr().modify(|reg| {
reg.set_eoc(true);
reg.set_eosmp(true);
});
// A.7.5 Single conversion sequence code example - Software trigger
T::regs().chselr().write(|reg| reg.set_chselx(channel as usize, true));
T::regs().smpr().modify(|reg| reg.set_smp(self.sample_time.into()));
T::regs().ier().modify(|w| w.set_eocie(true));
T::regs().cr().modify(|reg| reg.set_adstart(true));
while !T::regs().isr().read().eoc() {
// spin
}
let value = T::regs().dr().read().0 as u16;
// A.7.3 ADC disable code example
T::regs().cr().modify(|reg| reg.set_adstp(true));
while T::regs().cr().read().adstp() {
// spin
}
T::regs().cr().modify(|reg| reg.set_addis(true));
while T::regs().cr().read().aden() {
// spin
}
poll_fn(|cx| {
T::state().waker.register(cx.waker());
value
if T::regs().isr().read().eoc() {
Poll::Ready(())
} else {
Poll::Pending
}
})
.await;
T::regs().dr().read().data()
}
}
impl<'d, T: Instance> Drop for Adc<'d, T> {
fn drop(&mut self) {
// A.7.3 ADC disable code example
T::regs().cr().modify(|reg| reg.set_adstp(true));
while T::regs().cr().read().adstp() {}
T::regs().cr().modify(|reg| reg.set_addis(true));
while T::regs().cr().read().aden() {}
T::disable();
}
}

View File

@ -1,7 +1,6 @@
use embassy_hal_internal::into_ref;
use embedded_hal_02::blocking::delay::DelayUs;
use super::InternalChannel;
use crate::adc::{Adc, AdcPin, Instance, Resolution, SampleTime};
use crate::peripherals::ADC1;
use crate::time::Hertz;
@ -16,8 +15,8 @@ pub const VREF_CALIB_MV: u32 = 3300;
pub const ADC_POWERUP_TIME_US: u32 = 3;
pub struct VrefInt;
impl InternalChannel<ADC1> for VrefInt {}
impl super::sealed::InternalChannel<ADC1> for VrefInt {
impl AdcPin<ADC1> for VrefInt {}
impl super::sealed::AdcPin<ADC1> for VrefInt {
fn channel(&self) -> u8 {
17
}
@ -31,8 +30,8 @@ impl VrefInt {
}
pub struct Temperature;
impl InternalChannel<ADC1> for Temperature {}
impl super::sealed::InternalChannel<ADC1> for Temperature {
impl AdcPin<ADC1> for Temperature {}
impl super::sealed::AdcPin<ADC1> for Temperature {
fn channel(&self) -> u8 {
cfg_if::cfg_if! {
if #[cfg(any(stm32f40, stm32f41))] {
@ -52,8 +51,8 @@ impl Temperature {
}
pub struct Vbat;
impl InternalChannel<ADC1> for Vbat {}
impl super::sealed::InternalChannel<ADC1> for Vbat {
impl AdcPin<ADC1> for Vbat {}
impl super::sealed::AdcPin<ADC1> for Vbat {
fn channel(&self) -> u8 {
18
}
@ -125,7 +124,7 @@ where
/// [Adc::read_internal()] to perform conversion.
pub fn enable_vrefint(&self) -> VrefInt {
T::common_regs().ccr().modify(|reg| {
reg.set_tsvrefe(crate::pac::adccommon::vals::Tsvrefe::ENABLED);
reg.set_tsvrefe(true);
});
VrefInt {}
@ -138,7 +137,7 @@ where
/// temperature sensor will return vbat value.
pub fn enable_temperature(&self) -> Temperature {
T::common_regs().ccr().modify(|reg| {
reg.set_tsvrefe(crate::pac::adccommon::vals::Tsvrefe::ENABLED);
reg.set_tsvrefe(true);
});
Temperature {}
@ -148,7 +147,7 @@ where
/// [Adc::read_internal()] to perform conversion.
pub fn enable_vbat(&self) -> Vbat {
T::common_regs().ccr().modify(|reg| {
reg.set_vbate(crate::pac::adccommon::vals::Vbate::ENABLED);
reg.set_vbate(true);
});
Vbat {}
@ -176,22 +175,11 @@ where
T::regs().dr().read().0 as u16
}
pub fn read<P>(&mut self, pin: &mut P) -> u16
where
P: AdcPin<T>,
P: crate::gpio::sealed::Pin,
{
pub fn read(&mut self, pin: &mut impl AdcPin<T>) -> u16 {
pin.set_as_analog();
self.read_channel(pin.channel())
}
pub fn read_internal(&mut self, channel: &mut impl InternalChannel<T>) -> u16 {
self.read_channel(channel.channel())
}
fn read_channel(&mut self, channel: u8) -> u16 {
// Configure ADC
let channel = pin.channel();
// Select channel
T::regs().sqr3().write(|reg| reg.set_sq(0, channel));
@ -199,9 +187,7 @@ where
// Configure channel
Self::set_channel_sample_time(channel, self.sample_time);
let val = self.convert();
val
self.convert()
}
fn set_channel_sample_time(ch: u8, sample_time: SampleTime) {
@ -216,6 +202,10 @@ where
impl<'d, T: Instance> Drop for Adc<'d, T> {
fn drop(&mut self) {
T::regs().cr2().modify(|reg| {
reg.set_adon(false);
});
T::disable();
}
}

View File

@ -129,7 +129,6 @@ impl<'d, T: Instance, P: PHY> Ethernet<'d, T, P> {
#[cfg(any(eth_v1b, eth_v1c))]
critical_section::with(|_| {
RCC.apb2enr().modify(|w| w.set_syscfgen(true));
RCC.ahb1enr().modify(|w| {
w.set_ethen(true);
w.set_ethtxen(true);

View File

@ -34,8 +34,6 @@ impl interrupt::typelevel::Handler<interrupt::typelevel::ETH> for InterruptHandl
}
}
const MTU: usize = 1514; // 14 Ethernet header + 1500 IP packet
pub struct Ethernet<'d, T: Instance, P: PHY> {
_peri: PeripheralRef<'d, T>,
pub(crate) tx: TDesRing<'d>,
@ -80,7 +78,6 @@ impl<'d, T: Instance, P: PHY> Ethernet<'d, T, P> {
// Enable the necessary Clocks
#[cfg(not(rcc_h5))]
critical_section::with(|_| {
crate::pac::RCC.apb4enr().modify(|w| w.set_syscfgen(true));
crate::pac::RCC.ahb1enr().modify(|w| {
w.set_eth1macen(true);
w.set_eth1txen(true);
@ -102,9 +99,9 @@ impl<'d, T: Instance, P: PHY> Ethernet<'d, T, P> {
});
// RMII
crate::pac::SBS
crate::pac::SYSCFG
.pmcr()
.modify(|w| w.set_eth_sel_phy(crate::pac::sbs::vals::EthSelPhy::B_0X4));
.modify(|w| w.set_eth_sel_phy(crate::pac::syscfg::vals::EthSelPhy::B_0X4));
});
config_pins!(ref_clk, mdio, mdc, crs, rx_d0, rx_d1, tx_d0, tx_d1, tx_en);
@ -164,7 +161,7 @@ impl<'d, T: Instance, P: PHY> Ethernet<'d, T, P> {
dma.dmactx_cr().modify(|w| w.set_txpbl(1)); // 32 ?
dma.dmacrx_cr().modify(|w| {
w.set_rxpbl(1); // 32 ?
w.set_rbsz(MTU as u16);
w.set_rbsz(RX_BUFFER_SIZE as u16);
});
// NOTE(unsafe) We got the peripheral singleton, which means that `rcc::init` was called

View File

@ -6,7 +6,7 @@ use core::task::{Context, Poll};
use embassy_hal_internal::impl_peripheral;
use embassy_sync::waitqueue::AtomicWaker;
use crate::gpio::{AnyPin, Input, Pin as GpioPin};
use crate::gpio::{AnyPin, Input, Level, Pin as GpioPin};
use crate::pac::exti::regs::Lines;
use crate::pac::EXTI;
use crate::{interrupt, pac, peripherals, Peripheral};
@ -39,6 +39,9 @@ fn exticr_regs() -> pac::afio::Afio {
}
pub unsafe fn on_irq() {
#[cfg(feature = "low-power")]
crate::low_power::on_wakeup_irq();
#[cfg(not(any(exti_c0, exti_g0, exti_l5, exti_u5, exti_h5, exti_h50)))]
let bits = EXTI.pr(0).read().0;
#[cfg(any(exti_c0, exti_g0, exti_l5, exti_u5, exti_h5, exti_h50))]
@ -98,6 +101,10 @@ impl<'d, T: GpioPin> ExtiInput<'d, T> {
self.pin.is_low()
}
pub fn get_level(&self) -> Level {
self.pin.get_level()
}
pub async fn wait_for_high<'a>(&'a mut self) {
let fut = ExtiInputFuture::new(self.pin.pin.pin.pin(), self.pin.pin.pin.port(), true, false);
if self.is_high() {
@ -364,9 +371,4 @@ pub(crate) unsafe fn init() {
use crate::interrupt::typelevel::Interrupt;
foreach_exti_irq!(enable_irq);
#[cfg(not(any(rcc_wb, rcc_wl5, rcc_wle, stm32f1, exti_h5, exti_h50)))]
<crate::peripherals::SYSCFG as crate::rcc::sealed::RccPeripheral>::enable();
#[cfg(stm32f1)]
<crate::peripherals::AFIO as crate::rcc::sealed::RccPeripheral>::enable();
}

View File

@ -758,6 +758,9 @@ foreach_pin!(
);
pub(crate) unsafe fn init() {
#[cfg(afio)]
<crate::peripherals::AFIO as crate::rcc::sealed::RccPeripheral>::enable();
crate::_generated::init_gpio();
}

View File

@ -78,12 +78,76 @@ pub(crate) mod sealed {
pub trait Instance: RccPeripheral {
fn regs() -> crate::pac::hrtim::Hrtim;
fn set_master_frequency(frequency: Hertz);
fn set_master_frequency(frequency: Hertz) {
let f = frequency.0;
#[cfg(not(stm32f334))]
let timer_f = Self::frequency().0;
#[cfg(stm32f334)]
let timer_f = unsafe { crate::rcc::get_freqs() }.hrtim.unwrap_or(Self::frequency()).0;
fn set_channel_frequency(channnel: usize, frequency: Hertz);
let psc_min = (timer_f / f) / (u16::MAX as u32 / 32);
let psc = if Self::regs().isr().read().dllrdy() {
Prescaler::compute_min_high_res(psc_min)
} else {
Prescaler::compute_min_low_res(psc_min)
};
let timer_f = 32 * (timer_f / psc as u32);
let per: u16 = (timer_f / f) as u16;
let regs = Self::regs();
regs.mcr().modify(|w| w.set_ckpsc(psc.into()));
regs.mper().modify(|w| w.set_mper(per));
}
fn set_channel_frequency(channel: usize, frequency: Hertz) {
let f = frequency.0;
#[cfg(not(stm32f334))]
let timer_f = Self::frequency().0;
#[cfg(stm32f334)]
let timer_f = unsafe { crate::rcc::get_freqs() }.hrtim.unwrap_or(Self::frequency()).0;
let psc_min = (timer_f / f) / (u16::MAX as u32 / 32);
let psc = if Self::regs().isr().read().dllrdy() {
Prescaler::compute_min_high_res(psc_min)
} else {
Prescaler::compute_min_low_res(psc_min)
};
let timer_f = 32 * (timer_f / psc as u32);
let per: u16 = (timer_f / f) as u16;
let regs = Self::regs();
regs.tim(channel).cr().modify(|w| w.set_ckpsc(psc.into()));
regs.tim(channel).per().modify(|w| w.set_per(per));
}
/// Set the dead time as a proportion of max_duty
fn set_channel_dead_time(channnel: usize, dead_time: u16);
fn set_channel_dead_time(channel: usize, dead_time: u16) {
let regs = Self::regs();
let channel_psc: Prescaler = regs.tim(channel).cr().read().ckpsc().into();
// The dead-time base clock runs 4 times slower than the hrtim base clock
// u9::MAX = 511
let psc_min = (channel_psc as u32 * dead_time as u32) / (4 * 511);
let psc = if Self::regs().isr().read().dllrdy() {
Prescaler::compute_min_high_res(psc_min)
} else {
Prescaler::compute_min_low_res(psc_min)
};
let dt_val = (psc as u32 * dead_time as u32) / (4 * channel_psc as u32);
regs.tim(channel).dt().modify(|w| {
w.set_dtprsc(psc.into());
w.set_dtf(dt_val as u16);
w.set_dtr(dt_val as u16);
});
}
// fn enable_outputs(enable: bool);
//
@ -99,84 +163,6 @@ foreach_interrupt! {
fn regs() -> crate::pac::hrtim::Hrtim {
crate::pac::$inst
}
fn set_master_frequency(frequency: Hertz) {
use crate::rcc::sealed::RccPeripheral;
let f = frequency.0;
#[cfg(not(stm32f334))]
let timer_f = Self::frequency().0;
#[cfg(stm32f334)]
let timer_f = unsafe { crate::rcc::get_freqs() }.hrtim.unwrap_or(
Self::frequency()
).0;
let psc_min = (timer_f / f) / (u16::MAX as u32 / 32);
let psc = if Self::regs().isr().read().dllrdy() {
Prescaler::compute_min_high_res(psc_min)
} else {
Prescaler::compute_min_low_res(psc_min)
};
let timer_f = 32 * (timer_f / psc as u32);
let per: u16 = (timer_f / f) as u16;
let regs = Self::regs();
regs.mcr().modify(|w| w.set_ckpsc(psc.into()));
regs.mper().modify(|w| w.set_mper(per));
}
fn set_channel_frequency(channel: usize, frequency: Hertz) {
use crate::rcc::sealed::RccPeripheral;
let f = frequency.0;
#[cfg(not(stm32f334))]
let timer_f = Self::frequency().0;
#[cfg(stm32f334)]
let timer_f = unsafe { crate::rcc::get_freqs() }.hrtim.unwrap_or(
Self::frequency()
).0;
let psc_min = (timer_f / f) / (u16::MAX as u32 / 32);
let psc = if Self::regs().isr().read().dllrdy() {
Prescaler::compute_min_high_res(psc_min)
} else {
Prescaler::compute_min_low_res(psc_min)
};
let timer_f = 32 * (timer_f / psc as u32);
let per: u16 = (timer_f / f) as u16;
let regs = Self::regs();
regs.tim(channel).cr().modify(|w| w.set_ckpsc(psc.into()));
regs.tim(channel).per().modify(|w| w.set_per(per));
}
fn set_channel_dead_time(channel: usize, dead_time: u16) {
let regs = Self::regs();
let channel_psc: Prescaler = regs.tim(channel).cr().read().ckpsc().into();
// The dead-time base clock runs 4 times slower than the hrtim base clock
// u9::MAX = 511
let psc_min = (channel_psc as u32 * dead_time as u32) / (4 * 511);
let psc = if Self::regs().isr().read().dllrdy() {
Prescaler::compute_min_high_res(psc_min)
} else {
Prescaler::compute_min_low_res(psc_min)
};
let dt_val = (psc as u32 * dead_time as u32) / (4 * channel_psc as u32);
regs.tim(channel).dt().modify(|w| {
w.set_dtprsc(psc.into());
w.set_dtf(dt_val as u16);
w.set_dtr(dt_val as u16);
});
}
}
impl Instance for crate::peripherals::$inst {

View File

@ -518,7 +518,8 @@ impl Timings {
impl<'d, T: Instance> SetConfig for I2c<'d, T> {
type Config = Hertz;
fn set_config(&mut self, config: &Self::Config) {
type ConfigError = ();
fn set_config(&mut self, config: &Self::Config) -> Result<(), ()> {
let timings = Timings::new(T::frequency(), *config);
T::regs().cr2().modify(|reg| {
reg.set_freq(timings.freq);
@ -531,5 +532,7 @@ impl<'d, T: Instance> SetConfig for I2c<'d, T> {
T::regs().trise().modify(|reg| {
reg.set_trise(timings.trise);
});
Ok(())
}
}

View File

@ -1075,7 +1075,8 @@ mod eha {
impl<'d, T: Instance> SetConfig for I2c<'d, T> {
type Config = Hertz;
fn set_config(&mut self, config: &Self::Config) {
type ConfigError = ();
fn set_config(&mut self, config: &Self::Config) -> Result<(), ()> {
let timings = Timings::new(T::frequency(), *config);
T::regs().timingr().write(|reg| {
reg.set_presc(timings.prescale);
@ -1084,5 +1085,7 @@ impl<'d, T: Instance> SetConfig for I2c<'d, T> {
reg.set_sdadel(timings.sdadel);
reg.set_scldel(timings.scldel);
});
Ok(())
}
}

View File

@ -93,15 +93,30 @@ pub struct Ipcc;
impl Ipcc {
pub fn enable(_config: Config) {
// TODO: move these lines to the rcc mod
// set LPTIM1 & LPTIM2 clock source
crate::pac::RCC.ccipr().modify(|w| {
w.set_lptim1sel(0b00); // PCLK
w.set_lptim2sel(0b00); // PCLK
});
// set RF wake-up clock = LSE
crate::pac::RCC.csr().modify(|w| w.set_rfwkpsel(0b01));
IPCC::enable();
IPCC::reset();
// insert bus access and fence for delay
IPCC::enable();
compiler_fence(Ordering::SeqCst);
IPCC::set_cpu2(true);
_configure_pwr();
// insert bus access and fence for delay
IPCC::set_cpu2(true);
compiler_fence(Ordering::SeqCst);
let regs = IPCC::regs();
regs.cpu(0).cr().modify(|w| {
IPCC::regs().cpu(0).cr().modify(|w| {
w.set_rxoie(true);
w.set_txfie(true);
});
@ -263,18 +278,3 @@ pub(crate) mod sealed {
fn state() -> &'static State;
}
}
fn _configure_pwr() {
// TODO: move the rest of this to rcc
let rcc = crate::pac::RCC;
// TODO: required
// set RF wake-up clock = LSE
rcc.csr().modify(|w| w.set_rfwkpsel(0b01));
// set LPTIM1 & LPTIM2 clock source
rcc.ccipr().modify(|w| {
w.set_lptim1sel(0b00); // PCLK
w.set_lptim2sel(0b00); // PCLK
});
}

View File

@ -1,5 +1,5 @@
#![cfg_attr(not(test), no_std)]
#![cfg_attr(feature = "nightly", feature(async_fn_in_trait, impl_trait_projections))]
#![cfg_attr(feature = "nightly", feature(async_fn_in_trait))]
//! ## Feature flags
#![doc = document_features::document_features!(feature_label = r#"<span class="stab portability"><code>{feature}</code></span>"#)]
@ -49,12 +49,16 @@ pub mod i2s;
pub mod ipcc;
#[cfg(feature = "low-power")]
pub mod low_power;
#[cfg(opamp)]
pub mod opamp;
#[cfg(quadspi)]
pub mod qspi;
#[cfg(rng)]
pub mod rng;
#[cfg(all(rtc, not(rtc_v1)))]
pub mod rtc;
#[cfg(sai)]
pub mod sai;
#[cfg(sdmmc)]
pub mod sdmmc;
#[cfg(spi)]
@ -88,6 +92,7 @@ pub use crate::_generated::interrupt;
#[macro_export]
macro_rules! bind_interrupts {
($vis:vis struct $name:ident { $($irq:ident => $($handler:ty),*;)* }) => {
#[derive(Copy, Clone)]
$vis struct $name;
$(
@ -117,6 +122,7 @@ pub(crate) use stm32_metapac as pac;
use crate::interrupt::Priority;
#[cfg(feature = "rt")]
pub use crate::pac::NVIC_PRIO_BITS;
use crate::rcc::sealed::RccPeripheral;
#[non_exhaustive]
pub struct Config {
@ -154,7 +160,7 @@ pub fn init(config: Config) -> Peripherals {
#[cfg(dbgmcu)]
if config.enable_debug_during_sleep {
crate::pac::DBGMCU.cr().modify(|cr| {
#[cfg(any(dbgmcu_f0, dbgmcu_c0, dbgmcu_g0, dbgmcu_u5))]
#[cfg(any(dbgmcu_f0, dbgmcu_c0, dbgmcu_g0, dbgmcu_u5, dbgmcu_wba))]
{
cr.set_dbg_stop(true);
cr.set_dbg_standby(true);
@ -179,7 +185,26 @@ pub fn init(config: Config) -> Peripherals {
});
}
#[cfg(not(any(stm32f1, stm32wb, stm32wl)))]
peripherals::SYSCFG::enable();
#[cfg(not(any(stm32h5, stm32h7, stm32wb, stm32wl)))]
peripherals::PWR::enable();
#[cfg(not(any(stm32f2, stm32f4, stm32f7, stm32l0, stm32h5, stm32h7)))]
peripherals::FLASH::enable();
unsafe {
#[cfg(feature = "_split-pins-enabled")]
crate::pac::SYSCFG.pmcr().modify(|pmcr| {
#[cfg(feature = "split-pa0")]
pmcr.set_pa0so(true);
#[cfg(feature = "split-pa1")]
pmcr.set_pa1so(true);
#[cfg(feature = "split-pc2")]
pmcr.set_pc2so(true);
#[cfg(feature = "split-pc3")]
pmcr.set_pc3so(true);
});
gpio::init();
dma::init(
#[cfg(bdma)]

View File

@ -1,11 +1,11 @@
use core::arch::asm;
use core::marker::PhantomData;
use atomic_polyfill::{compiler_fence, Ordering};
use cortex_m::peripheral::SCB;
use embassy_executor::*;
use crate::interrupt;
use crate::interrupt::typelevel::Interrupt;
use crate::rcc::low_power_ready;
use crate::time_driver::{get_driver, RtcDriver};
@ -19,36 +19,20 @@ foreach_interrupt! {
(RTC, rtc, $block:ident, WKUP, $irq:ident) => {
#[interrupt]
unsafe fn $irq() {
unsafe { EXECUTOR.as_mut().unwrap() }.on_wakeup_irq();
EXECUTOR.as_mut().unwrap().on_wakeup_irq();
}
};
}
// pub fn timer_driver_pause_time() {
// pause_time();
// }
#[allow(dead_code)]
pub(crate) unsafe fn on_wakeup_irq() {
EXECUTOR.as_mut().unwrap().on_wakeup_irq();
}
pub fn stop_with_rtc(rtc: &'static Rtc) {
unsafe { EXECUTOR.as_mut().unwrap() }.stop_with_rtc(rtc)
}
// pub fn start_wakeup_alarm(requested_duration: embassy_time::Duration) {
// let rtc_instant = unsafe { EXECUTOR.as_mut().unwrap() }
// .rtc
// .unwrap()
// .start_wakeup_alarm(requested_duration);
//
// unsafe { EXECUTOR.as_mut().unwrap() }.last_stop = Some(rtc_instant);
// }
//
// pub fn set_sleepdeep() {
// unsafe { EXECUTOR.as_mut().unwrap() }.scb.set_sleepdeep();
// }
//
// pub fn stop_wakeup_alarm() -> RtcInstant {
// unsafe { EXECUTOR.as_mut().unwrap() }.rtc.unwrap().stop_wakeup_alarm()
// }
/// Thread mode executor, using WFE/SEV.
///
/// This is the simplest and most common kind of executor. It runs on
@ -84,39 +68,31 @@ impl Executor {
}
unsafe fn on_wakeup_irq(&mut self) {
trace!("low power: on wakeup irq");
self.time_driver.resume_time();
trace!("low power: resume time");
trace!("low power: resume");
}
pub(self) fn stop_with_rtc(&mut self, rtc: &'static Rtc) {
trace!("low power: stop with rtc configured");
self.time_driver.set_rtc(rtc);
crate::interrupt::typelevel::RTC_WKUP::unpend();
unsafe { crate::interrupt::typelevel::RTC_WKUP::enable() };
rtc.enable_wakeup_line();
trace!("low power: stop with rtc configured");
}
fn configure_pwr(&mut self) {
trace!("low power: configure_pwr");
self.scb.clear_sleepdeep();
compiler_fence(Ordering::SeqCst);
if !low_power_ready() {
trace!("low power: configure_pwr: low power not ready");
return;
trace!("low power: not ready to stop");
} else if self.time_driver.pause_time().is_err() {
trace!("low power: failed to pause time");
} else {
trace!("low power: stop");
self.scb.set_sleepdeep();
}
if self.time_driver.pause_time().is_err() {
trace!("low power: configure_pwr: time driver failed to pause");
return;
}
trace!("low power: enter stop...");
self.scb.set_sleepdeep();
}
/// Run the executor.

133
embassy-stm32/src/opamp.rs Normal file
View File

@ -0,0 +1,133 @@
#![macro_use]
use embassy_hal_internal::{into_ref, PeripheralRef};
use crate::Peripheral;
#[cfg(opamp_f3)]
pub struct OpAmpOutput<'d, 'p, T: Instance, P: NonInvertingPin<T>> {
_inner: &'d OpAmp<'d, T>,
_input: &'p mut P,
}
pub struct OpAmp<'d, T: Instance> {
_inner: PeripheralRef<'d, T>,
}
impl<'d, T: Instance> OpAmp<'d, T> {
pub fn new(opamp: impl Peripheral<P = T> + 'd) -> Self {
Self::new_inner(opamp)
}
fn new_inner(opamp: impl Peripheral<P = T> + 'd) -> Self {
into_ref!(opamp);
#[cfg(opamp_f3)]
T::regs().opampcsr().modify(|w| {
w.set_opampen(true);
});
#[cfg(opamp_g4)]
T::regs().opamp_csr().modify(|w| {
w.set_opaen(true);
});
Self { _inner: opamp }
}
#[cfg(opamp_f3)]
pub fn buffer_for<'a, 'b, P>(&'a mut self, pin: &'b mut P) -> OpAmpOutput<'a, 'b, T, P>
where
P: NonInvertingPin<T>,
{
#[cfg(opamp_f3)]
T::regs().opampcsr().modify(|w| {
w.set_vp_sel(pin.channel());
});
OpAmpOutput {
_inner: self,
_input: pin,
}
}
}
pub trait Instance: sealed::Instance + 'static {}
pub(crate) mod sealed {
pub trait Instance {
fn regs() -> crate::pac::opamp::Opamp;
}
pub trait NonInvertingPin<T: Instance> {
fn channel(&self) -> u8;
}
pub trait InvertingPin<T: Instance> {
fn channel(&self) -> u8;
}
}
pub trait NonInvertingPin<T: Instance>: sealed::NonInvertingPin<T> {}
pub trait InvertingPin<T: Instance>: sealed::InvertingPin<T> {}
#[cfg(opamp_f3)]
macro_rules! impl_opamp_output {
($inst:ident, $adc:ident, $ch:expr) => {
impl<'d, 'p, P: NonInvertingPin<crate::peripherals::$inst>> crate::adc::sealed::AdcPin<crate::peripherals::$adc>
for OpAmpOutput<'d, 'p, crate::peripherals::$inst, P>
{
fn channel(&self) -> u8 {
$ch
}
}
impl<'d, 'p, P: NonInvertingPin<crate::peripherals::$inst>> crate::adc::AdcPin<crate::peripherals::$adc>
for OpAmpOutput<'d, 'p, crate::peripherals::$inst, P>
{
}
};
}
#[cfg(opamp_f3)]
foreach_peripheral!(
(opamp, OPAMP1) => {
impl_opamp_output!(OPAMP1, ADC1, 3);
};
(opamp, OPAMP2) => {
impl_opamp_output!(OPAMP2, ADC2, 3);
};
(opamp, OPAMP3) => {
impl_opamp_output!(OPAMP3, ADC3, 1);
};
(opamp, OPAMP4) => {
impl_opamp_output!(OPAMP4, ADC4, 3);
};
);
foreach_peripheral! {
(opamp, $inst:ident) => {
impl sealed::Instance for crate::peripherals::$inst {
fn regs() -> crate::pac::opamp::Opamp {
crate::pac::$inst
}
}
impl Instance for crate::peripherals::$inst {
}
};
}
#[allow(unused_macros)]
macro_rules! impl_opamp_pin {
($inst:ident, $pin:ident, $ch:expr) => {
impl crate::opamp::NonInvertingPin<peripherals::$inst> for crate::peripherals::$pin {}
impl crate::opamp::sealed::NonInvertingPin<peripherals::$inst> for crate::peripherals::$pin {
fn channel(&self) -> u8 {
$ch
}
}
};
}

View File

@ -38,6 +38,22 @@ impl Into<u8> for QspiWidth {
}
}
#[allow(dead_code)]
#[derive(Copy, Clone)]
pub enum FlashSelection {
Flash1,
Flash2,
}
impl Into<bool> for FlashSelection {
fn into(self) -> bool {
match self {
FlashSelection::Flash1 => false,
FlashSelection::Flash2 => true,
}
}
}
#[derive(Copy, Clone)]
pub enum MemorySize {
_1KiB,

View File

@ -7,7 +7,7 @@ use enums::*;
use crate::dma::Transfer;
use crate::gpio::sealed::AFType;
use crate::gpio::AnyPin;
use crate::gpio::{AnyPin, Pull};
use crate::pac::quadspi::Quadspi as Regs;
use crate::rcc::RccPeripheral;
use crate::{peripherals, Peripheral};
@ -83,30 +83,30 @@ pub struct Qspi<'d, T: Instance, Dma> {
}
impl<'d, T: Instance, Dma> Qspi<'d, T, Dma> {
pub fn new(
pub fn new_bk1(
peri: impl Peripheral<P = T> + 'd,
d0: impl Peripheral<P = impl D0Pin<T>> + 'd,
d1: impl Peripheral<P = impl D1Pin<T>> + 'd,
d2: impl Peripheral<P = impl D2Pin<T>> + 'd,
d3: impl Peripheral<P = impl D3Pin<T>> + 'd,
d0: impl Peripheral<P = impl BK1D0Pin<T>> + 'd,
d1: impl Peripheral<P = impl BK1D1Pin<T>> + 'd,
d2: impl Peripheral<P = impl BK1D2Pin<T>> + 'd,
d3: impl Peripheral<P = impl BK1D3Pin<T>> + 'd,
sck: impl Peripheral<P = impl SckPin<T>> + 'd,
nss: impl Peripheral<P = impl NSSPin<T>> + 'd,
nss: impl Peripheral<P = impl BK1NSSPin<T>> + 'd,
dma: impl Peripheral<P = Dma> + 'd,
config: Config,
) -> Self {
into_ref!(peri, d0, d1, d2, d3, sck, nss);
sck.set_as_af(sck.af_num(), AFType::OutputPushPull);
sck.set_as_af_pull(sck.af_num(), AFType::OutputPushPull, Pull::None);
sck.set_speed(crate::gpio::Speed::VeryHigh);
nss.set_as_af(nss.af_num(), AFType::OutputPushPull);
nss.set_as_af_pull(nss.af_num(), AFType::OutputPushPull, Pull::Up);
nss.set_speed(crate::gpio::Speed::VeryHigh);
d0.set_as_af(d0.af_num(), AFType::OutputPushPull);
d0.set_as_af_pull(d0.af_num(), AFType::OutputPushPull, Pull::None);
d0.set_speed(crate::gpio::Speed::VeryHigh);
d1.set_as_af(d1.af_num(), AFType::OutputPushPull);
d1.set_as_af_pull(d1.af_num(), AFType::OutputPushPull, Pull::None);
d1.set_speed(crate::gpio::Speed::VeryHigh);
d2.set_as_af(d2.af_num(), AFType::OutputPushPull);
d2.set_as_af_pull(d2.af_num(), AFType::OutputPushPull, Pull::None);
d2.set_speed(crate::gpio::Speed::VeryHigh);
d3.set_as_af(d3.af_num(), AFType::OutputPushPull);
d3.set_as_af_pull(d3.af_num(), AFType::OutputPushPull, Pull::None);
d3.set_speed(crate::gpio::Speed::VeryHigh);
Self::new_inner(
@ -119,6 +119,47 @@ impl<'d, T: Instance, Dma> Qspi<'d, T, Dma> {
Some(nss.map_into()),
dma,
config,
FlashSelection::Flash2,
)
}
pub fn new_bk2(
peri: impl Peripheral<P = T> + 'd,
d0: impl Peripheral<P = impl BK2D0Pin<T>> + 'd,
d1: impl Peripheral<P = impl BK2D1Pin<T>> + 'd,
d2: impl Peripheral<P = impl BK2D2Pin<T>> + 'd,
d3: impl Peripheral<P = impl BK2D3Pin<T>> + 'd,
sck: impl Peripheral<P = impl SckPin<T>> + 'd,
nss: impl Peripheral<P = impl BK2NSSPin<T>> + 'd,
dma: impl Peripheral<P = Dma> + 'd,
config: Config,
) -> Self {
into_ref!(peri, d0, d1, d2, d3, sck, nss);
sck.set_as_af_pull(sck.af_num(), AFType::OutputPushPull, Pull::None);
sck.set_speed(crate::gpio::Speed::VeryHigh);
nss.set_as_af_pull(nss.af_num(), AFType::OutputPushPull, Pull::Up);
nss.set_speed(crate::gpio::Speed::VeryHigh);
d0.set_as_af_pull(d0.af_num(), AFType::OutputPushPull, Pull::None);
d0.set_speed(crate::gpio::Speed::VeryHigh);
d1.set_as_af_pull(d1.af_num(), AFType::OutputPushPull, Pull::None);
d1.set_speed(crate::gpio::Speed::VeryHigh);
d2.set_as_af_pull(d2.af_num(), AFType::OutputPushPull, Pull::None);
d2.set_speed(crate::gpio::Speed::VeryHigh);
d3.set_as_af_pull(d3.af_num(), AFType::OutputPushPull, Pull::None);
d3.set_speed(crate::gpio::Speed::VeryHigh);
Self::new_inner(
peri,
Some(d0.map_into()),
Some(d1.map_into()),
Some(d2.map_into()),
Some(d3.map_into()),
Some(sck.map_into()),
Some(nss.map_into()),
dma,
config,
FlashSelection::Flash2,
)
}
@ -132,22 +173,40 @@ impl<'d, T: Instance, Dma> Qspi<'d, T, Dma> {
nss: Option<PeripheralRef<'d, AnyPin>>,
dma: impl Peripheral<P = Dma> + 'd,
config: Config,
fsel: FlashSelection,
) -> Self {
into_ref!(peri, dma);
T::enable();
T::REGS.cr().write(|w| w.set_fthres(config.fifo_threshold.into()));
T::reset();
while T::REGS.sr().read().busy() {}
T::REGS.cr().write(|w| {
w.set_prescaler(config.prescaler);
#[cfg(stm32h7)]
{
use stm32_metapac::quadspi::regs::Cr;
// Apply precautionary steps according to the errata...
T::REGS.cr().write_value(Cr(0));
while T::REGS.sr().read().busy() {}
T::REGS.cr().write_value(Cr(0xFF000001));
T::REGS.ccr().write(|w| w.set_frcm(true));
T::REGS.ccr().write(|w| w.set_frcm(true));
T::REGS.cr().write_value(Cr(0));
while T::REGS.sr().read().busy() {}
}
T::REGS.cr().modify(|w| {
w.set_en(true);
//w.set_tcen(false);
w.set_sshift(false);
w.set_fthres(config.fifo_threshold.into());
w.set_prescaler(config.prescaler);
w.set_fsel(fsel.into());
});
T::REGS.dcr().write(|w| {
T::REGS.dcr().modify(|w| {
w.set_fsize(config.memory_size.into());
w.set_csht(config.cs_high_time.into());
w.set_ckmode(false);
w.set_ckmode(true);
});
Self {
@ -164,6 +223,7 @@ impl<'d, T: Instance, Dma> Qspi<'d, T, Dma> {
}
pub fn command(&mut self, transaction: TransferConfig) {
#[cfg(not(stm32h7))]
T::REGS.cr().modify(|v| v.set_dmaen(false));
self.setup_transaction(QspiMode::IndirectWrite, &transaction);
@ -172,6 +232,7 @@ impl<'d, T: Instance, Dma> Qspi<'d, T, Dma> {
}
pub fn blocking_read(&mut self, buf: &mut [u8], transaction: TransferConfig) {
#[cfg(not(stm32h7))]
T::REGS.cr().modify(|v| v.set_dmaen(false));
self.setup_transaction(QspiMode::IndirectWrite, &transaction);
@ -195,7 +256,10 @@ impl<'d, T: Instance, Dma> Qspi<'d, T, Dma> {
}
pub fn blocking_write(&mut self, buf: &[u8], transaction: TransferConfig) {
// STM32H7 does not have dmaen
#[cfg(not(stm32h7))]
T::REGS.cr().modify(|v| v.set_dmaen(false));
self.setup_transaction(QspiMode::IndirectWrite, &transaction);
if let Some(len) = transaction.data_len {
@ -238,6 +302,8 @@ impl<'d, T: Instance, Dma> Qspi<'d, T, Dma> {
)
};
// STM32H7 does not have dmaen
#[cfg(not(stm32h7))]
T::REGS.cr().modify(|v| v.set_dmaen(true));
transfer.blocking_wait();
@ -264,6 +330,8 @@ impl<'d, T: Instance, Dma> Qspi<'d, T, Dma> {
)
};
// STM32H7 does not have dmaen
#[cfg(not(stm32h7))]
T::REGS.cr().modify(|v| v.set_dmaen(true));
transfer.blocking_wait();
@ -313,11 +381,17 @@ pub(crate) mod sealed {
pub trait Instance: Peripheral<P = Self> + sealed::Instance + RccPeripheral {}
pin_trait!(SckPin, Instance);
pin_trait!(D0Pin, Instance);
pin_trait!(D1Pin, Instance);
pin_trait!(D2Pin, Instance);
pin_trait!(D3Pin, Instance);
pin_trait!(NSSPin, Instance);
pin_trait!(BK1D0Pin, Instance);
pin_trait!(BK1D1Pin, Instance);
pin_trait!(BK1D2Pin, Instance);
pin_trait!(BK1D3Pin, Instance);
pin_trait!(BK1NSSPin, Instance);
pin_trait!(BK2D0Pin, Instance);
pin_trait!(BK2D1Pin, Instance);
pin_trait!(BK2D2Pin, Instance);
pin_trait!(BK2D3Pin, Instance);
pin_trait!(BK2NSSPin, Instance);
dma_trait!(QuadDma, Instance);

View File

@ -1,5 +1,5 @@
#[allow(dead_code)]
#[derive(Default)]
#[derive(Default, Clone, Copy)]
pub enum LseDrive {
#[cfg(any(rtc_v2f7, rtc_v2l4))]
Low = 0,
@ -26,19 +26,7 @@ impl From<LseDrive> for crate::pac::rcc::vals::Lsedrv {
}
}
#[allow(dead_code)]
#[derive(Copy, Clone, Debug, PartialEq)]
#[repr(u8)]
pub enum RtcClockSource {
/// 00: No clock
NoClock = 0b00,
/// 01: LSE oscillator clock used as RTC clock
LSE = 0b01,
/// 10: LSI oscillator clock used as RTC clock
LSI = 0b10,
/// 11: HSE oscillator clock divided by 32 used as RTC clock
HSE = 0b11,
}
pub use crate::pac::rcc::vals::Rtcsel as RtcClockSource;
#[cfg(not(any(rtc_v2l0, rtc_v2l1, stm32c0)))]
#[allow(dead_code)]
@ -58,13 +46,13 @@ impl BackupDomain {
))]
#[allow(dead_code, unused_variables)]
fn modify<R>(f: impl FnOnce(&mut Bdcr) -> R) -> R {
#[cfg(any(rtc_v2f2, rtc_v2f3, rtc_v2l1))]
#[cfg(any(rtc_v2f2, rtc_v2f3, rtc_v2l1, rtc_v2l0))]
let cr = crate::pac::PWR.cr();
#[cfg(any(rtc_v2f4, rtc_v2f7, rtc_v2h7, rtc_v2l4, rtc_v2wb, rtc_v3, rtc_v3u5))]
let cr = crate::pac::PWR.cr1();
// TODO: Missing from PAC for l0 and f0?
#[cfg(not(any(rtc_v2f0, rtc_v2l0, rtc_v3u5)))]
#[cfg(not(any(rtc_v2f0, rtc_v3u5)))]
{
cr.modify(|w| w.set_dbp(true));
while !cr.read().dbp() {}
@ -99,101 +87,97 @@ impl BackupDomain {
rtc_v3u5
))]
#[allow(dead_code, unused_variables)]
pub fn configure_ls(clock_source: RtcClockSource, lse_drive: Option<LseDrive>) {
pub fn configure_ls(clock_source: RtcClockSource, lsi: bool, lse: Option<LseDrive>) {
use atomic_polyfill::{compiler_fence, Ordering};
match clock_source {
RtcClockSource::LSI => {
#[cfg(rtc_v3u5)]
let csr = crate::pac::RCC.bdcr();
#[cfg(not(rtc_v3u5))]
let csr = crate::pac::RCC.csr();
Self::modify(|_| {
#[cfg(not(rtc_v2wb))]
csr.modify(|w| w.set_lsion(true));
#[cfg(rtc_v2wb)]
csr.modify(|w| w.set_lsi1on(true));
});
#[cfg(not(rtc_v2wb))]
while !csr.read().lsirdy() {}
#[cfg(rtc_v2wb)]
while !csr.read().lsi1rdy() {}
}
RtcClockSource::LSE => {
let lse_drive = lse_drive.unwrap_or_default();
Self::modify(|w| {
#[cfg(any(rtc_v2f7, rtc_v2h7, rtc_v2l0, rtc_v2l4))]
w.set_lsedrv(lse_drive.into());
w.set_lseon(true);
});
while !Self::read().lserdy() {}
}
RtcClockSource::LSI => assert!(lsi),
RtcClockSource::LSE => assert!(&lse.is_some()),
_ => {}
};
Self::configure_rtc(clock_source);
}
if lsi {
#[cfg(rtc_v3u5)]
let csr = crate::pac::RCC.bdcr();
#[cfg(any(
rtc_v2f0, rtc_v2f2, rtc_v2f3, rtc_v2f4, rtc_v2f7, rtc_v2h7, rtc_v2l0, rtc_v2l1, rtc_v2l4, rtc_v2wb, rtc_v3,
rtc_v3u5
))]
#[allow(dead_code, unused_variables)]
pub fn configure_rtc(clock_source: RtcClockSource) {
let clock_source = clock_source as u8;
#[cfg(any(
not(any(rtc_v3, rtc_v3u5, rtc_v2wb)),
all(any(rtc_v3, rtc_v3u5), not(any(rcc_wl5, rcc_wle)))
))]
let clock_source = crate::pac::rcc::vals::Rtcsel::from_bits(clock_source);
#[cfg(not(rtc_v3u5))]
let csr = crate::pac::RCC.csr();
#[cfg(not(rtc_v2wb))]
Self::modify(|w| {
// Select RTC source
w.set_rtcsel(clock_source);
});
}
// Disable backup domain write protection
Self::modify(|_| {});
#[cfg(any(
rtc_v2f0, rtc_v2f2, rtc_v2f3, rtc_v2f4, rtc_v2f7, rtc_v2h7, rtc_v2l0, rtc_v2l1, rtc_v2l4, rtc_v2wb, rtc_v3,
rtc_v3u5
))]
#[allow(dead_code)]
pub fn enable_rtc() {
#[cfg(not(any(rcc_wb, rcc_wba)))]
csr.modify(|w| w.set_lsion(true));
#[cfg(any(rcc_wb, rcc_wba))]
csr.modify(|w| w.set_lsi1on(true));
#[cfg(not(any(rcc_wb, rcc_wba)))]
while !csr.read().lsirdy() {}
#[cfg(any(rcc_wb, rcc_wba))]
while !csr.read().lsi1rdy() {}
}
// backup domain configuration (LSEON, RTCEN, RTCSEL) is kept across resets.
// once set, changing it requires a backup domain reset.
// first check if the configuration matches what we want.
// check if it's already enabled and in the source we want.
let reg = Self::read();
let mut ok = true;
ok &= reg.rtcsel() == clock_source;
#[cfg(not(rcc_wba))]
{
ok &= reg.rtcen() == (clock_source != RtcClockSource::NOCLOCK);
}
ok &= reg.lseon() == lse.is_some();
#[cfg(any(rtc_v2f7, rtc_v2h7, rtc_v2l0, rtc_v2l4))]
if let Some(lse_drive) = lse {
ok &= reg.lsedrv() == lse_drive.into();
}
#[cfg(any(rtc_v2h7, rtc_v2l4, rtc_v2wb, rtc_v3, rtc_v3u5))]
assert!(!reg.lsecsson(), "RTC is not compatible with LSE CSS, yet.");
// if configuration is OK, we're done.
if ok {
// RTC code assumes backup domain is unlocked
Self::modify(|w| {});
if !reg.rtcen() {
#[cfg(not(any(rtc_v2l0, rtc_v2l1, rtc_v2f2)))]
trace!("BDCR ok: {:08x}", Self::read().0);
compiler_fence(Ordering::SeqCst);
return;
}
// If not OK, reset backup domain and configure it.
#[cfg(not(any(rcc_l0, rcc_l1)))]
{
Self::modify(|w| w.set_bdrst(true));
Self::modify(|w| w.set_bdrst(false));
}
if let Some(lse_drive) = lse {
Self::modify(|w| {
// Reset
#[cfg(not(any(rtc_v2l0, rtc_v2l1, rtc_v2f2)))]
w.set_bdrst(false);
#[cfg(any(rtc_v2f7, rtc_v2h7, rtc_v2l0, rtc_v2l4))]
w.set_lsedrv(lse_drive.into());
w.set_lseon(true);
});
while !Self::read().lserdy() {}
}
if clock_source != RtcClockSource::NOCLOCK {
Self::modify(|w| {
#[cfg(any(rtc_v2h7, rtc_v2l4, rtc_v2wb, rtc_v3, rtc_v3u5))]
assert!(!w.lsecsson(), "RTC is not compatible with LSE CSS, yet.");
#[cfg(not(rcc_wba))]
w.set_rtcen(true);
w.set_rtcsel(reg.rtcsel());
// Restore bcdr
#[cfg(any(rtc_v2l4, rtc_v2wb, rtc_v3, rtc_v3u5))]
w.set_lscosel(reg.lscosel());
#[cfg(any(rtc_v2l4, rtc_v2wb, rtc_v3, rtc_v3u5))]
w.set_lscoen(reg.lscoen());
w.set_lseon(reg.lseon());
#[cfg(any(rtc_v2f0, rtc_v2f7, rtc_v2h7, rtc_v2l4, rtc_v2wb, rtc_v3, rtc_v3u5))]
w.set_lsedrv(reg.lsedrv());
w.set_lsebyp(reg.lsebyp());
w.set_rtcsel(clock_source);
});
}
trace!("BDCR configured: {:08x}", Self::read().0);
compiler_fence(Ordering::SeqCst);
}
}

View File

@ -2,173 +2,55 @@ use core::ops::Div;
#[allow(unused_imports)]
use crate::pac::rcc;
pub use crate::pac::rcc::vals::{Hpre as AHBPrescaler, Ppre as APBPrescaler};
use crate::time::Hertz;
/// Voltage Scale
///
/// Represents the voltage range feeding the CPU core. The maximum core
/// clock frequency depends on this value.
///
/// Scale0 represents the highest voltage range
#[derive(Copy, Clone, PartialEq)]
pub enum VoltageScale {
Scale0,
Scale1,
#[cfg(not(any(rcc_wl5, rcc_wle)))]
Scale2,
#[cfg(not(any(rcc_wl5, rcc_wle)))]
Scale3,
}
/// AHB prescaler
#[derive(Clone, Copy, PartialEq)]
pub enum AHBPrescaler {
NotDivided,
Div2,
#[cfg(any(rcc_wb, rcc_wl5, rcc_wle))]
Div3,
Div4,
#[cfg(any(rcc_wb, rcc_wl5, rcc_wle))]
Div5,
#[cfg(any(rcc_wb, rcc_wl5, rcc_wle))]
Div6,
Div8,
#[cfg(any(rcc_wb, rcc_wl5, rcc_wle))]
Div10,
Div16,
#[cfg(any(rcc_wb, rcc_wl5, rcc_wle))]
Div32,
Div64,
Div128,
Div256,
Div512,
}
impl Div<AHBPrescaler> for Hertz {
type Output = Hertz;
fn div(self, rhs: AHBPrescaler) -> Self::Output {
let divisor = match rhs {
AHBPrescaler::NotDivided => 1,
AHBPrescaler::Div2 => 2,
AHBPrescaler::DIV1 => 1,
AHBPrescaler::DIV2 => 2,
#[cfg(any(rcc_wb, rcc_wl5, rcc_wle))]
AHBPrescaler::Div3 => 3,
AHBPrescaler::Div4 => 4,
AHBPrescaler::DIV3 => 3,
AHBPrescaler::DIV4 => 4,
#[cfg(any(rcc_wb, rcc_wl5, rcc_wle))]
AHBPrescaler::Div5 => 5,
AHBPrescaler::DIV5 => 5,
#[cfg(any(rcc_wb, rcc_wl5, rcc_wle))]
AHBPrescaler::Div6 => 6,
AHBPrescaler::Div8 => 8,
AHBPrescaler::DIV6 => 6,
AHBPrescaler::DIV8 => 8,
#[cfg(any(rcc_wb, rcc_wl5, rcc_wle))]
AHBPrescaler::Div10 => 10,
AHBPrescaler::Div16 => 16,
AHBPrescaler::DIV10 => 10,
AHBPrescaler::DIV16 => 16,
#[cfg(any(rcc_wb, rcc_wl5, rcc_wle))]
AHBPrescaler::Div32 => 32,
AHBPrescaler::Div64 => 64,
AHBPrescaler::Div128 => 128,
AHBPrescaler::Div256 => 256,
AHBPrescaler::Div512 => 512,
AHBPrescaler::DIV32 => 32,
#[cfg(not(rcc_wba))]
AHBPrescaler::DIV64 => 64,
#[cfg(not(rcc_wba))]
AHBPrescaler::DIV128 => 128,
#[cfg(not(rcc_wba))]
AHBPrescaler::DIV256 => 256,
#[cfg(not(rcc_wba))]
AHBPrescaler::DIV512 => 512,
_ => unreachable!(),
};
Hertz(self.0 / divisor)
}
}
#[cfg(not(any(rcc_g4, rcc_wb, rcc_wl5, rcc_wle)))]
impl From<AHBPrescaler> for rcc::vals::Hpre {
fn from(val: AHBPrescaler) -> rcc::vals::Hpre {
use rcc::vals::Hpre;
match val {
#[cfg(not(rcc_u5))]
AHBPrescaler::NotDivided => Hpre::DIV1,
#[cfg(rcc_u5)]
AHBPrescaler::NotDivided => Hpre::NONE,
AHBPrescaler::Div2 => Hpre::DIV2,
AHBPrescaler::Div4 => Hpre::DIV4,
AHBPrescaler::Div8 => Hpre::DIV8,
AHBPrescaler::Div16 => Hpre::DIV16,
AHBPrescaler::Div64 => Hpre::DIV64,
AHBPrescaler::Div128 => Hpre::DIV128,
AHBPrescaler::Div256 => Hpre::DIV256,
AHBPrescaler::Div512 => Hpre::DIV512,
}
}
}
#[cfg(any(rcc_wb, rcc_wl5, rcc_wle))]
impl From<AHBPrescaler> for u8 {
fn from(val: AHBPrescaler) -> u8 {
match val {
AHBPrescaler::NotDivided => 0x0,
AHBPrescaler::Div2 => 0x08,
AHBPrescaler::Div3 => 0x01,
AHBPrescaler::Div4 => 0x09,
AHBPrescaler::Div5 => 0x02,
AHBPrescaler::Div6 => 0x05,
AHBPrescaler::Div8 => 0x0a,
AHBPrescaler::Div10 => 0x06,
AHBPrescaler::Div16 => 0x0b,
AHBPrescaler::Div32 => 0x07,
AHBPrescaler::Div64 => 0x0c,
AHBPrescaler::Div128 => 0x0d,
AHBPrescaler::Div256 => 0x0e,
AHBPrescaler::Div512 => 0x0f,
}
}
}
/// APB prescaler
#[derive(Clone, Copy)]
pub enum APBPrescaler {
NotDivided,
Div2,
Div4,
Div8,
Div16,
}
impl Div<APBPrescaler> for Hertz {
type Output = Hertz;
fn div(self, rhs: APBPrescaler) -> Self::Output {
let divisor = match rhs {
APBPrescaler::NotDivided => 1,
APBPrescaler::Div2 => 2,
APBPrescaler::Div4 => 4,
APBPrescaler::Div8 => 8,
APBPrescaler::Div16 => 16,
APBPrescaler::DIV1 => 1,
APBPrescaler::DIV2 => 2,
APBPrescaler::DIV4 => 4,
APBPrescaler::DIV8 => 8,
APBPrescaler::DIV16 => 16,
_ => unreachable!(),
};
Hertz(self.0 / divisor)
}
}
#[cfg(not(any(rcc_f1, rcc_f100, rcc_f1cl, rcc_g4, rcc_h7, rcc_h7ab, rcc_wb, rcc_wl5, rcc_wle)))]
impl From<APBPrescaler> for rcc::vals::Ppre {
fn from(val: APBPrescaler) -> rcc::vals::Ppre {
use rcc::vals::Ppre;
match val {
#[cfg(not(rcc_u5))]
APBPrescaler::NotDivided => Ppre::DIV1,
#[cfg(rcc_u5)]
APBPrescaler::NotDivided => Ppre::NONE,
APBPrescaler::Div2 => Ppre::DIV2,
APBPrescaler::Div4 => Ppre::DIV4,
APBPrescaler::Div8 => Ppre::DIV8,
APBPrescaler::Div16 => Ppre::DIV16,
}
}
}
#[cfg(any(rcc_wb, rcc_wl5, rcc_wle))]
impl From<APBPrescaler> for u8 {
fn from(val: APBPrescaler) -> u8 {
match val {
APBPrescaler::NotDivided => 1,
APBPrescaler::Div2 => 0x04,
APBPrescaler::Div4 => 0x05,
APBPrescaler::Div8 => 0x06,
APBPrescaler::Div16 => 0x07,
}
}
}

View File

@ -58,8 +58,8 @@ impl Default for Config {
fn default() -> Config {
Config {
mux: ClockSrc::HSI(HSIPrescaler::NotDivided),
ahb_pre: AHBPrescaler::NotDivided,
apb_pre: APBPrescaler::NotDivided,
ahb_pre: AHBPrescaler::DIV1,
apb_pre: APBPrescaler::DIV1,
}
}
}
@ -151,20 +151,21 @@ pub(crate) unsafe fn init(config: Config) {
}
let ahb_div = match config.ahb_pre {
AHBPrescaler::NotDivided => 1,
AHBPrescaler::Div2 => 2,
AHBPrescaler::Div4 => 4,
AHBPrescaler::Div8 => 8,
AHBPrescaler::Div16 => 16,
AHBPrescaler::Div64 => 64,
AHBPrescaler::Div128 => 128,
AHBPrescaler::Div256 => 256,
AHBPrescaler::Div512 => 512,
AHBPrescaler::DIV1 => 1,
AHBPrescaler::DIV2 => 2,
AHBPrescaler::DIV4 => 4,
AHBPrescaler::DIV8 => 8,
AHBPrescaler::DIV16 => 16,
AHBPrescaler::DIV64 => 64,
AHBPrescaler::DIV128 => 128,
AHBPrescaler::DIV256 => 256,
AHBPrescaler::DIV512 => 512,
_ => unreachable!(),
};
let ahb_freq = sys_clk / ahb_div;
let (apb_freq, apb_tim_freq) = match config.apb_pre {
APBPrescaler::NotDivided => (ahb_freq, ahb_freq),
APBPrescaler::DIV1 => (ahb_freq, ahb_freq),
pre => {
let pre: Ppre = pre.into();
let pre: u8 = 1 << (pre.to_bits() - 3);

View File

@ -163,8 +163,8 @@ pub(crate) unsafe fn init(config: Config) {
// Only needed for stm32f103?
RCC.cfgr().modify(|w| {
w.set_adcpre(Adcpre::from_bits(apre_bits));
w.set_ppre2(Ppre1::from_bits(ppre2_bits));
w.set_ppre1(Ppre1::from_bits(ppre1_bits));
w.set_ppre2(Ppre::from_bits(ppre2_bits));
w.set_ppre1(Ppre::from_bits(ppre1_bits));
w.set_hpre(Hpre::from_bits(hpre_bits));
#[cfg(not(rcc_f100))]
w.set_usbpre(Usbpre::from_bits(usbpre as u8));

View File

@ -4,7 +4,7 @@ use core::ops::{Div, Mul};
pub use super::bus::{AHBPrescaler, APBPrescaler};
use crate::pac::flash::vals::Latency;
use crate::pac::rcc::vals::{Pllp, Pllsrc, Sw};
use crate::pac::{FLASH, PWR, RCC};
use crate::pac::{FLASH, RCC};
use crate::rcc::bd::BackupDomain;
use crate::rcc::{set_freqs, Clocks};
use crate::rtc::RtcClockSource;
@ -203,7 +203,20 @@ pub struct PLLClocks {
pub pll48_freq: Hertz,
}
pub use super::bus::VoltageScale;
/// Voltage range of the power supply used.
///
/// Used to calculate flash waitstates. See
/// RM0033 - Table 3. Number of wait states according to Cortex®-M3 clock frequency
pub enum VoltageScale {
/// 2.7 to 3.6 V
Range0,
/// 2.4 to 2.7 V
Range1,
/// 2.1 to 2.4 V
Range2,
/// 1.8 to 2.1 V
Range3,
}
impl VoltageScale {
const fn wait_states(&self, ahb_freq: Hertz) -> Option<Latency> {
@ -211,7 +224,7 @@ impl VoltageScale {
// Reference: RM0033 - Table 3. Number of wait states according to Cortex®-M3 clock
// frequency
match self {
VoltageScale::Scale3 => {
VoltageScale::Range3 => {
if ahb_freq <= 16_000_000 {
Some(Latency::WS0)
} else if ahb_freq <= 32_000_000 {
@ -232,7 +245,7 @@ impl VoltageScale {
None
}
}
VoltageScale::Scale2 => {
VoltageScale::Range2 => {
if ahb_freq <= 18_000_000 {
Some(Latency::WS0)
} else if ahb_freq <= 36_000_000 {
@ -251,7 +264,7 @@ impl VoltageScale {
None
}
}
VoltageScale::Scale1 => {
VoltageScale::Range1 => {
if ahb_freq <= 24_000_000 {
Some(Latency::WS0)
} else if ahb_freq <= 48_000_000 {
@ -266,7 +279,7 @@ impl VoltageScale {
None
}
}
VoltageScale::Scale0 => {
VoltageScale::Range0 => {
if ahb_freq <= 30_000_000 {
Some(Latency::WS0)
} else if ahb_freq <= 60_000_000 {
@ -291,6 +304,8 @@ pub struct Config {
pub pll: PLLConfig,
pub mux: ClockSrc,
pub rtc: Option<RtcClockSource>,
pub lsi: bool,
pub lse: Option<Hertz>,
pub voltage: VoltageScale,
pub ahb_pre: AHBPrescaler,
pub apb1_pre: APBPrescaler,
@ -305,12 +320,14 @@ impl Default for Config {
hsi: true,
pll_mux: PLLSrc::HSI,
pll: PLLConfig::default(),
voltage: VoltageScale::Scale3,
voltage: VoltageScale::Range3,
mux: ClockSrc::HSI,
rtc: None,
ahb_pre: AHBPrescaler::NotDivided,
apb1_pre: APBPrescaler::NotDivided,
apb2_pre: APBPrescaler::NotDivided,
lsi: false,
lse: None,
ahb_pre: AHBPrescaler::DIV1,
apb1_pre: APBPrescaler::DIV1,
apb2_pre: APBPrescaler::DIV1,
}
}
}
@ -383,7 +400,7 @@ pub(crate) unsafe fn init(config: Config) {
assert!(ahb_freq <= Hertz(120_000_000));
let (apb1_freq, apb1_tim_freq) = match config.apb1_pre {
APBPrescaler::NotDivided => (ahb_freq, ahb_freq),
APBPrescaler::DIV1 => (ahb_freq, ahb_freq),
pre => {
let freq = ahb_freq / pre;
(freq, Hertz(freq.0 * 2))
@ -393,7 +410,7 @@ pub(crate) unsafe fn init(config: Config) {
assert!(apb1_freq <= Hertz(30_000_000));
let (apb2_freq, apb2_tim_freq) = match config.apb2_pre {
APBPrescaler::NotDivided => (ahb_freq, ahb_freq),
APBPrescaler::DIV1 => (ahb_freq, ahb_freq),
pre => {
let freq = ahb_freq / pre;
(freq, Hertz(freq.0 * 2))
@ -418,12 +435,11 @@ pub(crate) unsafe fn init(config: Config) {
RCC.cr().modify(|w| w.set_hsion(false));
}
RCC.apb1enr().modify(|w| w.set_pwren(true));
PWR.cr().read();
config
.rtc
.map(|clock_source| BackupDomain::configure_ls(clock_source, None));
BackupDomain::configure_ls(
config.rtc.unwrap_or(RtcClockSource::NOCLOCK),
config.lsi,
config.lse.map(|_| Default::default()),
);
set_freqs(Clocks {
sys: sys_clk,

View File

@ -280,7 +280,7 @@ pub(crate) unsafe fn init(config: Config) {
}
});
#[cfg(rcc_f3)]
#[cfg(all(rcc_f3, adc3_common))]
let adc34 = config.adc.map(|adc| {
if !adc.is_bus() {
RCC.cfgr2().modify(|w| {
@ -291,9 +291,13 @@ pub(crate) unsafe fn init(config: Config) {
Hertz(sysclk / adc as u32)
})
} else {
// TODO: need to use only if adc32_common is present
crate::pac::ADC3_COMMON.ccr().modify(|w| {
assert!(!(adc.bus_div() == 1 && hpre_bits != Hpre::DIV1));
todo!()
w.set_ckmode(adc.into());
Hertz(sysclk / adc.bus_div() as u32)
})
}
});
@ -323,8 +327,10 @@ pub(crate) unsafe fn init(config: Config) {
ahb1: Hertz(hclk),
#[cfg(rcc_f3)]
adc: adc,
#[cfg(rcc_f3)]
#[cfg(all(rcc_f3, adc3_common))]
adc34: adc34,
#[cfg(all(rcc_f3, not(adc3_common)))]
adc34: None,
#[cfg(stm32f334)]
hrtim: hrtim,
});

View File

@ -3,7 +3,6 @@ use core::marker::PhantomData;
use embassy_hal_internal::into_ref;
use stm32_metapac::rcc::vals::{Mco1, Mco2, Mcopre};
use super::sealed::RccPeripheral;
use crate::gpio::sealed::AFType;
use crate::gpio::Speed;
use crate::pac::rcc::vals::{Hpre, Ppre, Sw};
@ -33,8 +32,13 @@ pub struct Config {
#[cfg(not(any(stm32f410, stm32f411, stm32f412, stm32f413, stm32f423, stm32f446)))]
pub plli2s: Option<Hertz>,
#[cfg(any(stm32f427, stm32f429, stm32f437, stm32f439, stm32f446, stm32f469, stm32f479))]
pub pllsai: Option<Hertz>,
pub pll48: bool,
pub rtc: Option<RtcClockSource>,
pub lsi: bool,
pub lse: Option<Hertz>,
}
#[cfg(stm32f410)]
@ -48,11 +52,10 @@ fn setup_i2s_pll(_vco_in: u32, _plli2s: Option<u32>) -> Option<u32> {
None
}
#[cfg(not(any(stm32f410, stm32f411, stm32f412, stm32f413, stm32f423, stm32f446)))]
fn setup_i2s_pll(vco_in: u32, plli2s: Option<u32>) -> Option<u32> {
#[cfg(not(any(stm32f410, stm32f411, stm32f412, stm32f413, stm32f423)))]
fn calculate_sai_i2s_pll_values(vco_in: u32, max_div: u32, target: Option<u32>) -> Option<(u32, u32, u32)> {
let min_div = 2;
let max_div = 7;
let target = match plli2s {
let target = match target {
Some(target) => target,
None => return None,
};
@ -76,15 +79,48 @@ fn setup_i2s_pll(vco_in: u32, plli2s: Option<u32>) -> Option<u32> {
})
.min_by_key(|(_, _, _, error)| *error)?;
Some((n, outdiv, output))
}
#[cfg(not(any(stm32f410, stm32f411, stm32f412, stm32f413, stm32f423, stm32f446)))]
fn setup_i2s_pll(vco_in: u32, plli2s: Option<u32>) -> Option<u32> {
let (n, outdiv, output) = calculate_sai_i2s_pll_values(vco_in, 7, plli2s)?;
RCC.plli2scfgr().modify(|w| {
w.set_plli2sn(n as u16);
w.set_plli2sr(outdiv as u8);
#[cfg(any(stm32f427, stm32f429, stm32f437, stm32f439, stm32f446, stm32f469, stm32f479))]
w.set_plli2sq(outdiv as u8); //set sai divider same as i2s
});
Some(output)
}
fn setup_pll(pllsrcclk: u32, use_hse: bool, pllsysclk: Option<u32>, plli2s: Option<u32>, pll48clk: bool) -> PllResults {
#[cfg(not(any(stm32f427, stm32f429, stm32f437, stm32f439, stm32f446, stm32f469, stm32f479)))]
fn setup_sai_pll(_vco_in: u32, _pllsai: Option<u32>) -> Option<u32> {
None
}
#[cfg(any(stm32f427, stm32f429, stm32f437, stm32f439, stm32f446, stm32f469, stm32f479))]
fn setup_sai_pll(vco_in: u32, pllsai: Option<u32>) -> Option<u32> {
let (n, outdiv, output) = calculate_sai_i2s_pll_values(vco_in, 15, pllsai)?;
RCC.pllsaicfgr().modify(|w| {
w.set_pllsain(n as u16);
w.set_pllsaiq(outdiv as u8);
});
Some(output)
}
fn setup_pll(
pllsrcclk: u32,
use_hse: bool,
pllsysclk: Option<u32>,
plli2s: Option<u32>,
pllsai: Option<u32>,
pll48clk: bool,
) -> PllResults {
use crate::pac::rcc::vals::{Pllp, Pllsrc};
let sysclk = pllsysclk.unwrap_or(pllsrcclk);
@ -96,6 +132,7 @@ fn setup_pll(pllsrcclk: u32, use_hse: bool, pllsysclk: Option<u32>, plli2s: Opti
pllsysclk: None,
pll48clk: None,
plli2sclk: None,
pllsaiclk: None,
};
}
// Input divisor from PLL source clock, must result to frequency in
@ -146,6 +183,7 @@ fn setup_pll(pllsrcclk: u32, use_hse: bool, pllsysclk: Option<u32>, plli2s: Opti
w.set_pllp(Pllp::from_bits(pllp as u8));
w.set_pllq(pllq as u8);
w.set_pllsrc(Pllsrc::from_bits(use_hse as u8));
w.set_pllr(0);
});
let real_pllsysclk = vco_in * plln / sysclk_div;
@ -155,6 +193,7 @@ fn setup_pll(pllsrcclk: u32, use_hse: bool, pllsysclk: Option<u32>, plli2s: Opti
pllsysclk: Some(real_pllsysclk),
pll48clk: if pll48clk { Some(real_pll48clk) } else { None },
plli2sclk: setup_i2s_pll(vco_in, plli2s),
pllsaiclk: setup_sai_pll(vco_in, pllsai),
}
}
@ -330,8 +369,6 @@ fn flash_setup(sysclk: u32) {
}
pub(crate) unsafe fn init(config: Config) {
crate::peripherals::PWR::enable();
let pllsrcclk = config.hse.map(|hse| hse.0).unwrap_or(HSI_FREQ.0);
let sysclk = config.sys_ck.map(|sys| sys.0).unwrap_or(pllsrcclk);
let sysclk_on_pll = sysclk != pllsrcclk;
@ -344,6 +381,10 @@ pub(crate) unsafe fn init(config: Config) {
config.plli2s.map(|i2s| i2s.0),
#[cfg(any(stm32f410, stm32f411, stm32f412, stm32f413, stm32f423, stm32f446))]
None,
#[cfg(any(stm32f427, stm32f429, stm32f437, stm32f439, stm32f446, stm32f469, stm32f479))]
config.pllsai.map(|sai| sai.0),
#[cfg(not(any(stm32f427, stm32f429, stm32f437, stm32f439, stm32f446, stm32f469, stm32f479)))]
None,
config.pll48,
);
@ -441,6 +482,12 @@ pub(crate) unsafe fn init(config: Config) {
while !RCC.cr().read().plli2srdy() {}
}
#[cfg(any(stm32f427, stm32f429, stm32f437, stm32f439, stm32f446, stm32f469, stm32f479))]
if plls.pllsaiclk.is_some() {
RCC.cr().modify(|w| w.set_pllsaion(true));
while !RCC.cr().read().pllsairdy() {}
}
RCC.cfgr().modify(|w| {
w.set_ppre2(Ppre::from_bits(ppre2_bits));
w.set_ppre1(Ppre::from_bits(ppre1_bits));
@ -461,12 +508,15 @@ pub(crate) unsafe fn init(config: Config) {
})
});
config
.rtc
.map(|clock_source| BackupDomain::configure_ls(clock_source, None));
BackupDomain::configure_ls(
config.rtc.unwrap_or(RtcClockSource::NOCLOCK),
config.lsi,
config.lse.map(|_| Default::default()),
);
let rtc = match config.rtc {
Some(RtcClockSource::LSI) => Some(LSI_FREQ),
Some(RtcClockSource::LSE) => Some(config.lse.unwrap()),
_ => None,
};
@ -488,7 +538,7 @@ pub(crate) unsafe fn init(config: Config) {
plli2s: plls.plli2sclk.map(Hertz),
#[cfg(any(stm32f427, stm32f429, stm32f437, stm32f439, stm32f446, stm32f469, stm32f479))]
pllsai: None,
pllsai: plls.pllsaiclk.map(Hertz),
rtc: rtc,
rtc_hse: None,
@ -501,6 +551,8 @@ struct PllResults {
pll48clk: Option<u32>,
#[allow(dead_code)]
plli2sclk: Option<u32>,
#[allow(dead_code)]
pllsaiclk: Option<u32>,
}
mod max {

View File

@ -1,7 +1,7 @@
use super::sealed::RccPeripheral;
use crate::pac::pwr::vals::Vos;
use crate::pac::rcc::vals::{Hpre, Ppre, Sw};
use crate::pac::{FLASH, PWR, RCC};
use crate::rcc::bd::{BackupDomain, RtcClockSource};
use crate::rcc::{set_freqs, Clocks};
use crate::time::Hertz;
@ -23,6 +23,9 @@ pub struct Config {
pub pclk2: Option<Hertz>,
pub pll48: bool,
pub rtc: Option<RtcClockSource>,
pub lsi: bool,
pub lse: Option<Hertz>,
}
fn setup_pll(pllsrcclk: u32, use_hse: bool, pllsysclk: Option<u32>, pll48clk: bool) -> PllResults {
@ -111,8 +114,6 @@ fn flash_setup(sysclk: u32) {
}
pub(crate) unsafe fn init(config: Config) {
crate::peripherals::PWR::enable();
if let Some(hse) = config.hse {
if config.bypass_hse {
assert!((max::HSE_BYPASS_MIN..=max::HSE_BYPASS_MAX).contains(&hse.0));
@ -212,10 +213,7 @@ pub(crate) unsafe fn init(config: Config) {
if plls.use_pll {
RCC.cr().modify(|w| w.set_pllon(false));
// enable PWR and setup VOSScale
RCC.apb1enr().modify(|w| w.set_pwren(true));
// setup VOSScale
let vos_scale = if sysclk <= 144_000_000 {
3
} else if sysclk <= 168_000_000 {
@ -265,6 +263,18 @@ pub(crate) unsafe fn init(config: Config) {
})
});
BackupDomain::configure_ls(
config.rtc.unwrap_or(RtcClockSource::NOCLOCK),
config.lsi,
config.lse.map(|_| Default::default()),
);
let rtc = match config.rtc {
Some(RtcClockSource::LSI) => Some(LSI_FREQ),
Some(RtcClockSource::LSE) => Some(config.lse.unwrap()),
_ => None,
};
set_freqs(Clocks {
sys: Hertz(sysclk),
apb1: Hertz(pclk1),
@ -278,6 +288,8 @@ pub(crate) unsafe fn init(config: Config) {
ahb3: Hertz(hclk),
pll48: plls.pll48clk.map(Hertz),
rtc,
});
}

View File

@ -186,8 +186,8 @@ impl Default for Config {
fn default() -> Config {
Config {
mux: ClockSrc::HSI16(HSI16Prescaler::NotDivided),
ahb_pre: AHBPrescaler::NotDivided,
apb_pre: APBPrescaler::NotDivided,
ahb_pre: AHBPrescaler::DIV1,
apb_pre: APBPrescaler::DIV1,
low_power_run: false,
}
}
@ -377,7 +377,7 @@ pub(crate) unsafe fn init(config: Config) {
let ahb_freq = Hertz(sys_clk) / config.ahb_pre;
let (apb_freq, apb_tim_freq) = match config.apb_pre {
APBPrescaler::NotDivided => (ahb_freq.0, ahb_freq.0),
APBPrescaler::DIV1 => (ahb_freq.0, ahb_freq.0),
pre => {
let pre: Ppre = pre.into();
let pre: u8 = 1 << (pre.to_bits() - 3);

View File

@ -1,5 +1,5 @@
use stm32_metapac::flash::vals::Latency;
use stm32_metapac::rcc::vals::{Adcsel, Hpre, Pllsrc, Ppre, Sw};
use stm32_metapac::rcc::vals::{Adcsel, Pllsrc, Sw};
use stm32_metapac::FLASH;
pub use super::bus::{AHBPrescaler, APBPrescaler};
@ -261,59 +261,29 @@ pub struct Pll {
pub div_r: Option<PllR>,
}
impl AHBPrescaler {
const fn div(self) -> u32 {
match self {
AHBPrescaler::NotDivided => 1,
AHBPrescaler::Div2 => 2,
AHBPrescaler::Div4 => 4,
AHBPrescaler::Div8 => 8,
AHBPrescaler::Div16 => 16,
AHBPrescaler::Div64 => 64,
AHBPrescaler::Div128 => 128,
AHBPrescaler::Div256 => 256,
AHBPrescaler::Div512 => 512,
}
fn ahb_div(ahb: AHBPrescaler) -> u32 {
match ahb {
AHBPrescaler::DIV1 => 1,
AHBPrescaler::DIV2 => 2,
AHBPrescaler::DIV4 => 4,
AHBPrescaler::DIV8 => 8,
AHBPrescaler::DIV16 => 16,
AHBPrescaler::DIV64 => 64,
AHBPrescaler::DIV128 => 128,
AHBPrescaler::DIV256 => 256,
AHBPrescaler::DIV512 => 512,
_ => unreachable!(),
}
}
impl APBPrescaler {
const fn div(self) -> u32 {
match self {
APBPrescaler::NotDivided => 1,
APBPrescaler::Div2 => 2,
APBPrescaler::Div4 => 4,
APBPrescaler::Div8 => 8,
APBPrescaler::Div16 => 16,
}
}
}
impl Into<Ppre> for APBPrescaler {
fn into(self) -> Ppre {
match self {
APBPrescaler::NotDivided => Ppre::DIV1,
APBPrescaler::Div2 => Ppre::DIV2,
APBPrescaler::Div4 => Ppre::DIV4,
APBPrescaler::Div8 => Ppre::DIV8,
APBPrescaler::Div16 => Ppre::DIV16,
}
}
}
impl Into<Hpre> for AHBPrescaler {
fn into(self) -> Hpre {
match self {
AHBPrescaler::NotDivided => Hpre::DIV1,
AHBPrescaler::Div2 => Hpre::DIV2,
AHBPrescaler::Div4 => Hpre::DIV4,
AHBPrescaler::Div8 => Hpre::DIV8,
AHBPrescaler::Div16 => Hpre::DIV16,
AHBPrescaler::Div64 => Hpre::DIV64,
AHBPrescaler::Div128 => Hpre::DIV128,
AHBPrescaler::Div256 => Hpre::DIV256,
AHBPrescaler::Div512 => Hpre::DIV512,
}
fn apb_div(apb: APBPrescaler) -> u32 {
match apb {
APBPrescaler::DIV1 => 1,
APBPrescaler::DIV2 => 2,
APBPrescaler::DIV4 => 4,
APBPrescaler::DIV8 => 8,
APBPrescaler::DIV16 => 16,
_ => unreachable!(),
}
}
@ -365,9 +335,9 @@ impl Default for Config {
fn default() -> Config {
Config {
mux: ClockSrc::HSI16,
ahb_pre: AHBPrescaler::NotDivided,
apb1_pre: APBPrescaler::NotDivided,
apb2_pre: APBPrescaler::NotDivided,
ahb_pre: AHBPrescaler::DIV1,
apb1_pre: APBPrescaler::DIV1,
apb2_pre: APBPrescaler::DIV1,
low_power_run: false,
pll: None,
clock_48mhz_src: None,
@ -512,22 +482,22 @@ pub(crate) unsafe fn init(config: Config) {
});
let ahb_freq: u32 = match config.ahb_pre {
AHBPrescaler::NotDivided => sys_clk,
pre => sys_clk / pre.div(),
AHBPrescaler::DIV1 => sys_clk,
pre => sys_clk / ahb_div(pre),
};
let (apb1_freq, apb1_tim_freq) = match config.apb1_pre {
APBPrescaler::NotDivided => (ahb_freq, ahb_freq),
APBPrescaler::DIV1 => (ahb_freq, ahb_freq),
pre => {
let freq = ahb_freq / pre.div();
let freq = ahb_freq / apb_div(pre);
(freq, freq * 2)
}
};
let (apb2_freq, apb2_tim_freq) = match config.apb2_pre {
APBPrescaler::NotDivided => (ahb_freq, ahb_freq),
APBPrescaler::DIV1 => (ahb_freq, ahb_freq),
pre => {
let freq = ahb_freq / pre.div();
let freq = ahb_freq / apb_div(pre);
(freq, freq * 2)
}
};

772
embassy-stm32/src/rcc/h.rs Normal file
View File

@ -0,0 +1,772 @@
use core::ops::RangeInclusive;
use crate::pac;
use crate::pac::pwr::vals::Vos;
#[cfg(stm32h5)]
pub use crate::pac::rcc::vals::Adcdacsel as AdcClockSource;
#[cfg(stm32h7)]
pub use crate::pac::rcc::vals::Adcsel as AdcClockSource;
pub use crate::pac::rcc::vals::Ckpersel as PerClockSource;
use crate::pac::rcc::vals::{Ckpersel, Hsidiv, Pllrge, Pllsrc, Pllvcosel, Sw, Timpre};
use crate::pac::{FLASH, PWR, RCC};
use crate::rcc::{set_freqs, Clocks};
use crate::time::Hertz;
/// HSI speed
pub const HSI_FREQ: Hertz = Hertz(64_000_000);
/// CSI speed
pub const CSI_FREQ: Hertz = Hertz(4_000_000);
/// HSI48 speed
pub const HSI48_FREQ: Hertz = Hertz(48_000_000);
/// LSI speed
pub const LSI_FREQ: Hertz = Hertz(32_000);
const VCO_RANGE: RangeInclusive<u32> = 150_000_000..=420_000_000;
#[cfg(any(stm32h5, pwr_h7rm0455))]
const VCO_WIDE_RANGE: RangeInclusive<u32> = 128_000_000..=560_000_000;
#[cfg(pwr_h7rm0468)]
const VCO_WIDE_RANGE: RangeInclusive<u32> = 192_000_000..=836_000_000;
#[cfg(any(pwr_h7rm0399, pwr_h7rm0433))]
const VCO_WIDE_RANGE: RangeInclusive<u32> = 192_000_000..=960_000_000;
pub use super::bus::{AHBPrescaler, APBPrescaler};
#[derive(Clone, Copy, Eq, PartialEq)]
pub enum VoltageScale {
Scale0,
Scale1,
Scale2,
Scale3,
}
#[derive(Clone, Copy, Eq, PartialEq)]
pub enum HseMode {
/// crystal/ceramic oscillator (HSEBYP=0)
Oscillator,
/// external analog clock (low swing) (HSEBYP=1, HSEEXT=0)
Bypass,
/// external digital clock (full swing) (HSEBYP=1, HSEEXT=1)
#[cfg(any(rcc_h5, rcc_h50))]
BypassDigital,
}
#[derive(Clone, Copy, Eq, PartialEq)]
pub struct Hse {
/// HSE frequency.
pub freq: Hertz,
/// HSE mode.
pub mode: HseMode,
}
#[derive(Clone, Copy, Eq, PartialEq)]
pub enum Hsi {
/// 64Mhz
Mhz64,
/// 32Mhz (divided by 2)
Mhz32,
/// 16Mhz (divided by 4)
Mhz16,
/// 8Mhz (divided by 8)
Mhz8,
}
#[derive(Clone, Copy, Eq, PartialEq)]
pub enum Sysclk {
/// HSI selected as sysclk
HSI,
/// HSE selected as sysclk
HSE,
/// CSI selected as sysclk
CSI,
/// PLL1_P selected as sysclk
Pll1P,
}
#[derive(Clone, Copy, Eq, PartialEq)]
pub enum PllSource {
Hsi,
Csi,
Hse,
}
#[derive(Clone, Copy)]
pub struct Pll {
/// Source clock selection.
#[cfg(stm32h5)]
pub source: PllSource,
/// PLL pre-divider (DIVM). Must be between 1 and 63.
pub prediv: u8,
/// PLL multiplication factor. Must be between 4 and 512.
pub mul: u16,
/// PLL P division factor. If None, PLL P output is disabled. Must be between 1 and 128.
/// On PLL1, it must be even (in particular, it cannot be 1.)
pub divp: Option<u16>,
/// PLL Q division factor. If None, PLL Q output is disabled. Must be between 1 and 128.
pub divq: Option<u16>,
/// PLL R division factor. If None, PLL R output is disabled. Must be between 1 and 128.
pub divr: Option<u16>,
}
fn apb_div_tim(apb: &APBPrescaler, clk: Hertz, tim: TimerPrescaler) -> Hertz {
match (tim, apb) {
(TimerPrescaler::DefaultX2, APBPrescaler::DIV1) => clk,
(TimerPrescaler::DefaultX2, APBPrescaler::DIV2) => clk,
(TimerPrescaler::DefaultX2, APBPrescaler::DIV4) => clk / 2u32,
(TimerPrescaler::DefaultX2, APBPrescaler::DIV8) => clk / 4u32,
(TimerPrescaler::DefaultX2, APBPrescaler::DIV16) => clk / 8u32,
(TimerPrescaler::DefaultX4, APBPrescaler::DIV1) => clk,
(TimerPrescaler::DefaultX4, APBPrescaler::DIV2) => clk,
(TimerPrescaler::DefaultX4, APBPrescaler::DIV4) => clk,
(TimerPrescaler::DefaultX4, APBPrescaler::DIV8) => clk / 2u32,
(TimerPrescaler::DefaultX4, APBPrescaler::DIV16) => clk / 4u32,
_ => unreachable!(),
}
}
/// Timer prescaler
#[derive(Clone, Copy, Eq, PartialEq)]
pub enum TimerPrescaler {
/// The timers kernel clock is equal to hclk if PPREx corresponds to a
/// division by 1 or 2, else it is equal to 2*pclk
DefaultX2,
/// The timers kernel clock is equal to hclk if PPREx corresponds to a
/// division by 1, 2 or 4, else it is equal to 4*pclk
DefaultX4,
}
impl From<TimerPrescaler> for Timpre {
fn from(value: TimerPrescaler) -> Self {
match value {
TimerPrescaler::DefaultX2 => Timpre::DEFAULTX2,
TimerPrescaler::DefaultX4 => Timpre::DEFAULTX4,
}
}
}
/// Configuration of the core clocks
#[non_exhaustive]
pub struct Config {
pub hsi: Option<Hsi>,
pub hse: Option<Hse>,
pub csi: bool,
pub hsi48: bool,
pub sys: Sysclk,
#[cfg(stm32h7)]
pub pll_src: PllSource,
pub pll1: Option<Pll>,
pub pll2: Option<Pll>,
#[cfg(any(rcc_h5, stm32h7))]
pub pll3: Option<Pll>,
pub d1c_pre: AHBPrescaler,
pub ahb_pre: AHBPrescaler,
pub apb1_pre: APBPrescaler,
pub apb2_pre: APBPrescaler,
pub apb3_pre: APBPrescaler,
#[cfg(stm32h7)]
pub apb4_pre: APBPrescaler,
pub per_clock_source: PerClockSource,
pub adc_clock_source: AdcClockSource,
pub timer_prescaler: TimerPrescaler,
pub voltage_scale: VoltageScale,
}
impl Default for Config {
fn default() -> Self {
Self {
hsi: Some(Hsi::Mhz64),
hse: None,
csi: false,
hsi48: false,
sys: Sysclk::HSI,
#[cfg(stm32h7)]
pll_src: PllSource::Hsi,
pll1: None,
pll2: None,
#[cfg(any(rcc_h5, stm32h7))]
pll3: None,
d1c_pre: AHBPrescaler::DIV1,
ahb_pre: AHBPrescaler::DIV1,
apb1_pre: APBPrescaler::DIV1,
apb2_pre: APBPrescaler::DIV1,
apb3_pre: APBPrescaler::DIV1,
#[cfg(stm32h7)]
apb4_pre: APBPrescaler::DIV1,
per_clock_source: PerClockSource::HSI,
adc_clock_source: AdcClockSource::from_bits(0), // PLL2_P on H7, HCLK on H5
timer_prescaler: TimerPrescaler::DefaultX2,
voltage_scale: VoltageScale::Scale0,
}
}
}
pub(crate) unsafe fn init(config: Config) {
// NB. The lower bytes of CR3 can only be written once after
// POR, and must be written with a valid combination. Refer to
// RM0433 Rev 7 6.8.4. This is partially enforced by dropping
// `self` at the end of this method, but of course we cannot
// know what happened between the previous POR and here.
#[cfg(pwr_h7rm0433)]
PWR.cr3().modify(|w| {
w.set_scuen(true);
w.set_ldoen(true);
w.set_bypass(false);
});
#[cfg(any(pwr_h7rm0399, pwr_h7rm0455, pwr_h7rm0468))]
PWR.cr3().modify(|w| {
// hardcode "Direct SPMS" for now, this is what works on nucleos with the
// default solderbridge configuration.
w.set_sden(true);
w.set_ldoen(false);
});
// Validate the supply configuration. If you are stuck here, it is
// because the voltages on your board do not match those specified
// in the D3CR.VOS and CR3.SDLEVEL fields. By default after reset
// VOS = Scale 3, so check that the voltage on the VCAP pins =
// 1.0V.
#[cfg(any(pwr_h7rm0433, pwr_h7rm0399, pwr_h7rm0455, pwr_h7rm0468))]
while !PWR.csr1().read().actvosrdy() {}
// Configure voltage scale.
#[cfg(any(pwr_h5, pwr_h50))]
{
PWR.voscr().modify(|w| {
w.set_vos(match config.voltage_scale {
VoltageScale::Scale0 => Vos::SCALE0,
VoltageScale::Scale1 => Vos::SCALE1,
VoltageScale::Scale2 => Vos::SCALE2,
VoltageScale::Scale3 => Vos::SCALE3,
})
});
while !PWR.vossr().read().vosrdy() {}
}
#[cfg(syscfg_h7)]
{
// in chips without the overdrive bit, we can go from any scale to any scale directly.
PWR.d3cr().modify(|w| {
w.set_vos(match config.voltage_scale {
VoltageScale::Scale0 => Vos::SCALE0,
VoltageScale::Scale1 => Vos::SCALE1,
VoltageScale::Scale2 => Vos::SCALE2,
VoltageScale::Scale3 => Vos::SCALE3,
})
});
while !PWR.d3cr().read().vosrdy() {}
}
#[cfg(syscfg_h7od)]
{
match config.voltage_scale {
VoltageScale::Scale0 => {
// to go to scale0, we must go to Scale1 first...
PWR.d3cr().modify(|w| w.set_vos(Vos::SCALE1));
while !PWR.d3cr().read().vosrdy() {}
// Then enable overdrive.
critical_section::with(|_| pac::SYSCFG.pwrcr().modify(|w| w.set_oden(1)));
while !PWR.d3cr().read().vosrdy() {}
}
_ => {
// for all other scales, we can go directly.
PWR.d3cr().modify(|w| {
w.set_vos(match config.voltage_scale {
VoltageScale::Scale0 => unreachable!(),
VoltageScale::Scale1 => Vos::SCALE1,
VoltageScale::Scale2 => Vos::SCALE2,
VoltageScale::Scale3 => Vos::SCALE3,
})
});
while !PWR.d3cr().read().vosrdy() {}
}
}
}
// Configure HSI
let hsi = match config.hsi {
None => {
RCC.cr().modify(|w| w.set_hsion(false));
None
}
Some(hsi) => {
let (freq, hsidiv) = match hsi {
Hsi::Mhz64 => (HSI_FREQ / 1u32, Hsidiv::DIV1),
Hsi::Mhz32 => (HSI_FREQ / 2u32, Hsidiv::DIV2),
Hsi::Mhz16 => (HSI_FREQ / 4u32, Hsidiv::DIV4),
Hsi::Mhz8 => (HSI_FREQ / 8u32, Hsidiv::DIV8),
};
RCC.cr().modify(|w| {
w.set_hsidiv(hsidiv);
w.set_hsion(true);
});
while !RCC.cr().read().hsirdy() {}
Some(freq)
}
};
// Configure HSE
let hse = match config.hse {
None => {
RCC.cr().modify(|w| w.set_hseon(false));
None
}
Some(hse) => {
RCC.cr().modify(|w| {
w.set_hsebyp(hse.mode != HseMode::Oscillator);
#[cfg(any(rcc_h5, rcc_h50))]
w.set_hseext(match hse.mode {
HseMode::Oscillator | HseMode::Bypass => pac::rcc::vals::Hseext::ANALOG,
HseMode::BypassDigital => pac::rcc::vals::Hseext::DIGITAL,
});
});
RCC.cr().modify(|w| w.set_hseon(true));
while !RCC.cr().read().hserdy() {}
Some(hse.freq)
}
};
// Configure HSI48.
RCC.cr().modify(|w| w.set_hsi48on(config.hsi48));
let _hsi48 = match config.hsi48 {
false => None,
true => {
while !RCC.cr().read().hsi48rdy() {}
Some(CSI_FREQ)
}
};
// Configure CSI.
RCC.cr().modify(|w| w.set_csion(config.csi));
let csi = match config.csi {
false => None,
true => {
while !RCC.cr().read().csirdy() {}
Some(CSI_FREQ)
}
};
// Configure PLLs.
let pll_input = PllInput {
csi,
hse,
hsi,
#[cfg(stm32h7)]
source: config.pll_src,
};
let pll1 = init_pll(0, config.pll1, &pll_input);
let pll2 = init_pll(1, config.pll2, &pll_input);
#[cfg(any(rcc_h5, stm32h7))]
let _pll3 = init_pll(2, config.pll3, &pll_input);
// Configure sysclk
let (sys, sw) = match config.sys {
Sysclk::HSI => (unwrap!(hsi), Sw::HSI),
Sysclk::HSE => (unwrap!(hse), Sw::HSE),
Sysclk::CSI => (unwrap!(csi), Sw::CSI),
Sysclk::Pll1P => (unwrap!(pll1.p), Sw::PLL1),
};
// Check limits.
#[cfg(stm32h5)]
let (hclk_max, pclk_max) = match config.voltage_scale {
VoltageScale::Scale0 => (Hertz(250_000_000), Hertz(250_000_000)),
VoltageScale::Scale1 => (Hertz(200_000_000), Hertz(200_000_000)),
VoltageScale::Scale2 => (Hertz(150_000_000), Hertz(150_000_000)),
VoltageScale::Scale3 => (Hertz(100_000_000), Hertz(100_000_000)),
};
#[cfg(stm32h7)]
let (d1cpre_clk_max, hclk_max, pclk_max) = match config.voltage_scale {
VoltageScale::Scale0 => (Hertz(480_000_000), Hertz(240_000_000), Hertz(120_000_000)),
VoltageScale::Scale1 => (Hertz(400_000_000), Hertz(200_000_000), Hertz(100_000_000)),
VoltageScale::Scale2 => (Hertz(300_000_000), Hertz(150_000_000), Hertz(75_000_000)),
VoltageScale::Scale3 => (Hertz(200_000_000), Hertz(100_000_000), Hertz(50_000_000)),
};
#[cfg(stm32h7)]
let hclk = {
let d1cpre_clk = sys / config.d1c_pre;
assert!(d1cpre_clk <= d1cpre_clk_max);
sys / config.ahb_pre
};
#[cfg(stm32h5)]
let hclk = sys / config.ahb_pre;
assert!(hclk <= hclk_max);
let apb1 = hclk / config.apb1_pre;
let apb1_tim = apb_div_tim(&config.apb1_pre, hclk, config.timer_prescaler);
assert!(apb1 <= pclk_max);
let apb2 = hclk / config.apb2_pre;
let apb2_tim = apb_div_tim(&config.apb2_pre, hclk, config.timer_prescaler);
assert!(apb2 <= pclk_max);
let apb3 = hclk / config.apb3_pre;
assert!(apb3 <= pclk_max);
#[cfg(stm32h7)]
let apb4 = hclk / config.apb4_pre;
#[cfg(stm32h7)]
assert!(apb4 <= pclk_max);
let _per_ck = match config.per_clock_source {
Ckpersel::HSI => hsi,
Ckpersel::CSI => csi,
Ckpersel::HSE => hse,
_ => unreachable!(),
};
#[cfg(stm32h7)]
let adc = match config.adc_clock_source {
AdcClockSource::PLL2_P => pll2.p,
AdcClockSource::PLL3_R => _pll3.r,
AdcClockSource::PER => _per_ck,
_ => unreachable!(),
};
#[cfg(stm32h5)]
let adc = match config.adc_clock_source {
AdcClockSource::HCLK => Some(hclk),
AdcClockSource::SYSCLK => Some(sys),
AdcClockSource::PLL2_R => pll2.r,
AdcClockSource::HSE => hse,
AdcClockSource::HSI_KER => hsi,
AdcClockSource::CSI_KER => csi,
_ => unreachable!(),
};
flash_setup(hclk, config.voltage_scale);
#[cfg(stm32h7)]
{
RCC.d1cfgr().modify(|w| {
w.set_d1cpre(config.d1c_pre);
w.set_d1ppre(config.apb3_pre);
w.set_hpre(config.ahb_pre);
});
// Ensure core prescaler value is valid before future lower core voltage
while RCC.d1cfgr().read().d1cpre() != config.d1c_pre {}
RCC.d2cfgr().modify(|w| {
w.set_d2ppre1(config.apb1_pre);
w.set_d2ppre2(config.apb2_pre);
});
RCC.d3cfgr().modify(|w| {
w.set_d3ppre(config.apb4_pre);
});
RCC.d1ccipr().modify(|w| {
w.set_ckpersel(config.per_clock_source);
});
RCC.d3ccipr().modify(|w| {
w.set_adcsel(config.adc_clock_source);
});
}
#[cfg(stm32h5)]
{
// Set hpre
RCC.cfgr2().modify(|w| w.set_hpre(config.ahb_pre));
while RCC.cfgr2().read().hpre() != config.ahb_pre {}
// set ppre
RCC.cfgr2().modify(|w| {
w.set_ppre1(config.apb1_pre);
w.set_ppre2(config.apb2_pre);
w.set_ppre3(config.apb3_pre);
});
RCC.ccipr5().modify(|w| {
w.set_ckpersel(config.per_clock_source);
w.set_adcdacsel(config.adc_clock_source)
});
}
RCC.cfgr().modify(|w| w.set_timpre(config.timer_prescaler.into()));
RCC.cfgr().modify(|w| w.set_sw(sw));
while RCC.cfgr().read().sws() != sw {}
// IO compensation cell - Requires CSI clock and SYSCFG
#[cfg(stm32h7)] // TODO h5
if csi.is_some() {
// Enable the compensation cell, using back-bias voltage code
// provide by the cell.
critical_section::with(|_| {
pac::SYSCFG.cccsr().modify(|w| {
w.set_en(true);
w.set_cs(false);
w.set_hslv(false);
})
});
while !pac::SYSCFG.cccsr().read().ready() {}
}
set_freqs(Clocks {
sys,
ahb1: hclk,
ahb2: hclk,
ahb3: hclk,
ahb4: hclk,
apb1,
apb2,
apb3,
#[cfg(stm32h7)]
apb4,
apb1_tim,
apb2_tim,
adc: adc,
});
}
struct PllInput {
hsi: Option<Hertz>,
hse: Option<Hertz>,
csi: Option<Hertz>,
#[cfg(stm32h7)]
source: PllSource,
}
struct PllOutput {
p: Option<Hertz>,
#[allow(dead_code)]
q: Option<Hertz>,
#[allow(dead_code)]
r: Option<Hertz>,
}
fn init_pll(num: usize, config: Option<Pll>, input: &PllInput) -> PllOutput {
let Some(config) = config else {
// Stop PLL
RCC.cr().modify(|w| w.set_pllon(num, false));
while RCC.cr().read().pllrdy(num) {}
// "To save power when PLL1 is not used, the value of PLL1M must be set to 0.""
#[cfg(stm32h7)]
RCC.pllckselr().write(|w| w.set_divm(num, 0));
#[cfg(stm32h5)]
RCC.pllcfgr(num).write(|w| w.set_divm(0));
return PllOutput {
p: None,
q: None,
r: None,
};
};
assert!(1 <= config.prediv && config.prediv <= 63);
assert!(4 <= config.mul && config.mul <= 512);
#[cfg(stm32h5)]
let source = config.source;
#[cfg(stm32h7)]
let source = input.source;
let (in_clk, src) = match source {
PllSource::Hsi => (unwrap!(input.hsi), Pllsrc::HSI),
PllSource::Hse => (unwrap!(input.hse), Pllsrc::HSE),
PllSource::Csi => (unwrap!(input.csi), Pllsrc::CSI),
};
let ref_clk = in_clk / config.prediv as u32;
let ref_range = match ref_clk.0 {
..=1_999_999 => Pllrge::RANGE1,
..=3_999_999 => Pllrge::RANGE2,
..=7_999_999 => Pllrge::RANGE4,
..=16_000_000 => Pllrge::RANGE8,
x => panic!("pll ref_clk out of range: {} mhz", x),
};
// The smaller range (150 to 420 MHz) must
// be chosen when the reference clock frequency is lower than 2 MHz.
let wide_allowed = ref_range != Pllrge::RANGE1;
let vco_clk = ref_clk * config.mul;
let vco_range = if VCO_RANGE.contains(&vco_clk.0) {
Pllvcosel::MEDIUMVCO
} else if wide_allowed && VCO_WIDE_RANGE.contains(&vco_clk.0) {
Pllvcosel::WIDEVCO
} else {
panic!("pll vco_clk out of range: {} mhz", vco_clk.0)
};
let p = config.divp.map(|div| {
assert!(1 <= div && div <= 128);
if num == 0 {
// on PLL1, DIVP must be even.
assert!(div % 2 == 0);
}
vco_clk / div
});
let q = config.divq.map(|div| {
assert!(1 <= div && div <= 128);
vco_clk / div
});
let r = config.divr.map(|div| {
assert!(1 <= div && div <= 128);
vco_clk / div
});
#[cfg(stm32h5)]
RCC.pllcfgr(num).write(|w| {
w.set_pllsrc(src);
w.set_divm(config.prediv);
w.set_pllvcosel(vco_range);
w.set_pllrge(ref_range);
w.set_pllfracen(false);
w.set_pllpen(p.is_some());
w.set_pllqen(q.is_some());
w.set_pllren(r.is_some());
});
#[cfg(stm32h7)]
{
RCC.pllckselr().modify(|w| {
w.set_divm(num, config.prediv);
w.set_pllsrc(src);
});
RCC.pllcfgr().modify(|w| {
w.set_pllvcosel(num, vco_range);
w.set_pllrge(num, ref_range);
w.set_pllfracen(num, false);
w.set_divpen(num, p.is_some());
w.set_divqen(num, q.is_some());
w.set_divren(num, r.is_some());
});
}
RCC.plldivr(num).write(|w| {
w.set_plln(config.mul - 1);
w.set_pllp((config.divp.unwrap_or(1) - 1) as u8);
w.set_pllq((config.divq.unwrap_or(1) - 1) as u8);
w.set_pllr((config.divr.unwrap_or(1) - 1) as u8);
});
RCC.cr().modify(|w| w.set_pllon(num, true));
while !RCC.cr().read().pllrdy(num) {}
PllOutput { p, q, r }
}
fn flash_setup(clk: Hertz, vos: VoltageScale) {
// RM0481 Rev 1, table 37
// LATENCY WRHIGHFREQ VOS3 VOS2 VOS1 VOS0
// 0 0 0 to 20 MHz 0 to 30 MHz 0 to 34 MHz 0 to 42 MHz
// 1 0 20 to 40 MHz 30 to 60 MHz 34 to 68 MHz 42 to 84 MHz
// 2 1 40 to 60 MHz 60 to 90 MHz 68 to 102 MHz 84 to 126 MHz
// 3 1 60 to 80 MHz 90 to 120 MHz 102 to 136 MHz 126 to 168 MHz
// 4 2 80 to 100 MHz 120 to 150 MHz 136 to 170 MHz 168 to 210 MHz
// 5 2 170 to 200 MHz 210 to 250 MHz
#[cfg(stm32h5)]
let (latency, wrhighfreq) = match (vos, clk.0) {
(VoltageScale::Scale0, ..=42_000_000) => (0, 0),
(VoltageScale::Scale0, ..=84_000_000) => (1, 0),
(VoltageScale::Scale0, ..=126_000_000) => (2, 1),
(VoltageScale::Scale0, ..=168_000_000) => (3, 1),
(VoltageScale::Scale0, ..=210_000_000) => (4, 2),
(VoltageScale::Scale0, ..=250_000_000) => (5, 2),
(VoltageScale::Scale1, ..=34_000_000) => (0, 0),
(VoltageScale::Scale1, ..=68_000_000) => (1, 0),
(VoltageScale::Scale1, ..=102_000_000) => (2, 1),
(VoltageScale::Scale1, ..=136_000_000) => (3, 1),
(VoltageScale::Scale1, ..=170_000_000) => (4, 2),
(VoltageScale::Scale1, ..=200_000_000) => (5, 2),
(VoltageScale::Scale2, ..=30_000_000) => (0, 0),
(VoltageScale::Scale2, ..=60_000_000) => (1, 0),
(VoltageScale::Scale2, ..=90_000_000) => (2, 1),
(VoltageScale::Scale2, ..=120_000_000) => (3, 1),
(VoltageScale::Scale2, ..=150_000_000) => (4, 2),
(VoltageScale::Scale3, ..=20_000_000) => (0, 0),
(VoltageScale::Scale3, ..=40_000_000) => (1, 0),
(VoltageScale::Scale3, ..=60_000_000) => (2, 1),
(VoltageScale::Scale3, ..=80_000_000) => (3, 1),
(VoltageScale::Scale3, ..=100_000_000) => (4, 2),
_ => unreachable!(),
};
#[cfg(flash_h7)]
let (latency, wrhighfreq) = match (vos, clk.0) {
// VOS 0 range VCORE 1.26V - 1.40V
(VoltageScale::Scale0, ..=70_000_000) => (0, 0),
(VoltageScale::Scale0, ..=140_000_000) => (1, 1),
(VoltageScale::Scale0, ..=185_000_000) => (2, 1),
(VoltageScale::Scale0, ..=210_000_000) => (2, 2),
(VoltageScale::Scale0, ..=225_000_000) => (3, 2),
(VoltageScale::Scale0, ..=240_000_000) => (4, 2),
// VOS 1 range VCORE 1.15V - 1.26V
(VoltageScale::Scale1, ..=70_000_000) => (0, 0),
(VoltageScale::Scale1, ..=140_000_000) => (1, 1),
(VoltageScale::Scale1, ..=185_000_000) => (2, 1),
(VoltageScale::Scale1, ..=210_000_000) => (2, 2),
(VoltageScale::Scale1, ..=225_000_000) => (3, 2),
// VOS 2 range VCORE 1.05V - 1.15V
(VoltageScale::Scale2, ..=55_000_000) => (0, 0),
(VoltageScale::Scale2, ..=110_000_000) => (1, 1),
(VoltageScale::Scale2, ..=165_000_000) => (2, 1),
(VoltageScale::Scale2, ..=224_000_000) => (3, 2),
// VOS 3 range VCORE 0.95V - 1.05V
(VoltageScale::Scale3, ..=45_000_000) => (0, 0),
(VoltageScale::Scale3, ..=90_000_000) => (1, 1),
(VoltageScale::Scale3, ..=135_000_000) => (2, 1),
(VoltageScale::Scale3, ..=180_000_000) => (3, 2),
(VoltageScale::Scale3, ..=224_000_000) => (4, 2),
_ => unreachable!(),
};
// See RM0455 Rev 10 Table 16. FLASH recommended number of wait
// states and programming delay
#[cfg(flash_h7ab)]
let (latency, wrhighfreq) = match (vos, clk.0) {
// VOS 0 range VCORE 1.25V - 1.35V
(VoltageScale::Scale0, ..=42_000_000) => (0, 0),
(VoltageScale::Scale0, ..=84_000_000) => (1, 0),
(VoltageScale::Scale0, ..=126_000_000) => (2, 1),
(VoltageScale::Scale0, ..=168_000_000) => (3, 1),
(VoltageScale::Scale0, ..=210_000_000) => (4, 2),
(VoltageScale::Scale0, ..=252_000_000) => (5, 2),
(VoltageScale::Scale0, ..=280_000_000) => (6, 3),
// VOS 1 range VCORE 1.15V - 1.25V
(VoltageScale::Scale1, ..=38_000_000) => (0, 0),
(VoltageScale::Scale1, ..=76_000_000) => (1, 0),
(VoltageScale::Scale1, ..=114_000_000) => (2, 1),
(VoltageScale::Scale1, ..=152_000_000) => (3, 1),
(VoltageScale::Scale1, ..=190_000_000) => (4, 2),
(VoltageScale::Scale1, ..=225_000_000) => (5, 2),
// VOS 2 range VCORE 1.05V - 1.15V
(VoltageScale::Scale2, ..=34) => (0, 0),
(VoltageScale::Scale2, ..=68) => (1, 0),
(VoltageScale::Scale2, ..=102) => (2, 1),
(VoltageScale::Scale2, ..=136) => (3, 1),
(VoltageScale::Scale2, ..=160) => (4, 2),
// VOS 3 range VCORE 0.95V - 1.05V
(VoltageScale::Scale3, ..=22) => (0, 0),
(VoltageScale::Scale3, ..=44) => (1, 0),
(VoltageScale::Scale3, ..=66) => (2, 1),
(VoltageScale::Scale3, ..=88) => (3, 1),
_ => unreachable!(),
};
debug!("flash: latency={} wrhighfreq={}", latency, wrhighfreq);
FLASH.acr().write(|w| {
w.set_wrhighfreq(wrhighfreq);
w.set_latency(latency);
});
while FLASH.acr().read().latency() != latency {}
}

View File

@ -1,511 +0,0 @@
use core::marker::PhantomData;
use stm32_metapac::rcc::vals::Timpre;
use crate::pac::pwr::vals::Vos;
use crate::pac::rcc::vals::{Hseext, Hsidiv, Mco1, Mco2, Pllrge, Pllsrc, Pllvcosel, Sw};
use crate::pac::{FLASH, PWR, RCC};
use crate::rcc::{set_freqs, Clocks};
use crate::time::Hertz;
use crate::{peripherals, Peripheral};
/// HSI speed
pub const HSI_FREQ: Hertz = Hertz(64_000_000);
/// CSI speed
pub const CSI_FREQ: Hertz = Hertz(4_000_000);
/// HSI48 speed
pub const HSI48_FREQ: Hertz = Hertz(48_000_000);
/// LSI speed
pub const LSI_FREQ: Hertz = Hertz(32_000);
const VCO_MIN: u32 = 150_000_000;
const VCO_MAX: u32 = 420_000_000;
const VCO_WIDE_MIN: u32 = 128_000_000;
const VCO_WIDE_MAX: u32 = 560_000_000;
pub use super::bus::{AHBPrescaler, APBPrescaler, VoltageScale};
pub enum HseMode {
/// crystal/ceramic oscillator (HSEBYP=0)
Oscillator,
/// external analog clock (low swing) (HSEBYP=1, HSEEXT=0)
BypassAnalog,
/// external digital clock (full swing) (HSEBYP=1, HSEEXT=1)
BypassDigital,
}
pub struct Hse {
/// HSE frequency.
pub freq: Hertz,
/// HSE mode.
pub mode: HseMode,
}
pub enum Hsi {
/// 64Mhz
Mhz64,
/// 32Mhz (divided by 2)
Mhz32,
/// 16Mhz (divided by 4)
Mhz16,
/// 8Mhz (divided by 8)
Mhz8,
}
pub enum Sysclk {
/// HSI selected as sysclk
HSI,
/// HSE selected as sysclk
HSE,
/// CSI selected as sysclk
CSI,
/// PLL1_P selected as sysclk
Pll1P,
}
pub enum PllSource {
Hsi,
Csi,
Hse,
}
pub struct Pll {
/// Source clock selection.
pub source: PllSource,
/// PLL pre-divider (DIVM). Must be between 1 and 63.
pub prediv: u8,
/// PLL multiplication factor. Must be between 4 and 512.
pub mul: u16,
/// PLL P division factor. If None, PLL P output is disabled. Must be between 1 and 128.
/// On PLL1, it must be even (in particular, it cannot be 1.)
pub divp: Option<u16>,
/// PLL Q division factor. If None, PLL Q output is disabled. Must be between 1 and 128.
pub divq: Option<u16>,
/// PLL R division factor. If None, PLL R output is disabled. Must be between 1 and 128.
pub divr: Option<u16>,
}
impl APBPrescaler {
fn div_tim(&self, clk: Hertz, tim: TimerPrescaler) -> Hertz {
match (tim, self) {
// The timers kernel clock is equal to rcc_hclk1 if PPRE1 or PPRE2 corresponds to a
// division by 1 or 2, else it is equal to 2 x Frcc_pclk1 or 2 x Frcc_pclk2
(TimerPrescaler::DefaultX2, Self::NotDivided) => clk,
(TimerPrescaler::DefaultX2, Self::Div2) => clk,
(TimerPrescaler::DefaultX2, Self::Div4) => clk / 2u32,
(TimerPrescaler::DefaultX2, Self::Div8) => clk / 4u32,
(TimerPrescaler::DefaultX2, Self::Div16) => clk / 8u32,
// The timers kernel clock is equal to 2 x Frcc_pclk1 or 2 x Frcc_pclk2 if PPRE1 or PPRE2
// corresponds to a division by 1, 2 or 4, else it is equal to 4 x Frcc_pclk1 or 4 x Frcc_pclk2
// this makes NO SENSE and is different than in the H7. Mistake in the RM??
(TimerPrescaler::DefaultX4, Self::NotDivided) => clk * 2u32,
(TimerPrescaler::DefaultX4, Self::Div2) => clk,
(TimerPrescaler::DefaultX4, Self::Div4) => clk / 2u32,
(TimerPrescaler::DefaultX4, Self::Div8) => clk / 2u32,
(TimerPrescaler::DefaultX4, Self::Div16) => clk / 4u32,
}
}
}
/// APB prescaler
#[derive(Clone, Copy)]
pub enum TimerPrescaler {
DefaultX2,
DefaultX4,
}
impl From<TimerPrescaler> for Timpre {
fn from(value: TimerPrescaler) -> Self {
match value {
TimerPrescaler::DefaultX2 => Timpre::DEFAULTX2,
TimerPrescaler::DefaultX4 => Timpre::DEFAULTX4,
}
}
}
/// Configuration of the core clocks
#[non_exhaustive]
pub struct Config {
pub hsi: Option<Hsi>,
pub hse: Option<Hse>,
pub csi: bool,
pub hsi48: bool,
pub sys: Sysclk,
pub pll1: Option<Pll>,
pub pll2: Option<Pll>,
#[cfg(rcc_h5)]
pub pll3: Option<Pll>,
pub ahb_pre: AHBPrescaler,
pub apb1_pre: APBPrescaler,
pub apb2_pre: APBPrescaler,
pub apb3_pre: APBPrescaler,
pub timer_prescaler: TimerPrescaler,
pub voltage_scale: VoltageScale,
}
impl Default for Config {
fn default() -> Self {
Self {
hsi: Some(Hsi::Mhz64),
hse: None,
csi: false,
hsi48: false,
sys: Sysclk::HSI,
pll1: None,
pll2: None,
#[cfg(rcc_h5)]
pll3: None,
ahb_pre: AHBPrescaler::NotDivided,
apb1_pre: APBPrescaler::NotDivided,
apb2_pre: APBPrescaler::NotDivided,
apb3_pre: APBPrescaler::NotDivided,
timer_prescaler: TimerPrescaler::DefaultX2,
voltage_scale: VoltageScale::Scale3,
}
}
}
pub(crate) mod sealed {
pub trait McoInstance {
type Source;
unsafe fn apply_clock_settings(source: Self::Source, prescaler: u8);
}
}
pub trait McoInstance: sealed::McoInstance + 'static {}
pin_trait!(McoPin, McoInstance);
macro_rules! impl_peri {
($peri:ident, $source:ident, $set_source:ident, $set_prescaler:ident) => {
impl sealed::McoInstance for peripherals::$peri {
type Source = $source;
unsafe fn apply_clock_settings(source: Self::Source, prescaler: u8) {
RCC.cfgr().modify(|w| {
w.$set_source(source);
w.$set_prescaler(prescaler);
});
}
}
impl McoInstance for peripherals::$peri {}
};
}
impl_peri!(MCO1, Mco1, set_mco1, set_mco1pre);
impl_peri!(MCO2, Mco2, set_mco2, set_mco2pre);
pub struct Mco<'d, T: McoInstance> {
phantom: PhantomData<&'d mut T>,
}
impl<'d, T: McoInstance> Mco<'d, T> {
pub fn new(
_peri: impl Peripheral<P = T> + 'd,
_pin: impl Peripheral<P = impl McoPin<T>> + 'd,
_source: T::Source,
) -> Self {
todo!();
}
}
pub(crate) unsafe fn init(config: Config) {
let (vos, max_clk) = match config.voltage_scale {
VoltageScale::Scale0 => (Vos::SCALE0, Hertz(250_000_000)),
VoltageScale::Scale1 => (Vos::SCALE1, Hertz(200_000_000)),
VoltageScale::Scale2 => (Vos::SCALE2, Hertz(150_000_000)),
VoltageScale::Scale3 => (Vos::SCALE3, Hertz(100_000_000)),
};
// Configure voltage scale.
PWR.voscr().modify(|w| w.set_vos(vos));
while !PWR.vossr().read().vosrdy() {}
// Configure HSI
let hsi = match config.hsi {
None => {
RCC.cr().modify(|w| w.set_hsion(false));
None
}
Some(hsi) => {
let (freq, hsidiv) = match hsi {
Hsi::Mhz64 => (HSI_FREQ / 1u32, Hsidiv::DIV1),
Hsi::Mhz32 => (HSI_FREQ / 2u32, Hsidiv::DIV2),
Hsi::Mhz16 => (HSI_FREQ / 4u32, Hsidiv::DIV4),
Hsi::Mhz8 => (HSI_FREQ / 8u32, Hsidiv::DIV8),
};
RCC.cr().modify(|w| {
w.set_hsidiv(hsidiv);
w.set_hsion(true);
});
while !RCC.cr().read().hsirdy() {}
Some(freq)
}
};
// Configure HSE
let hse = match config.hse {
None => {
RCC.cr().modify(|w| w.set_hseon(false));
None
}
Some(hse) => {
let (byp, ext) = match hse.mode {
HseMode::Oscillator => (false, Hseext::ANALOG),
HseMode::BypassAnalog => (true, Hseext::ANALOG),
HseMode::BypassDigital => (true, Hseext::DIGITAL),
};
RCC.cr().modify(|w| {
w.set_hsebyp(byp);
w.set_hseext(ext);
});
RCC.cr().modify(|w| w.set_hseon(true));
while !RCC.cr().read().hserdy() {}
Some(hse.freq)
}
};
// Configure HSI48.
RCC.cr().modify(|w| w.set_hsi48on(config.hsi48));
let _hsi48 = match config.hsi48 {
false => None,
true => {
while !RCC.cr().read().hsi48rdy() {}
Some(CSI_FREQ)
}
};
// Configure CSI.
RCC.cr().modify(|w| w.set_csion(config.csi));
let csi = match config.csi {
false => None,
true => {
while !RCC.cr().read().csirdy() {}
Some(CSI_FREQ)
}
};
// Configure PLLs.
let pll_input = PllInput { csi, hse, hsi };
let pll1 = init_pll(0, config.pll1, &pll_input);
let _pll2 = init_pll(1, config.pll2, &pll_input);
#[cfg(rcc_h5)]
let _pll3 = init_pll(2, config.pll3, &pll_input);
// Configure sysclk
let (sys, sw) = match config.sys {
Sysclk::HSI => (unwrap!(hsi), Sw::HSI),
Sysclk::HSE => (unwrap!(hse), Sw::HSE),
Sysclk::CSI => (unwrap!(csi), Sw::CSI),
Sysclk::Pll1P => (unwrap!(pll1.p), Sw::PLL1),
};
assert!(sys <= max_clk);
let hclk = sys / config.ahb_pre;
let apb1 = hclk / config.apb1_pre;
let apb1_tim = config.apb1_pre.div_tim(hclk, config.timer_prescaler);
let apb2 = hclk / config.apb2_pre;
let apb2_tim = config.apb2_pre.div_tim(hclk, config.timer_prescaler);
let apb3 = hclk / config.apb3_pre;
flash_setup(hclk, config.voltage_scale);
// Set hpre
let hpre = config.ahb_pre.into();
RCC.cfgr2().modify(|w| w.set_hpre(hpre));
while RCC.cfgr2().read().hpre() != hpre {}
// set ppre
RCC.cfgr2().modify(|w| {
w.set_ppre1(config.apb1_pre.into());
w.set_ppre2(config.apb2_pre.into());
w.set_ppre3(config.apb3_pre.into());
});
RCC.cfgr().modify(|w| w.set_timpre(config.timer_prescaler.into()));
RCC.cfgr().modify(|w| w.set_sw(sw));
while RCC.cfgr().read().sws() != sw {}
set_freqs(Clocks {
sys,
ahb1: hclk,
ahb2: hclk,
ahb3: hclk,
ahb4: hclk,
apb1,
apb2,
apb3,
apb1_tim,
apb2_tim,
adc: None,
});
}
struct PllInput {
hsi: Option<Hertz>,
hse: Option<Hertz>,
csi: Option<Hertz>,
}
struct PllOutput {
p: Option<Hertz>,
#[allow(dead_code)]
q: Option<Hertz>,
#[allow(dead_code)]
r: Option<Hertz>,
}
fn init_pll(num: usize, config: Option<Pll>, input: &PllInput) -> PllOutput {
let Some(config) = config else {
// Stop PLL
RCC.cr().modify(|w| w.set_pllon(num, false));
while RCC.cr().read().pllrdy(num) {}
// "To save power when PLL1 is not used, the value of PLL1M must be set to 0.""
RCC.pllcfgr(num).write(|w| {
w.set_divm(0);
});
return PllOutput {
p: None,
q: None,
r: None,
};
};
assert!(1 <= config.prediv && config.prediv <= 63);
assert!(4 <= config.mul && config.mul <= 512);
let (in_clk, src) = match config.source {
PllSource::Hsi => (unwrap!(input.hsi), Pllsrc::HSI),
PllSource::Hse => (unwrap!(input.hse), Pllsrc::HSE),
PllSource::Csi => (unwrap!(input.csi), Pllsrc::CSI),
};
let ref_clk = in_clk / config.prediv as u32;
let ref_range = match ref_clk.0 {
..=1_999_999 => Pllrge::RANGE1,
..=3_999_999 => Pllrge::RANGE2,
..=7_999_999 => Pllrge::RANGE4,
..=16_000_000 => Pllrge::RANGE8,
x => panic!("pll ref_clk out of range: {} mhz", x),
};
// The smaller range (150 to 420 MHz) must
// be chosen when the reference clock frequency is lower than 2 MHz.
let wide_allowed = ref_range != Pllrge::RANGE1;
let vco_clk = ref_clk * config.mul;
let vco_range = match vco_clk.0 {
VCO_MIN..=VCO_MAX => Pllvcosel::MEDIUMVCO,
VCO_WIDE_MIN..=VCO_WIDE_MAX if wide_allowed => Pllvcosel::WIDEVCO,
x => panic!("pll vco_clk out of range: {} mhz", x),
};
let p = config.divp.map(|div| {
assert!(1 <= div && div <= 128);
if num == 0 {
// on PLL1, DIVP must be even.
assert!(div % 2 == 0);
}
vco_clk / div
});
let q = config.divq.map(|div| {
assert!(1 <= div && div <= 128);
vco_clk / div
});
let r = config.divr.map(|div| {
assert!(1 <= div && div <= 128);
vco_clk / div
});
RCC.pllcfgr(num).write(|w| {
w.set_pllsrc(src);
w.set_divm(config.prediv);
w.set_pllvcosel(vco_range);
w.set_pllrge(ref_range);
w.set_pllfracen(false);
w.set_pllpen(p.is_some());
w.set_pllqen(q.is_some());
w.set_pllren(r.is_some());
});
RCC.plldivr(num).write(|w| {
w.set_plln(config.mul - 1);
w.set_pllp((config.divp.unwrap_or(1) - 1) as u8);
w.set_pllq((config.divq.unwrap_or(1) - 1) as u8);
w.set_pllr((config.divr.unwrap_or(1) - 1) as u8);
});
RCC.cr().modify(|w| w.set_pllon(num, true));
while !RCC.cr().read().pllrdy(num) {}
PllOutput { p, q, r }
}
fn flash_setup(clk: Hertz, vos: VoltageScale) {
// RM0481 Rev 1, table 37
// LATENCY WRHIGHFREQ VOS3 VOS2 VOS1 VOS0
// 0 0 0 to 20 MHz 0 to 30 MHz 0 to 34 MHz 0 to 42 MHz
// 1 0 20 to 40 MHz 30 to 60 MHz 34 to 68 MHz 42 to 84 MHz
// 2 1 40 to 60 MHz 60 to 90 MHz 68 to 102 MHz 84 to 126 MHz
// 3 1 60 to 80 MHz 90 to 120 MHz 102 to 136 MHz 126 to 168 MHz
// 4 2 80 to 100 MHz 120 to 150 MHz 136 to 170 MHz 168 to 210 MHz
// 5 2 170 to 200 MHz 210 to 250 MHz
// See RM0433 Rev 7 Table 17. FLASH recommended number of wait
// states and programming delay
let (latency, wrhighfreq) = match (vos, clk.0) {
(VoltageScale::Scale0, ..=42_000_000) => (0, 0),
(VoltageScale::Scale0, ..=84_000_000) => (1, 0),
(VoltageScale::Scale0, ..=126_000_000) => (2, 1),
(VoltageScale::Scale0, ..=168_000_000) => (3, 1),
(VoltageScale::Scale0, ..=210_000_000) => (4, 2),
(VoltageScale::Scale0, ..=250_000_000) => (5, 2),
(VoltageScale::Scale1, ..=34_000_000) => (0, 0),
(VoltageScale::Scale1, ..=68_000_000) => (1, 0),
(VoltageScale::Scale1, ..=102_000_000) => (2, 1),
(VoltageScale::Scale1, ..=136_000_000) => (3, 1),
(VoltageScale::Scale1, ..=170_000_000) => (4, 2),
(VoltageScale::Scale1, ..=200_000_000) => (5, 2),
(VoltageScale::Scale2, ..=30_000_000) => (0, 0),
(VoltageScale::Scale2, ..=60_000_000) => (1, 0),
(VoltageScale::Scale2, ..=90_000_000) => (2, 1),
(VoltageScale::Scale2, ..=120_000_000) => (3, 1),
(VoltageScale::Scale2, ..=150_000_000) => (4, 2),
(VoltageScale::Scale3, ..=20_000_000) => (0, 0),
(VoltageScale::Scale3, ..=40_000_000) => (1, 0),
(VoltageScale::Scale3, ..=60_000_000) => (2, 1),
(VoltageScale::Scale3, ..=80_000_000) => (3, 1),
(VoltageScale::Scale3, ..=100_000_000) => (4, 2),
_ => unreachable!(),
};
defmt::debug!("flash: latency={} wrhighfreq={}", latency, wrhighfreq);
FLASH.acr().write(|w| {
w.set_wrhighfreq(wrhighfreq);
w.set_latency(latency);
});
while FLASH.acr().read().latency() != latency {}
}

View File

@ -1,879 +0,0 @@
use core::marker::PhantomData;
use embassy_hal_internal::into_ref;
pub use pll::PllConfig;
use stm32_metapac::rcc::vals::{Mco1, Mco2};
use crate::gpio::sealed::AFType;
use crate::gpio::Speed;
use crate::pac::rcc::vals::{Adcsel, Ckpersel, Dppre, Hpre, Hsidiv, Pllsrc, Sw, Timpre};
use crate::pac::{PWR, RCC, SYSCFG};
use crate::rcc::{set_freqs, Clocks};
use crate::time::Hertz;
use crate::{peripherals, Peripheral};
/// HSI speed
pub const HSI_FREQ: Hertz = Hertz(64_000_000);
/// CSI speed
pub const CSI_FREQ: Hertz = Hertz(4_000_000);
/// HSI48 speed
pub const HSI48_FREQ: Hertz = Hertz(48_000_000);
/// LSI speed
pub const LSI_FREQ: Hertz = Hertz(32_000);
pub use super::bus::VoltageScale;
#[derive(Clone, Copy)]
pub enum AdcClockSource {
Pll2PCk,
Pll3RCk,
PerCk,
}
impl AdcClockSource {
pub fn adcsel(&self) -> Adcsel {
match self {
AdcClockSource::Pll2PCk => Adcsel::PLL2_P,
AdcClockSource::Pll3RCk => Adcsel::PLL3_R,
AdcClockSource::PerCk => Adcsel::PER,
}
}
}
impl Default for AdcClockSource {
fn default() -> Self {
Self::Pll2PCk
}
}
/// Core clock frequencies
#[derive(Clone, Copy)]
pub struct CoreClocks {
pub hclk: Hertz,
pub pclk1: Hertz,
pub pclk2: Hertz,
pub pclk3: Hertz,
pub pclk4: Hertz,
pub ppre1: u8,
pub ppre2: u8,
pub ppre3: u8,
pub ppre4: u8,
pub csi_ck: Option<Hertz>,
pub hsi_ck: Option<Hertz>,
pub hsi48_ck: Option<Hertz>,
pub lsi_ck: Option<Hertz>,
pub per_ck: Option<Hertz>,
pub hse_ck: Option<Hertz>,
pub pll1_p_ck: Option<Hertz>,
pub pll1_q_ck: Option<Hertz>,
pub pll1_r_ck: Option<Hertz>,
pub pll2_p_ck: Option<Hertz>,
pub pll2_q_ck: Option<Hertz>,
pub pll2_r_ck: Option<Hertz>,
pub pll3_p_ck: Option<Hertz>,
pub pll3_q_ck: Option<Hertz>,
pub pll3_r_ck: Option<Hertz>,
pub timx_ker_ck: Option<Hertz>,
pub timy_ker_ck: Option<Hertz>,
pub adc_ker_ck: Option<Hertz>,
pub sys_ck: Hertz,
pub c_ck: Hertz,
}
/// Configuration of the core clocks
#[non_exhaustive]
#[derive(Default)]
pub struct Config {
pub hse: Option<Hertz>,
pub bypass_hse: bool,
pub sys_ck: Option<Hertz>,
pub per_ck: Option<Hertz>,
pub hclk: Option<Hertz>,
pub pclk1: Option<Hertz>,
pub pclk2: Option<Hertz>,
pub pclk3: Option<Hertz>,
pub pclk4: Option<Hertz>,
pub pll1: PllConfig,
pub pll2: PllConfig,
pub pll3: PllConfig,
pub adc_clock_source: AdcClockSource,
}
/// Setup traceclk
/// Returns a pll1_r_ck
fn traceclk_setup(config: &mut Config, sys_use_pll1_p: bool) {
let pll1_r_ck = match (sys_use_pll1_p, config.pll1.r_ck) {
// pll1_p_ck selected as system clock but pll1_r_ck not
// set. The traceclk mux is synchronous with the system
// clock mux, but has pll1_r_ck as an input. In order to
// keep traceclk running, we force a pll1_r_ck.
(true, None) => Some(Hertz(unwrap!(config.pll1.p_ck).0 / 2)),
// Either pll1 not selected as system clock, free choice
// of pll1_r_ck. Or pll1 is selected, assume user has set
// a suitable pll1_r_ck frequency.
_ => config.pll1.r_ck,
};
config.pll1.r_ck = pll1_r_ck;
}
/// Divider calculator for pclk 1 - 4
///
/// Returns real pclk, bits, ppre and the timer kernel clock
fn ppre_calculate(
requested_pclk: u32,
hclk: u32,
max_pclk: u32,
tim_pre: Option<Timpre>,
) -> (u32, u8, u8, Option<u32>) {
let (bits, ppre) = match (hclk + requested_pclk - 1) / requested_pclk {
0 => panic!(),
1 => (0b000, 1),
2 => (0b100, 2),
3..=5 => (0b101, 4),
6..=11 => (0b110, 8),
_ => (0b111, 16),
};
let real_pclk = hclk / u32::from(ppre);
assert!(real_pclk <= max_pclk);
let tim_ker_clk = if let Some(tim_pre) = tim_pre {
let clk = match (bits, tim_pre) {
(0b101, Timpre::DEFAULTX2) => hclk / 2,
(0b110, Timpre::DEFAULTX4) => hclk / 2,
(0b110, Timpre::DEFAULTX2) => hclk / 4,
(0b111, Timpre::DEFAULTX4) => hclk / 4,
(0b111, Timpre::DEFAULTX2) => hclk / 8,
_ => hclk,
};
Some(clk)
} else {
None
};
(real_pclk, bits, ppre, tim_ker_clk)
}
/// Setup sys_ck
/// Returns sys_ck frequency, and a pll1_p_ck
fn sys_ck_setup(config: &mut Config, srcclk: Hertz) -> (Hertz, bool) {
// Compare available with wanted clocks
let sys_ck = config.sys_ck.unwrap_or(srcclk);
if sys_ck != srcclk {
// The requested system clock is not the immediately available
// HSE/HSI clock. Perhaps there are other ways of obtaining
// the requested system clock (such as `HSIDIV`) but we will
// ignore those for now.
//
// Therefore we must use pll1_p_ck
let pll1_p_ck = match config.pll1.p_ck {
Some(p_ck) => {
assert!(
p_ck == sys_ck,
"Error: Cannot set pll1_p_ck independently as it must be used to generate sys_ck"
);
Some(p_ck)
}
None => Some(sys_ck),
};
config.pll1.p_ck = pll1_p_ck;
(sys_ck, true)
} else {
// sys_ck is derived directly from a source clock
// (HSE/HSI). pll1_p_ck can be as requested
(sys_ck, false)
}
}
fn flash_setup(rcc_aclk: u32, vos: VoltageScale) {
use crate::pac::FLASH;
// ACLK in MHz, round down and subtract 1 from integers. eg.
// 61_999_999 -> 61MHz
// 62_000_000 -> 61MHz
// 62_000_001 -> 62MHz
let rcc_aclk_mhz = (rcc_aclk - 1) / 1_000_000;
// See RM0433 Rev 7 Table 17. FLASH recommended number of wait
// states and programming delay
#[cfg(flash_h7)]
let (wait_states, progr_delay) = match vos {
// VOS 0 range VCORE 1.26V - 1.40V
VoltageScale::Scale0 => match rcc_aclk_mhz {
0..=69 => (0, 0),
70..=139 => (1, 1),
140..=184 => (2, 1),
185..=209 => (2, 2),
210..=224 => (3, 2),
225..=239 => (4, 2),
_ => (7, 3),
},
// VOS 1 range VCORE 1.15V - 1.26V
VoltageScale::Scale1 => match rcc_aclk_mhz {
0..=69 => (0, 0),
70..=139 => (1, 1),
140..=184 => (2, 1),
185..=209 => (2, 2),
210..=224 => (3, 2),
_ => (7, 3),
},
// VOS 2 range VCORE 1.05V - 1.15V
VoltageScale::Scale2 => match rcc_aclk_mhz {
0..=54 => (0, 0),
55..=109 => (1, 1),
110..=164 => (2, 1),
165..=224 => (3, 2),
_ => (7, 3),
},
// VOS 3 range VCORE 0.95V - 1.05V
VoltageScale::Scale3 => match rcc_aclk_mhz {
0..=44 => (0, 0),
45..=89 => (1, 1),
90..=134 => (2, 1),
135..=179 => (3, 2),
180..=224 => (4, 2),
_ => (7, 3),
},
};
// See RM0455 Rev 10 Table 16. FLASH recommended number of wait
// states and programming delay
#[cfg(flash_h7ab)]
let (wait_states, progr_delay) = match vos {
// VOS 0 range VCORE 1.25V - 1.35V
VoltageScale::Scale0 => match rcc_aclk_mhz {
0..=42 => (0, 0),
43..=84 => (1, 0),
85..=126 => (2, 1),
127..=168 => (3, 1),
169..=210 => (4, 2),
211..=252 => (5, 2),
253..=280 => (6, 3),
_ => (7, 3),
},
// VOS 1 range VCORE 1.15V - 1.25V
VoltageScale::Scale1 => match rcc_aclk_mhz {
0..=38 => (0, 0),
39..=76 => (1, 0),
77..=114 => (2, 1),
115..=152 => (3, 1),
153..=190 => (4, 2),
191..=225 => (5, 2),
_ => (7, 3),
},
// VOS 2 range VCORE 1.05V - 1.15V
VoltageScale::Scale2 => match rcc_aclk_mhz {
0..=34 => (0, 0),
35..=68 => (1, 0),
69..=102 => (2, 1),
103..=136 => (3, 1),
137..=160 => (4, 2),
_ => (7, 3),
},
// VOS 3 range VCORE 0.95V - 1.05V
VoltageScale::Scale3 => match rcc_aclk_mhz {
0..=22 => (0, 0),
23..=44 => (1, 0),
45..=66 => (2, 1),
67..=88 => (3, 1),
_ => (7, 3),
},
};
FLASH.acr().write(|w| {
w.set_wrhighfreq(progr_delay);
w.set_latency(wait_states)
});
while FLASH.acr().read().latency() != wait_states {}
}
pub enum McoClock {
Disabled,
Bypassed,
Divided(u8),
}
impl McoClock {
fn into_raw(&self) -> u8 {
match self {
McoClock::Disabled => 0,
McoClock::Bypassed => 1,
McoClock::Divided(divisor) => {
if *divisor > 15 {
panic!("Mco divisor must be less than 15. Refer to the reference manual for more information.")
}
*divisor
}
}
}
}
#[derive(Copy, Clone)]
pub enum Mco1Source {
Hsi,
Lse,
Hse,
Pll1Q,
Hsi48,
}
impl Default for Mco1Source {
fn default() -> Self {
Self::Hsi
}
}
pub trait McoSource {
type Raw;
fn into_raw(&self) -> Self::Raw;
}
impl McoSource for Mco1Source {
type Raw = Mco1;
fn into_raw(&self) -> Self::Raw {
match self {
Mco1Source::Hsi => Mco1::HSI,
Mco1Source::Lse => Mco1::LSE,
Mco1Source::Hse => Mco1::HSE,
Mco1Source::Pll1Q => Mco1::PLL1_Q,
Mco1Source::Hsi48 => Mco1::HSI48,
}
}
}
#[derive(Copy, Clone)]
pub enum Mco2Source {
SysClk,
Pll2Q,
Hse,
Pll1Q,
Csi,
Lsi,
}
impl Default for Mco2Source {
fn default() -> Self {
Self::SysClk
}
}
impl McoSource for Mco2Source {
type Raw = Mco2;
fn into_raw(&self) -> Self::Raw {
match self {
Mco2Source::SysClk => Mco2::SYSCLK,
Mco2Source::Pll2Q => Mco2::PLL2_P,
Mco2Source::Hse => Mco2::HSE,
Mco2Source::Pll1Q => Mco2::PLL1_P,
Mco2Source::Csi => Mco2::CSI,
Mco2Source::Lsi => Mco2::LSI,
}
}
}
pub(crate) mod sealed {
pub trait McoInstance {
type Source;
unsafe fn apply_clock_settings(source: Self::Source, prescaler: u8);
}
}
pub trait McoInstance: sealed::McoInstance + 'static {}
pin_trait!(McoPin, McoInstance);
macro_rules! impl_peri {
($peri:ident, $source:ident, $set_source:ident, $set_prescaler:ident) => {
impl sealed::McoInstance for peripherals::$peri {
type Source = $source;
unsafe fn apply_clock_settings(source: Self::Source, prescaler: u8) {
RCC.cfgr().modify(|w| {
w.$set_source(source);
w.$set_prescaler(prescaler);
});
}
}
impl McoInstance for peripherals::$peri {}
};
}
impl_peri!(MCO1, Mco1, set_mco1, set_mco1pre);
impl_peri!(MCO2, Mco2, set_mco2, set_mco2pre);
pub struct Mco<'d, T: McoInstance> {
phantom: PhantomData<&'d mut T>,
}
impl<'d, T: McoInstance> Mco<'d, T> {
pub fn new(
_peri: impl Peripheral<P = T> + 'd,
pin: impl Peripheral<P = impl McoPin<T>> + 'd,
source: impl McoSource<Raw = T::Source>,
prescaler: McoClock,
) -> Self {
into_ref!(pin);
critical_section::with(|_| unsafe {
T::apply_clock_settings(source.into_raw(), prescaler.into_raw());
pin.set_as_af(pin.af_num(), AFType::OutputPushPull);
pin.set_speed(Speed::VeryHigh);
});
Self { phantom: PhantomData }
}
}
pub(crate) unsafe fn init(mut config: Config) {
// TODO make configurable?
let enable_overdrive = false;
// NB. The lower bytes of CR3 can only be written once after
// POR, and must be written with a valid combination. Refer to
// RM0433 Rev 7 6.8.4. This is partially enforced by dropping
// `self` at the end of this method, but of course we cannot
// know what happened between the previous POR and here.
#[cfg(pwr_h7)]
PWR.cr3().modify(|w| {
w.set_scuen(true);
w.set_ldoen(true);
w.set_bypass(false);
});
#[cfg(pwr_h7smps)]
PWR.cr3().modify(|w| {
// hardcode "Direct SPMS" for now, this is what works on nucleos with the
// default solderbridge configuration.
w.set_sden(true);
w.set_ldoen(false);
});
// Validate the supply configuration. If you are stuck here, it is
// because the voltages on your board do not match those specified
// in the D3CR.VOS and CR3.SDLEVEL fields. By default after reset
// VOS = Scale 3, so check that the voltage on the VCAP pins =
// 1.0V.
while !PWR.csr1().read().actvosrdy() {}
// Go to Scale 1
PWR.d3cr().modify(|w| w.set_vos(0b11));
while !PWR.d3cr().read().vosrdy() {}
let pwr_vos = if !enable_overdrive {
VoltageScale::Scale1
} else {
critical_section::with(|_| {
RCC.apb4enr().modify(|w| w.set_syscfgen(true));
SYSCFG.pwrcr().modify(|w| w.set_oden(1));
});
while !PWR.d3cr().read().vosrdy() {}
VoltageScale::Scale0
};
// Freeze the core clocks, returning a Core Clocks Distribution
// and Reset (CCDR) structure. The actual frequency of the clocks
// configured is returned in the `clocks` member of the CCDR
// structure.
//
// Note that `freeze` will never result in a clock _faster_ than
// that specified. It may result in a clock that is a factor of [1,
// 2) slower.
//
// `syscfg` is required to enable the I/O compensation cell.
//
// # Panics
//
// If a clock specification cannot be achieved within the
// hardware specification then this function will panic. This
// function may also panic if a clock specification can be
// achieved, but the mechanism for doing so is not yet
// implemented here.
let srcclk = config.hse.unwrap_or(HSI_FREQ); // Available clocks
let (sys_ck, sys_use_pll1_p) = sys_ck_setup(&mut config, srcclk);
// Configure traceclk from PLL if needed
traceclk_setup(&mut config, sys_use_pll1_p);
let (pll1_p_ck, pll1_q_ck, pll1_r_ck) = pll::pll_setup(srcclk.0, &config.pll1, 0);
let (pll2_p_ck, pll2_q_ck, pll2_r_ck) = pll::pll_setup(srcclk.0, &config.pll2, 1);
let (pll3_p_ck, pll3_q_ck, pll3_r_ck) = pll::pll_setup(srcclk.0, &config.pll3, 2);
let sys_ck = if sys_use_pll1_p {
Hertz(unwrap!(pll1_p_ck)) // Must have been set by sys_ck_setup
} else {
sys_ck
};
// This routine does not support HSIDIV != 1. To
// do so it would need to ensure all PLLxON bits are clear
// before changing the value of HSIDIV
let cr = RCC.cr().read();
assert!(cr.hsion());
assert!(cr.hsidiv() == Hsidiv::DIV1);
RCC.csr().modify(|w| w.set_lsion(true));
while !RCC.csr().read().lsirdy() {}
// per_ck from HSI by default
let (per_ck, ckpersel) = match (config.per_ck == config.hse, config.per_ck) {
(true, Some(hse)) => (hse, Ckpersel::HSE), // HSE
(_, Some(CSI_FREQ)) => (CSI_FREQ, Ckpersel::CSI), // CSI
_ => (HSI_FREQ, Ckpersel::HSI), // HSI
};
// D1 Core Prescaler
// Set to 1
let d1cpre_bits = 0;
let d1cpre_div = 1;
let sys_d1cpre_ck = sys_ck.0 / d1cpre_div;
// Refer to part datasheet "General operating conditions"
// table for (rev V). We do not assert checks for earlier
// revisions which may have lower limits.
let (sys_d1cpre_ck_max, rcc_hclk_max, pclk_max) = match pwr_vos {
VoltageScale::Scale0 => (480_000_000, 240_000_000, 120_000_000),
VoltageScale::Scale1 => (400_000_000, 200_000_000, 100_000_000),
VoltageScale::Scale2 => (300_000_000, 150_000_000, 75_000_000),
_ => (200_000_000, 100_000_000, 50_000_000),
};
assert!(sys_d1cpre_ck <= sys_d1cpre_ck_max);
let rcc_hclk = config.hclk.map(|v| v.0).unwrap_or(sys_d1cpre_ck / 2);
assert!(rcc_hclk <= rcc_hclk_max);
// Estimate divisor
let (hpre_bits, hpre_div) = match (sys_d1cpre_ck + rcc_hclk - 1) / rcc_hclk {
0 => panic!(),
1 => (Hpre::DIV1, 1),
2 => (Hpre::DIV2, 2),
3..=5 => (Hpre::DIV4, 4),
6..=11 => (Hpre::DIV8, 8),
12..=39 => (Hpre::DIV16, 16),
40..=95 => (Hpre::DIV64, 64),
96..=191 => (Hpre::DIV128, 128),
192..=383 => (Hpre::DIV256, 256),
_ => (Hpre::DIV512, 512),
};
// Calculate real AXI and AHB clock
let rcc_hclk = sys_d1cpre_ck / hpre_div;
assert!(rcc_hclk <= rcc_hclk_max);
let rcc_aclk = rcc_hclk; // AXI clock is always equal to AHB clock on H7
// Timer prescaler selection
let timpre = Timpre::DEFAULTX2;
let requested_pclk1 = config.pclk1.map(|v| v.0).unwrap_or_else(|| pclk_max.min(rcc_hclk / 2));
let (rcc_pclk1, ppre1_bits, ppre1, rcc_timerx_ker_ck) =
ppre_calculate(requested_pclk1, rcc_hclk, pclk_max, Some(timpre));
let requested_pclk2 = config.pclk2.map(|v| v.0).unwrap_or_else(|| pclk_max.min(rcc_hclk / 2));
let (rcc_pclk2, ppre2_bits, ppre2, rcc_timery_ker_ck) =
ppre_calculate(requested_pclk2, rcc_hclk, pclk_max, Some(timpre));
let requested_pclk3 = config.pclk3.map(|v| v.0).unwrap_or_else(|| pclk_max.min(rcc_hclk / 2));
let (rcc_pclk3, ppre3_bits, ppre3, _) = ppre_calculate(requested_pclk3, rcc_hclk, pclk_max, None);
let requested_pclk4 = config.pclk4.map(|v| v.0).unwrap_or_else(|| pclk_max.min(rcc_hclk / 2));
let (rcc_pclk4, ppre4_bits, ppre4, _) = ppre_calculate(requested_pclk4, rcc_hclk, pclk_max, None);
// Start switching clocks -------------------
// Ensure CSI is on and stable
RCC.cr().modify(|w| w.set_csion(true));
while !RCC.cr().read().csirdy() {}
// Ensure HSI48 is on and stable
RCC.cr().modify(|w| w.set_hsi48on(true));
while !RCC.cr().read().hsi48on() {}
// XXX: support MCO ?
let hse_ck = match config.hse {
Some(hse) => {
// Ensure HSE is on and stable
RCC.cr().modify(|w| {
w.set_hseon(true);
w.set_hsebyp(config.bypass_hse);
});
while !RCC.cr().read().hserdy() {}
Some(hse)
}
None => None,
};
let pllsrc = if config.hse.is_some() { Pllsrc::HSE } else { Pllsrc::HSI };
RCC.pllckselr().modify(|w| w.set_pllsrc(pllsrc));
let enable_pll = |pll| {
RCC.cr().modify(|w| w.set_pllon(pll, true));
while !RCC.cr().read().pllrdy(pll) {}
};
if pll1_p_ck.is_some() {
enable_pll(0);
}
if pll2_p_ck.is_some() {
enable_pll(1);
}
if pll3_p_ck.is_some() {
enable_pll(2);
}
// Core Prescaler / AHB Prescaler / APB3 Prescaler
RCC.d1cfgr().modify(|w| {
w.set_d1cpre(Hpre::from_bits(d1cpre_bits));
w.set_d1ppre(Dppre::from_bits(ppre3_bits));
w.set_hpre(hpre_bits)
});
// Ensure core prescaler value is valid before future lower
// core voltage
while RCC.d1cfgr().read().d1cpre().to_bits() != d1cpre_bits {}
flash_setup(rcc_aclk, pwr_vos);
// APB1 / APB2 Prescaler
RCC.d2cfgr().modify(|w| {
w.set_d2ppre1(Dppre::from_bits(ppre1_bits));
w.set_d2ppre2(Dppre::from_bits(ppre2_bits));
});
// APB4 Prescaler
RCC.d3cfgr().modify(|w| w.set_d3ppre(Dppre::from_bits(ppre4_bits)));
// Peripheral Clock (per_ck)
RCC.d1ccipr().modify(|w| w.set_ckpersel(ckpersel));
// ADC clock MUX
RCC.d3ccipr().modify(|w| w.set_adcsel(config.adc_clock_source.adcsel()));
let adc_ker_ck = match config.adc_clock_source {
AdcClockSource::Pll2PCk => pll2_p_ck.map(Hertz),
AdcClockSource::Pll3RCk => pll3_r_ck.map(Hertz),
AdcClockSource::PerCk => Some(per_ck),
};
// Set timer clocks prescaler setting
RCC.cfgr().modify(|w| w.set_timpre(timpre));
// Select system clock source
let sw = match (sys_use_pll1_p, config.hse.is_some()) {
(true, _) => Sw::PLL1,
(false, true) => Sw::HSE,
_ => Sw::HSI,
};
RCC.cfgr().modify(|w| w.set_sw(sw));
while RCC.cfgr().read().sws().to_bits() != sw.to_bits() {}
// IO compensation cell - Requires CSI clock and SYSCFG
assert!(RCC.cr().read().csirdy());
RCC.apb4enr().modify(|w| w.set_syscfgen(true));
// Enable the compensation cell, using back-bias voltage code
// provide by the cell.
critical_section::with(|_| {
SYSCFG.cccsr().modify(|w| {
w.set_en(true);
w.set_cs(false);
w.set_hslv(false);
})
});
while !SYSCFG.cccsr().read().ready() {}
let core_clocks = CoreClocks {
hclk: Hertz(rcc_hclk),
pclk1: Hertz(rcc_pclk1),
pclk2: Hertz(rcc_pclk2),
pclk3: Hertz(rcc_pclk3),
pclk4: Hertz(rcc_pclk4),
ppre1,
ppre2,
ppre3,
ppre4,
csi_ck: Some(CSI_FREQ),
hsi_ck: Some(HSI_FREQ),
hsi48_ck: Some(HSI48_FREQ),
lsi_ck: Some(LSI_FREQ),
per_ck: Some(per_ck),
hse_ck,
pll1_p_ck: pll1_p_ck.map(Hertz),
pll1_q_ck: pll1_q_ck.map(Hertz),
pll1_r_ck: pll1_r_ck.map(Hertz),
pll2_p_ck: pll2_p_ck.map(Hertz),
pll2_q_ck: pll2_q_ck.map(Hertz),
pll2_r_ck: pll2_r_ck.map(Hertz),
pll3_p_ck: pll3_p_ck.map(Hertz),
pll3_q_ck: pll3_q_ck.map(Hertz),
pll3_r_ck: pll3_r_ck.map(Hertz),
timx_ker_ck: rcc_timerx_ker_ck.map(Hertz),
timy_ker_ck: rcc_timery_ker_ck.map(Hertz),
adc_ker_ck,
sys_ck,
c_ck: Hertz(sys_d1cpre_ck),
};
set_freqs(Clocks {
sys: core_clocks.c_ck,
ahb1: core_clocks.hclk,
ahb2: core_clocks.hclk,
ahb3: core_clocks.hclk,
ahb4: core_clocks.hclk,
apb1: core_clocks.pclk1,
apb2: core_clocks.pclk2,
apb4: core_clocks.pclk4,
apb1_tim: core_clocks.timx_ker_ck.unwrap_or(core_clocks.pclk1),
apb2_tim: core_clocks.timy_ker_ck.unwrap_or(core_clocks.pclk2),
adc: core_clocks.adc_ker_ck,
});
}
mod pll {
use super::{Hertz, RCC};
const VCO_MIN: u32 = 150_000_000;
const VCO_MAX: u32 = 420_000_000;
#[derive(Default)]
pub struct PllConfig {
pub p_ck: Option<Hertz>,
pub q_ck: Option<Hertz>,
pub r_ck: Option<Hertz>,
}
pub(super) struct PllConfigResults {
pub ref_x_ck: u32,
pub pll_x_m: u32,
pub pll_x_p: u32,
pub vco_ck_target: u32,
}
fn vco_output_divider_setup(output: u32, plln: usize) -> (u32, u32) {
let pll_x_p = if plln == 0 {
if output > VCO_MAX / 2 {
1
} else {
((VCO_MAX / output) | 1) - 1 // Must be even or unity
}
} else {
// Specific to PLL2/3, will subtract 1 later
if output > VCO_MAX / 2 {
1
} else {
VCO_MAX / output
}
};
let vco_ck = output * pll_x_p;
assert!(pll_x_p < 128);
assert!(vco_ck >= VCO_MIN);
assert!(vco_ck <= VCO_MAX);
(vco_ck, pll_x_p)
}
/// # Safety
///
/// Must have exclusive access to the RCC register block
fn vco_setup(pll_src: u32, requested_output: u32, plln: usize) -> PllConfigResults {
use crate::pac::rcc::vals::{Pllrge, Pllvcosel};
let (vco_ck_target, pll_x_p) = vco_output_divider_setup(requested_output, plln);
// Input divisor, resulting in a reference clock in the range
// 1 to 2 MHz. Choose the highest reference clock (lowest m)
let pll_x_m = (pll_src + 1_999_999) / 2_000_000;
assert!(pll_x_m < 64);
// Calculate resulting reference clock
let ref_x_ck = pll_src / pll_x_m;
assert!((1_000_000..=2_000_000).contains(&ref_x_ck));
RCC.pllcfgr().modify(|w| {
w.set_pllvcosel(plln, Pllvcosel::MEDIUMVCO);
w.set_pllrge(plln, Pllrge::RANGE1);
});
PllConfigResults {
ref_x_ck,
pll_x_m,
pll_x_p,
vco_ck_target,
}
}
/// # Safety
///
/// Must have exclusive access to the RCC register block
pub(super) fn pll_setup(pll_src: u32, config: &PllConfig, plln: usize) -> (Option<u32>, Option<u32>, Option<u32>) {
use crate::pac::rcc::vals::Divp;
match config.p_ck {
Some(requested_output) => {
let config_results = vco_setup(pll_src, requested_output.0, plln);
let PllConfigResults {
ref_x_ck,
pll_x_m,
pll_x_p,
vco_ck_target,
} = config_results;
RCC.pllckselr().modify(|w| w.set_divm(plln, pll_x_m as u8));
// Feedback divider. Integer only
let pll_x_n = vco_ck_target / ref_x_ck;
assert!(pll_x_n >= 4);
assert!(pll_x_n <= 512);
RCC.plldivr(plln).modify(|w| w.set_divn1((pll_x_n - 1) as u16));
// No FRACN
RCC.pllcfgr().modify(|w| w.set_pllfracen(plln, false));
let vco_ck = ref_x_ck * pll_x_n;
RCC.plldivr(plln)
.modify(|w| w.set_divp1(Divp::from_bits((pll_x_p - 1) as u8)));
RCC.pllcfgr().modify(|w| w.set_divpen(plln, true));
// Calulate additional output dividers
let q_ck = match config.q_ck {
Some(Hertz(ck)) if ck > 0 => {
let div = (vco_ck + ck - 1) / ck;
RCC.plldivr(plln).modify(|w| w.set_divq1((div - 1) as u8));
RCC.pllcfgr().modify(|w| w.set_divqen(plln, true));
Some(vco_ck / div)
}
_ => None,
};
let r_ck = match config.r_ck {
Some(Hertz(ck)) if ck > 0 => {
let div = (vco_ck + ck - 1) / ck;
RCC.plldivr(plln).modify(|w| w.set_divr1((div - 1) as u8));
RCC.pllcfgr().modify(|w| w.set_divren(plln, true));
Some(vco_ck / div)
}
_ => None,
};
(Some(vco_ck / pll_x_p), q_ck, r_ck)
}
None => {
assert!(
config.q_ck.is_none(),
"Must set PLL P clock for Q clock to take effect!"
);
assert!(
config.r_ck.is_none(),
"Must set PLL P clock for R clock to take effect!"
);
(None, None, None)
}
}
}
}

View File

@ -1,8 +1,11 @@
use super::bd::BackupDomain;
pub use super::bus::{AHBPrescaler, APBPrescaler};
use super::RtcClockSource;
pub use crate::pac::pwr::vals::Vos as VoltageScale;
use crate::pac::rcc::vals::{Hpre, Msirange, Plldiv, Pllmul, Pllsrc, Ppre, Sw};
use crate::pac::RCC;
#[cfg(crs)]
use crate::pac::{crs, CRS, SYSCFG};
use crate::pac::{FLASH, PWR, RCC};
use crate::rcc::{set_freqs, Clocks};
use crate::time::Hertz;
@ -135,6 +138,10 @@ pub struct Config {
pub apb2_pre: APBPrescaler,
#[cfg(crs)]
pub enable_hsi48: bool,
pub rtc: Option<RtcClockSource>,
pub lse: Option<Hertz>,
pub lsi: bool,
pub voltage_scale: VoltageScale,
}
impl Default for Config {
@ -142,16 +149,25 @@ impl Default for Config {
fn default() -> Config {
Config {
mux: ClockSrc::MSI(MSIRange::default()),
ahb_pre: AHBPrescaler::NotDivided,
apb1_pre: APBPrescaler::NotDivided,
apb2_pre: APBPrescaler::NotDivided,
ahb_pre: AHBPrescaler::DIV1,
apb1_pre: APBPrescaler::DIV1,
apb2_pre: APBPrescaler::DIV1,
#[cfg(crs)]
enable_hsi48: false,
rtc: None,
lse: None,
lsi: false,
voltage_scale: VoltageScale::RANGE1,
}
}
}
pub(crate) unsafe fn init(config: Config) {
// Set voltage scale
while PWR.csr().read().vosf() {}
PWR.cr().write(|w| w.set_vos(config.voltage_scale));
while PWR.csr().read().vosf() {}
let (sys_clk, sw) = match config.mux {
ClockSrc::MSI(range) => {
// Set MSI range
@ -231,6 +247,28 @@ pub(crate) unsafe fn init(config: Config) {
}
};
BackupDomain::configure_ls(
config.rtc.unwrap_or(RtcClockSource::NOCLOCK),
config.lsi,
config.lse.map(|_| Default::default()),
);
let wait_states = match config.voltage_scale {
VoltageScale::RANGE1 => match sys_clk {
..=16_000_000 => 0,
_ => 1,
},
VoltageScale::RANGE2 => match sys_clk {
..=8_000_000 => 0,
_ => 1,
},
VoltageScale::RANGE3 => 0,
_ => unreachable!(),
};
FLASH.acr().modify(|w| {
w.set_latency(wait_states != 0);
});
RCC.cfgr().modify(|w| {
w.set_sw(sw);
w.set_hpre(config.ahb_pre.into());
@ -239,7 +277,7 @@ pub(crate) unsafe fn init(config: Config) {
});
let ahb_freq: u32 = match config.ahb_pre {
AHBPrescaler::NotDivided => sys_clk,
AHBPrescaler::DIV1 => sys_clk,
pre => {
let pre: Hpre = pre.into();
let pre = 1 << (pre.to_bits() as u32 - 7);
@ -248,7 +286,7 @@ pub(crate) unsafe fn init(config: Config) {
};
let (apb1_freq, apb1_tim_freq) = match config.apb1_pre {
APBPrescaler::NotDivided => (ahb_freq, ahb_freq),
APBPrescaler::DIV1 => (ahb_freq, ahb_freq),
pre => {
let pre: Ppre = pre.into();
let pre: u8 = 1 << (pre.to_bits() - 3);
@ -258,7 +296,7 @@ pub(crate) unsafe fn init(config: Config) {
};
let (apb2_freq, apb2_tim_freq) = match config.apb2_pre {
APBPrescaler::NotDivided => (ahb_freq, ahb_freq),
APBPrescaler::DIV1 => (ahb_freq, ahb_freq),
pre => {
let pre: Ppre = pre.into();
let pre: u8 = 1 << (pre.to_bits() - 3);
@ -269,13 +307,6 @@ pub(crate) unsafe fn init(config: Config) {
#[cfg(crs)]
if config.enable_hsi48 {
// Reset SYSCFG peripheral
RCC.apb2rstr().modify(|w| w.set_syscfgrst(true));
RCC.apb2rstr().modify(|w| w.set_syscfgrst(false));
// Enable SYSCFG peripheral
RCC.apb2enr().modify(|w| w.set_syscfgen(true));
// Reset CRS peripheral
RCC.apb1rstr().modify(|w| w.set_crsrst(true));
RCC.apb1rstr().modify(|w| w.set_crsrst(false));

View File

@ -138,9 +138,9 @@ impl Default for Config {
fn default() -> Config {
Config {
mux: ClockSrc::MSI(MSIRange::default()),
ahb_pre: AHBPrescaler::NotDivided,
apb1_pre: APBPrescaler::NotDivided,
apb2_pre: APBPrescaler::NotDivided,
ahb_pre: AHBPrescaler::DIV1,
apb1_pre: APBPrescaler::DIV1,
apb2_pre: APBPrescaler::DIV1,
}
}
}
@ -240,7 +240,7 @@ pub(crate) unsafe fn init(config: Config) {
});
let ahb_freq: u32 = match config.ahb_pre {
AHBPrescaler::NotDivided => sys_clk,
AHBPrescaler::DIV1 => sys_clk,
pre => {
let pre: Hpre = pre.into();
let pre = 1 << (pre.to_bits() as u32 - 7);
@ -249,7 +249,7 @@ pub(crate) unsafe fn init(config: Config) {
};
let (apb1_freq, apb1_tim_freq) = match config.apb1_pre {
APBPrescaler::NotDivided => (ahb_freq, ahb_freq),
APBPrescaler::DIV1 => (ahb_freq, ahb_freq),
pre => {
let pre: Ppre = pre.into();
let pre: u8 = 1 << (pre.to_bits() - 3);
@ -259,7 +259,7 @@ pub(crate) unsafe fn init(config: Config) {
};
let (apb2_freq, apb2_tim_freq) = match config.apb2_pre {
APBPrescaler::NotDivided => (ahb_freq, ahb_freq),
APBPrescaler::DIV1 => (ahb_freq, ahb_freq),
pre => {
let pre: Ppre = pre.into();
let pre: u8 = 1 << (pre.to_bits() - 3);

View File

@ -241,6 +241,8 @@ pub struct Config {
#[cfg(not(any(stm32l471, stm32l475, stm32l476, stm32l486)))]
pub hsi48: bool,
pub rtc_mux: RtcClockSource,
pub lse: Option<Hertz>,
pub lsi: bool,
}
impl Default for Config {
@ -248,13 +250,15 @@ impl Default for Config {
fn default() -> Config {
Config {
mux: ClockSrc::MSI(MSIRange::Range6),
ahb_pre: AHBPrescaler::NotDivided,
apb1_pre: APBPrescaler::NotDivided,
apb2_pre: APBPrescaler::NotDivided,
ahb_pre: AHBPrescaler::DIV1,
apb1_pre: APBPrescaler::DIV1,
apb2_pre: APBPrescaler::DIV1,
pllsai1: None,
#[cfg(not(any(stm32l471, stm32l475, stm32l476, stm32l486)))]
hsi48: false,
rtc_mux: RtcClockSource::LSI,
lsi: true,
lse: None,
}
}
}
@ -405,9 +409,7 @@ pub(crate) unsafe fn init(config: Config) {
while RCC.cfgr().read().sws() != Sw::MSI {}
}
RCC.apb1enr1().modify(|w| w.set_pwren(true));
BackupDomain::configure_ls(config.rtc_mux, None);
BackupDomain::configure_ls(config.rtc_mux, config.lsi, config.lse.map(|_| Default::default()));
let (sys_clk, sw) = match config.mux {
ClockSrc::MSI(range) => {
@ -576,7 +578,7 @@ pub(crate) unsafe fn init(config: Config) {
});
let ahb_freq: u32 = match config.ahb_pre {
AHBPrescaler::NotDivided => sys_clk,
AHBPrescaler::DIV1 => sys_clk,
pre => {
let pre: Hpre = pre.into();
let pre = 1 << (pre.to_bits() as u32 - 7);
@ -585,7 +587,7 @@ pub(crate) unsafe fn init(config: Config) {
};
let (apb1_freq, apb1_tim_freq) = match config.apb1_pre {
APBPrescaler::NotDivided => (ahb_freq, ahb_freq),
APBPrescaler::DIV1 => (ahb_freq, ahb_freq),
pre => {
let pre: Ppre = pre.into();
let pre: u8 = 1 << (pre.to_bits() - 3);
@ -595,7 +597,7 @@ pub(crate) unsafe fn init(config: Config) {
};
let (apb2_freq, apb2_tim_freq) = match config.apb2_pre {
APBPrescaler::NotDivided => (ahb_freq, ahb_freq),
APBPrescaler::DIV1 => (ahb_freq, ahb_freq),
pre => {
let pre: Ppre = pre.into();
let pre: u8 = 1 << (pre.to_bits() - 3);
@ -604,8 +606,6 @@ pub(crate) unsafe fn init(config: Config) {
}
};
RCC.apb1enr1().modify(|w| w.set_pwren(true));
set_freqs(Clocks {
sys: Hertz(sys_clk),
ahb1: Hertz(ahb_freq),

View File

@ -238,9 +238,9 @@ impl Default for Config {
fn default() -> Config {
Config {
mux: ClockSrc::MSI(MSIRange::Range6),
ahb_pre: AHBPrescaler::NotDivided,
apb1_pre: APBPrescaler::NotDivided,
apb2_pre: APBPrescaler::NotDivided,
ahb_pre: AHBPrescaler::DIV1,
apb1_pre: APBPrescaler::DIV1,
apb2_pre: APBPrescaler::DIV1,
pllsai1: None,
hsi48: false,
}
@ -317,11 +317,6 @@ pub(crate) unsafe fn init(config: Config) {
let freq = (src_freq / prediv.to_div() * mul.to_mul()) / div.to_div();
#[cfg(any(stm32l4px, stm32l4qx, stm32l4rx, stm32l4sx))]
assert!(freq <= 120_000_000);
#[cfg(not(any(stm32l4px, stm32l4qx, stm32l4rx, stm32l4sx)))]
assert!(freq <= 80_000_000);
RCC.pllcfgr().write(move |w| {
w.set_plln(mul.into());
w.set_pllm(prediv.into());
@ -407,7 +402,7 @@ pub(crate) unsafe fn init(config: Config) {
});
let ahb_freq: u32 = match config.ahb_pre {
AHBPrescaler::NotDivided => sys_clk,
AHBPrescaler::DIV1 => sys_clk,
pre => {
let pre: Hpre = pre.into();
let pre = 1 << (pre.to_bits() as u32 - 7);
@ -416,7 +411,7 @@ pub(crate) unsafe fn init(config: Config) {
};
let (apb1_freq, apb1_tim_freq) = match config.apb1_pre {
APBPrescaler::NotDivided => (ahb_freq, ahb_freq),
APBPrescaler::DIV1 => (ahb_freq, ahb_freq),
pre => {
let pre: Ppre = pre.into();
let pre: u8 = 1 << (pre.to_bits() - 3);
@ -426,7 +421,7 @@ pub(crate) unsafe fn init(config: Config) {
};
let (apb2_freq, apb2_tim_freq) = match config.apb2_pre {
APBPrescaler::NotDivided => (ahb_freq, ahb_freq),
APBPrescaler::DIV1 => (ahb_freq, ahb_freq),
pre => {
let pre: Ppre = pre.into();
let pre: u8 = 1 << (pre.to_bits() - 3);

View File

@ -0,0 +1,71 @@
use core::marker::PhantomData;
use embassy_hal_internal::into_ref;
use crate::gpio::sealed::AFType;
use crate::gpio::Speed;
pub use crate::pac::rcc::vals::{Mco1 as Mco1Source, Mco2 as Mco2Source};
use crate::pac::RCC;
use crate::{peripherals, Peripheral};
pub(crate) mod sealed {
pub trait McoInstance {
type Source;
unsafe fn apply_clock_settings(source: Self::Source, prescaler: u8);
}
}
pub trait McoInstance: sealed::McoInstance + 'static {}
pin_trait!(McoPin, McoInstance);
macro_rules! impl_peri {
($peri:ident, $source:ident, $set_source:ident, $set_prescaler:ident) => {
impl sealed::McoInstance for peripherals::$peri {
type Source = $source;
unsafe fn apply_clock_settings(source: Self::Source, prescaler: u8) {
RCC.cfgr().modify(|w| {
w.$set_source(source);
w.$set_prescaler(prescaler);
});
}
}
impl McoInstance for peripherals::$peri {}
};
}
impl_peri!(MCO1, Mco1Source, set_mco1, set_mco1pre);
impl_peri!(MCO2, Mco2Source, set_mco2, set_mco2pre);
pub struct Mco<'d, T: McoInstance> {
phantom: PhantomData<&'d mut T>,
}
impl<'d, T: McoInstance> Mco<'d, T> {
/// Create a new MCO instance.
///
/// `prescaler` must be between 1 and 15.
pub fn new(
_peri: impl Peripheral<P = T> + 'd,
pin: impl Peripheral<P = impl McoPin<T>> + 'd,
source: T::Source,
prescaler: u8,
) -> Self {
into_ref!(pin);
assert!(
1 <= prescaler && prescaler <= 15,
"Mco prescaler must be between 1 and 15. Refer to the reference manual for more information."
);
critical_section::with(|_| unsafe {
T::apply_clock_settings(source, prescaler);
pin.set_as_af(pin.af_num(), AFType::OutputPushPull);
pin.set_speed(Speed::VeryHigh);
});
Self { phantom: PhantomData }
}
}

View File

@ -1,12 +1,17 @@
#![macro_use]
pub(crate) mod bd;
pub mod bus;
use core::mem::MaybeUninit;
pub use crate::rcc::bd::RtcClockSource;
use crate::time::Hertz;
pub(crate) mod bd;
mod bus;
#[cfg(any(stm32h5, stm32h7))]
mod mco;
#[cfg(any(stm32h5, stm32h7))]
pub use mco::*;
#[cfg_attr(rcc_f0, path = "f0.rs")]
#[cfg_attr(any(rcc_f1, rcc_f100, rcc_f1cl), path = "f1.rs")]
#[cfg_attr(rcc_f2, path = "f2.rs")]
@ -16,20 +21,30 @@ use crate::time::Hertz;
#[cfg_attr(rcc_c0, path = "c0.rs")]
#[cfg_attr(rcc_g0, path = "g0.rs")]
#[cfg_attr(rcc_g4, path = "g4.rs")]
#[cfg_attr(any(rcc_h7, rcc_h7ab), path = "h7.rs")]
#[cfg_attr(any(rcc_h5, rcc_h50, rcc_h7, rcc_h7ab), path = "h.rs")]
#[cfg_attr(rcc_l0, path = "l0.rs")]
#[cfg_attr(rcc_l1, path = "l1.rs")]
#[cfg_attr(rcc_l4, path = "l4.rs")]
#[cfg_attr(rcc_l5, path = "l5.rs")]
#[cfg_attr(rcc_u5, path = "u5.rs")]
#[cfg_attr(rcc_wb, path = "wb.rs")]
#[cfg_attr(rcc_wba, path = "wba.rs")]
#[cfg_attr(any(rcc_wl5, rcc_wle), path = "wl.rs")]
#[cfg_attr(any(rcc_h5, rcc_h50), path = "h5.rs")]
mod _version;
pub use _version::*;
#[cfg(feature = "low-power")]
use atomic_polyfill::{AtomicU32, Ordering};
// Model Clock Configuration
//
// pub struct Clocks {
// hse: Option<Hertz>,
// hsi: bool,
// lse: Option<Hertz>,
// lsi: bool,
// rtc: RtcSource,
// }
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct Clocks {
@ -42,16 +57,18 @@ pub struct Clocks {
pub apb2: Hertz,
#[cfg(not(any(rcc_c0, rcc_g0)))]
pub apb2_tim: Hertz,
#[cfg(any(rcc_wl5, rcc_wle, rcc_h5, rcc_h50, rcc_u5))]
#[cfg(any(rcc_wl5, rcc_wle, rcc_h5, rcc_h50, rcc_h7, rcc_h7ab, rcc_u5))]
pub apb3: Hertz,
#[cfg(any(rcc_h7, rcc_h7ab))]
pub apb4: Hertz,
#[cfg(any(rcc_wba))]
pub apb7: Hertz,
// AHB
pub ahb1: Hertz,
#[cfg(any(
rcc_l4, rcc_l5, rcc_f2, rcc_f4, rcc_f410, rcc_f7, rcc_h5, rcc_h50, rcc_h7, rcc_h7ab, rcc_g4, rcc_u5, rcc_wb,
rcc_wl5, rcc_wle
rcc_wba, rcc_wl5, rcc_wle
))]
pub ahb2: Hertz,
#[cfg(any(
@ -59,7 +76,7 @@ pub struct Clocks {
rcc_wle
))]
pub ahb3: Hertz,
#[cfg(any(rcc_h5, rcc_h50, rcc_h7, rcc_h7ab))]
#[cfg(any(rcc_h5, rcc_h50, rcc_h7, rcc_h7ab, rcc_wba))]
pub ahb4: Hertz,
#[cfg(any(rcc_f2, rcc_f4, rcc_f410, rcc_f7))]
@ -80,7 +97,7 @@ pub struct Clocks {
#[cfg(stm32f334)]
pub hrtim: Option<Hertz>,
#[cfg(any(rcc_wb, rcc_f4, rcc_f410))]
#[cfg(any(rcc_wb, rcc_f4, rcc_f410, rcc_f7))]
/// Set only if the lsi or lse is configured, indicates stop is supported
pub rtc: Option<Hertz>,
@ -94,8 +111,7 @@ static CLOCK_REFCOUNT: AtomicU32 = AtomicU32::new(0);
#[cfg(feature = "low-power")]
pub fn low_power_ready() -> bool {
trace!("clock refcount: {}", CLOCK_REFCOUNT.load(Ordering::SeqCst));
// trace!("clock refcount: {}", CLOCK_REFCOUNT.load(Ordering::SeqCst));
CLOCK_REFCOUNT.load(Ordering::SeqCst) == 0
}

View File

@ -11,7 +11,7 @@ pub const HSI_FREQ: Hertz = Hertz(16_000_000);
/// LSI speed
pub const LSI_FREQ: Hertz = Hertz(32_000);
pub use super::bus::VoltageScale;
pub use crate::pac::pwr::vals::Vos as VoltageScale;
#[derive(Copy, Clone)]
pub enum ClockSrc {
@ -119,53 +119,13 @@ impl Into<Pllm> for PllM {
}
}
impl Into<u8> for AHBPrescaler {
fn into(self) -> u8 {
match self {
AHBPrescaler::NotDivided => 1,
AHBPrescaler::Div2 => 0x08,
AHBPrescaler::Div4 => 0x09,
AHBPrescaler::Div8 => 0x0a,
AHBPrescaler::Div16 => 0x0b,
AHBPrescaler::Div64 => 0x0c,
AHBPrescaler::Div128 => 0x0d,
AHBPrescaler::Div256 => 0x0e,
AHBPrescaler::Div512 => 0x0f,
}
}
}
impl Default for AHBPrescaler {
fn default() -> Self {
AHBPrescaler::NotDivided
}
}
impl Default for APBPrescaler {
fn default() -> Self {
APBPrescaler::NotDivided
}
}
impl Into<u8> for APBPrescaler {
fn into(self) -> u8 {
match self {
APBPrescaler::NotDivided => 1,
APBPrescaler::Div2 => 0x04,
APBPrescaler::Div4 => 0x05,
APBPrescaler::Div8 => 0x06,
APBPrescaler::Div16 => 0x07,
}
}
}
impl Into<Sw> for ClockSrc {
fn into(self) -> Sw {
match self {
ClockSrc::MSI(..) => Sw::MSIS,
ClockSrc::HSE(..) => Sw::HSE,
ClockSrc::HSI16 => Sw::HSI16,
ClockSrc::PLL1R(..) => Sw::PLL1R,
ClockSrc::PLL1R(..) => Sw::PLL1_R,
}
}
}
@ -239,10 +199,10 @@ impl Default for Config {
fn default() -> Self {
Self {
mux: ClockSrc::MSI(MSIRange::default()),
ahb_pre: Default::default(),
apb1_pre: Default::default(),
apb2_pre: Default::default(),
apb3_pre: Default::default(),
ahb_pre: AHBPrescaler::DIV1,
apb1_pre: APBPrescaler::DIV1,
apb2_pre: APBPrescaler::DIV1,
apb3_pre: APBPrescaler::DIV1,
hsi48: false,
}
}
@ -326,12 +286,12 @@ pub(crate) unsafe fn init(config: Config) {
}
// TODO make configurable
let power_vos = VoltageScale::Scale3;
let power_vos = VoltageScale::RANGE3;
// states and programming delay
let wait_states = match power_vos {
// VOS 0 range VCORE 1.26V - 1.40V
VoltageScale::Scale0 => {
// VOS 1 range VCORE 1.26V - 1.40V
VoltageScale::RANGE1 => {
if sys_clk < 32_000_000 {
0
} else if sys_clk < 64_000_000 {
@ -344,8 +304,8 @@ pub(crate) unsafe fn init(config: Config) {
4
}
}
// VOS 1 range VCORE 1.15V - 1.26V
VoltageScale::Scale1 => {
// VOS 2 range VCORE 1.15V - 1.26V
VoltageScale::RANGE2 => {
if sys_clk < 30_000_000 {
0
} else if sys_clk < 60_000_000 {
@ -356,8 +316,8 @@ pub(crate) unsafe fn init(config: Config) {
3
}
}
// VOS 2 range VCORE 1.05V - 1.15V
VoltageScale::Scale2 => {
// VOS 3 range VCORE 1.05V - 1.15V
VoltageScale::RANGE3 => {
if sys_clk < 24_000_000 {
0
} else if sys_clk < 48_000_000 {
@ -366,8 +326,8 @@ pub(crate) unsafe fn init(config: Config) {
2
}
}
// VOS 3 range VCORE 0.95V - 1.05V
VoltageScale::Scale3 => {
// VOS 4 range VCORE 0.95V - 1.05V
VoltageScale::RANGE4 => {
if sys_clk < 12_000_000 {
0
} else {
@ -395,7 +355,7 @@ pub(crate) unsafe fn init(config: Config) {
});
let ahb_freq: u32 = match config.ahb_pre {
AHBPrescaler::NotDivided => sys_clk,
AHBPrescaler::DIV1 => sys_clk,
pre => {
let pre: u8 = pre.into();
let pre = 1 << (pre as u32 - 7);
@ -404,7 +364,7 @@ pub(crate) unsafe fn init(config: Config) {
};
let (apb1_freq, apb1_tim_freq) = match config.apb1_pre {
APBPrescaler::NotDivided => (ahb_freq, ahb_freq),
APBPrescaler::DIV1 => (ahb_freq, ahb_freq),
pre => {
let pre: u8 = pre.into();
let pre: u8 = 1 << (pre - 3);
@ -414,7 +374,7 @@ pub(crate) unsafe fn init(config: Config) {
};
let (apb2_freq, apb2_tim_freq) = match config.apb2_pre {
APBPrescaler::NotDivided => (ahb_freq, ahb_freq),
APBPrescaler::DIV1 => (ahb_freq, ahb_freq),
pre => {
let pre: u8 = pre.into();
let pre: u8 = 1 << (pre - 3);
@ -424,7 +384,7 @@ pub(crate) unsafe fn init(config: Config) {
};
let (apb3_freq, _apb3_tim_freq) = match config.apb3_pre {
APBPrescaler::NotDivided => (ahb_freq, ahb_freq),
APBPrescaler::DIV1 => (ahb_freq, ahb_freq),
pre => {
let pre: u8 = pre.into();
let pre: u8 = 1 << (pre - 3);

View File

@ -108,6 +108,7 @@ pub struct Pll {
pub struct Config {
pub hse: Option<Hse>,
pub lse: Option<Hertz>,
pub lsi: bool,
pub sys: Sysclk,
pub mux: Option<PllMux>,
pub pll48: Option<Pll48Source>,
@ -135,7 +136,8 @@ pub const WPAN_DEFAULT: Config = Config {
prediv: 2,
}),
pll48: None,
rtc: None,
rtc: Some(RtcClockSource::LSE),
lsi: false,
pll: Some(Pll {
mul: 12,
@ -145,11 +147,11 @@ pub const WPAN_DEFAULT: Config = Config {
}),
pllsai: None,
ahb1_pre: AHBPrescaler::NotDivided,
ahb2_pre: AHBPrescaler::Div2,
ahb3_pre: AHBPrescaler::NotDivided,
apb1_pre: APBPrescaler::NotDivided,
apb2_pre: APBPrescaler::NotDivided,
ahb1_pre: AHBPrescaler::DIV1,
ahb2_pre: AHBPrescaler::DIV2,
ahb3_pre: AHBPrescaler::DIV1,
apb1_pre: APBPrescaler::DIV1,
apb2_pre: APBPrescaler::DIV1,
};
impl Default for Config {
@ -164,12 +166,13 @@ impl Default for Config {
pll: None,
pllsai: None,
rtc: None,
lsi: false,
ahb1_pre: AHBPrescaler::NotDivided,
ahb2_pre: AHBPrescaler::NotDivided,
ahb3_pre: AHBPrescaler::NotDivided,
apb1_pre: APBPrescaler::NotDivided,
apb2_pre: APBPrescaler::NotDivided,
ahb1_pre: AHBPrescaler::DIV1,
ahb2_pre: AHBPrescaler::DIV1,
ahb3_pre: AHBPrescaler::DIV1,
apb1_pre: APBPrescaler::DIV1,
apb2_pre: APBPrescaler::DIV1,
}
}
}
@ -209,7 +212,7 @@ pub(crate) fn compute_clocks(config: &Config) -> Clocks {
};
let ahb1_clk = match config.ahb1_pre {
AHBPrescaler::NotDivided => sys_clk,
AHBPrescaler::DIV1 => sys_clk,
pre => {
let pre: u8 = pre.into();
let pre = 1u32 << (pre as u32 - 7);
@ -218,7 +221,7 @@ pub(crate) fn compute_clocks(config: &Config) -> Clocks {
};
let ahb2_clk = match config.ahb2_pre {
AHBPrescaler::NotDivided => sys_clk,
AHBPrescaler::DIV1 => sys_clk,
pre => {
let pre: u8 = pre.into();
let pre = 1u32 << (pre as u32 - 7);
@ -227,7 +230,7 @@ pub(crate) fn compute_clocks(config: &Config) -> Clocks {
};
let ahb3_clk = match config.ahb3_pre {
AHBPrescaler::NotDivided => sys_clk,
AHBPrescaler::DIV1 => sys_clk,
pre => {
let pre: u8 = pre.into();
let pre = 1u32 << (pre as u32 - 7);
@ -236,7 +239,7 @@ pub(crate) fn compute_clocks(config: &Config) -> Clocks {
};
let (apb1_clk, apb1_tim_clk) = match config.apb1_pre {
APBPrescaler::NotDivided => (ahb1_clk, ahb1_clk),
APBPrescaler::DIV1 => (ahb1_clk, ahb1_clk),
pre => {
let pre: u8 = pre.into();
let pre: u8 = 1 << (pre - 3);
@ -246,7 +249,7 @@ pub(crate) fn compute_clocks(config: &Config) -> Clocks {
};
let (apb2_clk, apb2_tim_clk) = match config.apb2_pre {
APBPrescaler::NotDivided => (ahb1_clk, ahb1_clk),
APBPrescaler::DIV1 => (ahb1_clk, ahb1_clk),
pre => {
let pre: u8 = pre.into();
let pre: u8 = 1 << (pre - 3);
@ -294,9 +297,11 @@ pub(crate) fn configure_clocks(config: &Config) {
rcc.cfgr().modify(|w| w.set_stopwuck(true));
config
.rtc
.map(|clock_source| BackupDomain::configure_ls(clock_source, None));
BackupDomain::configure_ls(
config.rtc.unwrap_or(RtcClockSource::NOCLOCK),
config.lsi,
config.lse.map(|_| Default::default()),
);
match &config.hse {
Some(hse) => {

View File

@ -0,0 +1,154 @@
use stm32_metapac::rcc::vals::{Pllsrc, Sw};
use crate::pac::{FLASH, RCC};
use crate::rcc::{set_freqs, Clocks};
use crate::time::Hertz;
/// HSI speed
pub const HSI_FREQ: Hertz = Hertz(16_000_000);
/// LSI speed
pub const LSI_FREQ: Hertz = Hertz(32_000);
pub use crate::pac::pwr::vals::Vos as VoltageScale;
pub use crate::pac::rcc::vals::{Hpre as AHBPrescaler, Ppre as APBPrescaler};
#[derive(Copy, Clone)]
pub enum ClockSrc {
HSE(Hertz),
HSI16,
}
#[derive(Clone, Copy, Debug)]
pub enum PllSrc {
HSE(Hertz),
HSI16,
}
impl Into<Pllsrc> for PllSrc {
fn into(self) -> Pllsrc {
match self {
PllSrc::HSE(..) => Pllsrc::HSE32,
PllSrc::HSI16 => Pllsrc::HSI16,
}
}
}
impl Into<Sw> for ClockSrc {
fn into(self) -> Sw {
match self {
ClockSrc::HSE(..) => Sw::HSE32,
ClockSrc::HSI16 => Sw::HSI16,
}
}
}
#[derive(Copy, Clone)]
pub struct Config {
pub mux: ClockSrc,
pub ahb_pre: AHBPrescaler,
pub apb1_pre: APBPrescaler,
pub apb2_pre: APBPrescaler,
pub apb7_pre: APBPrescaler,
}
impl Default for Config {
fn default() -> Self {
Self {
mux: ClockSrc::HSI16,
ahb_pre: AHBPrescaler::DIV1,
apb1_pre: APBPrescaler::DIV1,
apb2_pre: APBPrescaler::DIV1,
apb7_pre: APBPrescaler::DIV1,
}
}
}
pub(crate) unsafe fn init(config: Config) {
let sys_clk = match config.mux {
ClockSrc::HSE(freq) => {
RCC.cr().write(|w| w.set_hseon(true));
while !RCC.cr().read().hserdy() {}
freq
}
ClockSrc::HSI16 => {
RCC.cr().write(|w| w.set_hsion(true));
while !RCC.cr().read().hsirdy() {}
HSI_FREQ
}
};
// TODO make configurable
let power_vos = VoltageScale::RANGE1;
// states and programming delay
let wait_states = match power_vos {
VoltageScale::RANGE1 => match sys_clk.0 {
..=32_000_000 => 0,
..=64_000_000 => 1,
..=96_000_000 => 2,
..=100_000_000 => 3,
_ => 4,
},
VoltageScale::RANGE2 => match sys_clk.0 {
..=8_000_000 => 0,
..=16_000_000 => 1,
_ => 2,
},
};
FLASH.acr().modify(|w| {
w.set_latency(wait_states);
});
RCC.cfgr1().modify(|w| {
w.set_sw(config.mux.into());
});
RCC.cfgr2().modify(|w| {
w.set_hpre(config.ahb_pre.into());
w.set_ppre1(config.apb1_pre.into());
w.set_ppre2(config.apb2_pre.into());
});
RCC.cfgr3().modify(|w| {
w.set_ppre7(config.apb7_pre.into());
});
let ahb_freq = sys_clk / config.ahb_pre;
let (apb1_freq, apb1_tim_freq) = match config.apb1_pre {
APBPrescaler::DIV1 => (ahb_freq, ahb_freq),
pre => {
let freq = ahb_freq / pre;
(freq, freq * 2u32)
}
};
let (apb2_freq, apb2_tim_freq) = match config.apb2_pre {
APBPrescaler::DIV1 => (ahb_freq, ahb_freq),
pre => {
let freq = ahb_freq / pre;
(freq, freq * 2u32)
}
};
let (apb7_freq, _apb7_tim_freq) = match config.apb7_pre {
APBPrescaler::DIV1 => (ahb_freq, ahb_freq),
pre => {
let freq = ahb_freq / pre;
(freq, freq * 2u32)
}
};
set_freqs(Clocks {
sys: sys_clk,
ahb1: ahb_freq,
ahb2: ahb_freq,
ahb4: ahb_freq,
apb1: apb1_freq,
apb2: apb2_freq,
apb7: apb7_freq,
apb1_tim: apb1_tim_freq,
apb2_tim: apb2_tim_freq,
});
}

View File

@ -1,4 +1,5 @@
pub use super::bus::{AHBPrescaler, APBPrescaler, VoltageScale};
pub use super::bus::{AHBPrescaler, APBPrescaler};
pub use crate::pac::pwr::vals::Vos as VoltageScale;
use crate::pac::rcc::vals::Adcsel;
use crate::pac::{FLASH, RCC};
use crate::rcc::bd::{BackupDomain, RtcClockSource};
@ -75,9 +76,9 @@ impl MSIRange {
fn vos(&self) -> VoltageScale {
if self > &MSIRange::Range8 {
VoltageScale::Scale0
VoltageScale::RANGE1
} else {
VoltageScale::Scale1
VoltageScale::RANGE2
}
}
}
@ -138,6 +139,8 @@ pub struct Config {
pub apb1_pre: APBPrescaler,
pub apb2_pre: APBPrescaler,
pub rtc_mux: RtcClockSource,
pub lse: Option<Hertz>,
pub lsi: bool,
pub adc_clock_source: AdcClockSource,
}
@ -146,11 +149,13 @@ impl Default for Config {
fn default() -> Config {
Config {
mux: ClockSrc::MSI(MSIRange::default()),
ahb_pre: AHBPrescaler::NotDivided,
shd_ahb_pre: AHBPrescaler::NotDivided,
apb1_pre: APBPrescaler::NotDivided,
apb2_pre: APBPrescaler::NotDivided,
ahb_pre: AHBPrescaler::DIV1,
shd_ahb_pre: AHBPrescaler::DIV1,
apb1_pre: APBPrescaler::DIV1,
apb2_pre: APBPrescaler::DIV1,
rtc_mux: RtcClockSource::LSI,
lsi: true,
lse: None,
adc_clock_source: AdcClockSource::default(),
}
}
@ -166,13 +171,13 @@ pub enum Lsedrv {
pub(crate) unsafe fn init(config: Config) {
let (sys_clk, sw, vos) = match config.mux {
ClockSrc::HSI16 => (HSI_FREQ.0, 0x01, VoltageScale::Scale1),
ClockSrc::HSE32 => (HSE32_FREQ.0, 0x02, VoltageScale::Scale0),
ClockSrc::HSI16 => (HSI_FREQ.0, 0x01, VoltageScale::RANGE2),
ClockSrc::HSE32 => (HSE32_FREQ.0, 0x02, VoltageScale::RANGE1),
ClockSrc::MSI(range) => (range.freq(), 0x00, range.vos()),
};
let ahb_freq: u32 = match config.ahb_pre {
AHBPrescaler::NotDivided => sys_clk,
AHBPrescaler::DIV1 => sys_clk,
pre => {
let pre: u8 = pre.into();
let pre = 1 << (pre as u32 - 7);
@ -181,7 +186,7 @@ pub(crate) unsafe fn init(config: Config) {
};
let shd_ahb_freq: u32 = match config.shd_ahb_pre {
AHBPrescaler::NotDivided => sys_clk,
AHBPrescaler::DIV1 => sys_clk,
pre => {
let pre: u8 = pre.into();
let pre = 1 << (pre as u32 - 7);
@ -190,7 +195,7 @@ pub(crate) unsafe fn init(config: Config) {
};
let (apb1_freq, apb1_tim_freq) = match config.apb1_pre {
APBPrescaler::NotDivided => (ahb_freq, ahb_freq),
APBPrescaler::DIV1 => (ahb_freq, ahb_freq),
pre => {
let pre: u8 = pre.into();
let pre: u8 = 1 << (pre - 3);
@ -200,7 +205,7 @@ pub(crate) unsafe fn init(config: Config) {
};
let (apb2_freq, apb2_tim_freq) = match config.apb2_pre {
APBPrescaler::NotDivided => (ahb_freq, ahb_freq),
APBPrescaler::DIV1 => (ahb_freq, ahb_freq),
pre => {
let pre: u8 = pre.into();
let pre: u8 = 1 << (pre - 3);
@ -212,16 +217,17 @@ pub(crate) unsafe fn init(config: Config) {
// Adjust flash latency
let flash_clk_src_freq: u32 = shd_ahb_freq;
let ws = match vos {
VoltageScale::Scale0 => match flash_clk_src_freq {
VoltageScale::RANGE1 => match flash_clk_src_freq {
0..=18_000_000 => 0b000,
18_000_001..=36_000_000 => 0b001,
_ => 0b010,
},
VoltageScale::Scale1 => match flash_clk_src_freq {
VoltageScale::RANGE2 => match flash_clk_src_freq {
0..=6_000_000 => 0b000,
6_000_001..=12_000_000 => 0b001,
_ => 0b010,
},
_ => unreachable!(),
};
FLASH.acr().modify(|w| {
@ -231,7 +237,7 @@ pub(crate) unsafe fn init(config: Config) {
while FLASH.acr().read().latency() != ws {}
// Enables the LSI if configured
BackupDomain::configure_ls(config.rtc_mux, None);
BackupDomain::configure_ls(config.rtc_mux, config.lsi, config.lse.map(|_| Default::default()));
match config.mux {
ClockSrc::HSI16 => {
@ -267,7 +273,7 @@ pub(crate) unsafe fn init(config: Config) {
}
RCC.extcfgr().modify(|w| {
if config.shd_ahb_pre == AHBPrescaler::NotDivided {
if config.shd_ahb_pre == AHBPrescaler::DIV1 {
w.set_shdhpre(0);
} else {
w.set_shdhpre(config.shd_ahb_pre.into());
@ -276,11 +282,7 @@ pub(crate) unsafe fn init(config: Config) {
RCC.cfgr().modify(|w| {
w.set_sw(sw.into());
if config.ahb_pre == AHBPrescaler::NotDivided {
w.set_hpre(0);
} else {
w.set_hpre(config.ahb_pre.into());
}
w.set_hpre(config.ahb_pre);
w.set_ppre1(config.apb1_pre.into());
w.set_ppre2(config.apb2_pre.into());
});

View File

@ -164,7 +164,7 @@ impl<'d, T: Instance> Rng<'d, T> {
return Err(Error::SeedError);
}
// write bytes to chunk
for (dest, src) in chunk.iter_mut().zip(random_word.to_be_bytes().iter()) {
for (dest, src) in chunk.iter_mut().zip(random_word.to_ne_bytes().iter()) {
*dest = *src
}
}
@ -195,7 +195,7 @@ impl<'d, T: Instance> RngCore for Rng<'d, T> {
fn fill_bytes(&mut self, dest: &mut [u8]) {
for chunk in dest.chunks_mut(4) {
let rand = self.next_u32();
for (slot, num) in chunk.iter_mut().zip(rand.to_be_bytes().iter()) {
for (slot, num) in chunk.iter_mut().zip(rand.to_ne_bytes().iter()) {
*slot = *num
}
}

View File

@ -10,7 +10,6 @@ use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::blocking_mutex::Mutex;
pub use self::datetime::{DateTime, DayOfWeek, Error as DateTimeError};
use crate::rcc::bd::BackupDomain;
pub use crate::rcc::RtcClockSource;
use crate::time::Hertz;
@ -83,12 +82,44 @@ impl core::ops::Sub for RtcInstant {
}
}
pub struct RtcTimeProvider {
_private: (),
}
impl RtcTimeProvider {
/// Return the current datetime.
///
/// # Errors
///
/// Will return an `RtcError::InvalidDateTime` if the stored value in the system is not a valid [`DayOfWeek`].
pub fn now(&self) -> Result<DateTime, RtcError> {
let r = RTC::regs();
let tr = r.tr().read();
let second = bcd2_to_byte((tr.st(), tr.su()));
let minute = bcd2_to_byte((tr.mnt(), tr.mnu()));
let hour = bcd2_to_byte((tr.ht(), tr.hu()));
// Reading either RTC_SSR or RTC_TR locks the values in the higher-order
// calendar shadow registers until RTC_DR is read.
let dr = r.dr().read();
let weekday = dr.wdu();
let day = bcd2_to_byte((dr.dt(), dr.du()));
let month = bcd2_to_byte((dr.mt() as u8, dr.mu()));
let year = bcd2_to_byte((dr.yt(), dr.yu())) as u16 + 1970_u16;
self::datetime::datetime(year, month, day, weekday, hour, minute, second).map_err(RtcError::InvalidDateTime)
}
}
/// RTC Abstraction
pub struct Rtc {
#[cfg(feature = "low-power")]
stop_time: Mutex<CriticalSectionRawMutex, Cell<Option<RtcInstant>>>,
#[cfg(not(feature = "low-power"))]
_private: (),
}
#[non_exhaustive]
#[derive(Copy, Clone, PartialEq)]
pub struct RtcConfig {
/// The subsecond counter frequency; default is 256
@ -124,31 +155,17 @@ impl Default for RtcCalibrationCyclePeriod {
impl Rtc {
pub fn new(_rtc: impl Peripheral<P = RTC>, rtc_config: RtcConfig) -> Self {
#[cfg(any(rcc_wb, rcc_f4, rcc_f410))]
use crate::rcc::get_freqs;
RTC::enable_peripheral_clk();
BackupDomain::enable_rtc();
#[cfg(any(rcc_wle, rcc_wl5, rcc_g4, rcc_g0, rtc_v2l4, rtc_v2wb))]
<RTC as crate::rcc::sealed::RccPeripheral>::enable();
let mut this = Self {
#[cfg(feature = "low-power")]
stop_time: Mutex::const_new(CriticalSectionRawMutex::new(), Cell::new(None)),
#[cfg(not(feature = "low-power"))]
_private: (),
};
#[cfg(any(rcc_wb, rcc_f4, rcc_f410))]
let freqs = unsafe { get_freqs() };
// Load the clock frequency from the rcc mod, if supported
#[cfg(any(rcc_wb, rcc_f4, rcc_f410))]
let frequency = match freqs.rtc {
Some(hertz) => hertz,
None => freqs.rtc_hse.unwrap(),
};
// Assume the default value, if not supported
#[cfg(not(any(rcc_wb, rcc_f4, rcc_f410)))]
let frequency = Hertz(32_768);
let frequency = Self::frequency();
let async_psc = ((frequency.0 / rtc_config.frequency.0) - 1) as u8;
let sync_psc = (rtc_config.frequency.0 - 1) as u16;
@ -157,6 +174,27 @@ impl Rtc {
this
}
fn frequency() -> Hertz {
#[cfg(any(rcc_wb, rcc_f4, rcc_f410))]
let freqs = unsafe { crate::rcc::get_freqs() };
// Load the clock frequency from the rcc mod, if supported
#[cfg(any(rcc_wb, rcc_f4, rcc_f410))]
match freqs.rtc {
Some(hertz) => hertz,
None => freqs.rtc_hse.unwrap(),
}
// Assume the default value, if not supported
#[cfg(not(any(rcc_wb, rcc_f4, rcc_f410)))]
Hertz(32_768)
}
/// Acquire a [`RtcTimeProvider`] instance.
pub const fn time_provider(&self) -> RtcTimeProvider {
RtcTimeProvider { _private: () }
}
/// Set the datetime to a new value.
///
/// # Errors
@ -189,21 +227,7 @@ impl Rtc {
///
/// Will return an `RtcError::InvalidDateTime` if the stored value in the system is not a valid [`DayOfWeek`].
pub fn now(&self) -> Result<DateTime, RtcError> {
let r = RTC::regs();
let tr = r.tr().read();
let second = bcd2_to_byte((tr.st(), tr.su()));
let minute = bcd2_to_byte((tr.mnt(), tr.mnu()));
let hour = bcd2_to_byte((tr.ht(), tr.hu()));
// Reading either RTC_SSR or RTC_TR locks the values in the higher-order
// calendar shadow registers until RTC_DR is read.
let dr = r.dr().read();
let weekday = dr.wdu();
let day = bcd2_to_byte((dr.dt(), dr.du()));
let month = bcd2_to_byte((dr.mt() as u8, dr.mu()));
let year = bcd2_to_byte((dr.yt(), dr.yu())) as u16 + 1970_u16;
self::datetime::datetime(year, month, day, weekday, hour, minute, second).map_err(RtcError::InvalidDateTime)
self.time_provider().now()
}
/// Check if daylight savings time is active.
@ -264,12 +288,16 @@ pub(crate) mod sealed {
pub trait Instance {
const BACKUP_REGISTER_COUNT: usize;
#[cfg(feature = "low-power")]
const EXTI_WAKEUP_LINE: usize;
#[cfg(feature = "low-power")]
type WakeupInterrupt: crate::interrupt::typelevel::Interrupt;
fn regs() -> Rtc {
crate::pac::RTC
}
fn enable_peripheral_clk();
/// Read content of the backup register.
///
/// The registers retain their values during wakes from standby mode or system resets. They also

View File

@ -15,7 +15,7 @@ pub(crate) enum WakeupPrescaler {
Div16 = 16,
}
#[cfg(any(stm32wb, stm32f4))]
#[cfg(any(stm32wb, stm32f4, stm32l0))]
impl From<WakeupPrescaler> for crate::pac::rtc::vals::Wucksel {
fn from(val: WakeupPrescaler) -> Self {
use crate::pac::rtc::vals::Wucksel;
@ -29,7 +29,7 @@ impl From<WakeupPrescaler> for crate::pac::rtc::vals::Wucksel {
}
}
#[cfg(any(stm32wb, stm32f4))]
#[cfg(any(stm32wb, stm32f4, stm32l0))]
impl From<crate::pac::rtc::vals::Wucksel> for WakeupPrescaler {
fn from(val: crate::pac::rtc::vals::Wucksel) -> Self {
use crate::pac::rtc::vals::Wucksel;
@ -64,24 +64,25 @@ impl super::Rtc {
#[cfg(feature = "low-power")]
/// start the wakeup alarm and wtih a duration that is as close to but less than
/// the requested duration, and record the instant the wakeup alarm was started
pub(crate) fn start_wakeup_alarm(&self, requested_duration: embassy_time::Duration) {
pub(crate) fn start_wakeup_alarm(
&self,
requested_duration: embassy_time::Duration,
cs: critical_section::CriticalSection,
) {
use embassy_time::{Duration, TICK_HZ};
use crate::rcc::get_freqs;
// Panic if the rcc mod knows we're not using low-power rtc
#[cfg(any(rcc_wb, rcc_f4, rcc_f410))]
unsafe { crate::rcc::get_freqs() }.rtc.unwrap();
let rtc_hz = unsafe { get_freqs() }.rtc.unwrap().0 as u64;
let rtc_ticks = requested_duration.as_ticks() * rtc_hz / TICK_HZ;
let requested_duration = requested_duration.as_ticks().clamp(0, u32::MAX as u64);
let rtc_hz = Self::frequency().0 as u64;
let rtc_ticks = requested_duration * rtc_hz / TICK_HZ;
let prescaler = WakeupPrescaler::compute_min((rtc_ticks / u16::MAX as u64) as u32);
// adjust the rtc ticks to the prescaler and subtract one rtc tick
let rtc_ticks = rtc_ticks / prescaler as u64;
let rtc_ticks = if rtc_ticks >= u16::MAX as u64 {
u16::MAX - 1
} else {
rtc_ticks as u16
}
.saturating_sub(1);
let rtc_ticks = rtc_ticks.clamp(0, (u16::MAX - 1) as u64).saturating_sub(1) as u16;
self.write(false, |regs| {
regs.cr().modify(|w| w.set_wute(false));
@ -102,41 +103,47 @@ impl super::Rtc {
self.instant(),
);
critical_section::with(|cs| assert!(self.stop_time.borrow(cs).replace(Some(self.instant())).is_none()))
}
#[cfg(feature = "low-power")]
pub(crate) fn enable_wakeup_line(&self) {
use crate::pac::EXTI;
EXTI.rtsr(0).modify(|w| w.set_line(22, true));
EXTI.imr(0).modify(|w| w.set_line(22, true));
assert!(self.stop_time.borrow(cs).replace(Some(self.instant())).is_none())
}
#[cfg(feature = "low-power")]
/// stop the wakeup alarm and return the time elapsed since `start_wakeup_alarm`
/// was called, otherwise none
pub(crate) fn stop_wakeup_alarm(&self) -> Option<embassy_time::Duration> {
pub(crate) fn stop_wakeup_alarm(&self, cs: critical_section::CriticalSection) -> Option<embassy_time::Duration> {
use crate::interrupt::typelevel::Interrupt;
trace!("rtc: stop wakeup alarm at {}", self.instant());
if RTC::regs().cr().read().wute() {
trace!("rtc: stop wakeup alarm at {}", self.instant());
self.write(false, |regs| {
regs.cr().modify(|w| w.set_wutie(false));
regs.cr().modify(|w| w.set_wute(false));
regs.isr().modify(|w| w.set_wutf(false));
self.write(false, |regs| {
regs.cr().modify(|w| w.set_wutie(false));
regs.cr().modify(|w| w.set_wute(false));
regs.isr().modify(|w| w.set_wutf(false));
crate::pac::EXTI.pr(0).modify(|w| w.set_line(22, true));
crate::interrupt::typelevel::RTC_WKUP::unpend();
});
crate::pac::EXTI
.pr(0)
.modify(|w| w.set_line(RTC::EXTI_WAKEUP_LINE, true));
critical_section::with(|cs| {
if let Some(stop_time) = self.stop_time.borrow(cs).take() {
Some(self.instant() - stop_time)
} else {
None
}
})
<RTC as crate::rtc::sealed::Instance>::WakeupInterrupt::unpend();
});
}
self.stop_time
.borrow(cs)
.take()
.map(|stop_time| self.instant() - stop_time)
}
#[cfg(feature = "low-power")]
pub(crate) fn enable_wakeup_line(&self) {
use crate::interrupt::typelevel::Interrupt;
use crate::pac::EXTI;
<RTC as crate::rtc::sealed::Instance>::WakeupInterrupt::unpend();
unsafe { <RTC as crate::rtc::sealed::Instance>::WakeupInterrupt::enable() };
EXTI.rtsr(0).modify(|w| w.set_line(RTC::EXTI_WAKEUP_LINE, true));
EXTI.imr(0).modify(|w| w.set_line(RTC::EXTI_WAKEUP_LINE, true));
}
/// Applies the RTC config
@ -259,30 +266,17 @@ impl super::Rtc {
impl sealed::Instance for crate::peripherals::RTC {
const BACKUP_REGISTER_COUNT: usize = 20;
fn enable_peripheral_clk() {
#[cfg(any(rtc_v2l4, rtc_v2wb))]
{
// enable peripheral clock for communication
crate::pac::RCC.apb1enr1().modify(|w| w.set_rtcapben(true));
#[cfg(all(feature = "low-power", stm32f4))]
const EXTI_WAKEUP_LINE: usize = 22;
// read to allow the pwr clock to enable
crate::pac::PWR.cr1().read();
}
#[cfg(any(rtc_v2f2))]
{
// enable peripheral clock for communication
crate::pac::RCC.apb1enr().modify(|w| w.set_pwren(true));
#[cfg(all(feature = "low-power", stm32l0))]
const EXTI_WAKEUP_LINE: usize = 20;
// read to allow the pwr clock to enable
crate::pac::PWR.cr().read();
}
#[cfg(all(feature = "low-power", stm32f4))]
type WakeupInterrupt = crate::interrupt::typelevel::RTC_WKUP;
#[cfg(any(rtc_v2f0))]
{
// enable peripheral clock for communication
crate::pac::RCC.apb1enr().modify(|w| w.set_pwren(true));
}
}
#[cfg(all(feature = "low-power", stm32l0))]
type WakeupInterrupt = crate::interrupt::typelevel::RTC;
fn read_backup_register(rtc: &Rtc, register: usize) -> Option<u32> {
if register < Self::BACKUP_REGISTER_COUNT {

View File

@ -128,23 +128,6 @@ impl super::Rtc {
impl sealed::Instance for crate::peripherals::RTC {
const BACKUP_REGISTER_COUNT: usize = 32;
fn enable_peripheral_clk() {
#[cfg(any(rcc_wle, rcc_wl5, rcc_g4))]
{
// enable peripheral clock for communication
crate::pac::RCC.apb1enr1().modify(|w| w.set_rtcapben(true));
}
#[cfg(rcc_g0)]
{
// enable peripheral clock for communication
crate::pac::RCC.apbenr1().modify(|w| w.set_rtcapben(true));
}
// read to allow the pwr clock to enable
crate::pac::PWR.cr1().read();
}
fn read_backup_register(_rtc: &Rtc, register: usize) -> Option<u32> {
#[allow(clippy::if_same_then_else)]
if register < Self::BACKUP_REGISTER_COUNT {

1066
embassy-stm32/src/sai/mod.rs Normal file

File diff suppressed because it is too large Load Diff

View File

@ -323,7 +323,7 @@ impl<'d, T: Instance, Tx, Rx> Spi<'d, T, Tx, Rx> {
}
/// Reconfigures it with the supplied config.
pub fn reconfigure(&mut self, config: Config) {
fn set_config(&mut self, config: Config) {
let cpha = config.raw_phase();
let cpol = config.raw_polarity();
@ -1061,7 +1061,10 @@ foreach_peripheral!(
impl<'d, T: Instance, Tx, Rx> SetConfig for Spi<'d, T, Tx, Rx> {
type Config = Config;
fn set_config(&mut self, config: &Self::Config) {
self.reconfigure(*config);
type ConfigError = ();
fn set_config(&mut self, config: &Self::Config) -> Result<(), ()> {
self.set_config(*config);
Ok(())
}
}

View File

@ -266,32 +266,28 @@ impl RtcDriver {
f(alarm.ctx.get());
}
#[cfg(feature = "low-power")]
/// Set the rtc but panic if it's already been set
pub(crate) fn set_rtc(&self, rtc: &'static Rtc) {
critical_section::with(|cs| assert!(self.rtc.borrow(cs).replace(Some(rtc)).is_none()));
}
/*
Low-power private functions: all operate within a critical seciton
*/
#[cfg(feature = "low-power")]
/// Compute the approximate amount of time until the next alarm
fn time_until_next_alarm(&self) -> embassy_time::Duration {
critical_section::with(|cs| {
let now = self.now() + 32;
fn time_until_next_alarm(&self, cs: CriticalSection) -> embassy_time::Duration {
let now = self.now() + 32;
embassy_time::Duration::from_ticks(
self.alarms
.borrow(cs)
.iter()
.map(|alarm: &AlarmState| alarm.timestamp.get().saturating_sub(now))
.min()
.unwrap_or(u64::MAX),
)
})
embassy_time::Duration::from_ticks(
self.alarms
.borrow(cs)
.iter()
.map(|alarm: &AlarmState| alarm.timestamp.get().saturating_sub(now))
.min()
.unwrap_or(u64::MAX),
)
}
#[cfg(feature = "low-power")]
/// Add the given offset to the current time
fn add_time(&self, offset: embassy_time::Duration) {
fn add_time(&self, offset: embassy_time::Duration, cs: CriticalSection) {
let offset = offset.as_ticks();
let cnt = T::regs_gp16().cnt().read().cnt() as u32;
let period = self.period.load(Ordering::SeqCst);
@ -322,59 +318,77 @@ impl RtcDriver {
T::regs_gp16().cnt().write(|w| w.set_cnt(cnt as u16));
// Now, recompute all alarms
critical_section::with(|cs| {
for i in 0..ALARM_COUNT {
let alarm_handle = unsafe { AlarmHandle::new(i as u8) };
let alarm = self.get_alarm(cs, alarm_handle);
for i in 0..ALARM_COUNT {
let alarm_handle = unsafe { AlarmHandle::new(i as u8) };
let alarm = self.get_alarm(cs, alarm_handle);
self.set_alarm(alarm_handle, alarm.timestamp.get());
}
})
self.set_alarm(alarm_handle, alarm.timestamp.get());
}
}
#[cfg(feature = "low-power")]
/// Stop the wakeup alarm, if enabled, and add the appropriate offset
fn stop_wakeup_alarm(&self) {
fn stop_wakeup_alarm(&self, cs: CriticalSection) {
if let Some(offset) = self.rtc.borrow(cs).get().unwrap().stop_wakeup_alarm(cs) {
self.add_time(offset, cs);
}
}
/*
Low-power public functions: all create a critical section
*/
#[cfg(feature = "low-power")]
/// Set the rtc but panic if it's already been set
pub(crate) fn set_rtc(&self, rtc: &'static Rtc) {
critical_section::with(|cs| {
if let Some(offset) = self.rtc.borrow(cs).get().unwrap().stop_wakeup_alarm() {
self.add_time(offset);
}
rtc.stop_wakeup_alarm(cs);
assert!(self.rtc.borrow(cs).replace(Some(rtc)).is_none())
});
}
#[cfg(feature = "low-power")]
/// Pause the timer if ready; return err if not
pub(crate) fn pause_time(&self) -> Result<(), ()> {
/*
If the wakeup timer is currently running, then we need to stop it and
add the elapsed time to the current time
*/
self.stop_wakeup_alarm();
critical_section::with(|cs| {
/*
If the wakeup timer is currently running, then we need to stop it and
add the elapsed time to the current time, as this will impact the result
of `time_until_next_alarm`.
*/
self.stop_wakeup_alarm(cs);
let time_until_next_alarm = self.time_until_next_alarm();
if time_until_next_alarm < embassy_time::Duration::from_millis(250) {
Err(())
} else {
critical_section::with(|cs| {
let time_until_next_alarm = self.time_until_next_alarm(cs);
if time_until_next_alarm < embassy_time::Duration::from_millis(250) {
Err(())
} else {
self.rtc
.borrow(cs)
.get()
.unwrap()
.start_wakeup_alarm(time_until_next_alarm);
});
.start_wakeup_alarm(time_until_next_alarm, cs);
T::regs_gp16().cr1().modify(|w| w.set_cen(false));
T::regs_gp16().cr1().modify(|w| w.set_cen(false));
Ok(())
}
Ok(())
}
})
}
#[cfg(feature = "low-power")]
/// Resume the timer with the given offset
pub(crate) fn resume_time(&self) {
self.stop_wakeup_alarm();
if T::regs_gp16().cr1().read().cen() {
// Time isn't currently stopped
T::regs_gp16().cr1().modify(|w| w.set_cen(true));
return;
}
critical_section::with(|cs| {
self.stop_wakeup_alarm(cs);
T::regs_gp16().cr1().modify(|w| w.set_cen(true));
})
}
}

View File

@ -5,7 +5,6 @@ pub mod simple_pwm;
use stm32_metapac::timer::vals;
use crate::interrupt;
use crate::rcc::sealed::RccPeripheral as __RccPeri;
use crate::rcc::RccPeripheral;
use crate::time::Hertz;
@ -15,33 +14,95 @@ pub mod low_level {
}
pub(crate) mod sealed {
use super::*;
pub trait Basic16bitInstance: RccPeripheral {
type Interrupt: interrupt::typelevel::Interrupt;
fn regs() -> crate::pac::timer::TimBasic;
fn start(&mut self);
fn start(&mut self) {
Self::regs().cr1().modify(|r| r.set_cen(true));
}
fn stop(&mut self);
fn stop(&mut self) {
Self::regs().cr1().modify(|r| r.set_cen(false));
}
fn reset(&mut self);
fn reset(&mut self) {
Self::regs().cnt().write(|r| r.set_cnt(0));
}
fn set_frequency(&mut self, frequency: Hertz);
fn set_frequency(&mut self, frequency: Hertz) {
let f = frequency.0;
let timer_f = Self::frequency().0;
assert!(f > 0);
let pclk_ticks_per_timer_period = timer_f / f;
let psc: u16 = unwrap!(((pclk_ticks_per_timer_period - 1) / (1 << 16)).try_into());
let arr: u16 = unwrap!((pclk_ticks_per_timer_period / (u32::from(psc) + 1)).try_into());
fn clear_update_interrupt(&mut self) -> bool;
let regs = Self::regs();
regs.psc().write(|r| r.set_psc(psc));
regs.arr().write(|r| r.set_arr(arr));
fn enable_update_interrupt(&mut self, enable: bool);
regs.cr1().modify(|r| r.set_urs(vals::Urs::COUNTERONLY));
regs.egr().write(|r| r.set_ug(true));
regs.cr1().modify(|r| r.set_urs(vals::Urs::ANYEVENT));
}
fn clear_update_interrupt(&mut self) -> bool {
let regs = Self::regs();
let sr = regs.sr().read();
if sr.uif() {
regs.sr().modify(|r| {
r.set_uif(false);
});
true
} else {
false
}
}
fn enable_update_interrupt(&mut self, enable: bool) {
Self::regs().dier().write(|r| r.set_uie(enable));
}
fn set_autoreload_preload(&mut self, enable: vals::Arpe) {
Self::regs().cr1().modify(|r| r.set_arpe(enable));
}
}
pub trait GeneralPurpose16bitInstance: Basic16bitInstance {
fn regs_gp16() -> crate::pac::timer::TimGp16;
fn set_count_direction(&mut self, direction: vals::Dir) {
Self::regs_gp16().cr1().modify(|r| r.set_dir(direction));
}
fn set_clock_division(&mut self, ckd: vals::Ckd) {
Self::regs_gp16().cr1().modify(|r| r.set_ckd(ckd));
}
}
pub trait GeneralPurpose32bitInstance: GeneralPurpose16bitInstance {
fn regs_gp32() -> crate::pac::timer::TimGp32;
fn set_frequency(&mut self, frequency: Hertz);
fn set_frequency(&mut self, frequency: Hertz) {
let f = frequency.0;
assert!(f > 0);
let timer_f = Self::frequency().0;
let pclk_ticks_per_timer_period = (timer_f / f) as u64;
let psc: u16 = unwrap!(((pclk_ticks_per_timer_period - 1) / (1 << 32)).try_into());
let arr: u32 = unwrap!((pclk_ticks_per_timer_period / (psc as u64 + 1)).try_into());
let regs = Self::regs_gp32();
regs.psc().write(|r| r.set_psc(psc));
regs.arr().write(|r| r.set_arr(arr));
regs.cr1().modify(|r| r.set_urs(vals::Urs::COUNTERONLY));
regs.egr().write(|r| r.set_ug(true));
regs.cr1().modify(|r| r.set_urs(vals::Urs::ANYEVENT));
}
}
pub trait AdvancedControlInstance: GeneralPurpose16bitInstance {
@ -49,40 +110,115 @@ pub(crate) mod sealed {
}
pub trait CaptureCompare16bitInstance: GeneralPurpose16bitInstance {
/// Global output enable. Does not do anything on non-advanced timers.
fn enable_outputs(&mut self, enable: bool);
fn set_input_capture_filter(&mut self, channel: Channel, icf: vals::Icf) {
let raw_channel = channel.raw();
Self::regs_gp16()
.ccmr_input(raw_channel / 2)
.modify(|r| r.set_icf(raw_channel % 2, icf));
}
fn set_output_compare_mode(&mut self, channel: Channel, mode: OutputCompareMode);
fn clear_input_interrupt(&mut self, channel: Channel) {
Self::regs_gp16().sr().modify(|r| r.set_ccif(channel.raw(), false));
}
fn set_output_polarity(&mut self, channel: Channel, polarity: OutputPolarity);
fn enable_input_interrupt(&mut self, channel: Channel, enable: bool) {
Self::regs_gp16().dier().modify(|r| r.set_ccie(channel.raw(), enable));
}
fn set_input_capture_prescaler(&mut self, channel: Channel, factor: u8) {
let raw_channel = channel.raw();
Self::regs_gp16()
.ccmr_input(raw_channel / 2)
.modify(|r| r.set_icpsc(raw_channel % 2, factor));
}
fn enable_channel(&mut self, channel: Channel, enable: bool);
fn set_input_ti_selection(&mut self, channel: Channel, tisel: InputTISelection) {
let raw_channel = channel.raw();
Self::regs_gp16()
.ccmr_input(raw_channel / 2)
.modify(|r| r.set_ccs(raw_channel % 2, tisel.into()));
}
fn set_input_capture_mode(&mut self, channel: Channel, mode: InputCaptureMode) {
Self::regs_gp16().ccer().modify(|r| match mode {
InputCaptureMode::Rising => {
r.set_ccnp(channel.raw(), false);
r.set_ccp(channel.raw(), false);
}
InputCaptureMode::Falling => {
r.set_ccnp(channel.raw(), false);
r.set_ccp(channel.raw(), true);
}
InputCaptureMode::BothEdges => {
r.set_ccnp(channel.raw(), true);
r.set_ccp(channel.raw(), true);
}
});
}
fn enable_outputs(&mut self, _enable: bool) {}
fn set_compare_value(&mut self, channel: Channel, value: u16);
fn set_output_compare_mode(&mut self, channel: Channel, mode: OutputCompareMode) {
let r = Self::regs_gp16();
let raw_channel: usize = channel.raw();
r.ccmr_output(raw_channel / 2)
.modify(|w| w.set_ocm(raw_channel % 2, mode.into()));
}
fn get_max_compare_value(&self) -> u16;
fn set_output_polarity(&mut self, channel: Channel, polarity: OutputPolarity) {
Self::regs_gp16()
.ccer()
.modify(|w| w.set_ccp(channel.raw(), polarity.into()));
}
fn enable_channel(&mut self, channel: Channel, enable: bool) {
Self::regs_gp16().ccer().modify(|w| w.set_cce(channel.raw(), enable));
}
fn set_compare_value(&mut self, channel: Channel, value: u16) {
Self::regs_gp16().ccr(channel.raw()).modify(|w| w.set_ccr(value));
}
fn get_capture_value(&mut self, channel: Channel) -> u16 {
Self::regs_gp16().ccr(channel.raw()).read().ccr()
}
fn get_max_compare_value(&self) -> u16 {
Self::regs_gp16().arr().read().arr()
}
}
pub trait ComplementaryCaptureCompare16bitInstance: CaptureCompare16bitInstance {
fn set_complementary_output_polarity(&mut self, channel: Channel, polarity: OutputPolarity);
pub trait ComplementaryCaptureCompare16bitInstance: CaptureCompare16bitInstance + AdvancedControlInstance {
fn set_complementary_output_polarity(&mut self, channel: Channel, polarity: OutputPolarity) {
Self::regs_advanced()
.ccer()
.modify(|w| w.set_ccnp(channel.raw(), polarity.into()));
}
fn set_dead_time_clock_division(&mut self, value: vals::Ckd);
fn set_dead_time_clock_division(&mut self, value: vals::Ckd) {
Self::regs_advanced().cr1().modify(|w| w.set_ckd(value));
}
fn set_dead_time_value(&mut self, value: u8);
fn set_dead_time_value(&mut self, value: u8) {
Self::regs_advanced().bdtr().modify(|w| w.set_dtg(value));
}
fn enable_complementary_channel(&mut self, channel: Channel, enable: bool);
fn enable_complementary_channel(&mut self, channel: Channel, enable: bool) {
Self::regs_advanced()
.ccer()
.modify(|w| w.set_ccne(channel.raw(), enable));
}
}
pub trait CaptureCompare32bitInstance: GeneralPurpose32bitInstance {
fn set_output_compare_mode(&mut self, channel: Channel, mode: OutputCompareMode);
pub trait CaptureCompare32bitInstance: GeneralPurpose32bitInstance + CaptureCompare16bitInstance {
fn set_compare_value(&mut self, channel: Channel, value: u32) {
Self::regs_gp32().ccr(channel.raw()).modify(|w| w.set_ccr(value));
}
fn set_output_polarity(&mut self, channel: Channel, polarity: OutputPolarity);
fn get_capture_value(&mut self, channel: Channel) -> u32 {
Self::regs_gp32().ccr(channel.raw()).read().ccr()
}
fn enable_channel(&mut self, channel: Channel, enable: bool);
fn set_compare_value(&mut self, channel: Channel, value: u32);
fn get_max_compare_value(&self) -> u32;
fn get_max_compare_value(&self) -> u32 {
Self::regs_gp32().arr().read().arr()
}
}
}
@ -105,6 +241,30 @@ impl Channel {
}
}
#[derive(Clone, Copy)]
pub enum InputCaptureMode {
Rising,
Falling,
BothEdges,
}
#[derive(Clone, Copy)]
pub enum InputTISelection {
Normal,
Alternate,
TRC,
}
impl From<InputTISelection> for stm32_metapac::timer::vals::CcmrInputCcs {
fn from(tisel: InputTISelection) -> Self {
match tisel {
InputTISelection::Normal => stm32_metapac::timer::vals::CcmrInputCcs::TI4,
InputTISelection::Alternate => stm32_metapac::timer::vals::CcmrInputCcs::TI3,
InputTISelection::TRC => stm32_metapac::timer::vals::CcmrInputCcs::TRC,
}
}
}
#[derive(Clone, Copy)]
pub enum OutputCompareMode {
Frozen,
@ -195,53 +355,6 @@ macro_rules! impl_basic_16bit_timer {
fn regs() -> crate::pac::timer::TimBasic {
unsafe { crate::pac::timer::TimBasic::from_ptr(crate::pac::$inst.as_ptr()) }
}
fn start(&mut self) {
Self::regs().cr1().modify(|r| r.set_cen(true));
}
fn stop(&mut self) {
Self::regs().cr1().modify(|r| r.set_cen(false));
}
fn reset(&mut self) {
Self::regs().cnt().write(|r| r.set_cnt(0));
}
fn set_frequency(&mut self, frequency: Hertz) {
use core::convert::TryInto;
let f = frequency.0;
let timer_f = Self::frequency().0;
assert!(f > 0);
let pclk_ticks_per_timer_period = timer_f / f;
let psc: u16 = unwrap!(((pclk_ticks_per_timer_period - 1) / (1 << 16)).try_into());
let arr: u16 = unwrap!((pclk_ticks_per_timer_period / (u32::from(psc) + 1)).try_into());
let regs = Self::regs();
regs.psc().write(|r| r.set_psc(psc));
regs.arr().write(|r| r.set_arr(arr));
regs.cr1().modify(|r| r.set_urs(vals::Urs::COUNTERONLY));
regs.egr().write(|r| r.set_ug(true));
regs.cr1().modify(|r| r.set_urs(vals::Urs::ANYEVENT));
}
fn clear_update_interrupt(&mut self) -> bool {
let regs = Self::regs();
let sr = regs.sr().read();
if sr.uif() {
regs.sr().modify(|r| {
r.set_uif(false);
});
true
} else {
false
}
}
fn enable_update_interrupt(&mut self, enable: bool) {
Self::regs().dier().write(|r| r.set_uie(enable));
}
}
};
}
@ -253,24 +366,6 @@ macro_rules! impl_32bit_timer {
fn regs_gp32() -> crate::pac::timer::TimGp32 {
crate::pac::$inst
}
fn set_frequency(&mut self, frequency: Hertz) {
use core::convert::TryInto;
let f = frequency.0;
assert!(f > 0);
let timer_f = Self::frequency().0;
let pclk_ticks_per_timer_period = (timer_f / f) as u64;
let psc: u16 = unwrap!(((pclk_ticks_per_timer_period - 1) / (1 << 32)).try_into());
let arr: u32 = unwrap!(((pclk_ticks_per_timer_period / (psc as u64 + 1)).try_into()));
let regs = Self::regs_gp32();
regs.psc().write(|r| r.set_psc(psc));
regs.arr().write(|r| r.set_arr(arr));
regs.cr1().modify(|r| r.set_urs(vals::Urs::COUNTERONLY));
regs.egr().write(|r| r.set_ug(true));
regs.cr1().modify(|r| r.set_urs(vals::Urs::ANYEVENT));
}
}
};
}
@ -278,41 +373,7 @@ macro_rules! impl_32bit_timer {
#[allow(unused)]
macro_rules! impl_compare_capable_16bit {
($inst:ident) => {
impl sealed::CaptureCompare16bitInstance for crate::peripherals::$inst {
fn enable_outputs(&mut self, _enable: bool) {}
fn set_output_compare_mode(&mut self, channel: Channel, mode: OutputCompareMode) {
use sealed::GeneralPurpose16bitInstance;
let r = Self::regs_gp16();
let raw_channel: usize = channel.raw();
r.ccmr_output(raw_channel / 2)
.modify(|w| w.set_ocm(raw_channel % 2, mode.into()));
}
fn set_output_polarity(&mut self, channel: Channel, polarity: OutputPolarity) {
use sealed::GeneralPurpose16bitInstance;
Self::regs_gp16()
.ccer()
.modify(|w| w.set_ccp(channel.raw(), polarity.into()));
}
fn enable_channel(&mut self, channel: Channel, enable: bool) {
use sealed::GeneralPurpose16bitInstance;
Self::regs_gp16()
.ccer()
.modify(|w| w.set_cce(channel.raw(), enable));
}
fn set_compare_value(&mut self, channel: Channel, value: u16) {
use sealed::GeneralPurpose16bitInstance;
Self::regs_gp16().ccr(channel.raw()).modify(|w| w.set_ccr(value));
}
fn get_max_compare_value(&self) -> u16 {
use sealed::GeneralPurpose16bitInstance;
Self::regs_gp16().arr().read().arr()
}
}
impl sealed::CaptureCompare16bitInstance for crate::peripherals::$inst {}
};
}
@ -344,40 +405,7 @@ foreach_interrupt! {
impl CaptureCompare32bitInstance for crate::peripherals::$inst {}
impl GeneralPurpose16bitInstance for crate::peripherals::$inst {}
impl GeneralPurpose32bitInstance for crate::peripherals::$inst {}
impl sealed::CaptureCompare32bitInstance for crate::peripherals::$inst {
fn set_output_compare_mode(
&mut self,
channel: Channel,
mode: OutputCompareMode,
) {
use crate::timer::sealed::GeneralPurpose32bitInstance;
let raw_channel = channel.raw();
Self::regs_gp32().ccmr_output(raw_channel / 2).modify(|w| w.set_ocm(raw_channel % 2, mode.into()));
}
fn set_output_polarity(&mut self, channel: Channel, polarity: OutputPolarity) {
use crate::timer::sealed::GeneralPurpose32bitInstance;
Self::regs_gp32()
.ccer()
.modify(|w| w.set_ccp(channel.raw(), polarity.into()));
}
fn enable_channel(&mut self, channel: Channel, enable: bool) {
use crate::timer::sealed::GeneralPurpose32bitInstance;
Self::regs_gp32().ccer().modify(|w| w.set_cce(channel.raw(), enable));
}
fn set_compare_value(&mut self, channel: Channel, value: u32) {
use crate::timer::sealed::GeneralPurpose32bitInstance;
Self::regs_gp32().ccr(channel.raw()).modify(|w| w.set_ccr(value));
}
fn get_max_compare_value(&self) -> u32 {
use crate::timer::sealed::GeneralPurpose32bitInstance;
Self::regs_gp32().arr().read().arr() as u32
}
}
impl sealed::CaptureCompare32bitInstance for crate::peripherals::$inst {}
impl sealed::GeneralPurpose16bitInstance for crate::peripherals::$inst {
fn regs_gp16() -> crate::pac::timer::TimGp16 {
@ -394,7 +422,8 @@ foreach_interrupt! {
impl CaptureCompare16bitInstance for crate::peripherals::$inst {}
impl ComplementaryCaptureCompare16bitInstance for crate::peripherals::$inst {}
impl AdvancedControlInstance for crate::peripherals::$inst {}
impl sealed::CaptureCompare16bitInstance for crate::peripherals::$inst {}
impl sealed::ComplementaryCaptureCompare16bitInstance for crate::peripherals::$inst {}
impl sealed::GeneralPurpose16bitInstance for crate::peripherals::$inst {
fn regs_gp16() -> crate::pac::timer::TimGp16 {
unsafe { crate::pac::timer::TimGp16::from_ptr(crate::pac::$inst.as_ptr()) }
@ -407,77 +436,7 @@ foreach_interrupt! {
}
}
impl sealed::CaptureCompare16bitInstance for crate::peripherals::$inst {
fn enable_outputs(&mut self, enable: bool) {
use crate::timer::sealed::AdvancedControlInstance;
let r = Self::regs_advanced();
r.bdtr().modify(|w| w.set_moe(enable));
}
fn set_output_compare_mode(
&mut self,
channel: Channel,
mode: OutputCompareMode,
) {
use crate::timer::sealed::AdvancedControlInstance;
let r = Self::regs_advanced();
let raw_channel: usize = channel.raw();
r.ccmr_output(raw_channel / 2)
.modify(|w| w.set_ocm(raw_channel % 2, mode.into()));
}
fn set_output_polarity(&mut self, channel: Channel, polarity: OutputPolarity) {
use crate::timer::sealed::AdvancedControlInstance;
Self::regs_advanced()
.ccer()
.modify(|w| w.set_ccp(channel.raw(), polarity.into()));
}
fn enable_channel(&mut self, channel: Channel, enable: bool) {
use crate::timer::sealed::AdvancedControlInstance;
Self::regs_advanced()
.ccer()
.modify(|w| w.set_cce(channel.raw(), enable));
}
fn set_compare_value(&mut self, channel: Channel, value: u16) {
use crate::timer::sealed::AdvancedControlInstance;
Self::regs_advanced()
.ccr(channel.raw())
.modify(|w| w.set_ccr(value));
}
fn get_max_compare_value(&self) -> u16 {
use crate::timer::sealed::AdvancedControlInstance;
Self::regs_advanced().arr().read().arr()
}
}
impl sealed::ComplementaryCaptureCompare16bitInstance for crate::peripherals::$inst {
fn set_complementary_output_polarity(&mut self, channel: Channel, polarity: OutputPolarity) {
use crate::timer::sealed::AdvancedControlInstance;
Self::regs_advanced()
.ccer()
.modify(|w| w.set_ccnp(channel.raw(), polarity.into()));
}
fn set_dead_time_clock_division(&mut self, value: vals::Ckd) {
use crate::timer::sealed::AdvancedControlInstance;
Self::regs_advanced().cr1().modify(|w| w.set_ckd(value));
}
fn set_dead_time_value(&mut self, value: u8) {
use crate::timer::sealed::AdvancedControlInstance;
Self::regs_advanced().bdtr().modify(|w| w.set_dtg(value));
}
fn enable_complementary_channel(&mut self, channel: Channel, enable: bool) {
use crate::timer::sealed::AdvancedControlInstance;
Self::regs_advanced()
.ccer()
.modify(|w| w.set_ccne(channel.raw(), enable));
}
}
};

View File

@ -114,6 +114,33 @@ pub struct BufferedUartRx<'d, T: BasicInstance> {
phantom: PhantomData<&'d mut T>,
}
impl<'d, T: BasicInstance> SetConfig for BufferedUart<'d, T> {
type Config = Config;
type ConfigError = ();
fn set_config(&mut self, config: &Self::Config) -> Result<(), ()> {
self.set_config(config).map_err(|_| ())
}
}
impl<'d, T: BasicInstance> SetConfig for BufferedUartRx<'d, T> {
type Config = Config;
type ConfigError = ();
fn set_config(&mut self, config: &Self::Config) -> Result<(), ()> {
self.set_config(config).map_err(|_| ())
}
}
impl<'d, T: BasicInstance> SetConfig for BufferedUartTx<'d, T> {
type Config = Config;
type ConfigError = ();
fn set_config(&mut self, config: &Self::Config) -> Result<(), ()> {
self.set_config(config).map_err(|_| ())
}
}
impl<'d, T: BasicInstance> BufferedUart<'d, T> {
pub fn new(
peri: impl Peripheral<P = T> + 'd,
@ -123,7 +150,7 @@ impl<'d, T: BasicInstance> BufferedUart<'d, T> {
tx_buffer: &'d mut [u8],
rx_buffer: &'d mut [u8],
config: Config,
) -> BufferedUart<'d, T> {
) -> Result<Self, ConfigError> {
// UartRx and UartTx have one refcount ea.
T::enable();
T::enable();
@ -142,7 +169,7 @@ impl<'d, T: BasicInstance> BufferedUart<'d, T> {
tx_buffer: &'d mut [u8],
rx_buffer: &'d mut [u8],
config: Config,
) -> BufferedUart<'d, T> {
) -> Result<Self, ConfigError> {
into_ref!(cts, rts);
// UartRx and UartTx have one refcount ea.
@ -170,7 +197,7 @@ impl<'d, T: BasicInstance> BufferedUart<'d, T> {
tx_buffer: &'d mut [u8],
rx_buffer: &'d mut [u8],
config: Config,
) -> BufferedUart<'d, T> {
) -> Result<Self, ConfigError> {
into_ref!(de);
// UartRx and UartTx have one refcount ea.
@ -193,7 +220,7 @@ impl<'d, T: BasicInstance> BufferedUart<'d, T> {
tx_buffer: &'d mut [u8],
rx_buffer: &'d mut [u8],
config: Config,
) -> BufferedUart<'d, T> {
) -> Result<Self, ConfigError> {
into_ref!(_peri, rx, tx);
let state = T::buffered_state();
@ -206,7 +233,7 @@ impl<'d, T: BasicInstance> BufferedUart<'d, T> {
rx.set_as_af(rx.af_num(), AFType::Input);
tx.set_as_af(tx.af_num(), AFType::OutputPushPull);
configure(r, &config, T::frequency(), T::KIND, true, true);
configure(r, &config, T::frequency(), T::KIND, true, true)?;
r.cr1().modify(|w| {
#[cfg(lpuart_v2)]
@ -219,15 +246,19 @@ impl<'d, T: BasicInstance> BufferedUart<'d, T> {
T::Interrupt::unpend();
unsafe { T::Interrupt::enable() };
Self {
Ok(Self {
rx: BufferedUartRx { phantom: PhantomData },
tx: BufferedUartTx { phantom: PhantomData },
}
})
}
pub fn split(self) -> (BufferedUartTx<'d, T>, BufferedUartRx<'d, T>) {
(self.tx, self.rx)
}
fn set_config(&mut self, config: &Config) -> Result<(), ConfigError> {
reconfigure::<T>(config)
}
}
impl<'d, T: BasicInstance> BufferedUartRx<'d, T> {
@ -304,6 +335,10 @@ impl<'d, T: BasicInstance> BufferedUartRx<'d, T> {
T::Interrupt::pend();
}
}
fn set_config(&mut self, config: &Config) -> Result<(), ConfigError> {
reconfigure::<T>(config)
}
}
impl<'d, T: BasicInstance> BufferedUartTx<'d, T> {
@ -374,6 +409,10 @@ impl<'d, T: BasicInstance> BufferedUartTx<'d, T> {
}
}
}
fn set_config(&mut self, config: &Config) -> Result<(), ConfigError> {
reconfigure::<T>(config)
}
}
impl<'d, T: BasicInstance> Drop for BufferedUartRx<'d, T> {

View File

@ -5,6 +5,7 @@ use core::marker::PhantomData;
use core::sync::atomic::{compiler_fence, Ordering};
use core::task::Poll;
use embassy_embedded_hal::SetConfig;
use embassy_hal_internal::drop::OnDrop;
use embassy_hal_internal::{into_ref, PeripheralRef};
use futures::future::{select, Either};
@ -12,11 +13,10 @@ use futures::future::{select, Either};
use crate::dma::{NoDma, Transfer};
use crate::gpio::sealed::AFType;
use crate::interrupt::typelevel::Interrupt;
#[cfg(not(any(usart_v1, usart_v2)))]
#[allow(unused_imports)]
#[cfg(not(any(usart_v1, usart_v2)))]
use crate::pac::usart::regs::Isr as Sr;
#[cfg(any(usart_v1, usart_v2))]
#[allow(unused_imports)]
use crate::pac::usart::regs::Sr;
#[cfg(not(any(usart_v1, usart_v2)))]
use crate::pac::usart::Lpuart as Regs;
@ -75,12 +75,14 @@ impl<T: BasicInstance> interrupt::typelevel::Handler<T::Interrupt> for Interrupt
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum DataBits {
DataBits8,
DataBits9,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Parity {
ParityNone,
ParityEven,
@ -88,6 +90,7 @@ pub enum Parity {
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum StopBits {
#[doc = "1 stop bit"]
STOP1,
@ -99,6 +102,14 @@ pub enum StopBits {
STOP1P5,
}
#[non_exhaustive]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum ConfigError {
BaudrateTooLow,
BaudrateTooHigh,
}
#[non_exhaustive]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Config {
@ -168,11 +179,30 @@ pub struct Uart<'d, T: BasicInstance, TxDma = NoDma, RxDma = NoDma> {
rx: UartRx<'d, T, RxDma>,
}
impl<'d, T: BasicInstance, TxDma, RxDma> SetConfig for Uart<'d, T, TxDma, RxDma> {
type Config = Config;
type ConfigError = ();
fn set_config(&mut self, config: &Self::Config) -> Result<(), ()> {
self.tx.set_config(config).map_err(|_| ())?;
self.rx.set_config(config).map_err(|_| ())
}
}
pub struct UartTx<'d, T: BasicInstance, TxDma = NoDma> {
phantom: PhantomData<&'d mut T>,
tx_dma: PeripheralRef<'d, TxDma>,
}
impl<'d, T: BasicInstance, TxDma> SetConfig for UartTx<'d, T, TxDma> {
type Config = Config;
type ConfigError = ();
fn set_config(&mut self, config: &Self::Config) -> Result<(), ()> {
self.set_config(config).map_err(|_| ())
}
}
pub struct UartRx<'d, T: BasicInstance, RxDma = NoDma> {
_peri: PeripheralRef<'d, T>,
rx_dma: PeripheralRef<'d, RxDma>,
@ -181,6 +211,15 @@ pub struct UartRx<'d, T: BasicInstance, RxDma = NoDma> {
buffered_sr: stm32_metapac::usart::regs::Sr,
}
impl<'d, T: BasicInstance, RxDma> SetConfig for UartRx<'d, T, RxDma> {
type Config = Config;
type ConfigError = ();
fn set_config(&mut self, config: &Self::Config) -> Result<(), ()> {
self.set_config(config).map_err(|_| ())
}
}
impl<'d, T: BasicInstance, TxDma> UartTx<'d, T, TxDma> {
/// Useful if you only want Uart Tx. It saves 1 pin and consumes a little less power.
pub fn new(
@ -188,7 +227,7 @@ impl<'d, T: BasicInstance, TxDma> UartTx<'d, T, TxDma> {
tx: impl Peripheral<P = impl TxPin<T>> + 'd,
tx_dma: impl Peripheral<P = TxDma> + 'd,
config: Config,
) -> Self {
) -> Result<Self, ConfigError> {
T::enable();
T::reset();
@ -201,7 +240,7 @@ impl<'d, T: BasicInstance, TxDma> UartTx<'d, T, TxDma> {
cts: impl Peripheral<P = impl CtsPin<T>> + 'd,
tx_dma: impl Peripheral<P = TxDma> + 'd,
config: Config,
) -> Self {
) -> Result<Self, ConfigError> {
into_ref!(cts);
T::enable();
@ -219,22 +258,26 @@ impl<'d, T: BasicInstance, TxDma> UartTx<'d, T, TxDma> {
tx: impl Peripheral<P = impl TxPin<T>> + 'd,
tx_dma: impl Peripheral<P = TxDma> + 'd,
config: Config,
) -> Self {
) -> Result<Self, ConfigError> {
into_ref!(_peri, tx, tx_dma);
let r = T::regs();
tx.set_as_af(tx.af_num(), AFType::OutputPushPull);
configure(r, &config, T::frequency(), T::KIND, false, true);
configure(r, &config, T::frequency(), T::KIND, false, true)?;
// create state once!
let _s = T::state();
Self {
Ok(Self {
tx_dma,
phantom: PhantomData,
}
})
}
fn set_config(&mut self, config: &Config) -> Result<(), ConfigError> {
reconfigure::<T>(config)
}
pub async fn write(&mut self, buffer: &[u8]) -> Result<(), Error>
@ -277,7 +320,7 @@ impl<'d, T: BasicInstance, RxDma> UartRx<'d, T, RxDma> {
rx: impl Peripheral<P = impl RxPin<T>> + 'd,
rx_dma: impl Peripheral<P = RxDma> + 'd,
config: Config,
) -> Self {
) -> Result<Self, ConfigError> {
T::enable();
T::reset();
@ -291,7 +334,7 @@ impl<'d, T: BasicInstance, RxDma> UartRx<'d, T, RxDma> {
rts: impl Peripheral<P = impl RtsPin<T>> + 'd,
rx_dma: impl Peripheral<P = RxDma> + 'd,
config: Config,
) -> Self {
) -> Result<Self, ConfigError> {
into_ref!(rts);
T::enable();
@ -310,14 +353,14 @@ impl<'d, T: BasicInstance, RxDma> UartRx<'d, T, RxDma> {
rx: impl Peripheral<P = impl RxPin<T>> + 'd,
rx_dma: impl Peripheral<P = RxDma> + 'd,
config: Config,
) -> Self {
) -> Result<Self, ConfigError> {
into_ref!(peri, rx, rx_dma);
let r = T::regs();
rx.set_as_af(rx.af_num(), AFType::Input);
configure(r, &config, T::frequency(), T::KIND, true, false);
configure(r, &config, T::frequency(), T::KIND, true, false)?;
T::Interrupt::unpend();
unsafe { T::Interrupt::enable() };
@ -325,13 +368,17 @@ impl<'d, T: BasicInstance, RxDma> UartRx<'d, T, RxDma> {
// create state once!
let _s = T::state();
Self {
Ok(Self {
_peri: peri,
rx_dma,
detect_previous_overrun: config.detect_previous_overrun,
#[cfg(any(usart_v1, usart_v2))]
buffered_sr: stm32_metapac::usart::regs::Sr(0),
}
})
}
fn set_config(&mut self, config: &Config) -> Result<(), ConfigError> {
reconfigure::<T>(config)
}
#[cfg(any(usart_v1, usart_v2))]
@ -646,7 +693,7 @@ impl<'d, T: BasicInstance, TxDma, RxDma> Uart<'d, T, TxDma, RxDma> {
tx_dma: impl Peripheral<P = TxDma> + 'd,
rx_dma: impl Peripheral<P = RxDma> + 'd,
config: Config,
) -> Self {
) -> Result<Self, ConfigError> {
// UartRx and UartTx have one refcount ea.
T::enable();
T::enable();
@ -665,7 +712,7 @@ impl<'d, T: BasicInstance, TxDma, RxDma> Uart<'d, T, TxDma, RxDma> {
tx_dma: impl Peripheral<P = TxDma> + 'd,
rx_dma: impl Peripheral<P = RxDma> + 'd,
config: Config,
) -> Self {
) -> Result<Self, ConfigError> {
into_ref!(cts, rts);
// UartRx and UartTx have one refcount ea.
@ -692,7 +739,7 @@ impl<'d, T: BasicInstance, TxDma, RxDma> Uart<'d, T, TxDma, RxDma> {
tx_dma: impl Peripheral<P = TxDma> + 'd,
rx_dma: impl Peripheral<P = RxDma> + 'd,
config: Config,
) -> Self {
) -> Result<Self, ConfigError> {
into_ref!(de);
// UartRx and UartTx have one refcount ea.
@ -714,7 +761,7 @@ impl<'d, T: BasicInstance, TxDma, RxDma> Uart<'d, T, TxDma, RxDma> {
tx_dma: impl Peripheral<P = TxDma> + 'd,
rx_dma: impl Peripheral<P = RxDma> + 'd,
config: Config,
) -> Self {
) -> Result<Self, ConfigError> {
into_ref!(peri, rx, tx, tx_dma, rx_dma);
let r = T::regs();
@ -736,7 +783,7 @@ impl<'d, T: BasicInstance, TxDma, RxDma> Uart<'d, T, TxDma, RxDma> {
}
}
configure(r, &config, T::frequency(), T::KIND, true, true);
configure(r, &config, T::frequency(), T::KIND, true, true)?;
T::Interrupt::unpend();
unsafe { T::Interrupt::enable() };
@ -744,7 +791,7 @@ impl<'d, T: BasicInstance, TxDma, RxDma> Uart<'d, T, TxDma, RxDma> {
// create state once!
let _s = T::state();
Self {
Ok(Self {
tx: UartTx {
tx_dma,
phantom: PhantomData,
@ -756,7 +803,7 @@ impl<'d, T: BasicInstance, TxDma, RxDma> Uart<'d, T, TxDma, RxDma> {
#[cfg(any(usart_v1, usart_v2))]
buffered_sr: stm32_metapac::usart::regs::Sr(0),
},
}
})
}
pub async fn write(&mut self, buffer: &[u8]) -> Result<(), Error>
@ -804,7 +851,27 @@ impl<'d, T: BasicInstance, TxDma, RxDma> Uart<'d, T, TxDma, RxDma> {
}
}
fn configure(r: Regs, config: &Config, pclk_freq: Hertz, kind: Kind, enable_rx: bool, enable_tx: bool) {
fn reconfigure<T: BasicInstance>(config: &Config) -> Result<(), ConfigError> {
T::Interrupt::disable();
let r = T::regs();
let cr = r.cr1().read();
configure(r, config, T::frequency(), T::KIND, cr.re(), cr.te())?;
T::Interrupt::unpend();
unsafe { T::Interrupt::enable() };
Ok(())
}
fn configure(
r: Regs,
config: &Config,
pclk_freq: Hertz,
kind: Kind,
enable_rx: bool,
enable_tx: bool,
) -> Result<(), ConfigError> {
if !enable_rx && !enable_tx {
panic!("USART: At least one of RX or TX should be enabled");
}
@ -872,7 +939,7 @@ fn configure(r: Regs, config: &Config, pclk_freq: Hertz, kind: Kind, enable_rx:
found_brr = Some(brr);
break;
}
panic!("USART: baudrate too high");
return Err(ConfigError::BaudrateTooHigh);
}
if brr < brr_max {
@ -884,7 +951,7 @@ fn configure(r: Regs, config: &Config, pclk_freq: Hertz, kind: Kind, enable_rx:
}
}
let brr = found_brr.expect("USART: baudrate too low");
let brr = found_brr.ok_or(ConfigError::BaudrateTooLow)?;
#[cfg(not(usart_v1))]
let oversampling = if over8 { "8 bit" } else { "16 bit" };
@ -930,12 +997,16 @@ fn configure(r: Regs, config: &Config, pclk_freq: Hertz, kind: Kind, enable_rx:
});
#[cfg(not(usart_v1))]
w.set_over8(vals::Over8::from_bits(over8 as _));
#[cfg(usart_v4)]
w.set_fifoen(true);
});
#[cfg(not(usart_v1))]
r.cr3().modify(|w| {
w.set_onebit(config.assume_noise_free);
});
Ok(())
}
mod eh02 {

View File

@ -3,10 +3,11 @@ use core::mem;
use core::sync::atomic::{compiler_fence, Ordering};
use core::task::Poll;
use embassy_embedded_hal::SetConfig;
use embassy_hal_internal::PeripheralRef;
use futures::future::{select, Either};
use super::{clear_interrupt_flags, rdr, sr, BasicInstance, Error, UartRx};
use super::{clear_interrupt_flags, rdr, reconfigure, sr, BasicInstance, Config, ConfigError, Error, UartRx};
use crate::dma::ReadableRingBuffer;
use crate::usart::{Regs, Sr};
@ -15,6 +16,15 @@ pub struct RingBufferedUartRx<'d, T: BasicInstance, RxDma: super::RxDma<T>> {
ring_buf: ReadableRingBuffer<'d, RxDma, u8>,
}
impl<'d, T: BasicInstance, RxDma: super::RxDma<T>> SetConfig for RingBufferedUartRx<'d, T, RxDma> {
type Config = Config;
type ConfigError = ();
fn set_config(&mut self, config: &Self::Config) -> Result<(), ()> {
self.set_config(config).map_err(|_| ())
}
}
impl<'d, T: BasicInstance, RxDma: super::RxDma<T>> UartRx<'d, T, RxDma> {
/// Turn the `UartRx` into a buffered uart which can continously receive in the background
/// without the possibility of loosing bytes. The `dma_buf` is a buffer registered to the
@ -54,6 +64,11 @@ impl<'d, T: BasicInstance, RxDma: super::RxDma<T>> RingBufferedUartRx<'d, T, RxD
Err(err)
}
fn set_config(&mut self, config: &Config) -> Result<(), ConfigError> {
self.teardown_uart();
reconfigure::<T>(config)
}
/// Start uart background receive
fn setup_uart(&mut self) {
// fence before starting DMA.

View File

@ -264,10 +264,7 @@ impl<'d, T: Instance> Driver<'d, T> {
let regs = T::regs();
#[cfg(stm32l5)]
{
crate::peripherals::PWR::enable();
crate::pac::PWR.cr2().modify(|w| w.set_usv(true));
}
crate::pac::PWR.cr2().modify(|w| w.set_usv(true));
#[cfg(pwr_h5)]
crate::pac::PWR.usbscr().modify(|w| w.set_usb33sv(true));

View File

@ -540,10 +540,7 @@ impl<'d, T: Instance> Bus<'d, T> {
impl<'d, T: Instance> Bus<'d, T> {
fn init(&mut self) {
#[cfg(stm32l4)]
{
crate::peripherals::PWR::enable();
critical_section::with(|_| crate::pac::PWR.cr2().modify(|w| w.set_usv(true)));
}
critical_section::with(|_| crate::pac::PWR.cr2().modify(|w| w.set_usv(true)));
#[cfg(stm32f7)]
{
@ -618,15 +615,10 @@ impl<'d, T: Instance> Bus<'d, T> {
{
// Enable USB power
critical_section::with(|_| {
crate::pac::RCC.ahb3enr().modify(|w| {
w.set_pwren(true);
});
cortex_m::asm::delay(2);
crate::pac::PWR.svmcr().modify(|w| {
w.set_usv(true);
w.set_uvmen(true);
});
})
});
// Wait for USB power to stabilize

View File

@ -1,5 +1,5 @@
#![cfg_attr(not(any(feature = "std", feature = "wasm")), no_std)]
#![cfg_attr(feature = "nightly", feature(async_fn_in_trait, impl_trait_projections))]
#![cfg_attr(feature = "nightly", feature(async_fn_in_trait))]
#![allow(clippy::new_without_default)]
#![doc = include_str!("../README.md")]
#![warn(missing_docs)]

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