1 Star 17 Fork 3

Lee Lup Yuen 李立源 / stm32-blue-pill-rust

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

stm32-blue-pill-rust

Rust for STM32 Blue Pill with Visual Studio Code.

Read the article: https://medium.com/@ly.lee/coding-the-stm32-blue-pill-with-rust-and-visual-studio-code-b21615d8a20

Based on:

  1. Jorge Aparicio's Discovery book: https://japaric.github.io/discovery/

  2. Jorge Aparicio's HAL for Blue Pill: https://japaric.github.io/stm32f103xx-hal/stm32f103xx_hal/

  3. Jorge Aparicio's Cortex-M Quickstart: https://docs.rs/cortex-m-quickstart/0.2.7/cortex_m_quickstart/

  4. Nerijus Arlauskas's Embedded Rust blog: http://nercury.github.io/rust/embedded/experiments/2018/04/29/rust-embedded-01-discovery-vl-flipping-bits.html


Connecting the STM32 Blue Pill to ST-Link V2 USB Debugger

STM32 Blue Pill ST-Link V2 USB Debugger
V3 [Red] 3.3V (Pin 8)
IO [Orange] SWDIO (Pin 4)
CLK [Brown] SWDCLK (Pin 2)
GND [Black] GND (Pin 6)

Installation and Usage

Install Prerequisites

  • For Ubuntu only: Install required packages (arm-none-eabi-gdb is obsolete)

    sudo apt install pkg-config cmake libssl-dev zlib1g-dev gdb-multiarch curl git
    
    sudo ln -s /usr/bin/gdb-multiarch /usr/bin/arm-none-eabi-gdb

Install ARM Cross-Compiler and Linker

  • For Windows:

    1. Install ARM Cross-Compiler and Linker from the ARM Developer Website:
      https://developer.arm.com/open-source/gnu-toolchain/gnu-rm/downloads

    2. Scroll down the page till you find
      Windows 32-bit File: gcc-arm-none-eabi-…-win32.exe
      Click Download

    3. Select the "Add path to environment variable" option at the last install step

    4. In Windows Explorer, browse to
      C:\Program Files (x86)\GNU Tools Arm Embedded\7 2018-q2-update\bin
      (The 7 2018-q2-update part may be different for your installation)

    5. Copy the file arm-none-eabi-ar.exe to ar.exe
      This ar.exe workaround is temporary until we find a fix for the Windows Rust build

  • For Ubuntu:

    sudo apt install binutils-arm-none-eabi gcc-arm-none-eabi

Check ARM Cross-Compiler Installation

  1. Open a new Windows or Ubuntu command prompt (not Windows Bash) and enter

    arm-none-eabi-gcc -v
  2. You should see something like version 5.4.1 20160919 (release)

  3. If you see no errors, close the command prompt.

  4. If you see an error, update your PATH environment variable so that it includes the folder for the ARM ".exe" files.

Install OpenOCD For Debugging Blue Pill

  • For Windows:

    1. Download OpenOCD (for debugging the Blue Pill) from the unofficial OpenOCD release website:
      https://github.com/gnu-mcu-eclipse/openocd/releases
      Look for gnu-mcu-eclipse-openocd-…-win64.zip

    2. Unzip the OpenOCD download and copy the OpenOCD files into c:\openocd such that opencd.exe is located in the folder c:\openocd\bin

  • For Ubuntu:

    sudo apt install openocd

For Windows only: Install ST-Link USB Driver

  1. For Windows only: Download the ST-Link USB driver from the ST-Link Driver Website (email registration required):
    http://www.st.com/en/embedded-software/stsw-link009.html

  2. Scroll down and click the Get Software button

  3. Unzip the ST-Link download. Double-click the dpinst_amd64.exe installer.

For Windows only: Install Build Tools

  1. For Windows only: Install Build Tools for Visual Studio 2017 (needed by rustup) from
    https://aka.ms/buildtools

  2. Under "Workloads", select Visual C++ Build Tools.
    Warning: The download is 1.1 GB and you need 4.8 GB of free disk space.

Install rustup

  1. Install rustup (the Rust toolchain installer) from
    https://rustup.rs/

  2. If you see a message about Windows Defender SmartScreen,  click More Info and Run Anyway.

  3. Select the default installation option when prompted.
    For Ubuntu only: Log out and log in again to update the PATH

  4. Switch to the nightly Rust toolchain (instead of stable or beta). Open a new Windows or Ubuntu command prompt (not Windows Bash) and enter:

    rustup default nightly
  5. Install the rust-std component thumbv7m-none-eabi to cross-compile for ARM Cortex-M3 (the processor used in the Blue Pill):

    rustup target add thumbv7m-none-eabi

Download stm32-blue-pill-rust Source Files

  • Download the source files from GitHub:
    (You may install git from https://gitforwindows.org)

    git clone https://github.com/lupyuen/stm32-blue-pill-rust.git
    cd stm32-blue-pill-rust

Install Visual Studio Code

  1. Install Visual Studio Code from
    https://code.visualstudio.com/download

  2. Launch Visual Studio Code and install the following extensions (just click the links below followed by the Install button and Open Visual Studio Code):

  3. In Visual Studio Code, click Install when prompted to install the above extensions

  4. Restart Visual Studio Code

  5. Click File → Open Workspace

  6. Browse to the stm32-blue-pill-rust folder and select workspace.code-workspace

  7. In the Explorer → Workspace pane at left, browse to the source folder src and select the Rust source file main.rs

  8. When prompted, install the Rust Language Service (RLS), which provides Autocomplete and "Go To Definition" features for Rust.

Compiling the Rust program in Visual Studio Code

  1. In Visual Studio Code, click Tasks → Run Build Task.

  2. Wait a while for the Rust program to be compiled.

  3. Check the log in the Terminal window at the bottom of the Visual Studio Code screen.

  4. When you see Finished released [optimized + debuginfo] target(s), that means the Rust program has been compiled successfully.

  5. We'll proceed to the next step to run the program.

  6. But if you see an error, you'll have to fix the error and recompile the program. Just mouse over the filename and line number in the log, and press Ctrl-click to jump to the offending line of code.

Running the Rust program in Visual Studio Code

  1. Click Tasks → Run Task

  2. Select Connect To STM32 Blue Pill

  3. Check the messages from OpenOCD in the Terminal window at the bottom of Visual Studio Code.

  4. When you see Listening on port 3333 for gdb connections, our program is ready to be started on the Blue Pill.

  5. Click Debug → Start Debugging

  6. Note: There is a bug in the debugger for Ubuntu: gdb stops with an error. To be fixed. Meanwhile you can use the command-line debugger in Ubuntu.

Building from the Command Line

  1. Build the application:

    cargo clean
    cargo check --release
    cargo build --release
  2. You should see something like:

    Finished release [optimized + debuginfo] target(s) in 1.43s
  3. Sanity check for the built application

    arm-none-eabi-readelf -h target/thumbv7m-none-eabi/release/stm32-blue-pill-rust
  4. You should see something like:

    ELF Header:
      Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00
      Class:                             ELF32
      Data:                              2's complement, little endian
      Version:                           1 (current)
      OS/ABI:                            UNIX 1. System V
      ABI Version:                       0
      Type:                              EXEC (Executable file)
      Machine:                           ARM
      Version:                           0x1
      Entry point address:               0x8000cfb
      Start of program headers:          52 (bytes into file)
      Start of section headers:          258948 (bytes into file)
      Flags:                             0x5000200, Version5 EABI, soft-float ABI
      Size of this header:               52 (bytes)
      Size of program headers:           32 (bytes)
      Number of program headers:         3
      Size of section headers:           40 (bytes)
      Number of section headers:         21
      Section header string table index: 20

Debugging from the Command Line

  1. Launch OpenOCD on a terminal. Scripts are located at /usr/share/openocd/scripts

    • For Windows:

      c:\openocd\bin\openocd -f interface/stlink-v2.cfg -f target/stm32f1x.cfg
    • For Ubuntu:

      openocd -f interface/stlink-v2.cfg -f target/stm32f1x.cfg
  2. You should see something like:

    GNU MCU Eclipse 64-bits Open On-Chip Debugger 0.10.0+dev-00487-gaf359c18 (2018-05-12-19:30)
    Licensed under GNU GPL v2
    For bug reports, read http://openocd.org/doc/doxygen/bugs.html
    WARNING: interface/stlink-v2.cfg is deprecated, please switch to interface/stlink.cfg
    Info : auto-selecting first available session transport "hla_swd". To override use 'transport select <transport>'.
    Info : The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD
    adapter speed: 1000 kHz
    adapter_nsrst_delay: 100
    none separate
    Info : Listening on port 6666 for tcl connections
    Info : Listening on port 4444 for telnet connections
    Info : Unable to match requested speed 1000 kHz, using 950 kHz
    Info : Unable to match requested speed 1000 kHz, using 950 kHz
    Info : clock speed 950 kHz
    Info : STLINK v2 JTAG v17 API v2 SWIM v4 VID 0x0483 PID 0x3748
    Info : using stlink api v2
    Info : Target voltage: 3.225397
    Info : stm32f1x.cpu: hardware has 6 breakpoints, 4 watchpoints
    Info : Listening on port 3333 for gdb connections
  3. Start a debug session in another command window:

    arm-none-eabi-gdb -x loader.gdb target/thumbv7m-none-eabi/release/stm32-blue-pill-rust
  4. Common GDB commands:

    • step: Execute the current source line, step into functions if present. Same as the step into command in Visual Studio Code.

    • next: Execute the current source line, don't step into functions. Same as the step over command in Visual Studio Code.

    • where: Show stack trace.

    • where full: Show stack trace with local variables.

    More commands: https://darkdust.net/files/GDB%20Cheat%20Sheet.pdf


Visual Studio Code Configuration

Customisation of the Visual Studio Code UI was done through the following files:

Task configuration - .vscode/tasks.json

Defines the following tasks:

  1. Connect: Launches OpenOCD. Uses different commands for Ubuntu and Windows (opencd vs c:\opencd\bin\opencd).

  2. Build: Executes cargo build --release. Configured as the default build task.

  3. Remove: Executes cargo clean

  4. Check: Executes cargo check --release

Debugger configuration - .vscode/launch.json

  • Launches the following command when the debugger is started:

    arm-none-eabi-gdb -x loader.gdb target/thumbv7m-none-eabi/release/stm32-blue-pill-rust
  • This command causes gdb to execute the loader.gdb script at the start of debugging.

  • The mandatory parameter target/thumbv7m-none-eabi/release/stm32-blue-pill-rust is redundant. The target is specified again in loader.gdb.

Debugger script - loader.gdb

  1. This is the GDB script for loading and running programs in STM32 Blue Pill.

  2. Called when debugging begins. Defined in .vscode/launch.json

  3. This file used to be .gdbinit, which could not be autoloaded due to autoloading security in GDB.

  4. Set architecture to ARM 32-bit. Needed for gdb-multiarch on Ubuntu.

  5. Send GDB commands to OpenOCD, which listens on port 3333. Extend the timeout.

  6. Disable all messages.

  7. Enable ARM semihosting to show debug console output in OpenOCD console.

  8. Reset the device.

  9. Specify target/thumbv7m-none-eabi/release/stm32-blue-pill-rust as the target program to be debugged. Must be specified here (not the command line) because the VSCode debugger will fail without it.

  10. Load the program into device memory.

  11. Set breakpoint at the main() function.

  12. Run the program and stop at the main() function.

  13. Remove the breakpoint at the main() function.

  14. Step into the first line of the main() function. Else gdb will complain about entry macros file missing.

  15. TODO: Write program to flash memory so that it becomes permanent.


How This Rust Crate Was Created

  1. Install Cargo clone and add subcommands:

    cargo install cargo-clone
    cargo install cargo-edit
  2. Clone the quickstart crate

    cargo clone cortex-m-quickstart && cd $_
  3. Change the crate name, author and version in Cargo.toml:

    [package]
    authors = ["Jorge Aparicio <jorge@japaric.io>"]
    name = "demo"
    version = "0.1.0"
  4. Specify the memory layout of the target device. Since board support crate for stm32f103xx provides this file, we remove both the memory.x and build.rs files.

    rm memory.x build.rs
  5. Set a default build target

    cat >>.cargo/config <<'EOF'
    
    [build]
    target = "thumbv7m-none-eabi"
    EOF
  6. Depend on a HAL implementation.

    cargo add https://github.com/japaric/stm32f103xx
    cargo add https://github.com/japaric/stm32f103xx-hal
  7. Copy the delay sample application from https://github.com/japaric/stm32f103xx-hal into src\main.rs

    rm -r src/* && cp ../stm32f103xx_hal/examples/delay.rs src/main.rs

References

Windows Setup for Embedded Rust: https://japaric.github.io/discovery/03-setup/windows.html

Peripheral I/O with Embedded HAL: http://blog.japaric.io/brave-new-io/

Embedded Rust Blog: http://blog.japaric.io/

Embedded Rust Book (work in progress): https://github.com/rust-lang-nursery/embedded-wg/tree/master/books/embedded-rust-book

Rust RTFM Docs and Book (work in progress): https://github.com/japaric/cortex-m-rtfm/tree/gh-pages

Awesome Embedded Rust (covers other hardware platforms): https://github.com/rust-embedded/awesome-embedded-rust

Details of rustup: https://github.com/rust-lang-nursery/rustup.rs

STM32F103C8 Website: https://www.st.com/en/microcontrollers/stm32f103c8.html

STM32F103C8 Datasheet: https://www.st.com/resource/en/datasheet/stm32f103c8.pdf

STM32F103C8 Reference Manual: https://www.st.com/content/ccc/resource/technical/document/reference_manual/59/b9/ba/7f/11/af/43/d5/CD00171190.pdf/files/CD00171190.pdf/jcr:content/translations/en.CD00171190.pdf

STM32F103C8 Flash Programming: https://www.st.com/content/ccc/resource/technical/document/programming_manual/10/98/e8/d4/2b/51/4b/f5/CD00283419.pdf/files/CD00283419.pdf/jcr:content/translations/en.CD00283419.pdf

STM32F103C8 ARM Cortex M3 Programming: https://www.st.com/content/ccc/resource/technical/document/programming_manual/5b/ca/8d/83/56/7f/40/08/CD00228163.pdf/files/CD00228163.pdf/jcr:content/translations/en.CD00228163.pdf


License

Licensed under either of

at your option.


Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

Rust for STM32 Blue Pill with Visual Studio Code 展开 收起
Rust 等 3 种语言
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
Rust
1
https://gitee.com/lupyuen/stm32-blue-pill-rust.git
git@gitee.com:lupyuen/stm32-blue-pill-rust.git
lupyuen
stm32-blue-pill-rust
stm32-blue-pill-rust
master

搜索帮助

14c37bed 8189591 565d56ea 8189591