* add mt3620 lib as submodule

* Add PWMAudio project

* add vscode settings

* add PWM Audio to contents
This commit is contained in:
James Devine 2022-12-01 18:36:32 +00:00 коммит произвёл GitHub
Родитель 6232891f46
Коммит b2f9eb3308
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
16 изменённых файлов: 317 добавлений и 2 удалений

5
.gitmodules поставляемый
Просмотреть файл

@ -55,4 +55,7 @@
url = https://github.com/kiwipower/nutkin.git
[submodule "AzureSphereSquirrel/HLCore/squirrel"]
path = AzureSphereSquirrel/HLCore/squirrel
url = https://github.com/CoderScribe/squirrel.git
url = https://github.com/CoderScribe/squirrel.git
[submodule "PWMAudio/lib"]
path = PWMAudio/lib
url = https://github.com/CodethinkLabs/mt3620-m4-drivers.git

3
PWMAudio/.gitignore поставляемый Normal file
Просмотреть файл

@ -0,0 +1,3 @@
# Ignore output directories
/out/
/install/

12
PWMAudio/.vscode/settings.json поставляемый Normal file
Просмотреть файл

@ -0,0 +1,12 @@
{
"cmake.generator": "Ninja",
"cmake.buildDirectory": "${workspaceRoot}/out/${buildType}-${command:azuresphere.AzureSphereTargetApiSet}",
"cmake.buildToolArgs": [ "-v" ],
"cmake.configureSettings": {
"CMAKE_TOOLCHAIN_FILE": "${command:azuresphere.AzureSphereSdkDir}/CMakeFiles/AzureSphereRTCoreToolchain.cmake",
"ARM_GNU_PATH": "${command:azuresphere.ArmGnuPath}",
"AZURE_SPHERE_TARGET_API_SET": "latest-beta"
},
"cmake.configureOnOpen": true,
"C_Cpp.default.configurationProvider": "vector-of-bool.cmake-tools"
}

15
PWMAudio/CMakeLists.txt Normal file
Просмотреть файл

@ -0,0 +1,15 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
cmake_minimum_required (VERSION 3.10)
project (PWMAudioRT C)
azsphere_configure_tools(TOOLS_REVISION "22.11")
# Create executable
add_executable(${PROJECT_NAME} main.c lib/VectorTable.c lib/GPT.c lib/GPIO.c)
target_link_libraries (${PROJECT_NAME})
set_target_properties (${PROJECT_NAME} PROPERTIES LINK_DEPENDS ${CMAKE_SOURCE_DIR}/linker.ld)
azsphere_target_add_image_package(${PROJECT_NAME})

Просмотреть файл

@ -0,0 +1,4 @@
{
"enableCMake": true,
"sourceDirectory": [ "$projectname$" ]
}

21
PWMAudio/LICENSE.txt Normal file
Просмотреть файл

@ -0,0 +1,21 @@
Copyright (c) Microsoft Corporation.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

103
PWMAudio/README.md Normal file
Просмотреть файл

@ -0,0 +1,103 @@
# PWM driven audio using the real time cores
This gallery project shows how to use the realtime cores to generate PWM (Pulse Width Modulation) audio with a compatible buzzer. It also provides additional understanding on how the PWM hardware module operates on the MT3620.
## Contents
| File/folder | Description |
|-------------|-------------|
| `/images` | The images used in this readme. |
| `/lib` | The CodeThink M4 (real time core) drivers. |
| `CMakeLists.txt` | The file that specifies how to build this project. |
| `main.c` | The source file containing the code to generate PWM audio. |
| `README.md` | This README file. |
| `LICENSE.txt` | The license for the project. |
## Prerequisites
- An Azure Sphere-based device with development features (see [Get started with Azure Sphere](https://azure.microsoft.com/en-us/services/azure-sphere/get-started/) for more information).
- Setup a development environment for Azure Sphere (see [Quickstarts to set up your Azure Sphere device](https://docs.microsoft.com/en-us/azure-sphere/install/overview) for more information).
- A PWM driven buzzer (e.g. https://www.digikey.com/en/products/detail/tdk-corporation/PS1240P02BT/935924).
Note that the Azure Sphere Real-Time Core application is configured for the 22.11 SDK release.
## Using the project
1. Connect a buzzer to PWM0 and Ground as shown in this picture:
![](./images/connect-mt3620.jpg)
2. Configure the clock source to use for sound generation. At the top of `main.c`, there are macros to swap between clock sources used for PWM generation. To use the 2MHz clock source, ensure `USE_2M_SOURCE` is defined. To use the 32KHz clock source, ensure `USE_32K_SOURCE` is defined.
1. Ensuring the buzzer is adequately connected to the MT3620, build and deploy the application.
1. The buzzer will emit an ascending and descending C major scale.
To understand how PWM operation differs on the MT3620 real time cores to other microcontrollers, read on.
## PWM in general
PWM stands for pulse width modulation. PWM is often discussed with respect to the following terms: frequency, period and duty cycle. These terms are captured in the figure below as a reminder:
![](./images/pwm.png)
* Duty cycle - is the time a signal is active. In the figure, the duty cycle is "50%" because the signal is active (logical one) for 50% of the period.
* Period - is the time taken for the PWM signal to complete one cycle.
* Frequency - is the number of periods that occur in a specified timeframe, usually one second. For example, if a PWM signal was emitting the above signal at 50 times a second, the frequency would be: 1000/50 = 20 Hz.
## PWM on the MT3620
Though many chips allow the user to specify the frequency of the PWM module, the MT3620 does not. Instead, it allows the user to select a the clock frequency used to drive the PWM hardware peripheral, and tune the on and off time of the PWM signal. This is captured in the image below:
![](./images/pwm-mt3620.png)
This requires a slight change in the mental model of how PWM works. Now, the period and frequency are defined by the on an off times written to the PWM peripheral.
As the on/off time registers are measured in ticks, we must calculate the register values based on the clock frequency used to drive the PWM. The resolution of the clock source therefore defines the minimum and maximum frequencies that can be generated by the PWM module.
There are three clock sources available to the PWM module:
* 32KHz - the PWM signal can change every 31 microseconds (1000000 / 32768).
* 2MHz - the PWM signal can change every 0.5 microseconds (1000000 / 2000000).
* XTAL - defined per board (if available).
It therefore stands to reason that if high frequency signals are required, the PWM module should be configured with the 2MHz clock source. For audio purposes, either the 32KHz or 2MHz clock source should be adequate.
### Calculating the desired PWM frequency
Given a frequency in Hertz, we can calculate the parameters to the PWM peripheral required to achieve that frequency. The following steps calculate the on/off register values for 440 Hz (the note A):
1. Calculate the required period of the PWM signal to achieve the given frequency: 1000000/440 = 2272 microseconds.
1. Audio signals typically have a 50% duty cycle, divide the PWM period by two: 2272 / 2 = 1136 microseconds. This will be the basis of the value for both on and off.
1. Finally, convert the on and off value to be in terms of clock ticks. For example, if the clock frequency is 32 KHz (32768), the on/off values must be multiplied as follows: 1136 / (1000000/32768) = 37 clock ticks.
Note that when calculating on/off register values for a 2MHz clock, values must be calculated with respect to nanoseconds (replace 1000000 with 1000000000).
## Expected support for the code
This code is not formally maintained, but we will make a best effort to respond to/address any issues you encounter.
## How to report an issue
If you run into an issue with this code, please open a GitHub issue against this repo.
## Contributing
This project welcomes contributions and suggestions. Most contributions require you to
agree to a Contributor License Agreement (CLA) declaring that you have the right to,
and actually do, grant us the rights to use your contribution. For details, visit
https://cla.microsoft.com.
When you submit a pull request, a CLA-bot will automatically determine whether you need
to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the
instructions provided by the bot. You will only need to do this once across all repositories using our CLA.
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/)
or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
## License
See [LICENSE.txt](./LICENSE.txt)

Просмотреть файл

@ -0,0 +1,12 @@
{
"SchemaVersion": 1,
"Name": "PWMAudioRT",
"ComponentId": "2d9ed42d-cc67-4f0d-ae83-2df45a2ecb1b",
"EntryPoint": "/bin/app",
"CmdArgs": [],
"Capabilities": {
"Gpio": [ 12 ],
"Pwm": ["PWM-CONTROLLER-0"]
},
"ApplicationType": "RealTimeCapable"
}

Двоичные данные
PWMAudio/images/connect-mt3620.jpg Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 3.7 MiB

Двоичные данные
PWMAudio/images/pwm-mt3620.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 16 KiB

Двоичные данные
PWMAudio/images/pwm.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 13 KiB

14
PWMAudio/launch.vs.json Normal file
Просмотреть файл

@ -0,0 +1,14 @@
{
"version": "0.2.1",
"configurations": [
{
"type": "azurespheredbg",
"name": "PWMAudio (RTCore)",
"project": "CMakeLists.txt",
"workingDirectory": "${workspaceRoot}",
"applicationPath": "${debugInfo.target}",
"imagePath": "${debugInfo.targetImage}",
"partnerComponents": []
}
]
}

1
PWMAudio/lib Submodule

@ -0,0 +1 @@
Subproject commit 12d10ce79664f54476fa74b3c0436864e324abf2

56
PWMAudio/linker.ld Normal file
Просмотреть файл

@ -0,0 +1,56 @@
/* Copyright (c) Codethink Ltd. All rights reserved.
Licensed under the MIT License. */
MEMORY
{
TCM (rwx) : ORIGIN = 0x00100000, LENGTH = 192K
SYSRAM (rwx) : ORIGIN = 0x22000000, LENGTH = 64K
FLASH (rx) : ORIGIN = 0x10000000, LENGTH = 1M
}
/* The data and BSS regions can be placed in TCM or SYSRAM. The code and read-only regions can
be placed in TCM, SYSRAM, or FLASH. See
https://docs.microsoft.com/en-us/azure-sphere/app-development/memory-latency for information
about which types of memory which are available to real-time capable applications on the
MT3620, and when they should be used. */
REGION_ALIAS("CODE_REGION", TCM);
REGION_ALIAS("RODATA_REGION", TCM);
REGION_ALIAS("DATA_REGION", TCM);
REGION_ALIAS("BSS_REGION", TCM);
ENTRY(ExceptionVectorTable)
SECTIONS
{
/* The exception vector's virtual address must be aligned to a power of two,
which is determined by its size and set via CODE_REGION. See definition of
ExceptionVectorTable in main.c.
When the code is run from XIP flash, it must be loaded to virtual address
0x10000000 and be aligned to a 32-byte offset within the ELF file. */
.text : ALIGN(32) {
KEEP(*(.vector_table))
*(.text)
} >CODE_REGION
.rodata : {
*(.rodata)
} >RODATA_REGION
.data : {
*(.data)
} >DATA_REGION
.bss : {
*(.bss)
} >BSS_REGION
.sysram : {
*(.sysram)
} >SYSRAM
. = ALIGN(4);
end = . ;
StackTop = ORIGIN(TCM) + LENGTH(TCM);
}

70
PWMAudio/main.c Normal file
Просмотреть файл

@ -0,0 +1,70 @@
/* Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. */
#include <stddef.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include "lib/CPUFreq.h"
#include "lib/VectorTable.h"
#include "lib/NVIC.h"
#include "lib/GPIO.h"
#include "lib/mt3620/gpio.h"
#include "lib/GPT.h"
#include "lib/UART.h"
#include "lib/Print.h"
#include "lib/GPT.h"
#define USE_2M_SOURCE
// #define USE_32K_SOURCE
const uint32_t notes_hz[8] = {
262, // c
294, // d
330, // e
350, // f
392, // g
440, // a
494, // b
523 // c
};
void set_pwm0(int frequency_hz) {
#if defined(USE_32K_SOURCE)
uint32_t time_base = 1000000;
uint32_t base_frequency = MT3620_PWM_32k;
uint32_t freq_multiplier = 1;
#elif defined(USE_2M_SOURCE)
uint32_t time_base = 1000000000;
uint32_t base_frequency = MT3620_PWM_2M;
#else
#error "Please define either: USE_32K_SOURCE or USE_2M_SOURCE"
#endif
// desired frequency in microseconds (for 32 KHz clock; nanoseconds for 2M clock)
uint32_t freq_us = (time_base / frequency_hz) / 2;
uint32_t tick_value = freq_us / (time_base / base_frequency);
PWM_ConfigurePin(0, base_frequency, tick_value, tick_value);
}
_Noreturn void RTCoreMain(void)
{
VectorTableInit();
CPUFreq_Set(26000000);
GPT *timer = GPT_Open(MT3620_UNIT_GPT1, 32768, GPT_MODE_REPEAT);
while(1) {
for (int i = 0; i < 8; i++) {
set_pwm0(notes_hz[i]);
GPT_WaitTimer_Blocking(timer, 500, GPT_UNITS_MILLISEC);
}
for (int i = 7; i >= 0; i--) {
set_pwm0(notes_hz[i]);
GPT_WaitTimer_Blocking(timer, 500, GPT_UNITS_MILLISEC);
}
}
}

Просмотреть файл

@ -41,7 +41,8 @@ Each folder within this repository contains a README.md file that describes the
| [OSNetworkRequirementChecker-HLApp](OSNetworkRequirementChecker-HLApp) | A sample app that performs DNS resolver and custom NTP test for diagnosing networking connectivity problems. |
| [OSNetworkRequirementChecker-PC](OSNetworkRequirementChecker-PC) | A PC command line utility for diagnosing networking connectivity issues. |
| [OpenSourceProjectsSupportingExternalPeripherals](OpenSourceProjectsSupportingExternalPeripherals) | This is a list of open-source projects supporting external hardware on the Azure Sphere MT3620 platform |
| [ParseDeviceLog](ParseDeviceLog) | Tools that can parse device logs in to human readable format
| [ParseDeviceLog](ParseDeviceLog) | Tools that can parse device logs in to human readable format |
| [PWMAudio](PWMAudio) | Generate tones using PWM on the real-time cores |
| [RS485Driver](RS485Driver) | An RS-485 real-time driver with HL-Core interfacing API. |
| [ServiceAPIDeviceCodeAuth](ServiceAPIDeviceCodeAuth) | Code snippet to access public rest api using device code flow from a web app. |
| [SetIoTCentralPropsForDeviceGroup](SetIoTCentralPropsForDeviceGroup) | Utility that makes it easy to set an Azure IoT Central Device Twin property for all devices in an Azure Sphere Device Group. |