diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml
deleted file mode 100644
index 95128b46..00000000
--- a/.github/workflows/docs.yml
+++ /dev/null
@@ -1,64 +0,0 @@
-name: Documentation
-
-on:
- schedule:
- # run at 5am every day
- - cron: '0 5 * * *'
- push:
- paths:
- - '.github/workflows/docs.yml'
- - 'doc/settings.json'
- - 'doc/exclude_patterns.inc'
- - 'doc/**'
- pull_request:
- paths:
- - '.github/workflows/docs.yml'
- - 'doc/settings.json'
- - 'doc/exclude-patterns.inc'
- - 'doc/**'
-
- # Allow manually triggering the workflow.
- workflow_dispatch: {}
-
-env:
- XCORE_DOC_BUILDER: 'ghcr.io/xmos/doc_builder:v2.0.0'
-
-jobs:
- build_documentation:
- name: Build and package documentation
- if: github.repository_owner == 'xmos'
- runs-on: ubuntu-latest
- steps:
- - name: Checkout this repo
- uses: actions/checkout@v3
-
- - uses: actions/setup-python@v4
- with:
- python-version: '3.10.x'
-
- - name: Pull doc_builder container
- run: |
- docker pull ${XCORE_DOC_BUILDER}
-
- - name: Build documentation
- run: |
- # Move files specific to this repo
- mv 'doc/settings.json' 'settings.json'
- mv 'doc/substitutions.rst-inc' 'doc/substitutions.rst'
-
- docker run --user "$(id -u):$(id -g)" \
- --rm \
- -v ${{ github.workspace }}:/build \
- -e EXCLUDE_PATTERNS="/build/doc/exclude-patterns.inc" \
- -e OUTPUT_DIR=/build/doc/_build_sw_pll \
- -e PDF=1 \
- -e DOXYGEN_INCLUDE=/build/doc/Doxyfile.inc \
- -e DOXYGEN_INPUT=ignore ${XCORE_DOC_BUILDER}
-
- - name: Save documentation artifacts
- uses: actions/upload-artifact@v3
- with:
- name: docs-sw_pll
- path: doc/_build_sw_pll
- if-no-files-found: error # 'warn' or 'ignore' are also available, defaults to `warn`
- retention-days: 30
diff --git a/.gitignore b/.gitignore
index 7c9e7606..4eb3cce7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -5,3 +5,6 @@ compile_commands.json
.python-version
__pycache__/
modules/
+doc/doc/_build
+doc/_out
+_build
diff --git a/.xmos_ignore_source_check b/.xmos_ignore_source_check
index 63de3bba..65067d42 100644
--- a/.xmos_ignore_source_check
+++ b/.xmos_ignore_source_check
@@ -1 +1,3 @@
python/sw_pll/pll_calc.py
+register_setup.h
+fractions.h
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 792d01b3..d6bcbaa2 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -1,6 +1,13 @@
lib_sw_pll library change log
=============================
+2.0.0
+-----
+
+ * ADDED: Double integral term to controller
+ * ADDED: Sigma Delta Modulator option for PLL
+ * CHANGED: Refactored Python model into analogous objects
+
1.1.0
-----
diff --git a/CMakeLists.txt b/CMakeLists.txt
index d16dc38a..3cfcc1bf 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -22,4 +22,6 @@ if(PROJECT_IS_TOP_LEVEL)
add_subdirectory(modules/fwk_io)
add_subdirectory(tests/test_app)
add_subdirectory(tests/test_app_low_level_api)
+ add_subdirectory(tests/test_app_sdm_dco)
+ add_subdirectory(tests/test_app_sdm_ctrl)
endif()
diff --git a/Jenkinsfile b/Jenkinsfile
index c644b7cc..b04fce8d 100644
--- a/Jenkinsfile
+++ b/Jenkinsfile
@@ -25,34 +25,88 @@ pipeline {
)
}
environment {
+ REPO = 'lib_sw_pll'
PYTHON_VERSION = "3.10.5"
VENV_DIRNAME = ".venv"
}
stages {
- stage('ci') {
+ stage('Build and tests') {
agent {
label 'linux&&64'
}
- steps {
- sh 'mkdir lib_sw_pll'
- // source checks require the directory
- // name to be the same as the repo name
- dir('lib_sw_pll') {
- // checkout repo
- checkout scm
- installPipfile(false)
- withVenv {
- withTools(params.TOOLS_VERSION) {
- sh './tools/ci/checkout-submodules.sh'
- catchError {
- sh './tools/ci/do-ci.sh'
+ stages{
+ stage('Checkout'){
+ steps {
+ sh 'mkdir ${REPO}'
+ // source checks require the directory
+ // name to be the same as the repo name
+ dir("${REPO}") {
+ // checkout repo
+ checkout scm
+ installPipfile(false)
+ withVenv {
+ withTools(params.TOOLS_VERSION) {
+ sh './tools/ci/checkout-submodules.sh'
+ }
}
- zip archive: true, zipFile: "build.zip", dir: "build"
- zip archive: true, zipFile: "tests.zip", dir: "tests/bin"
- archiveArtifacts artifacts: "tests/bin/timing-report.txt", allowEmptyArchive: false
+ }
+ }
+ }
+ stage('Docs') {
+ environment { XMOSDOC_VERSION = "v4.0" }
+ steps {
+ dir("${REPO}") {
+ sh "docker pull ghcr.io/xmos/xmosdoc:$XMOSDOC_VERSION"
+ sh """docker run -u "\$(id -u):\$(id -g)" \
+ --rm \
+ -v \$(pwd):/build \
+ ghcr.io/xmos/xmosdoc:$XMOSDOC_VERSION -v html latex"""
+
+ // Zip and archive doc files
+ zip dir: "doc/_build/", zipFile: "sw_pll_docs.zip"
+ archiveArtifacts artifacts: "sw_pll_docs.zip"
+ }
+ }
+ }
+ stage('Build'){
+ steps {
+ dir("${REPO}") {
+ withVenv {
+ withTools(params.TOOLS_VERSION) {
+ sh './tools/ci/do-ci-build.sh'
+ }
+ }
+ }
+ }
+ }
+ stage('Test'){
+ steps {
+ dir("${REPO}") {
+ withVenv {
+ withTools(params.TOOLS_VERSION) {
+ catchError {
+ sh './tools/ci/do-ci-tests.sh'
+ }
+ zip archive: true, zipFile: "build.zip", dir: "build"
+ zip archive: true, zipFile: "tests.zip", dir: "tests/bin"
+ archiveArtifacts artifacts: "tests/bin/timing-report*.txt", allowEmptyArchive: false
- junit 'tests/results.xml'
+ junit 'tests/results.xml'
+ }
+ }
+ }
+ }
+ }
+ stage('Python examples'){
+ steps {
+ dir("${REPO}") {
+ withVenv {
+ catchError {
+ sh './tools/ci/do-model-examples.sh'
+ }
+ archiveArtifacts artifacts: "python/sw_pll/*.png,python/sw_pll/*.wav", allowEmptyArchive: false
+ }
}
}
}
diff --git a/README.rst b/README.rst
index 5379723d..fe32ea5f 100644
--- a/README.rst
+++ b/README.rst
@@ -3,23 +3,32 @@ lib_sw_pll
This library contains software that, together with the on-chip application PLL, provides a PLL that will generate a clock phase locked to an input clock.
-********************************
-Building and running the example
-********************************
+It supports both Look Up Table (LUT) and Sigma Delta Modulated (SDM) Digitally Controlled Oscillators (DCO), a Phase Frequency Detector (PFD) and
+configurable Proportional Integral (PI) controllers which together form a hybrid Software/Hardware Phase Locked Loop (PLL).
-Ensure a correctly configured installation of the XMOS tools.
+Examples are provided showing a master clock locking to a low frequency input reference clock and also to an I2S slave interface.
+
+*********************************
+Building and running the examples
+*********************************
+
+Ensure a correctly configured installation of the XMOS tools and open an XTC command shell. Please check that the XMOS tools are correctly
+sourced by running the following command::
+
+ $ xcc
+ xcc: no input files
.. note::
Instructions for installing and configuring the XMOS tools appear on `the XMOS web site `_.
-Place the fwk_core and fwk_io repositories in the modules directory of lib_sw_pll.
+Place the fwk_core and fwk_io repositories in the modules directory of lib_sw_pll. These are required dependencies for the example apps.
To do so, from the root of lib_sw_pll (where this read me file exists) type::
mkdir modules
- pushd modules
+ cd modules
git clone --recurse-submodules git@github.com:xmos/fwk_core.git
git clone --recurse-submodules git@github.com:xmos/fwk_io.git
- popd
+ cd ..
.. note::
The fwk_core and fwk_io repositories have not been sub-moduled into this Git repository because only the examples depend upon them.
@@ -30,43 +39,33 @@ On linux::
cmake -B build -DCMAKE_TOOLCHAIN_FILE=modules/fwk_io/xmos_cmake_toolchain/xs3a.cmake
cd build
- make simple
+ make simple_lut simple_sdm i2s_slave_lut
On Windows::
- cmake -G "NMake Makefiles" -B build -DCMAKE_TOOLCHAIN_FILE=modules/fwk_io/xmos_cmake_toolchain/xs3a.cmake
+ cmake -G "Ninja" -B build -DCMAKE_TOOLCHAIN_FILE=modules/fwk_io/xmos_cmake_toolchain/xs3a.cmake
cd build
- nmake simple
+ ninja simple_lut simple_sdm i2s_slave_lut
-To run the firmware, first connect LRCLK and BCLK (connects the test clock output to the PLL input)
-and run the following command where can be *simple* which uses the XCORE-AI-EXPLORER board
-or *i2s_slave* which uses either the EVK3600 of EVK3800 board::
+To run the firmware, first connect LRCLK and BCLK (connects the test clock output to the PLL reference input)
+and run the following command where can be *simple_lut* or *simple_sdm* which use the XCORE-AI-EXPLORER board
+or *i2s_slave_lut* which uses the XK-VOICE-SQ66 board::
xrun --xscope .xe
-For simple.xe, to see the PLL lock, put one scope probe on either LRCLK/BCLK (reference) and the other on PORT_I2S_DAC_DATA to see the
-recovered clock which has been hardware divided back down to the same rate as the input clock.
+For simple_xxx.xe, to see the PLL lock, put one scope probe on either LRCLK/BCLK (reference input) and the other on PORT_I2S_DAC_DATA to see the
+recovered clock which has been hardware divided back down to the same rate as the input reference clock.
-For i2s_slave.xe you will need to connect a 48kHz I2S master to the LRCLK, BCLK pins. You may then observe the I2S input being
+For i2s_slave_lut.xe you will need to connect a 48kHz I2S master to the LRCLK, BCLK pins. You may then observe the I2S input data being
looped back to the output and the MCLK being generated. A divided version of MCLK is output on PORT_I2S_DATA2 which allows
-direct comparison of the input reference (LRCLK) with the recovered clock at the same frequency.
-
-*****************
-Running the tests
-*****************
-
-A test is available which checks the C implementation and the simulator, to run it::
+direct comparison of the input reference (LRCLK) with the recovered clock at the same, and locked, frequency.
- cmake -B build -DCMAKE_TOOLCHAIN_FILE=xmos_cmake_toolchain/xs3a.cmake
- cmake --build build --target test_app
- pip install -r .
- cd tests
- pytest
*********************************
Generating new PLL configurations
*********************************
-Please see `doc/sw_pll.rst` for further details on how to design and build new sw_pll configurations. This covers the tradeoff between lock range, noise and memory usage.
\ No newline at end of file
+Please see `doc/rst/sw_pll.rst` for further details on how to design and build new sw_pll configurations. This covers the tradeoff between lock range,
+oscillator noise and resource usage.
\ No newline at end of file
diff --git a/doc/Doxyfile b/doc/Doxyfile
deleted file mode 100644
index 0f13efb7..00000000
--- a/doc/Doxyfile
+++ /dev/null
@@ -1,2550 +0,0 @@
-# Doxyfile 1.8.17
-
-# This file describes the settings to be used by the documentation system
-# doxygen (www.doxygen.org) for a project.
-#
-# All text after a double hash (##) is considered a comment and is placed in
-# front of the TAG it is preceding.
-#
-# All text after a single hash (#) is considered a comment and will be ignored.
-# The format is:
-# TAG = value [value, ...]
-# For lists, items can also be appended using:
-# TAG += value [value, ...]
-# Values that contain spaces should be placed between quotes (\" \").
-
-#---------------------------------------------------------------------------
-# Project related configuration options
-#---------------------------------------------------------------------------
-
-# This tag specifies the encoding used for all characters in the configuration
-# file that follow. The default is UTF-8 which is also the encoding used for all
-# text before the first occurrence of this tag. Doxygen uses libiconv (or the
-# iconv built into libc) for the transcoding. See
-# https://www.gnu.org/software/libiconv/ for the list of possible encodings.
-# The default value is: UTF-8.
-
-DOXYFILE_ENCODING = UTF-8
-
-# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by
-# double-quotes, unless you are using Doxywizard) that should identify the
-# project for which the documentation is generated. This name is used in the
-# title of most generated pages and in a few other places.
-# The default value is: My Project.
-
-PROJECT_NAME =
-
-# The PROJECT_NUMBER tag can be used to enter a project or revision number. This
-# could be handy for archiving the generated documentation or if some version
-# control system is used.
-
-PROJECT_NUMBER =
-
-# Using the PROJECT_BRIEF tag one can provide an optional one line description
-# for a project that appears at the top of each page and should give viewer a
-# quick idea about the purpose of the project. Keep the description short.
-
-PROJECT_BRIEF =
-
-# With the PROJECT_LOGO tag one can specify a logo or an icon that is included
-# in the documentation. The maximum height of the logo should not exceed 55
-# pixels and the maximum width should not exceed 200 pixels. Doxygen will copy
-# the logo to the output directory.
-
-PROJECT_LOGO =
-
-# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path
-# into which the generated documentation will be written. If a relative path is
-# entered, it will be relative to the location where doxygen was started. If
-# left blank the current directory will be used.
-
-OUTPUT_DIRECTORY = $(DOXYGEN_OUTPUT)
-
-# If the CREATE_SUBDIRS tag is set to YES then doxygen will create 4096 sub-
-# directories (in 2 levels) under the output directory of each output format and
-# will distribute the generated files over these directories. Enabling this
-# option can be useful when feeding doxygen a huge amount of source files, where
-# putting all generated files in the same directory would otherwise causes
-# performance problems for the file system.
-# The default value is: NO.
-
-CREATE_SUBDIRS = NO
-
-# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII
-# characters to appear in the names of generated files. If set to NO, non-ASCII
-# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode
-# U+3044.
-# The default value is: NO.
-
-ALLOW_UNICODE_NAMES = NO
-
-# The OUTPUT_LANGUAGE tag is used to specify the language in which all
-# documentation generated by doxygen is written. Doxygen will use this
-# information to generate all constant output in the proper language.
-# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese,
-# Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States),
-# Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian,
-# Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages),
-# Korean, Korean-en (Korean with English messages), Latvian, Lithuanian,
-# Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian,
-# Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish,
-# Ukrainian and Vietnamese.
-# The default value is: English.
-
-OUTPUT_LANGUAGE = English
-
-# The OUTPUT_TEXT_DIRECTION tag is used to specify the direction in which all
-# documentation generated by doxygen is written. Doxygen will use this
-# information to generate all generated output in the proper direction.
-# Possible values are: None, LTR, RTL and Context.
-# The default value is: None.
-
-OUTPUT_TEXT_DIRECTION = None
-
-# If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member
-# descriptions after the members that are listed in the file and class
-# documentation (similar to Javadoc). Set to NO to disable this.
-# The default value is: YES.
-
-BRIEF_MEMBER_DESC = YES
-
-# If the REPEAT_BRIEF tag is set to YES, doxygen will prepend the brief
-# description of a member or function before the detailed description
-#
-# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
-# brief descriptions will be completely suppressed.
-# The default value is: YES.
-
-REPEAT_BRIEF = YES
-
-# This tag implements a quasi-intelligent brief description abbreviator that is
-# used to form the text in various listings. Each string in this list, if found
-# as the leading text of the brief description, will be stripped from the text
-# and the result, after processing the whole list, is used as the annotated
-# text. Otherwise, the brief description is used as-is. If left blank, the
-# following values are used ($name is automatically replaced with the name of
-# the entity):The $name class, The $name widget, The $name file, is, provides,
-# specifies, contains, represents, a, an and the.
-
-ABBREVIATE_BRIEF = "The $name class" \
- "The $name widget" \
- "The $name file" \
- is \
- provides \
- specifies \
- contains \
- represents \
- a \
- an \
- the
-
-# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
-# doxygen will generate a detailed section even if there is only a brief
-# description.
-# The default value is: NO.
-
-ALWAYS_DETAILED_SEC = NO
-
-# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all
-# inherited members of a class in the documentation of that class as if those
-# members were ordinary class members. Constructors, destructors and assignment
-# operators of the base classes will not be shown.
-# The default value is: NO.
-
-INLINE_INHERITED_MEMB = NO
-
-# If the FULL_PATH_NAMES tag is set to YES, doxygen will prepend the full path
-# before files name in the file list and in the header files. If set to NO the
-# shortest path that makes the file name unique will be used
-# The default value is: YES.
-
-FULL_PATH_NAMES = YES
-
-# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path.
-# Stripping is only done if one of the specified strings matches the left-hand
-# part of the path. The tag can be used to show relative paths in the file list.
-# If left blank the directory from which doxygen is run is used as the path to
-# strip.
-#
-# Note that you can specify absolute paths here, but also relative paths, which
-# will be relative from the directory where doxygen is started.
-# This tag requires that the tag FULL_PATH_NAMES is set to YES.
-
-STRIP_FROM_PATH =
-
-# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the
-# path mentioned in the documentation of a class, which tells the reader which
-# header file to include in order to use a class. If left blank only the name of
-# the header file containing the class definition is used. Otherwise one should
-# specify the list of include paths that are normally passed to the compiler
-# using the -I flag.
-
-STRIP_FROM_INC_PATH =
-
-# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but
-# less readable) file names. This can be useful is your file systems doesn't
-# support long names like on DOS, Mac, or CD-ROM.
-# The default value is: NO.
-
-SHORT_NAMES = NO
-
-# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the
-# first line (until the first dot) of a Javadoc-style comment as the brief
-# description. If set to NO, the Javadoc-style will behave just like regular Qt-
-# style comments (thus requiring an explicit @brief command for a brief
-# description.)
-# The default value is: NO.
-
-JAVADOC_AUTOBRIEF = NO
-
-# If the JAVADOC_BANNER tag is set to YES then doxygen will interpret a line
-# such as
-# /***************
-# as being the beginning of a Javadoc-style comment "banner". If set to NO, the
-# Javadoc-style will behave just like regular comments and it will not be
-# interpreted by doxygen.
-# The default value is: NO.
-
-JAVADOC_BANNER = NO
-
-# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first
-# line (until the first dot) of a Qt-style comment as the brief description. If
-# set to NO, the Qt-style will behave just like regular Qt-style comments (thus
-# requiring an explicit \brief command for a brief description.)
-# The default value is: NO.
-
-QT_AUTOBRIEF = NO
-
-# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a
-# multi-line C++ special comment block (i.e. a block of //! or /// comments) as
-# a brief description. This used to be the default behavior. The new default is
-# to treat a multi-line C++ comment block as a detailed description. Set this
-# tag to YES if you prefer the old behavior instead.
-#
-# Note that setting this tag to YES also means that rational rose comments are
-# not recognized any more.
-# The default value is: NO.
-
-MULTILINE_CPP_IS_BRIEF = NO
-
-# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the
-# documentation from any documented member that it re-implements.
-# The default value is: YES.
-
-INHERIT_DOCS = YES
-
-# If the SEPARATE_MEMBER_PAGES tag is set to YES then doxygen will produce a new
-# page for each member. If set to NO, the documentation of a member will be part
-# of the file/class/namespace that contains it.
-# The default value is: NO.
-
-SEPARATE_MEMBER_PAGES = NO
-
-# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen
-# uses this value to replace tabs by spaces in code fragments.
-# Minimum value: 1, maximum value: 16, default value: 4.
-
-TAB_SIZE = 4
-
-# This tag can be used to specify a number of aliases that act as commands in
-# the documentation. An alias has the form:
-# name=value
-# For example adding
-# "sideeffect=@par Side Effects:\n"
-# will allow you to put the command \sideeffect (or @sideeffect) in the
-# documentation, which will result in a user-defined paragraph with heading
-# "Side Effects:". You can put \n's in the value part of an alias to insert
-# newlines (in the resulting output). You can put ^^ in the value part of an
-# alias to insert a newline as if a physical newline was in the original file.
-# When you need a literal { or } or , in the value part of an alias you have to
-# escape them by means of a backslash (\), this can lead to conflicts with the
-# commands \{ and \} for these it is advised to use the version @{ and @} or use
-# a double escape (\\{ and \\})
-
-ALIASES =
-
-# This tag can be used to specify a number of word-keyword mappings (TCL only).
-# A mapping has the form "name=value". For example adding "class=itcl::class"
-# will allow you to use the command class in the itcl::class meaning.
-
-TCL_SUBST =
-
-# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources
-# only. Doxygen will then generate output that is more tailored for C. For
-# instance, some of the names that are used will be different. The list of all
-# members will be omitted, etc.
-# The default value is: NO.
-
-OPTIMIZE_OUTPUT_FOR_C = YES
-
-# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or
-# Python sources only. Doxygen will then generate output that is more tailored
-# for that language. For instance, namespaces will be presented as packages,
-# qualified scopes will look different, etc.
-# The default value is: NO.
-
-OPTIMIZE_OUTPUT_JAVA = NO
-
-# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
-# sources. Doxygen will then generate output that is tailored for Fortran.
-# The default value is: NO.
-
-OPTIMIZE_FOR_FORTRAN = NO
-
-# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
-# sources. Doxygen will then generate output that is tailored for VHDL.
-# The default value is: NO.
-
-OPTIMIZE_OUTPUT_VHDL = NO
-
-# Set the OPTIMIZE_OUTPUT_SLICE tag to YES if your project consists of Slice
-# sources only. Doxygen will then generate output that is more tailored for that
-# language. For instance, namespaces will be presented as modules, types will be
-# separated into more groups, etc.
-# The default value is: NO.
-
-OPTIMIZE_OUTPUT_SLICE = NO
-
-# Doxygen selects the parser to use depending on the extension of the files it
-# parses. With this tag you can assign which parser to use for a given
-# extension. Doxygen has a built-in mapping, but you can override or extend it
-# using this tag. The format is ext=language, where ext is a file extension, and
-# language is one of the parsers supported by doxygen: IDL, Java, JavaScript,
-# Csharp (C#), C, C++, D, PHP, md (Markdown), Objective-C, Python, Slice,
-# Fortran (fixed format Fortran: FortranFixed, free formatted Fortran:
-# FortranFree, unknown formatted Fortran: Fortran. In the later case the parser
-# tries to guess whether the code is fixed or free formatted code, this is the
-# default for Fortran type files), VHDL, tcl. For instance to make doxygen treat
-# .inc files as Fortran files (default is PHP), and .f files as C (default is
-# Fortran), use: inc=Fortran f=C.
-#
-# Note: For files without extension you can use no_extension as a placeholder.
-#
-# Note that for custom extensions you also need to set FILE_PATTERNS otherwise
-# the files are not read by doxygen.
-
-EXTENSION_MAPPING = h=C c=C
-
-# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments
-# according to the Markdown format, which allows for more readable
-# documentation. See https://daringfireball.net/projects/markdown/ for details.
-# The output of markdown processing is further processed by doxygen, so you can
-# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in
-# case of backward compatibilities issues.
-# The default value is: YES.
-
-MARKDOWN_SUPPORT = YES
-
-# When the TOC_INCLUDE_HEADINGS tag is set to a non-zero value, all headings up
-# to that level are automatically included in the table of contents, even if
-# they do not have an id attribute.
-# Note: This feature currently applies only to Markdown headings.
-# Minimum value: 0, maximum value: 99, default value: 5.
-# This tag requires that the tag MARKDOWN_SUPPORT is set to YES.
-
-TOC_INCLUDE_HEADINGS = 5
-
-# When enabled doxygen tries to link words that correspond to documented
-# classes, or namespaces to their corresponding documentation. Such a link can
-# be prevented in individual cases by putting a % sign in front of the word or
-# globally by setting AUTOLINK_SUPPORT to NO.
-# The default value is: YES.
-
-AUTOLINK_SUPPORT = YES
-
-# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
-# to include (a tag file for) the STL sources as input, then you should set this
-# tag to YES in order to let doxygen match functions declarations and
-# definitions whose arguments contain STL classes (e.g. func(std::string);
-# versus func(std::string) {}). This also make the inheritance and collaboration
-# diagrams that involve STL classes more complete and accurate.
-# The default value is: NO.
-
-BUILTIN_STL_SUPPORT = NO
-
-# If you use Microsoft's C++/CLI language, you should set this option to YES to
-# enable parsing support.
-# The default value is: NO.
-
-CPP_CLI_SUPPORT = NO
-
-# Set the SIP_SUPPORT tag to YES if your project consists of sip (see:
-# https://www.riverbankcomputing.com/software/sip/intro) sources only. Doxygen
-# will parse them like normal C++ but will assume all classes use public instead
-# of private inheritance when no explicit protection keyword is present.
-# The default value is: NO.
-
-SIP_SUPPORT = NO
-
-# For Microsoft's IDL there are propget and propput attributes to indicate
-# getter and setter methods for a property. Setting this option to YES will make
-# doxygen to replace the get and set methods by a property in the documentation.
-# This will only work if the methods are indeed getting or setting a simple
-# type. If this is not the case, or you want to show the methods anyway, you
-# should set this option to NO.
-# The default value is: YES.
-
-IDL_PROPERTY_SUPPORT = YES
-
-# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
-# tag is set to YES then doxygen will reuse the documentation of the first
-# member in the group (if any) for the other members of the group. By default
-# all members of a group must be documented explicitly.
-# The default value is: NO.
-
-DISTRIBUTE_GROUP_DOC = YES
-
-# If one adds a struct or class to a group and this option is enabled, then also
-# any nested class or struct is added to the same group. By default this option
-# is disabled and one has to add nested compounds explicitly via \ingroup.
-# The default value is: NO.
-
-GROUP_NESTED_COMPOUNDS = NO
-
-# Set the SUBGROUPING tag to YES to allow class member groups of the same type
-# (for instance a group of public functions) to be put as a subgroup of that
-# type (e.g. under the Public Functions section). Set it to NO to prevent
-# subgrouping. Alternatively, this can be done per class using the
-# \nosubgrouping command.
-# The default value is: YES.
-
-SUBGROUPING = YES
-
-# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions
-# are shown inside the group in which they are included (e.g. using \ingroup)
-# instead of on a separate page (for HTML and Man pages) or section (for LaTeX
-# and RTF).
-#
-# Note that this feature does not work in combination with
-# SEPARATE_MEMBER_PAGES.
-# The default value is: NO.
-
-INLINE_GROUPED_CLASSES = NO
-
-# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions
-# with only public data fields or simple typedef fields will be shown inline in
-# the documentation of the scope in which they are defined (i.e. file,
-# namespace, or group documentation), provided this scope is documented. If set
-# to NO, structs, classes, and unions are shown on a separate page (for HTML and
-# Man pages) or section (for LaTeX and RTF).
-# The default value is: NO.
-
-INLINE_SIMPLE_STRUCTS = NO
-
-# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or
-# enum is documented as struct, union, or enum with the name of the typedef. So
-# typedef struct TypeS {} TypeT, will appear in the documentation as a struct
-# with name TypeT. When disabled the typedef will appear as a member of a file,
-# namespace, or class. And the struct will be named TypeS. This can typically be
-# useful for C code in case the coding convention dictates that all compound
-# types are typedef'ed and only the typedef is referenced, never the tag name.
-# The default value is: NO.
-
-TYPEDEF_HIDES_STRUCT = YES
-
-# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This
-# cache is used to resolve symbols given their name and scope. Since this can be
-# an expensive process and often the same symbol appears multiple times in the
-# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small
-# doxygen will become slower. If the cache is too large, memory is wasted. The
-# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range
-# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536
-# symbols. At the end of a run doxygen will report the cache usage and suggest
-# the optimal cache size from a speed point of view.
-# Minimum value: 0, maximum value: 9, default value: 0.
-
-LOOKUP_CACHE_SIZE = 0
-
-#---------------------------------------------------------------------------
-# Build related configuration options
-#---------------------------------------------------------------------------
-
-# If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in
-# documentation are documented, even if no documentation was available. Private
-# class members and static file members will be hidden unless the
-# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES.
-# Note: This will also disable the warnings about undocumented members that are
-# normally produced when WARNINGS is set to YES.
-# The default value is: NO.
-
-EXTRACT_ALL = YES
-
-# If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will
-# be included in the documentation.
-# The default value is: NO.
-
-EXTRACT_PRIVATE = NO
-
-# If the EXTRACT_PRIV_VIRTUAL tag is set to YES, documented private virtual
-# methods of a class will be included in the documentation.
-# The default value is: NO.
-
-EXTRACT_PRIV_VIRTUAL = NO
-
-# If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal
-# scope will be included in the documentation.
-# The default value is: NO.
-
-EXTRACT_PACKAGE = NO
-
-# If the EXTRACT_STATIC tag is set to YES, all static members of a file will be
-# included in the documentation.
-# The default value is: NO.
-
-EXTRACT_STATIC = YES
-
-# If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined
-# locally in source files will be included in the documentation. If set to NO,
-# only classes defined in header files are included. Does not have any effect
-# for Java sources.
-# The default value is: YES.
-
-EXTRACT_LOCAL_CLASSES = YES
-
-# This flag is only useful for Objective-C code. If set to YES, local methods,
-# which are defined in the implementation section but not in the interface are
-# included in the documentation. If set to NO, only methods in the interface are
-# included.
-# The default value is: NO.
-
-EXTRACT_LOCAL_METHODS = NO
-
-# If this flag is set to YES, the members of anonymous namespaces will be
-# extracted and appear in the documentation as a namespace called
-# 'anonymous_namespace{file}', where file will be replaced with the base name of
-# the file that contains the anonymous namespace. By default anonymous namespace
-# are hidden.
-# The default value is: NO.
-
-EXTRACT_ANON_NSPACES = NO
-
-# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all
-# undocumented members inside documented classes or files. If set to NO these
-# members will be included in the various overviews, but no documentation
-# section is generated. This option has no effect if EXTRACT_ALL is enabled.
-# The default value is: NO.
-
-HIDE_UNDOC_MEMBERS = NO
-
-# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all
-# undocumented classes that are normally visible in the class hierarchy. If set
-# to NO, these classes will be included in the various overviews. This option
-# has no effect if EXTRACT_ALL is enabled.
-# The default value is: NO.
-
-HIDE_UNDOC_CLASSES = NO
-
-# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend
-# declarations. If set to NO, these declarations will be included in the
-# documentation.
-# The default value is: NO.
-
-HIDE_FRIEND_COMPOUNDS = NO
-
-# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any
-# documentation blocks found inside the body of a function. If set to NO, these
-# blocks will be appended to the function's detailed documentation block.
-# The default value is: NO.
-
-HIDE_IN_BODY_DOCS = NO
-
-# The INTERNAL_DOCS tag determines if documentation that is typed after a
-# \internal command is included. If the tag is set to NO then the documentation
-# will be excluded. Set it to YES to include the internal documentation.
-# The default value is: NO.
-
-INTERNAL_DOCS = NO
-
-# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file
-# names in lower-case letters. If set to YES, upper-case letters are also
-# allowed. This is useful if you have classes or files whose names only differ
-# in case and if your file system supports case sensitive file names. Windows
-# (including Cygwin) ands Mac users are advised to set this option to NO.
-# The default value is: system dependent.
-
-CASE_SENSE_NAMES = YES
-
-# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with
-# their full class and namespace scopes in the documentation. If set to YES, the
-# scope will be hidden.
-# The default value is: NO.
-
-HIDE_SCOPE_NAMES = NO
-
-# If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will
-# append additional text to a page's title, such as Class Reference. If set to
-# YES the compound reference will be hidden.
-# The default value is: NO.
-
-HIDE_COMPOUND_REFERENCE= NO
-
-# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of
-# the files that are included by a file in the documentation of that file.
-# The default value is: YES.
-
-SHOW_INCLUDE_FILES = YES
-
-# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each
-# grouped member an include statement to the documentation, telling the reader
-# which file to include in order to use the member.
-# The default value is: NO.
-
-SHOW_GROUPED_MEMB_INC = NO
-
-# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include
-# files with double quotes in the documentation rather than with sharp brackets.
-# The default value is: NO.
-
-FORCE_LOCAL_INCLUDES = NO
-
-# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the
-# documentation for inline members.
-# The default value is: YES.
-
-INLINE_INFO = YES
-
-# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the
-# (detailed) documentation of file and class members alphabetically by member
-# name. If set to NO, the members will appear in declaration order.
-# The default value is: YES.
-
-SORT_MEMBER_DOCS = YES
-
-# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief
-# descriptions of file, namespace and class members alphabetically by member
-# name. If set to NO, the members will appear in declaration order. Note that
-# this will also influence the order of the classes in the class list.
-# The default value is: NO.
-
-SORT_BRIEF_DOCS = NO
-
-# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the
-# (brief and detailed) documentation of class members so that constructors and
-# destructors are listed first. If set to NO the constructors will appear in the
-# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS.
-# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief
-# member documentation.
-# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting
-# detailed member documentation.
-# The default value is: NO.
-
-SORT_MEMBERS_CTORS_1ST = NO
-
-# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy
-# of group names into alphabetical order. If set to NO the group names will
-# appear in their defined order.
-# The default value is: NO.
-
-SORT_GROUP_NAMES = NO
-
-# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by
-# fully-qualified names, including namespaces. If set to NO, the class list will
-# be sorted only by class name, not including the namespace part.
-# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
-# Note: This option applies only to the class list, not to the alphabetical
-# list.
-# The default value is: NO.
-
-SORT_BY_SCOPE_NAME = NO
-
-# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper
-# type resolution of all parameters of a function it will reject a match between
-# the prototype and the implementation of a member function even if there is
-# only one candidate or it is obvious which candidate to choose by doing a
-# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still
-# accept a match between prototype and implementation in such cases.
-# The default value is: NO.
-
-STRICT_PROTO_MATCHING = NO
-
-# The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo
-# list. This list is created by putting \todo commands in the documentation.
-# The default value is: YES.
-
-GENERATE_TODOLIST = YES
-
-# The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test
-# list. This list is created by putting \test commands in the documentation.
-# The default value is: YES.
-
-GENERATE_TESTLIST = YES
-
-# The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug
-# list. This list is created by putting \bug commands in the documentation.
-# The default value is: YES.
-
-GENERATE_BUGLIST = YES
-
-# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO)
-# the deprecated list. This list is created by putting \deprecated commands in
-# the documentation.
-# The default value is: YES.
-
-GENERATE_DEPRECATEDLIST= YES
-
-# The ENABLED_SECTIONS tag can be used to enable conditional documentation
-# sections, marked by \if ... \endif and \cond
-# ... \endcond blocks.
-
-ENABLED_SECTIONS =
-
-# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the
-# initial value of a variable or macro / define can have for it to appear in the
-# documentation. If the initializer consists of more lines than specified here
-# it will be hidden. Use a value of 0 to hide initializers completely. The
-# appearance of the value of individual variables and macros / defines can be
-# controlled using \showinitializer or \hideinitializer command in the
-# documentation regardless of this setting.
-# Minimum value: 0, maximum value: 10000, default value: 30.
-
-MAX_INITIALIZER_LINES = 30
-
-# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at
-# the bottom of the documentation of classes and structs. If set to YES, the
-# list will mention the files that were used to generate the documentation.
-# The default value is: YES.
-
-SHOW_USED_FILES = YES
-
-# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This
-# will remove the Files entry from the Quick Index and from the Folder Tree View
-# (if specified).
-# The default value is: YES.
-
-SHOW_FILES = YES
-
-# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces
-# page. This will remove the Namespaces entry from the Quick Index and from the
-# Folder Tree View (if specified).
-# The default value is: YES.
-
-SHOW_NAMESPACES = YES
-
-# The FILE_VERSION_FILTER tag can be used to specify a program or script that
-# doxygen should invoke to get the current version for each file (typically from
-# the version control system). Doxygen will invoke the program by executing (via
-# popen()) the command command input-file, where command is the value of the
-# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided
-# by doxygen. Whatever the program writes to standard output is used as the file
-# version. For an example see the documentation.
-
-FILE_VERSION_FILTER =
-
-# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed
-# by doxygen. The layout file controls the global structure of the generated
-# output files in an output format independent way. To create the layout file
-# that represents doxygen's defaults, run doxygen with the -l option. You can
-# optionally specify a file name after the option, if omitted DoxygenLayout.xml
-# will be used as the name of the layout file.
-#
-# Note that if you run doxygen from a directory containing a file called
-# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE
-# tag is left empty.
-
-LAYOUT_FILE =
-
-# The CITE_BIB_FILES tag can be used to specify one or more bib files containing
-# the reference definitions. This must be a list of .bib files. The .bib
-# extension is automatically appended if omitted. This requires the bibtex tool
-# to be installed. See also https://en.wikipedia.org/wiki/BibTeX for more info.
-# For LaTeX the style of the bibliography can be controlled using
-# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the
-# search path. See also \cite for info how to create references.
-
-CITE_BIB_FILES =
-
-#---------------------------------------------------------------------------
-# Configuration options related to warning and progress messages
-#---------------------------------------------------------------------------
-
-# The QUIET tag can be used to turn on/off the messages that are generated to
-# standard output by doxygen. If QUIET is set to YES this implies that the
-# messages are off.
-# The default value is: NO.
-
-QUIET = NO
-
-# The WARNINGS tag can be used to turn on/off the warning messages that are
-# generated to standard error (stderr) by doxygen. If WARNINGS is set to YES
-# this implies that the warnings are on.
-#
-# Tip: Turn warnings on while writing the documentation.
-# The default value is: YES.
-
-WARNINGS = YES
-
-# If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate
-# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag
-# will automatically be disabled.
-# The default value is: YES.
-
-WARN_IF_UNDOCUMENTED = YES
-
-# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for
-# potential errors in the documentation, such as not documenting some parameters
-# in a documented function, or documenting parameters that don't exist or using
-# markup commands wrongly.
-# The default value is: YES.
-
-WARN_IF_DOC_ERROR = YES
-
-# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that
-# are documented, but have no documentation for their parameters or return
-# value. If set to NO, doxygen will only warn about wrong or incomplete
-# parameter documentation, but not about the absence of documentation. If
-# EXTRACT_ALL is set to YES then this flag will automatically be disabled.
-# The default value is: NO.
-
-WARN_NO_PARAMDOC = NO
-
-# If the WARN_AS_ERROR tag is set to YES then doxygen will immediately stop when
-# a warning is encountered.
-# The default value is: NO.
-
-WARN_AS_ERROR = NO
-
-# The WARN_FORMAT tag determines the format of the warning messages that doxygen
-# can produce. The string should contain the $file, $line, and $text tags, which
-# will be replaced by the file and line number from which the warning originated
-# and the warning text. Optionally the format may contain $version, which will
-# be replaced by the version of the file (if it could be obtained via
-# FILE_VERSION_FILTER)
-# The default value is: $file:$line: $text.
-
-WARN_FORMAT = "$file:$line: $text"
-
-# The WARN_LOGFILE tag can be used to specify a file to which warning and error
-# messages should be written. If left blank the output is written to standard
-# error (stderr).
-
-WARN_LOGFILE =
-
-#---------------------------------------------------------------------------
-# Configuration options related to the input files
-#---------------------------------------------------------------------------
-
-# The INPUT tag is used to specify the files and/or directories that contain
-# documented source files. You may enter file names like myfile.cpp or
-# directories like /usr/src/myproject. Separate the files or directories with
-# spaces. See also FILE_PATTERNS and EXTENSION_MAPPING
-# Note: If this tag is empty the current directory is searched.
-
-INPUT =
-
-# This tag can be used to specify the character encoding of the source files
-# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses
-# libiconv (or the iconv built into libc) for the transcoding. See the libiconv
-# documentation (see: https://www.gnu.org/software/libiconv/) for the list of
-# possible encodings.
-# The default value is: UTF-8.
-
-INPUT_ENCODING = UTF-8
-
-# If the value of the INPUT tag contains directories, you can use the
-# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and
-# *.h) to filter out the source-files in the directories.
-#
-# Note that for custom extensions or not directly supported extensions you also
-# need to set EXTENSION_MAPPING for the extension otherwise the files are not
-# read by doxygen.
-#
-# If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp,
-# *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h,
-# *.hh, *.hxx, *.hpp, *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc,
-# *.m, *.markdown, *.md, *.mm, *.dox (to be provided as doxygen C comment),
-# *.doc (to be provided as doxygen C comment), *.txt (to be provided as doxygen
-# C comment), *.py, *.pyw, *.f90, *.f95, *.f03, *.f08, *.f, *.for, *.tcl, *.vhd,
-# *.vhdl, *.ucf, *.qsf and *.ice.
-
-FILE_PATTERNS = *.h \
- *.md
-
-# The RECURSIVE tag can be used to specify whether or not subdirectories should
-# be searched for input files as well.
-# The default value is: NO.
-
-RECURSIVE = YES
-
-# The EXCLUDE tag can be used to specify files and/or directories that should be
-# excluded from the INPUT source files. This way you can easily exclude a
-# subdirectory from a directory tree whose root is specified with the INPUT tag.
-#
-# Note that relative paths are relative to the directory from which doxygen is
-# run.
-
-EXCLUDE =
-
-# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or
-# directories that are symbolic links (a Unix file system feature) are excluded
-# from the input.
-# The default value is: NO.
-
-EXCLUDE_SYMLINKS = NO
-
-# If the value of the INPUT tag contains directories, you can use the
-# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
-# certain files from those directories.
-#
-# Note that the wildcards are matched against the file with absolute path, so to
-# exclude all test directories for example use the pattern */test/*
-
-EXCLUDE_PATTERNS =
-
-# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
-# (namespaces, classes, functions, etc.) that should be excluded from the
-# output. The symbol name can be a fully qualified name, a word, or if the
-# wildcard * is used, a substring. Examples: ANamespace, AClass,
-# AClass::ANamespace, ANamespace::*Test
-#
-# Note that the wildcards are matched against the file with absolute path, so to
-# exclude all test directories use the pattern */test/*
-
-EXCLUDE_SYMBOLS =
-
-# The EXAMPLE_PATH tag can be used to specify one or more files or directories
-# that contain example code fragments that are included (see the \include
-# command).
-
-EXAMPLE_PATH =
-
-# If the value of the EXAMPLE_PATH tag contains directories, you can use the
-# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and
-# *.h) to filter out the source-files in the directories. If left blank all
-# files are included.
-
-EXAMPLE_PATTERNS = *
-
-# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
-# searched for input files to be used with the \include or \dontinclude commands
-# irrespective of the value of the RECURSIVE tag.
-# The default value is: NO.
-
-EXAMPLE_RECURSIVE = NO
-
-# The IMAGE_PATH tag can be used to specify one or more files or directories
-# that contain images that are to be included in the documentation (see the
-# \image command).
-
-IMAGE_PATH =
-
-# The INPUT_FILTER tag can be used to specify a program that doxygen should
-# invoke to filter for each input file. Doxygen will invoke the filter program
-# by executing (via popen()) the command:
-#
-#
-#
-# where is the value of the INPUT_FILTER tag, and is the
-# name of an input file. Doxygen will then use the output that the filter
-# program writes to standard output. If FILTER_PATTERNS is specified, this tag
-# will be ignored.
-#
-# Note that the filter must not add or remove lines; it is applied before the
-# code is scanned, but not when the output code is generated. If lines are added
-# or removed, the anchors will not be placed correctly.
-#
-# Note that for custom extensions or not directly supported extensions you also
-# need to set EXTENSION_MAPPING for the extension otherwise the files are not
-# properly processed by doxygen.
-
-INPUT_FILTER =
-
-# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
-# basis. Doxygen will compare the file name with each pattern and apply the
-# filter if there is a match. The filters are a list of the form: pattern=filter
-# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how
-# filters are used. If the FILTER_PATTERNS tag is empty or if none of the
-# patterns match the file name, INPUT_FILTER is applied.
-#
-# Note that for custom extensions or not directly supported extensions you also
-# need to set EXTENSION_MAPPING for the extension otherwise the files are not
-# properly processed by doxygen.
-
-FILTER_PATTERNS =
-
-# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
-# INPUT_FILTER) will also be used to filter the input files that are used for
-# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES).
-# The default value is: NO.
-
-FILTER_SOURCE_FILES = NO
-
-# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file
-# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and
-# it is also possible to disable source filtering for a specific pattern using
-# *.ext= (so without naming a filter).
-# This tag requires that the tag FILTER_SOURCE_FILES is set to YES.
-
-FILTER_SOURCE_PATTERNS =
-
-# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that
-# is part of the input, its contents will be placed on the main page
-# (index.html). This can be useful if you have a project on for instance GitHub
-# and want to reuse the introduction page also for the doxygen output.
-
-USE_MDFILE_AS_MAINPAGE =
-
-#---------------------------------------------------------------------------
-# Configuration options related to source browsing
-#---------------------------------------------------------------------------
-
-# If the SOURCE_BROWSER tag is set to YES then a list of source files will be
-# generated. Documented entities will be cross-referenced with these sources.
-#
-# Note: To get rid of all source code in the generated output, make sure that
-# also VERBATIM_HEADERS is set to NO.
-# The default value is: NO.
-
-SOURCE_BROWSER = NO
-
-# Setting the INLINE_SOURCES tag to YES will include the body of functions,
-# classes and enums directly into the documentation.
-# The default value is: NO.
-
-INLINE_SOURCES = NO
-
-# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any
-# special comment blocks from generated source code fragments. Normal C, C++ and
-# Fortran comments will always remain visible.
-# The default value is: YES.
-
-STRIP_CODE_COMMENTS = YES
-
-# If the REFERENCED_BY_RELATION tag is set to YES then for each documented
-# entity all documented functions referencing it will be listed.
-# The default value is: NO.
-
-REFERENCED_BY_RELATION = NO
-
-# If the REFERENCES_RELATION tag is set to YES then for each documented function
-# all documented entities called/used by that function will be listed.
-# The default value is: NO.
-
-REFERENCES_RELATION = NO
-
-# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set
-# to YES then the hyperlinks from functions in REFERENCES_RELATION and
-# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will
-# link to the documentation.
-# The default value is: YES.
-
-REFERENCES_LINK_SOURCE = YES
-
-# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the
-# source code will show a tooltip with additional information such as prototype,
-# brief description and links to the definition and documentation. Since this
-# will make the HTML file larger and loading of large files a bit slower, you
-# can opt to disable this feature.
-# The default value is: YES.
-# This tag requires that the tag SOURCE_BROWSER is set to YES.
-
-SOURCE_TOOLTIPS = YES
-
-# If the USE_HTAGS tag is set to YES then the references to source code will
-# point to the HTML generated by the htags(1) tool instead of doxygen built-in
-# source browser. The htags tool is part of GNU's global source tagging system
-# (see https://www.gnu.org/software/global/global.html). You will need version
-# 4.8.6 or higher.
-#
-# To use it do the following:
-# - Install the latest version of global
-# - Enable SOURCE_BROWSER and USE_HTAGS in the configuration file
-# - Make sure the INPUT points to the root of the source tree
-# - Run doxygen as normal
-#
-# Doxygen will invoke htags (and that will in turn invoke gtags), so these
-# tools must be available from the command line (i.e. in the search path).
-#
-# The result: instead of the source browser generated by doxygen, the links to
-# source code will now point to the output of htags.
-# The default value is: NO.
-# This tag requires that the tag SOURCE_BROWSER is set to YES.
-
-USE_HTAGS = NO
-
-# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a
-# verbatim copy of the header file for each class for which an include is
-# specified. Set to NO to disable this.
-# See also: Section \class.
-# The default value is: YES.
-
-VERBATIM_HEADERS = YES
-
-# If the CLANG_ASSISTED_PARSING tag is set to YES then doxygen will use the
-# clang parser (see: http://clang.llvm.org/) for more accurate parsing at the
-# cost of reduced performance. This can be particularly helpful with template
-# rich C++ code for which doxygen's built-in parser lacks the necessary type
-# information.
-# Note: The availability of this option depends on whether or not doxygen was
-# generated with the -Duse_libclang=ON option for CMake.
-# The default value is: NO.
-
-CLANG_ASSISTED_PARSING = NO
-
-# If clang assisted parsing is enabled you can provide the compiler with command
-# line options that you would normally use when invoking the compiler. Note that
-# the include paths will already be set by doxygen for the files and directories
-# specified with INPUT and INCLUDE_PATH.
-# This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES.
-
-CLANG_OPTIONS =
-
-# If clang assisted parsing is enabled you can provide the clang parser with the
-# path to the compilation database (see:
-# http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html) used when the files
-# were built. This is equivalent to specifying the "-p" option to a clang tool,
-# such as clang-check. These options will then be passed to the parser.
-# Note: The availability of this option depends on whether or not doxygen was
-# generated with the -Duse_libclang=ON option for CMake.
-
-CLANG_DATABASE_PATH =
-
-#---------------------------------------------------------------------------
-# Configuration options related to the alphabetical class index
-#---------------------------------------------------------------------------
-
-# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all
-# compounds will be generated. Enable this if the project contains a lot of
-# classes, structs, unions or interfaces.
-# The default value is: YES.
-
-ALPHABETICAL_INDEX = YES
-
-# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in
-# which the alphabetical index list will be split.
-# Minimum value: 1, maximum value: 20, default value: 5.
-# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
-
-COLS_IN_ALPHA_INDEX = 5
-
-# In case all classes in a project start with a common prefix, all classes will
-# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag
-# can be used to specify a prefix (or a list of prefixes) that should be ignored
-# while generating the index headers.
-# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
-
-IGNORE_PREFIX =
-
-#---------------------------------------------------------------------------
-# Configuration options related to the HTML output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output
-# The default value is: YES.
-
-GENERATE_HTML = YES
-
-# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a
-# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
-# it.
-# The default directory is: html.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_OUTPUT = html
-
-# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each
-# generated HTML page (for example: .htm, .php, .asp).
-# The default value is: .html.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_FILE_EXTENSION = .html
-
-# The HTML_HEADER tag can be used to specify a user-defined HTML header file for
-# each generated HTML page. If the tag is left blank doxygen will generate a
-# standard header.
-#
-# To get valid HTML the header file that includes any scripts and style sheets
-# that doxygen needs, which is dependent on the configuration options used (e.g.
-# the setting GENERATE_TREEVIEW). It is highly recommended to start with a
-# default header using
-# doxygen -w html new_header.html new_footer.html new_stylesheet.css
-# YourConfigFile
-# and then modify the file new_header.html. See also section "Doxygen usage"
-# for information on how to generate the default header that doxygen normally
-# uses.
-# Note: The header is subject to change so you typically have to regenerate the
-# default header when upgrading to a newer version of doxygen. For a description
-# of the possible markers and block names see the documentation.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_HEADER =
-
-# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each
-# generated HTML page. If the tag is left blank doxygen will generate a standard
-# footer. See HTML_HEADER for more information on how to generate a default
-# footer and what special commands can be used inside the footer. See also
-# section "Doxygen usage" for information on how to generate the default footer
-# that doxygen normally uses.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_FOOTER =
-
-# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style
-# sheet that is used by each HTML page. It can be used to fine-tune the look of
-# the HTML output. If left blank doxygen will generate a default style sheet.
-# See also section "Doxygen usage" for information on how to generate the style
-# sheet that doxygen normally uses.
-# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as
-# it is more robust and this tag (HTML_STYLESHEET) will in the future become
-# obsolete.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_STYLESHEET =
-
-# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined
-# cascading style sheets that are included after the standard style sheets
-# created by doxygen. Using this option one can overrule certain style aspects.
-# This is preferred over using HTML_STYLESHEET since it does not replace the
-# standard style sheet and is therefore more robust against future updates.
-# Doxygen will copy the style sheet files to the output directory.
-# Note: The order of the extra style sheet files is of importance (e.g. the last
-# style sheet in the list overrules the setting of the previous ones in the
-# list). For an example see the documentation.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_EXTRA_STYLESHEET =
-
-# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or
-# other source files which should be copied to the HTML output directory. Note
-# that these files will be copied to the base HTML output directory. Use the
-# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these
-# files. In the HTML_STYLESHEET file, use the file name only. Also note that the
-# files will be copied as-is; there are no commands or markers available.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_EXTRA_FILES =
-
-# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen
-# will adjust the colors in the style sheet and background images according to
-# this color. Hue is specified as an angle on a colorwheel, see
-# https://en.wikipedia.org/wiki/Hue for more information. For instance the value
-# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300
-# purple, and 360 is red again.
-# Minimum value: 0, maximum value: 359, default value: 220.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_COLORSTYLE_HUE = 220
-
-# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors
-# in the HTML output. For a value of 0 the output will use grayscales only. A
-# value of 255 will produce the most vivid colors.
-# Minimum value: 0, maximum value: 255, default value: 100.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_COLORSTYLE_SAT = 100
-
-# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the
-# luminance component of the colors in the HTML output. Values below 100
-# gradually make the output lighter, whereas values above 100 make the output
-# darker. The value divided by 100 is the actual gamma applied, so 80 represents
-# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not
-# change the gamma.
-# Minimum value: 40, maximum value: 240, default value: 80.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_COLORSTYLE_GAMMA = 80
-
-# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
-# page will contain the date and time when the page was generated. Setting this
-# to YES can help to show when doxygen was last run and thus if the
-# documentation is up to date.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_TIMESTAMP = NO
-
-# If the HTML_DYNAMIC_MENUS tag is set to YES then the generated HTML
-# documentation will contain a main index with vertical navigation menus that
-# are dynamically created via JavaScript. If disabled, the navigation index will
-# consists of multiple levels of tabs that are statically embedded in every HTML
-# page. Disable this option to support browsers that do not have JavaScript,
-# like the Qt help browser.
-# The default value is: YES.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_DYNAMIC_MENUS = YES
-
-# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
-# documentation will contain sections that can be hidden and shown after the
-# page has loaded.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_DYNAMIC_SECTIONS = NO
-
-# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries
-# shown in the various tree structured indices initially; the user can expand
-# and collapse entries dynamically later on. Doxygen will expand the tree to
-# such a level that at most the specified number of entries are visible (unless
-# a fully collapsed tree already exceeds this amount). So setting the number of
-# entries 1 will produce a full collapsed tree by default. 0 is a special value
-# representing an infinite number of entries and will result in a full expanded
-# tree by default.
-# Minimum value: 0, maximum value: 9999, default value: 100.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-HTML_INDEX_NUM_ENTRIES = 100
-
-# If the GENERATE_DOCSET tag is set to YES, additional index files will be
-# generated that can be used as input for Apple's Xcode 3 integrated development
-# environment (see: https://developer.apple.com/xcode/), introduced with OSX
-# 10.5 (Leopard). To create a documentation set, doxygen will generate a
-# Makefile in the HTML output directory. Running make will produce the docset in
-# that directory and running make install will install the docset in
-# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at
-# startup. See https://developer.apple.com/library/archive/featuredarticles/Doxy
-# genXcode/_index.html for more information.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-GENERATE_DOCSET = NO
-
-# This tag determines the name of the docset feed. A documentation feed provides
-# an umbrella under which multiple documentation sets from a single provider
-# (such as a company or product suite) can be grouped.
-# The default value is: Doxygen generated docs.
-# This tag requires that the tag GENERATE_DOCSET is set to YES.
-
-DOCSET_FEEDNAME = "Doxygen generated docs"
-
-# This tag specifies a string that should uniquely identify the documentation
-# set bundle. This should be a reverse domain-name style string, e.g.
-# com.mycompany.MyDocSet. Doxygen will append .docset to the name.
-# The default value is: org.doxygen.Project.
-# This tag requires that the tag GENERATE_DOCSET is set to YES.
-
-DOCSET_BUNDLE_ID = org.doxygen.Project
-
-# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify
-# the documentation publisher. This should be a reverse domain-name style
-# string, e.g. com.mycompany.MyDocSet.documentation.
-# The default value is: org.doxygen.Publisher.
-# This tag requires that the tag GENERATE_DOCSET is set to YES.
-
-DOCSET_PUBLISHER_ID = org.doxygen.Publisher
-
-# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher.
-# The default value is: Publisher.
-# This tag requires that the tag GENERATE_DOCSET is set to YES.
-
-DOCSET_PUBLISHER_NAME = Publisher
-
-# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three
-# additional HTML index files: index.hhp, index.hhc, and index.hhk. The
-# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop
-# (see: https://www.microsoft.com/en-us/download/details.aspx?id=21138) on
-# Windows.
-#
-# The HTML Help Workshop contains a compiler that can convert all HTML output
-# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML
-# files are now used as the Windows 98 help format, and will replace the old
-# Windows help format (.hlp) on all Windows platforms in the future. Compressed
-# HTML files also contain an index, a table of contents, and you can search for
-# words in the documentation. The HTML workshop also contains a viewer for
-# compressed HTML files.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-GENERATE_HTMLHELP = NO
-
-# The CHM_FILE tag can be used to specify the file name of the resulting .chm
-# file. You can add a path in front of the file if the result should not be
-# written to the html output directory.
-# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
-
-CHM_FILE =
-
-# The HHC_LOCATION tag can be used to specify the location (absolute path
-# including file name) of the HTML help compiler (hhc.exe). If non-empty,
-# doxygen will try to run the HTML help compiler on the generated index.hhp.
-# The file has to be specified with full path.
-# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
-
-HHC_LOCATION =
-
-# The GENERATE_CHI flag controls if a separate .chi index file is generated
-# (YES) or that it should be included in the master .chm file (NO).
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
-
-GENERATE_CHI = NO
-
-# The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc)
-# and project file content.
-# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
-
-CHM_INDEX_ENCODING =
-
-# The BINARY_TOC flag controls whether a binary table of contents is generated
-# (YES) or a normal table of contents (NO) in the .chm file. Furthermore it
-# enables the Previous and Next buttons.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
-
-BINARY_TOC = NO
-
-# The TOC_EXPAND flag can be set to YES to add extra items for group members to
-# the table of contents of the HTML help documentation and to the tree view.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
-
-TOC_EXPAND = NO
-
-# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and
-# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that
-# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help
-# (.qch) of the generated HTML documentation.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-GENERATE_QHP = NO
-
-# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify
-# the file name of the resulting .qch file. The path specified is relative to
-# the HTML output folder.
-# This tag requires that the tag GENERATE_QHP is set to YES.
-
-QCH_FILE =
-
-# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help
-# Project output. For more information please see Qt Help Project / Namespace
-# (see: https://doc.qt.io/archives/qt-4.8/qthelpproject.html#namespace).
-# The default value is: org.doxygen.Project.
-# This tag requires that the tag GENERATE_QHP is set to YES.
-
-QHP_NAMESPACE = org.doxygen.Project
-
-# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt
-# Help Project output. For more information please see Qt Help Project / Virtual
-# Folders (see: https://doc.qt.io/archives/qt-4.8/qthelpproject.html#virtual-
-# folders).
-# The default value is: doc.
-# This tag requires that the tag GENERATE_QHP is set to YES.
-
-QHP_VIRTUAL_FOLDER = doc
-
-# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom
-# filter to add. For more information please see Qt Help Project / Custom
-# Filters (see: https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom-
-# filters).
-# This tag requires that the tag GENERATE_QHP is set to YES.
-
-QHP_CUST_FILTER_NAME =
-
-# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the
-# custom filter to add. For more information please see Qt Help Project / Custom
-# Filters (see: https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom-
-# filters).
-# This tag requires that the tag GENERATE_QHP is set to YES.
-
-QHP_CUST_FILTER_ATTRS =
-
-# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this
-# project's filter section matches. Qt Help Project / Filter Attributes (see:
-# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#filter-attributes).
-# This tag requires that the tag GENERATE_QHP is set to YES.
-
-QHP_SECT_FILTER_ATTRS =
-
-# The QHG_LOCATION tag can be used to specify the location of Qt's
-# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the
-# generated .qhp file.
-# This tag requires that the tag GENERATE_QHP is set to YES.
-
-QHG_LOCATION =
-
-# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be
-# generated, together with the HTML files, they form an Eclipse help plugin. To
-# install this plugin and make it available under the help contents menu in
-# Eclipse, the contents of the directory containing the HTML and XML files needs
-# to be copied into the plugins directory of eclipse. The name of the directory
-# within the plugins directory should be the same as the ECLIPSE_DOC_ID value.
-# After copying Eclipse needs to be restarted before the help appears.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-GENERATE_ECLIPSEHELP = NO
-
-# A unique identifier for the Eclipse help plugin. When installing the plugin
-# the directory name containing the HTML and XML files should also have this
-# name. Each documentation set should have its own identifier.
-# The default value is: org.doxygen.Project.
-# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES.
-
-ECLIPSE_DOC_ID = org.doxygen.Project
-
-# If you want full control over the layout of the generated HTML pages it might
-# be necessary to disable the index and replace it with your own. The
-# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top
-# of each HTML page. A value of NO enables the index and the value YES disables
-# it. Since the tabs in the index contain the same information as the navigation
-# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-DISABLE_INDEX = NO
-
-# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
-# structure should be generated to display hierarchical information. If the tag
-# value is set to YES, a side panel will be generated containing a tree-like
-# index structure (just like the one that is generated for HTML Help). For this
-# to work a browser that supports JavaScript, DHTML, CSS and frames is required
-# (i.e. any modern browser). Windows users are probably better off using the
-# HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can
-# further fine-tune the look of the index. As an example, the default style
-# sheet generated by doxygen has an example that shows how to put an image at
-# the root of the tree instead of the PROJECT_NAME. Since the tree basically has
-# the same information as the tab index, you could consider setting
-# DISABLE_INDEX to YES when enabling this option.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-GENERATE_TREEVIEW = NO
-
-# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that
-# doxygen will group on one line in the generated HTML documentation.
-#
-# Note that a value of 0 will completely suppress the enum values from appearing
-# in the overview section.
-# Minimum value: 0, maximum value: 20, default value: 4.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-ENUM_VALUES_PER_LINE = 4
-
-# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used
-# to set the initial width (in pixels) of the frame in which the tree is shown.
-# Minimum value: 0, maximum value: 1500, default value: 250.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-TREEVIEW_WIDTH = 250
-
-# If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to
-# external symbols imported via tag files in a separate window.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-EXT_LINKS_IN_WINDOW = NO
-
-# If the HTML_FORMULA_FORMAT option is set to svg, doxygen will use the pdf2svg
-# tool (see https://github.com/dawbarton/pdf2svg) or inkscape (see
-# https://inkscape.org) to generate formulas as SVG images instead of PNGs for
-# the HTML output. These images will generally look nicer at scaled resolutions.
-# Possible values are: png (the default) and svg (looks nicer but requires the
-# pdf2svg or inkscape tool).
-# The default value is: png.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-# HTML_FORMULA_FORMAT = png
-
-# Use this tag to change the font size of LaTeX formulas included as images in
-# the HTML documentation. When you change the font size after a successful
-# doxygen run you need to manually remove any form_*.png images from the HTML
-# output directory to force them to be regenerated.
-# Minimum value: 8, maximum value: 50, default value: 10.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-FORMULA_FONTSIZE = 10
-
-# Use the FORMULA_TRANSPARENT tag to determine whether or not the images
-# generated for formulas are transparent PNGs. Transparent PNGs are not
-# supported properly for IE 6.0, but are supported on all modern browsers.
-#
-# Note that when changing this option you need to delete any form_*.png files in
-# the HTML output directory before the changes have effect.
-# The default value is: YES.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-FORMULA_TRANSPARENT = YES
-
-# The FORMULA_MACROFILE can contain LaTeX \newcommand and \renewcommand commands
-# to create new LaTeX commands to be used in formulas as building blocks. See
-# the section "Including formulas" for details.
-
-FORMULA_MACROFILE =
-
-# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see
-# https://www.mathjax.org) which uses client side JavaScript for the rendering
-# instead of using pre-rendered bitmaps. Use this if you do not have LaTeX
-# installed or if you want to formulas look prettier in the HTML output. When
-# enabled you may also need to install MathJax separately and configure the path
-# to it using the MATHJAX_RELPATH option.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-USE_MATHJAX = No
-
-# When MathJax is enabled you can set the default output format to be used for
-# the MathJax output. See the MathJax site (see:
-# http://docs.mathjax.org/en/latest/output.html) for more details.
-# Possible values are: HTML-CSS (which is slower, but has the best
-# compatibility), NativeMML (i.e. MathML) and SVG.
-# The default value is: HTML-CSS.
-# This tag requires that the tag USE_MATHJAX is set to YES.
-
-MATHJAX_FORMAT = HTML-CSS
-
-# When MathJax is enabled you need to specify the location relative to the HTML
-# output directory using the MATHJAX_RELPATH option. The destination directory
-# should contain the MathJax.js script. For instance, if the mathjax directory
-# is located at the same level as the HTML output directory, then
-# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax
-# Content Delivery Network so you can quickly see the result without installing
-# MathJax. However, it is strongly recommended to install a local copy of
-# MathJax from https://www.mathjax.org before deployment.
-# The default value is: https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/.
-# This tag requires that the tag USE_MATHJAX is set to YES.
-
-MATHJAX_RELPATH = https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/
-
-# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax
-# extension names that should be enabled during MathJax rendering. For example
-# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols
-# This tag requires that the tag USE_MATHJAX is set to YES.
-
-MATHJAX_EXTENSIONS =
-
-# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces
-# of code that will be used on startup of the MathJax code. See the MathJax site
-# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an
-# example see the documentation.
-# This tag requires that the tag USE_MATHJAX is set to YES.
-
-MATHJAX_CODEFILE =
-
-# When the SEARCHENGINE tag is enabled doxygen will generate a search box for
-# the HTML output. The underlying search engine uses javascript and DHTML and
-# should work on any modern browser. Note that when using HTML help
-# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET)
-# there is already a search function so this one should typically be disabled.
-# For large projects the javascript based search engine can be slow, then
-# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to
-# search using the keyboard; to jump to the search box use + S
-# (what the is depends on the OS and browser, but it is typically
-# , /, or both). Inside the search box use the to jump into the search results window, the results can be navigated
-# using the . Press to select an item or to cancel
-# the search. The filter options can be selected when the cursor is inside the
-# search box by pressing +. Also here use the
-# to select a filter and or to activate or cancel the filter
-# option.
-# The default value is: YES.
-# This tag requires that the tag GENERATE_HTML is set to YES.
-
-SEARCHENGINE = YES
-
-# When the SERVER_BASED_SEARCH tag is enabled the search engine will be
-# implemented using a web server instead of a web client using JavaScript. There
-# are two flavors of web server based searching depending on the EXTERNAL_SEARCH
-# setting. When disabled, doxygen will generate a PHP script for searching and
-# an index file used by the script. When EXTERNAL_SEARCH is enabled the indexing
-# and searching needs to be provided by external tools. See the section
-# "External Indexing and Searching" for details.
-# The default value is: NO.
-# This tag requires that the tag SEARCHENGINE is set to YES.
-
-SERVER_BASED_SEARCH = NO
-
-# When EXTERNAL_SEARCH tag is enabled doxygen will no longer generate the PHP
-# script for searching. Instead the search results are written to an XML file
-# which needs to be processed by an external indexer. Doxygen will invoke an
-# external search engine pointed to by the SEARCHENGINE_URL option to obtain the
-# search results.
-#
-# Doxygen ships with an example indexer (doxyindexer) and search engine
-# (doxysearch.cgi) which are based on the open source search engine library
-# Xapian (see: https://xapian.org/).
-#
-# See the section "External Indexing and Searching" for details.
-# The default value is: NO.
-# This tag requires that the tag SEARCHENGINE is set to YES.
-
-EXTERNAL_SEARCH = NO
-
-# The SEARCHENGINE_URL should point to a search engine hosted by a web server
-# which will return the search results when EXTERNAL_SEARCH is enabled.
-#
-# Doxygen ships with an example indexer (doxyindexer) and search engine
-# (doxysearch.cgi) which are based on the open source search engine library
-# Xapian (see: https://xapian.org/). See the section "External Indexing and
-# Searching" for details.
-# This tag requires that the tag SEARCHENGINE is set to YES.
-
-SEARCHENGINE_URL =
-
-# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed
-# search data is written to a file for indexing by an external tool. With the
-# SEARCHDATA_FILE tag the name of this file can be specified.
-# The default file is: searchdata.xml.
-# This tag requires that the tag SEARCHENGINE is set to YES.
-
-SEARCHDATA_FILE = searchdata.xml
-
-# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the
-# EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is
-# useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple
-# projects and redirect the results back to the right project.
-# This tag requires that the tag SEARCHENGINE is set to YES.
-
-EXTERNAL_SEARCH_ID =
-
-# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen
-# projects other than the one defined by this configuration file, but that are
-# all added to the same external search index. Each project needs to have a
-# unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id of
-# to a relative location where the documentation can be found. The format is:
-# EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ...
-# This tag requires that the tag SEARCHENGINE is set to YES.
-
-EXTRA_SEARCH_MAPPINGS =
-
-#---------------------------------------------------------------------------
-# Configuration options related to the LaTeX output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_LATEX tag is set to YES, doxygen will generate LaTeX output.
-# The default value is: YES.
-
-GENERATE_LATEX = NO
-
-# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. If a
-# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
-# it.
-# The default directory is: latex.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_OUTPUT = latex
-
-# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
-# invoked.
-#
-# Note that when not enabling USE_PDFLATEX the default is latex when enabling
-# USE_PDFLATEX the default is pdflatex and when in the later case latex is
-# chosen this is overwritten by pdflatex. For specific output languages the
-# default can have been set differently, this depends on the implementation of
-# the output language.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_CMD_NAME =
-
-# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to generate
-# index for LaTeX.
-# Note: This tag is used in the Makefile / make.bat.
-# See also: LATEX_MAKEINDEX_CMD for the part in the generated output file
-# (.tex).
-# The default file is: makeindex.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-MAKEINDEX_CMD_NAME = makeindex
-
-# The LATEX_MAKEINDEX_CMD tag can be used to specify the command name to
-# generate index for LaTeX. In case there is no backslash (\) as first character
-# it will be automatically added in the LaTeX code.
-# Note: This tag is used in the generated output file (.tex).
-# See also: MAKEINDEX_CMD_NAME for the part in the Makefile / make.bat.
-# The default value is: makeindex.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_MAKEINDEX_CMD = makeindex
-
-# If the COMPACT_LATEX tag is set to YES, doxygen generates more compact LaTeX
-# documents. This may be useful for small projects and may help to save some
-# trees in general.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-COMPACT_LATEX = NO
-
-# The PAPER_TYPE tag can be used to set the paper type that is used by the
-# printer.
-# Possible values are: a4 (210 x 297 mm), letter (8.5 x 11 inches), legal (8.5 x
-# 14 inches) and executive (7.25 x 10.5 inches).
-# The default value is: a4.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-PAPER_TYPE = a4
-
-# The EXTRA_PACKAGES tag can be used to specify one or more LaTeX package names
-# that should be included in the LaTeX output. The package can be specified just
-# by its name or with the correct syntax as to be used with the LaTeX
-# \usepackage command. To get the times font for instance you can specify :
-# EXTRA_PACKAGES=times or EXTRA_PACKAGES={times}
-# To use the option intlimits with the amsmath package you can specify:
-# EXTRA_PACKAGES=[intlimits]{amsmath}
-# If left blank no extra packages will be included.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-EXTRA_PACKAGES =
-
-# The LATEX_HEADER tag can be used to specify a personal LaTeX header for the
-# generated LaTeX document. The header should contain everything until the first
-# chapter. If it is left blank doxygen will generate a standard header. See
-# section "Doxygen usage" for information on how to let doxygen write the
-# default header to a separate file.
-#
-# Note: Only use a user-defined header if you know what you are doing! The
-# following commands have a special meaning inside the header: $title,
-# $datetime, $date, $doxygenversion, $projectname, $projectnumber,
-# $projectbrief, $projectlogo. Doxygen will replace $title with the empty
-# string, for the replacement values of the other commands the user is referred
-# to HTML_HEADER.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_HEADER =
-
-# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for the
-# generated LaTeX document. The footer should contain everything after the last
-# chapter. If it is left blank doxygen will generate a standard footer. See
-# LATEX_HEADER for more information on how to generate a default footer and what
-# special commands can be used inside the footer.
-#
-# Note: Only use a user-defined footer if you know what you are doing!
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_FOOTER =
-
-# The LATEX_EXTRA_STYLESHEET tag can be used to specify additional user-defined
-# LaTeX style sheets that are included after the standard style sheets created
-# by doxygen. Using this option one can overrule certain style aspects. Doxygen
-# will copy the style sheet files to the output directory.
-# Note: The order of the extra style sheet files is of importance (e.g. the last
-# style sheet in the list overrules the setting of the previous ones in the
-# list).
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_EXTRA_STYLESHEET =
-
-# The LATEX_EXTRA_FILES tag can be used to specify one or more extra images or
-# other source files which should be copied to the LATEX_OUTPUT output
-# directory. Note that the files will be copied as-is; there are no commands or
-# markers available.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_EXTRA_FILES =
-
-# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated is
-# prepared for conversion to PDF (using ps2pdf or pdflatex). The PDF file will
-# contain links (just like the HTML output) instead of page references. This
-# makes the output suitable for online browsing using a PDF viewer.
-# The default value is: YES.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-PDF_HYPERLINKS = YES
-
-# If the USE_PDFLATEX tag is set to YES, doxygen will use pdflatex to generate
-# the PDF file directly from the LaTeX files. Set this option to YES, to get a
-# higher quality PDF documentation.
-# The default value is: YES.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-USE_PDFLATEX = YES
-
-# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \batchmode
-# command to the generated LaTeX files. This will instruct LaTeX to keep running
-# if errors occur, instead of asking the user for help. This option is also used
-# when generating formulas in HTML.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_BATCHMODE = NO
-
-# If the LATEX_HIDE_INDICES tag is set to YES then doxygen will not include the
-# index chapters (such as File Index, Compound Index, etc.) in the output.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_HIDE_INDICES = NO
-
-# If the LATEX_SOURCE_CODE tag is set to YES then doxygen will include source
-# code with syntax highlighting in the LaTeX output.
-#
-# Note that which sources are shown also depends on other settings such as
-# SOURCE_BROWSER.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_SOURCE_CODE = NO
-
-# The LATEX_BIB_STYLE tag can be used to specify the style to use for the
-# bibliography, e.g. plainnat, or ieeetr. See
-# https://en.wikipedia.org/wiki/BibTeX and \cite for more info.
-# The default value is: plain.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_BIB_STYLE = plain
-
-# If the LATEX_TIMESTAMP tag is set to YES then the footer of each generated
-# page will contain the date and time when the page was generated. Setting this
-# to NO can help when comparing the output of multiple runs.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_TIMESTAMP = NO
-
-# The LATEX_EMOJI_DIRECTORY tag is used to specify the (relative or absolute)
-# path from which the emoji images will be read. If a relative path is entered,
-# it will be relative to the LATEX_OUTPUT directory. If left blank the
-# LATEX_OUTPUT directory will be used.
-# This tag requires that the tag GENERATE_LATEX is set to YES.
-
-LATEX_EMOJI_DIRECTORY =
-
-#---------------------------------------------------------------------------
-# Configuration options related to the RTF output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_RTF tag is set to YES, doxygen will generate RTF output. The
-# RTF output is optimized for Word 97 and may not look too pretty with other RTF
-# readers/editors.
-# The default value is: NO.
-
-GENERATE_RTF = NO
-
-# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. If a
-# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
-# it.
-# The default directory is: rtf.
-# This tag requires that the tag GENERATE_RTF is set to YES.
-
-RTF_OUTPUT = rtf
-
-# If the COMPACT_RTF tag is set to YES, doxygen generates more compact RTF
-# documents. This may be useful for small projects and may help to save some
-# trees in general.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_RTF is set to YES.
-
-COMPACT_RTF = NO
-
-# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated will
-# contain hyperlink fields. The RTF file will contain links (just like the HTML
-# output) instead of page references. This makes the output suitable for online
-# browsing using Word or some other Word compatible readers that support those
-# fields.
-#
-# Note: WordPad (write) and others do not support links.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_RTF is set to YES.
-
-RTF_HYPERLINKS = NO
-
-# Load stylesheet definitions from file. Syntax is similar to doxygen's
-# configuration file, i.e. a series of assignments. You only have to provide
-# replacements, missing definitions are set to their default value.
-#
-# See also section "Doxygen usage" for information on how to generate the
-# default style sheet that doxygen normally uses.
-# This tag requires that the tag GENERATE_RTF is set to YES.
-
-RTF_STYLESHEET_FILE =
-
-# Set optional variables used in the generation of an RTF document. Syntax is
-# similar to doxygen's configuration file. A template extensions file can be
-# generated using doxygen -e rtf extensionFile.
-# This tag requires that the tag GENERATE_RTF is set to YES.
-
-RTF_EXTENSIONS_FILE =
-
-# If the RTF_SOURCE_CODE tag is set to YES then doxygen will include source code
-# with syntax highlighting in the RTF output.
-#
-# Note that which sources are shown also depends on other settings such as
-# SOURCE_BROWSER.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_RTF is set to YES.
-
-RTF_SOURCE_CODE = NO
-
-#---------------------------------------------------------------------------
-# Configuration options related to the man page output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_MAN tag is set to YES, doxygen will generate man pages for
-# classes and files.
-# The default value is: NO.
-
-GENERATE_MAN = NO
-
-# The MAN_OUTPUT tag is used to specify where the man pages will be put. If a
-# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
-# it. A directory man3 will be created inside the directory specified by
-# MAN_OUTPUT.
-# The default directory is: man.
-# This tag requires that the tag GENERATE_MAN is set to YES.
-
-MAN_OUTPUT = man
-
-# The MAN_EXTENSION tag determines the extension that is added to the generated
-# man pages. In case the manual section does not start with a number, the number
-# 3 is prepended. The dot (.) at the beginning of the MAN_EXTENSION tag is
-# optional.
-# The default value is: .3.
-# This tag requires that the tag GENERATE_MAN is set to YES.
-
-MAN_EXTENSION = .3
-
-# The MAN_SUBDIR tag determines the name of the directory created within
-# MAN_OUTPUT in which the man pages are placed. If defaults to man followed by
-# MAN_EXTENSION with the initial . removed.
-# This tag requires that the tag GENERATE_MAN is set to YES.
-
-MAN_SUBDIR =
-
-# If the MAN_LINKS tag is set to YES and doxygen generates man output, then it
-# will generate one additional man file for each entity documented in the real
-# man page(s). These additional files only source the real man page, but without
-# them the man command would be unable to find the correct page.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_MAN is set to YES.
-
-MAN_LINKS = NO
-
-#---------------------------------------------------------------------------
-# Configuration options related to the XML output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_XML tag is set to YES, doxygen will generate an XML file that
-# captures the structure of the code including all documentation.
-# The default value is: NO.
-
-GENERATE_XML = YES
-
-# The XML_OUTPUT tag is used to specify where the XML pages will be put. If a
-# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
-# it.
-# The default directory is: xml.
-# This tag requires that the tag GENERATE_XML is set to YES.
-
-XML_OUTPUT = xml
-
-# If the XML_PROGRAMLISTING tag is set to YES, doxygen will dump the program
-# listings (including syntax highlighting and cross-referencing information) to
-# the XML output. Note that enabling this will significantly increase the size
-# of the XML output.
-# The default value is: YES.
-# This tag requires that the tag GENERATE_XML is set to YES.
-
-XML_PROGRAMLISTING = YES
-
-# If the XML_NS_MEMB_FILE_SCOPE tag is set to YES, doxygen will include
-# namespace members in file scope as well, matching the HTML output.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_XML is set to YES.
-
-XML_NS_MEMB_FILE_SCOPE = NO
-
-#---------------------------------------------------------------------------
-# Configuration options related to the DOCBOOK output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_DOCBOOK tag is set to YES, doxygen will generate Docbook files
-# that can be used to generate PDF.
-# The default value is: NO.
-
-GENERATE_DOCBOOK = NO
-
-# The DOCBOOK_OUTPUT tag is used to specify where the Docbook pages will be put.
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be put in
-# front of it.
-# The default directory is: docbook.
-# This tag requires that the tag GENERATE_DOCBOOK is set to YES.
-
-DOCBOOK_OUTPUT = docbook
-
-# If the DOCBOOK_PROGRAMLISTING tag is set to YES, doxygen will include the
-# program listings (including syntax highlighting and cross-referencing
-# information) to the DOCBOOK output. Note that enabling this will significantly
-# increase the size of the DOCBOOK output.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_DOCBOOK is set to YES.
-
-DOCBOOK_PROGRAMLISTING = NO
-
-#---------------------------------------------------------------------------
-# Configuration options for the AutoGen Definitions output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_AUTOGEN_DEF tag is set to YES, doxygen will generate an
-# AutoGen Definitions (see http://autogen.sourceforge.net/) file that captures
-# the structure of the code including all documentation. Note that this feature
-# is still experimental and incomplete at the moment.
-# The default value is: NO.
-
-GENERATE_AUTOGEN_DEF = NO
-
-#---------------------------------------------------------------------------
-# Configuration options related to the Perl module output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_PERLMOD tag is set to YES, doxygen will generate a Perl module
-# file that captures the structure of the code including all documentation.
-#
-# Note that this feature is still experimental and incomplete at the moment.
-# The default value is: NO.
-
-GENERATE_PERLMOD = NO
-
-# If the PERLMOD_LATEX tag is set to YES, doxygen will generate the necessary
-# Makefile rules, Perl scripts and LaTeX code to be able to generate PDF and DVI
-# output from the Perl module output.
-# The default value is: NO.
-# This tag requires that the tag GENERATE_PERLMOD is set to YES.
-
-PERLMOD_LATEX = NO
-
-# If the PERLMOD_PRETTY tag is set to YES, the Perl module output will be nicely
-# formatted so it can be parsed by a human reader. This is useful if you want to
-# understand what is going on. On the other hand, if this tag is set to NO, the
-# size of the Perl module output will be much smaller and Perl will parse it
-# just the same.
-# The default value is: YES.
-# This tag requires that the tag GENERATE_PERLMOD is set to YES.
-
-PERLMOD_PRETTY = YES
-
-# The names of the make variables in the generated doxyrules.make file are
-# prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. This is useful
-# so different doxyrules.make files included by the same Makefile don't
-# overwrite each other's variables.
-# This tag requires that the tag GENERATE_PERLMOD is set to YES.
-
-PERLMOD_MAKEVAR_PREFIX =
-
-#---------------------------------------------------------------------------
-# Configuration options related to the preprocessor
-#---------------------------------------------------------------------------
-
-# If the ENABLE_PREPROCESSING tag is set to YES, doxygen will evaluate all
-# C-preprocessor directives found in the sources and include files.
-# The default value is: YES.
-
-ENABLE_PREPROCESSING = YES
-
-# If the MACRO_EXPANSION tag is set to YES, doxygen will expand all macro names
-# in the source code. If set to NO, only conditional compilation will be
-# performed. Macro expansion can be done in a controlled way by setting
-# EXPAND_ONLY_PREDEF to YES.
-# The default value is: NO.
-# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
-
-MACRO_EXPANSION = YES
-
-# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES then
-# the macro expansion is limited to the macros specified with the PREDEFINED and
-# EXPAND_AS_DEFINED tags.
-# The default value is: NO.
-# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
-
-EXPAND_ONLY_PREDEF = YES
-
-# If the SEARCH_INCLUDES tag is set to YES, the include files in the
-# INCLUDE_PATH will be searched if a #include is found.
-# The default value is: YES.
-# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
-
-SEARCH_INCLUDES = YES
-
-# The INCLUDE_PATH tag can be used to specify one or more directories that
-# contain include files that are not input files but should be processed by the
-# preprocessor.
-# This tag requires that the tag SEARCH_INCLUDES is set to YES.
-
-INCLUDE_PATH =
-
-# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
-# patterns (like *.h and *.hpp) to filter out the header-files in the
-# directories. If left blank, the patterns specified with FILE_PATTERNS will be
-# used.
-# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
-
-INCLUDE_FILE_PATTERNS =
-
-# The PREDEFINED tag can be used to specify one or more macro names that are
-# defined before the preprocessor is started (similar to the -D option of e.g.
-# gcc). The argument of the tag is a list of macros of the form: name or
-# name=definition (no spaces). If the definition and the "=" are omitted, "=1"
-# is assumed. To prevent a macro definition from being undefined via #undef or
-# recursively expanded use the := operator instead of the = operator.
-# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
-
-PREDEFINED =
-
-# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this
-# tag can be used to specify a list of macro names that should be expanded. The
-# macro definition that is found in the sources will be used. Use the PREDEFINED
-# tag if you want to use a different macro definition that overrules the
-# definition found in the source code.
-# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
-
-EXPAND_AS_DEFINED =
-
-# If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will
-# remove all references to function-like macros that are alone on a line, have
-# an all uppercase name, and do not end with a semicolon. Such function macros
-# are typically used for boiler-plate code, and will confuse the parser if not
-# removed.
-# The default value is: YES.
-# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
-
-SKIP_FUNCTION_MACROS = YES
-
-#---------------------------------------------------------------------------
-# Configuration options related to external references
-#---------------------------------------------------------------------------
-
-# The TAGFILES tag can be used to specify one or more tag files. For each tag
-# file the location of the external documentation should be added. The format of
-# a tag file without this location is as follows:
-# TAGFILES = file1 file2 ...
-# Adding location for the tag files is done as follows:
-# TAGFILES = file1=loc1 "file2 = loc2" ...
-# where loc1 and loc2 can be relative or absolute paths or URLs. See the
-# section "Linking to external documentation" for more information about the use
-# of tag files.
-# Note: Each tag file must have a unique name (where the name does NOT include
-# the path). If a tag file is not located in the directory in which doxygen is
-# run, you must also specify the path to the tagfile here.
-
-TAGFILES =
-
-# When a file name is specified after GENERATE_TAGFILE, doxygen will create a
-# tag file that is based on the input files it reads. See section "Linking to
-# external documentation" for more information about the usage of tag files.
-
-GENERATE_TAGFILE =
-
-# If the ALLEXTERNALS tag is set to YES, all external class will be listed in
-# the class index. If set to NO, only the inherited external classes will be
-# listed.
-# The default value is: NO.
-
-ALLEXTERNALS = NO
-
-# If the EXTERNAL_GROUPS tag is set to YES, all external groups will be listed
-# in the modules index. If set to NO, only the current project's groups will be
-# listed.
-# The default value is: YES.
-
-EXTERNAL_GROUPS = YES
-
-# If the EXTERNAL_PAGES tag is set to YES, all external pages will be listed in
-# the related pages index. If set to NO, only the current project's pages will
-# be listed.
-# The default value is: YES.
-
-EXTERNAL_PAGES = YES
-
-#---------------------------------------------------------------------------
-# Configuration options related to the dot tool
-#---------------------------------------------------------------------------
-
-# If the CLASS_DIAGRAMS tag is set to YES, doxygen will generate a class diagram
-# (in HTML and LaTeX) for classes with base or super classes. Setting the tag to
-# NO turns the diagrams off. Note that this option also works with HAVE_DOT
-# disabled, but it is recommended to install and use dot, since it yields more
-# powerful graphs.
-# The default value is: YES.
-
-CLASS_DIAGRAMS = YES
-
-# You can include diagrams made with dia in doxygen documentation. Doxygen will
-# then run dia to produce the diagram and insert it in the documentation. The
-# DIA_PATH tag allows you to specify the directory where the dia binary resides.
-# If left empty dia is assumed to be found in the default search path.
-
-DIA_PATH =
-
-# If set to YES the inheritance and collaboration graphs will hide inheritance
-# and usage relations if the target is undocumented or is not a class.
-# The default value is: YES.
-
-HIDE_UNDOC_RELATIONS = YES
-
-# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
-# available from the path. This tool is part of Graphviz (see:
-# http://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent
-# Bell Labs. The other options in this section have no effect if this option is
-# set to NO
-# The default value is: NO.
-
-HAVE_DOT = NO
-
-# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is allowed
-# to run in parallel. When set to 0 doxygen will base this on the number of
-# processors available in the system. You can set it explicitly to a value
-# larger than 0 to get control over the balance between CPU load and processing
-# speed.
-# Minimum value: 0, maximum value: 32, default value: 0.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_NUM_THREADS = 0
-
-# When you want a differently looking font in the dot files that doxygen
-# generates you can specify the font name using DOT_FONTNAME. You need to make
-# sure dot is able to find the font, which can be done by putting it in a
-# standard location or by setting the DOTFONTPATH environment variable or by
-# setting DOT_FONTPATH to the directory containing the font.
-# The default value is: Helvetica.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_FONTNAME = Helvetica
-
-# The DOT_FONTSIZE tag can be used to set the size (in points) of the font of
-# dot graphs.
-# Minimum value: 4, maximum value: 24, default value: 10.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_FONTSIZE = 10
-
-# By default doxygen will tell dot to use the default font as specified with
-# DOT_FONTNAME. If you specify a different font using DOT_FONTNAME you can set
-# the path where dot can find it using this tag.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_FONTPATH =
-
-# If the CLASS_GRAPH tag is set to YES then doxygen will generate a graph for
-# each documented class showing the direct and indirect inheritance relations.
-# Setting this tag to YES will force the CLASS_DIAGRAMS tag to NO.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-CLASS_GRAPH = YES
-
-# If the COLLABORATION_GRAPH tag is set to YES then doxygen will generate a
-# graph for each documented class showing the direct and indirect implementation
-# dependencies (inheritance, containment, and class references variables) of the
-# class with other documented classes.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-COLLABORATION_GRAPH = YES
-
-# If the GROUP_GRAPHS tag is set to YES then doxygen will generate a graph for
-# groups, showing the direct groups dependencies.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-GROUP_GRAPHS = YES
-
-# If the UML_LOOK tag is set to YES, doxygen will generate inheritance and
-# collaboration diagrams in a style similar to the OMG's Unified Modeling
-# Language.
-# The default value is: NO.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-UML_LOOK = NO
-
-# If the UML_LOOK tag is enabled, the fields and methods are shown inside the
-# class node. If there are many fields or methods and many nodes the graph may
-# become too big to be useful. The UML_LIMIT_NUM_FIELDS threshold limits the
-# number of items for each type to make the size more manageable. Set this to 0
-# for no limit. Note that the threshold may be exceeded by 50% before the limit
-# is enforced. So when you set the threshold to 10, up to 15 fields may appear,
-# but if the number exceeds 15, the total amount of fields shown is limited to
-# 10.
-# Minimum value: 0, maximum value: 100, default value: 10.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-UML_LIMIT_NUM_FIELDS = 10
-
-# If the TEMPLATE_RELATIONS tag is set to YES then the inheritance and
-# collaboration graphs will show the relations between templates and their
-# instances.
-# The default value is: NO.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-TEMPLATE_RELATIONS = NO
-
-# If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are set to
-# YES then doxygen will generate a graph for each documented file showing the
-# direct and indirect include dependencies of the file with other documented
-# files.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-INCLUDE_GRAPH = YES
-
-# If the INCLUDED_BY_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are
-# set to YES then doxygen will generate a graph for each documented file showing
-# the direct and indirect include dependencies of the file with other documented
-# files.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-INCLUDED_BY_GRAPH = YES
-
-# If the CALL_GRAPH tag is set to YES then doxygen will generate a call
-# dependency graph for every global function or class method.
-#
-# Note that enabling this option will significantly increase the time of a run.
-# So in most cases it will be better to enable call graphs for selected
-# functions only using the \callgraph command. Disabling a call graph can be
-# accomplished by means of the command \hidecallgraph.
-# The default value is: NO.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-CALL_GRAPH = YES
-
-# If the CALLER_GRAPH tag is set to YES then doxygen will generate a caller
-# dependency graph for every global function or class method.
-#
-# Note that enabling this option will significantly increase the time of a run.
-# So in most cases it will be better to enable caller graphs for selected
-# functions only using the \callergraph command. Disabling a caller graph can be
-# accomplished by means of the command \hidecallergraph.
-# The default value is: NO.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-CALLER_GRAPH = NO
-
-# If the GRAPHICAL_HIERARCHY tag is set to YES then doxygen will graphical
-# hierarchy of all classes instead of a textual one.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-GRAPHICAL_HIERARCHY = YES
-
-# If the DIRECTORY_GRAPH tag is set to YES then doxygen will show the
-# dependencies a directory has on other directories in a graphical way. The
-# dependency relations are determined by the #include relations between the
-# files in the directories.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DIRECTORY_GRAPH = YES
-
-# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
-# generated by dot. For an explanation of the image formats see the section
-# output formats in the documentation of the dot tool (Graphviz (see:
-# http://www.graphviz.org/)).
-# Note: If you choose svg you need to set HTML_FILE_EXTENSION to xhtml in order
-# to make the SVG files visible in IE 9+ (other browsers do not have this
-# requirement).
-# Possible values are: png, jpg, gif, svg, png:gd, png:gd:gd, png:cairo,
-# png:cairo:gd, png:cairo:cairo, png:cairo:gdiplus, png:gdiplus and
-# png:gdiplus:gdiplus.
-# The default value is: png.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_IMAGE_FORMAT = png
-
-# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to
-# enable generation of interactive SVG images that allow zooming and panning.
-#
-# Note that this requires a modern browser other than Internet Explorer. Tested
-# and working are Firefox, Chrome, Safari, and Opera.
-# Note: For IE 9+ you need to set HTML_FILE_EXTENSION to xhtml in order to make
-# the SVG files visible. Older versions of IE do not have SVG support.
-# The default value is: NO.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-INTERACTIVE_SVG = NO
-
-# The DOT_PATH tag can be used to specify the path where the dot tool can be
-# found. If left blank, it is assumed the dot tool can be found in the path.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_PATH =
-
-# The DOTFILE_DIRS tag can be used to specify one or more directories that
-# contain dot files that are included in the documentation (see the \dotfile
-# command).
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOTFILE_DIRS =
-
-# The MSCFILE_DIRS tag can be used to specify one or more directories that
-# contain msc files that are included in the documentation (see the \mscfile
-# command).
-
-MSCFILE_DIRS =
-
-# The DIAFILE_DIRS tag can be used to specify one or more directories that
-# contain dia files that are included in the documentation (see the \diafile
-# command).
-
-DIAFILE_DIRS =
-
-# When using plantuml, the PLANTUML_JAR_PATH tag should be used to specify the
-# path where java can find the plantuml.jar file. If left blank, it is assumed
-# PlantUML is not used or called during a preprocessing step. Doxygen will
-# generate a warning when it encounters a \startuml command in this case and
-# will not generate output for the diagram.
-
-PLANTUML_JAR_PATH =
-
-# When using plantuml, the PLANTUML_CFG_FILE tag can be used to specify a
-# configuration file for plantuml.
-
-PLANTUML_CFG_FILE =
-
-# When using plantuml, the specified paths are searched for files specified by
-# the !include statement in a plantuml block.
-
-PLANTUML_INCLUDE_PATH =
-
-# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes
-# that will be shown in the graph. If the number of nodes in a graph becomes
-# larger than this value, doxygen will truncate the graph, which is visualized
-# by representing a node as a red box. Note that doxygen if the number of direct
-# children of the root node in a graph is already larger than
-# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note that
-# the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
-# Minimum value: 0, maximum value: 10000, default value: 50.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_GRAPH_MAX_NODES = 50
-
-# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the graphs
-# generated by dot. A depth value of 3 means that only nodes reachable from the
-# root by following a path via at most 3 edges will be shown. Nodes that lay
-# further from the root node will be omitted. Note that setting this option to 1
-# or 2 may greatly reduce the computation time needed for large code bases. Also
-# note that the size of a graph can be further restricted by
-# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
-# Minimum value: 0, maximum value: 1000, default value: 0.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-MAX_DOT_GRAPH_DEPTH = 0
-
-# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent
-# background. This is disabled by default, because dot on Windows does not seem
-# to support this out of the box.
-#
-# Warning: Depending on the platform used, enabling this option may lead to
-# badly anti-aliased labels on the edges of a graph (i.e. they become hard to
-# read).
-# The default value is: NO.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_TRANSPARENT = NO
-
-# Set the DOT_MULTI_TARGETS tag to YES to allow dot to generate multiple output
-# files in one run (i.e. multiple -o and -T options on the command line). This
-# makes dot run faster, but since only newer versions of dot (>1.8.10) support
-# this, this feature is disabled by default.
-# The default value is: NO.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_MULTI_TARGETS = NO
-
-# If the GENERATE_LEGEND tag is set to YES doxygen will generate a legend page
-# explaining the meaning of the various boxes and arrows in the dot generated
-# graphs.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-GENERATE_LEGEND = YES
-
-# If the DOT_CLEANUP tag is set to YES, doxygen will remove the intermediate dot
-# files that are used to generate the various graphs.
-# The default value is: YES.
-# This tag requires that the tag HAVE_DOT is set to YES.
-
-DOT_CLEANUP = YES
-
-# (optionally) Include part of a configuration file from another configuration file.
-#
-# Because this @INCLUDE happens at the end of this config file, the settings in the
-# included config file will override the settings above.
-
-@INCLUDE = $(DOXYGEN_INCLUDE)
\ No newline at end of file
diff --git a/doc/diagram_source/PLL_block_diagram.drawio b/doc/diagram_source/PLL_block_diagram.drawio
new file mode 100644
index 00000000..a3087952
--- /dev/null
+++ b/doc/diagram_source/PLL_block_diagram.drawio
@@ -0,0 +1,66 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/doc/diagram_source/lut_pll.drawio b/doc/diagram_source/lut_pll.drawio
new file mode 100644
index 00000000..d3d7742d
--- /dev/null
+++ b/doc/diagram_source/lut_pll.drawio
@@ -0,0 +1,80 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/doc/diagram_source/resource_setup_sw_pll_i2s_slave_example.drawio b/doc/diagram_source/resource_setup_sw_pll_i2s_slave_example.drawio
new file mode 100644
index 00000000..26b4b269
--- /dev/null
+++ b/doc/diagram_source/resource_setup_sw_pll_i2s_slave_example.drawio
@@ -0,0 +1,124 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/doc/diagram_source/resource_setup_sw_pll_simple_example.drawio b/doc/diagram_source/resource_setup_sw_pll_simple_example.drawio
new file mode 100644
index 00000000..a2a09979
--- /dev/null
+++ b/doc/diagram_source/resource_setup_sw_pll_simple_example.drawio
@@ -0,0 +1,130 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/doc/diagram_source/sdm_pll.drawio b/doc/diagram_source/sdm_pll.drawio
new file mode 100644
index 00000000..d5641a57
--- /dev/null
+++ b/doc/diagram_source/sdm_pll.drawio
@@ -0,0 +1,54 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/doc/diagram_source/sdm_threads.drawio b/doc/diagram_source/sdm_threads.drawio
new file mode 100644
index 00000000..317c58d3
--- /dev/null
+++ b/doc/diagram_source/sdm_threads.drawio
@@ -0,0 +1,37 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/doc/diagram_source/sw_pll_model_architecture.drawio b/doc/diagram_source/sw_pll_model_architecture.drawio
new file mode 100644
index 00000000..d7b6f38e
--- /dev/null
+++ b/doc/diagram_source/sw_pll_model_architecture.drawio
@@ -0,0 +1,47 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/doc/exclude-patterns.inc b/doc/exclude-patterns.inc
index 1cd66753..03f27852 100644
--- a/doc/exclude-patterns.inc
+++ b/doc/exclude-patterns.inc
@@ -1,14 +1,12 @@
# The following patterns are to be excluded from the documentation build
-documents/README.rst
-xcore_sdk
+LICENSE.rst
+CHANGELOG.rst
+README.rst
+README.md
+modules
test
build
-# Do not build .md files
-
-*.md
-**/*.md
-
# Do not build the app docs
examples/*
tools/*
diff --git a/doc/index.rst b/doc/index.rst
index 0687b70f..9947865f 100644
--- a/doc/index.rst
+++ b/doc/index.rst
@@ -3,6 +3,6 @@ SW PLL DOCUMENTATION
####################
.. toctree::
- :maxdepth: 2
+ :maxdepth: 3
- sw_pll
+ rst/sw_pll
diff --git a/doc/rst/images/PLL_block_diagram.png b/doc/rst/images/PLL_block_diagram.png
new file mode 100644
index 00000000..9d24548f
Binary files /dev/null and b/doc/rst/images/PLL_block_diagram.png differ
diff --git a/doc/images/sw_pll_range.png b/doc/rst/images/lut_dco_range.png
similarity index 100%
rename from doc/images/sw_pll_range.png
rename to doc/rst/images/lut_dco_range.png
diff --git a/doc/rst/images/lut_pll.png b/doc/rst/images/lut_pll.png
new file mode 100644
index 00000000..df9efd2e
Binary files /dev/null and b/doc/rst/images/lut_pll.png differ
diff --git a/doc/rst/images/modulated_fft_lut.png b/doc/rst/images/modulated_fft_lut.png
new file mode 100644
index 00000000..b839907d
Binary files /dev/null and b/doc/rst/images/modulated_fft_lut.png differ
diff --git a/doc/rst/images/modulated_fft_sdm.png b/doc/rst/images/modulated_fft_sdm.png
new file mode 100644
index 00000000..f896beb5
Binary files /dev/null and b/doc/rst/images/modulated_fft_sdm.png differ
diff --git a/doc/images/pll_step_response.png b/doc/rst/images/pll_step_response.png
similarity index 100%
rename from doc/images/pll_step_response.png
rename to doc/rst/images/pll_step_response.png
diff --git a/doc/rst/images/resource_setup_sw_pll_i2s_slave_example.png b/doc/rst/images/resource_setup_sw_pll_i2s_slave_example.png
new file mode 100644
index 00000000..ca6d8215
Binary files /dev/null and b/doc/rst/images/resource_setup_sw_pll_i2s_slave_example.png differ
diff --git a/doc/rst/images/resource_setup_sw_pll_simple_example.png b/doc/rst/images/resource_setup_sw_pll_simple_example.png
new file mode 100644
index 00000000..615ce14b
Binary files /dev/null and b/doc/rst/images/resource_setup_sw_pll_simple_example.png differ
diff --git a/doc/rst/images/sdm_dco_range.png b/doc/rst/images/sdm_dco_range.png
new file mode 100644
index 00000000..dbd22256
Binary files /dev/null and b/doc/rst/images/sdm_dco_range.png differ
diff --git a/doc/rst/images/sdm_pll.png b/doc/rst/images/sdm_pll.png
new file mode 100644
index 00000000..80dd1e6c
Binary files /dev/null and b/doc/rst/images/sdm_pll.png differ
diff --git a/doc/rst/images/sdm_threads.png b/doc/rst/images/sdm_threads.png
new file mode 100644
index 00000000..1a584a2b
Binary files /dev/null and b/doc/rst/images/sdm_threads.png differ
diff --git a/doc/rst/images/tracking_lut.png b/doc/rst/images/tracking_lut.png
new file mode 100644
index 00000000..ced9ce56
Binary files /dev/null and b/doc/rst/images/tracking_lut.png differ
diff --git a/doc/rst/images/tracking_sdm.png b/doc/rst/images/tracking_sdm.png
new file mode 100644
index 00000000..1a103d63
Binary files /dev/null and b/doc/rst/images/tracking_sdm.png differ
diff --git a/doc/rst/sw_pll.rst b/doc/rst/sw_pll.rst
new file mode 100644
index 00000000..850790e6
--- /dev/null
+++ b/doc/rst/sw_pll.rst
@@ -0,0 +1,511 @@
+How the Software PLL works
+==========================
+
+Introduction
+------------
+
+A Phase Locked Loop (PLL) is a normally dedicated hardware that allows generation of a clock which is synchronised
+to an input reference clock by both phase and frequency. They consist of a number of sub-components:
+
+ - A Phase Frequency Detector (PFD) which measures the difference (error) between a reference clock and the divided generated clock.
+ - A control loop, typically a Proportional Integral (PI) controller to close the loop and zero the error.
+ - A Digitally Controlled Oscillator (DCO) which converts a control signal into a clock frequency.
+
+.. figure:: ./images/PLL_block_diagram.png
+ :width: 100%
+
+ Basic PLL Block Diagram
+
+
+xcore-ai devices have on-chip a secondary PLL sometimes known as the Application PLL. This PLL
+multiplies the clock from the on-board crystal source and has a fractional register allowing very fine control
+over the multiplication and division ratios from software.
+
+However, it does not support an external reference clock input and so cannot natively track and lock
+to an external clock reference. This software PLL module provides a set of scripts and firmware which enables the
+provision of an input reference clock which, along with a control loop, allows tracking of the external reference
+over a certain range. It also provides a lower level API to allow tracking of virtual clocks rather than
+physical signals.
+
+There are two types of PLL, or specifically Digitally Controlled Oscillators (DCO), supported in this library.
+There are trade-offs between the two types of DCO which are summarised in the following table.
+
+.. list-table:: LUT vs SDM DCO trade-offs
+ :widths: 15 30 30
+ :header-rows: 1
+
+ * - Comparison item
+ - LUT DCO
+ - SDM DCO
+ * - Jitter
+ - Low, 1-2 ns
+ - Very Low, 10-50 ps
+ * - Memory Usage
+ - Low, ~2.5 kB
+ - Low, ~2 kB
+ * - MIPS Usage
+ - Low - ~1
+ - High - ~50
+ * - Lock Range PPM
+ - Moderate, 100-1000
+ - Wide, 1500-3000
+
+LUT based DCO
+-------------
+
+The LUT based DCO allows a discrete set of fractional settings resulting in a fixed number of frequency steps.
+The LUT is pre-computed table which provides a set of monotonically increasing frequency register settings. The LUT
+based DCO requires very low compute allowing it to be run in a sample-based loop at audio
+frequencies such as 48kHz or 44.1kHz. It required two bytes per LUT entry and provides reasonable
+jitter performance suitable for voice or entry level Hi-Fi.
+
+.. figure:: ./images/lut_pll.png
+ :width: 100%
+
+ LUT DCO based PLL
+
+
+The range is governed by the look up table (LUT) which has a finite number of entries and consequently
+has a frequency step size. This affects the output jitter performance when the controller oscillates between two
+settings once locked. Note that the actual range and number of steps is highly configurable.
+
+.. figure:: ./images/lut_dco_range.png
+ :width: 100%
+
+ Example of LUT Discrete Output Frequencies
+
+
+The index into the LUT is controlled by a
+PI controller which multiplies the error input and integral error input by the supplied loop constants.
+An integrated `wind up` limiter for the integral term is nominally set at 2x the maximum LUT index
+deviation to prevent excessive overshoot where the starting input error is high. A double integrator term
+is also available to help zero phase error.
+
+A time domain plot of how the controller (typically running at around 100 Hz) selects between adjacent
+LUT entries, and the consequential frequency modulation effect, can be seen in the following diagrams.
+
+.. figure:: ./images/tracking_lut.png
+ :width: 100%
+
+ LUT selection when tracking a constant input frequency
+
+.. figure:: ./images/modulated_fft_lut.png
+ :width: 100%
+
+ LUT noise plot when when tracking a constant input frequency
+
+SDM Based DCO
+-------------
+
+The SDM based DCO provides a fixed number (9 in this case) of frequency steps which are jumped between
+at a high rate (eg. 1 MHz) but requires a dedicated logical core to run the SDM algorithm and update the PLL
+fractional register. The SDM is third order.
+
+The SDM typically provides better audio quality by pushing the noise floor up into the
+inaudible part of the spectrum. A fixed set of SDM coefficients and loop filters are provided which
+have been hand tuned to provide either 24.576 MHz or 22.5792 MHz low jitter clocks and are suitable for Hi-Fi
+and professional audio applications.
+
+.. figure:: ./images/sdm_pll.png
+ :width: 100%
+
+ SDM DCO based PLL
+
+The steps for the SDM output are quite large which means a wide range is typically available.
+
+.. figure:: ./images/sdm_dco_range.png
+ :width: 100%
+
+ SDM discrete output frequencies
+
+A time domain plot of how the Sigma Delta Modulator jumps rapidly between multiple frequencies and the consequential
+spread of the noise floor can be seen in the following diagrams.
+
+.. figure:: ./images/tracking_sdm.png
+ :width: 100%
+
+ SDM frequency selection when tracking a constant input frequency
+
+.. figure:: ./images/modulated_fft_sdm.png
+ :width: 100%
+
+ SDM noise plot when when tracking a constant input frequency
+
+Phase Frequency Detector
+------------------------
+
+The Software PLL PFD detects frequency by counting clocks over a specific time period. The clock counted is the output from the PLL and the
+time period over which the count happens is a multiple of the input reference clock. This way the frequency difference between the
+input and output clock can be directly measured by comparing the read count increment with the expected count increment for the
+nominal case where the input and output are locked.
+
+The PFD cannot directly measure phase, however, by taking the time integral of the frequency we can derive the phase which can be done
+by the PI controller.
+
+The PFD uses three chip resources:
+
+- A one bit port to capture the PLL output clock (always Port 1D on Tile[1] of xcore-ai)
+- A clock block to turn the captured PLL output clock into a signal which can be distributed across the xcore tile
+- An input port (either one already in use or an unconnected dummy port such as Port 32A) clocked from the above clock block. The in-built counter of this port
+ can then be read and provides a count of the PLL output clock.
+
+Two diagrams showing practical xcore resource setups are shown in the `Example Applictaion Resource Setup`_ section.
+
+The port timers are 16 bits and so the PFD must account for wrapping because the overflow period at, for example, 24.576 MHz
+is 2.67 milliseconds and a typical control period is in the order 10 milliseconds.
+
+There may be cases where the port timer sampling time cannot be guaranteed to be fully isochronous, such as when a significant number of
+instructions exist between a hardware event occur between the reference clock transition and the port timer sampling. In these cases
+an optional jitter reduction scheme is provided allow scaling of the read port timer value. This scheme is used in the ``i2s_slave_lut``
+example where the port timer read is precisely delayed until the transition of the next BCLK which removes the instruction timing jitter
+that would otherwise be present. The cost is 1/64th of LR clock time of lost processing in the I2S callbacks but the benefit is the jitter
+caused by variable instruction timing to be eliminated.
+
+
+Proportional Integral Controller
+--------------------------------
+
+The PI controller uses fixed point (15Q16) types and 64 bit intermediate terms to calculate the error and accumulated error which are summed to produce the
+output. In addition a double integral term is included to allow calculation of the integral term of phase error, which itself
+is the integral of the frequency error which is the output from the PFD.
+
+Wind-up protection is included in the PI controller which clips the integral and double integral accumulator terms and is nominally
+set to LUT size for the LUT based DCO and the control range for the SDM based DCO.
+
+The SDM controller also includes a low-pass filter for additional jitter reduction.
+
+See the `Tuning the Software PLL`_ section for information about how to optimise the PI controller.
+
+Simulation Model
+================
+
+A complete model of the Software PLL is provided and is written in Python version 3.
+
+Contents
+--------
+
+In the ``python/sw_pll`` directory you will find multiple files::
+
+ .
+ ├── analysis_tools.py
+ ├── app_pll_model.py
+ ├── controller_model.py
+ ├── dco_model.py
+ ├── pfd_model.py
+ ├── pll_calc.py
+ └── sw_pll_sim.py
+
+These are all installable as a Python PIP module by running ``pip install -e .`` from the root of the repo.
+
+Typically you do not need to access any file other than ``sw_pll_sim.py`` which brings in the other files as modules when run.
+
+``analysis_tools.py`` contains audio analysis tools for assessing the frequency modulation of a tone from the jitter in
+the recovered clock.
+
+``controller_model.py`` models the PI controllers used in the Software PLL system.
+
+``dco_model.py`` contains a model of the LUT and SDM digitally controlled oscillators.
+
+``pfd_model.py`` models the Phase Frequency Detector which is used when inputting a reference clock to the Software PLL.
+
+
+``app_pll_model.py`` models the Application PLL hardware and allows reading/writing include files suitable for inclusion into xcore
+firmware projects.
+
+``pll_calc.py`` is the command line script that generates the LUT. It is quite a complex to use script which requires in depth
+knowledge of the operation of the App PLL. Instead it is recommended to use ``app_pll_model.py`` which calls ``pll_calc.py`` which
+wraps the script with sensible defaults, or better, use one of the provided profiles driven by ``sw_pll_sim.py``.
+
+Running the PI simulation and LUT generation script
+---------------------------------------------------
+
+By running ``sw_pll_sim.py`` a number of operations will take place:
+
+ - The ``fractions.h`` LUT include file will be generated (LUT PLL only - this is not needed by SDM)
+ - The ``register_setup.h`` PLL configuration file will be generated for inclusion in your xcore project.
+ - A graphical view of the LUT settings showing index vs. output frequency is generated.
+ - A time domain simulation of the PI loop showing the response to steps and out of range reference inputs is run.
+ - A wave file containing a 1 kHz modulated tone for offline analysis.
+ - A log FFT plot of the 1 kHz tone to see how the PLL frequency steps affect a pure tone.
+ - A summary report of the PLL range is also printed to the console.
+
+The directory listing following running of ``sw_pll_sim.py`` will be added to as follows::
+
+ .
+ ├── fractions.h
+ ├── register_setup.h
+ ├── tracking_lut.png
+ ├── tracking_sdm.png
+ ├── modulated_tone_1000Hz_lut.wav
+ ├── modulated_tone_1000Hz_sdm.wav
+ ├── modulated_fft_lut.png
+ └── modulated_fft_sdm.png
+
+
+Below you can see the step response of the control loop when the target frequency is changed during the simulation.
+You can see it track smaller step changes but for the
+larger steps it can be seen to clip and not reach the input step, which is larger than the used LUT size will
+allow. The LUT size can be increased if needed to accommodate a wider range.
+
+The step response is quite fast and you can see even a very sharp change in frequency is accommodated in just
+a handful of control loop iterations.
+
+.. image:: ./images/pll_step_response.png
+ :width: 100%
+
+
+Tuning the Software PLL
+=======================
+
+LUT based PLL Tuning
+--------------------
+
+PI controller
+.............
+
+Typically the PID loop tuning should start with 0 *Kp* term and a small (e.g. 1.0) *Ki* term.
+
+ - Decreasing the ref_to_loop_call_rate parameter will cause the control loop to execute more frequently and larger constants will be needed.
+ - Try tuning *Ki* value until the desired response curve (settling time, overshoot etc.) is achieved in the ``tracking_xxx.png`` output.
+ - *Kp* can normally remain zero, but you may wish to add a small value to improve step response
+
+.. note::
+ After changing the configuration, ensure you delete `fractions.h` otherwise the script will re-use the last calculated values. This is done to speed execution time of the script by avoiding the generation step.
+
+A double integral term is supported in the PI loop because the the clock counting PFD included measures
+the frequency error. The phase error is the integral of the frequency error and hence if phase locking
+is required as well as frequency locking then we need to support the integral of the integral of
+the frequency error. Changing the Kp, Ki and Kii constants and observing the simulated (or hardware response)
+to a reference change is all that is needed in this case.
+
+.. note::
+ In the python simulation file ``sw_pll_sim.py``, the PI constants *Kp*, *Ki* and optionally *Kii* can be found in the functions `run_lut_sw_pll_sim()` and `run_sd_sw_pll_sim()`.
+
+Typically a small Kii term is used, if needed, because it accumulates very quickly.
+
+
+LUT Example Configurations
+..........................
+
+The LUT implementation requires an offline generation stage which has many possibilities for customisation.
+
+A number of example configurations, which demonstrate the effect on PPM, step size etc. of changing various parameters, is provided in the ``sw_pll_sim.py`` file.
+Search for ``profiles`` and ``profile_choice`` in this file. Change profile choice index to select the different example profiles and run the python file again.
+
+.. list-table:: Example LUT DCO configurations
+ :widths: 50 50 50 50 50
+ :header-rows: 1
+
+ * - Output frequency MHz
+ - Reference frequency kHz
+ - Range +/- PPM
+ - Average step size Hz
+ - LUT size bytes
+ * - 12.288
+ - 48.0
+ - 250
+ - 29.3
+ - 426
+ * - 12.288
+ - 48.0
+ - 500
+ - 30.4
+ - 826
+ * - 12.288
+ - 48.0
+ - 1000
+ - 31.0
+ - 1580
+ * - 24.576
+ - 48.0
+ - 500
+ - 60.8
+ - 826
+ * - 24.576
+ - 48.0
+ - 100
+ - 9.5
+ - 1050
+ * - 6.144
+ - 16.0
+ - 150
+ - 30.2
+ - 166
+
+.. note::
+ The physical PLL actually multiplies the input crystal, not the reference input clock.
+ It is the PFD and software control loop that detects the frequency error and controls the fractional register to make the PLL track the input.
+ A change in the reference input clock parameter only affects the control loop and its associated constants such as how often the PI controller is called.
+
+
+Custom LUT Generation Guidance
+..............................
+
+The fractions lookup table is a trade-off between PPM range and frequency step size. Frequency
+step size will affect jitter amplitude as it is the amount that the PLL will change frequency when it needs
+to adjust. Typically, the locked control loop will slowly oscillate between two values that
+straddle the target frequency, depending on input frequency.
+
+Small discontinuities in the LUT may be experienced in certain ranges, particularly close to 0.5 fractional values, so it is preferable
+to keep in the lower or upper half of the fractional range. However the LUT table is always monotonic
+and so control instability will not occur for that reason. The range of the LUT Software PLL can be seen
+in the ``lut_dco_range.png`` image. It should be a reasonably linear response without significant
+discontinuities. If discontinuities are seen, try moving the range towards 0.0 or 1.0 where fewer discontinuities may
+be observed due the step in the fractions.
+
+Steps to vary the LUT PPM range and frequency step size
+.......................................................
+
+
+1. Ascertain your target PPM range, step size and maximum tolerable table size. Each lookup value is 16 bits so the total size in bytes is 2 * n.
+2. Start with the given example values and run the generator to see if the above three parameters meet your needs. The values are reported by ``sw_pll_sim.py``.
+3. If you need to increase the PPM range, you may either:
+ - Decrease the ``min_F`` to allow the fractional value to have a greater effect. This will also increase step size. It will not affect the LUT size.
+ - Increase the range of ``fracmin`` and ``fracmax``. Try to keep the range closer to 0 or 1.0. This will decrease step size and increase LUT size.
+4. If you need to decrease the step size you may either:
+ - Increase the ``min_F`` to allow the fractional value to have a greater effect. This will also reduce the PPM range. When the generation script is run the allowable F values are reported so you can tune the ``min_F`` to force use of a higher F value.
+ - Increase the ``max_denom`` beyond 80. This will increase the LUT size (finer step resolution) but not affect the PPM range. Note this will increase the intrinsic jitter of the PLL hardware on chip due to the way the fractional divider works. 80 has been chosen for a reasonable tradeoff between step size and PLL intrinsic jitter and pushes this jitter beyond 40 kHz which is out of the audio band. The lowest intrinsic fractional PLL jitter freq is input frequency (normally 24 MHz) / ref divider / largest value of n.
+5. If the +/-PPM range is not symmetrical and you wish it to be, then adjust the ``fracmin`` and ``fracmax`` values around the center point that the PLL finder algorithm has found. For example if the -PPM range is to great, increase ``fracmin`` and if the +PPM range is too great, decrease the ``fracmax`` value.
+
+
+.. note::
+ When the process has completed, please inspect the ``lut_dco_range.png`` output figure which shows how the fractional PLL setting affects the output frequency.
+ This should be monotonic and not contain an significant discontinuities for the control loop to operate satisfactorily.
+
+SDM based PLL Tuning
+--------------------
+
+SDM Available Configurations
+............................
+
+The SDM implementation only allows tuning of the PI loop; the DCO section is hand optimised for the provided profiles shown
+below. There are two target PLL output frequencies and two options for SDM update rate depending on how much performance
+is available from the SDM task.
+
+
+.. list-table:: SDM DCO configurations
+ :widths: 50 50 50 50 50
+ :header-rows: 1
+
+ * - Output frequency MHz
+ - Range +/- PPM
+ - Jitter ps
+ - Noise Floor dBc
+ - SDM update rate kHz
+ * - 24.576
+ - 3000
+ - 10
+ - -100
+ - 1000
+ * - 22.5792
+ - 3300
+ - 10
+ - -100
+ - 1000
+ * - 24.576
+ - 1500
+ - 50
+ - -93
+ - 500
+ * - 22.5792
+ - 1500
+ - 50
+ - -93
+ - 500
+
+The SDM based DCO Software PLL has been pre-tuned and should not need modification in normal circumstances. Due to the large control range values
+needed by the SDM DCO, a relatively large integral term is used which applies a gain term. If you do need to tune the SDM DCO PI controller then
+it is recommended to start with the provided values in the example in ``/examples/simple_sdm``.
+
+Transferring the results to C
+-----------------------------
+
+Once the LUT has been generated or SDM profile selected and has simulated in Python, the values can be transferred to the firmware application. Control loop constants
+can be directly transferred to the `init()` functions and the generated `.h` files can be copied directly into the source directory
+of your project.
+
+For further information, either consult the ``sw_pll.h`` API file (included at the end of this document) or follow one of the examples in the ``/examples`` directory.
+
+
+
+Example Application Resource Setup
+==================================
+
+The xcore-ai device has a number of resources on chip which can be connected together to manage signals and application clocks.
+In the provided examples both `clock blocks` and `ports` are connected together to provide an input to
+the PFD which calculates frequency error. Resources are additionally provide an optional prescaled output clock for comparison with the input reference.
+
+Simple Example Resource Setup
+-----------------------------
+
+The output from the PLL is counted using a port timer via the `clk_mclk` clock block.
+
+In addition, a precise timing barrier is implemented by clocking a dummy port from the clock block
+clocked by the reference clock input. This provides a precise sampling point of the PLL output clock count.
+
+The resource setup code is contained in ``resource_setup.h`` and ``resource_setup.c`` using intrinsic functions in ``lib_xcore``.
+To help visualise how these resources work together, please see the below diagram.
+
+.. figure:: ./images/resource_setup_sw_pll_simple_example.png
+ :width: 100%
+
+ Use of Ports and Clock Blocks in the Simple Examples
+
+
+I2S Slave Example Resource Setup
+--------------------------------
+
+The I2S slave component already uses a clock block which captures the bit clock input. In addition to this,
+the PLL output is used to clock a dummy port's counter which is used as the input to the PFD.
+
+Since the precise sampling time of the PLL output clock count is variable due to instruction timing between
+the I2S LRCLK transition and the capture of the PLL output clock count in the I2S callback, an additional dummy port is used.
+This precisely synchronises the capture of the PLL output clock count relative to the BCLK transition and
+the relationship between these is used to reconstruct the absolute frequency difference with minimal input jitter.
+
+.. figure:: ./images/resource_setup_sw_pll_i2s_slave_example.png
+ :width: 100%
+
+ Use of Ports and Clock Blocks in the I2S Slave Example
+
+Software PLL API
+================
+
+The Application Programmer Interface (API) for the Software PLL is shown below. It is split into items specific to LUT and SDM DCOs .
+
+In addition to the standard API which takes a clock counting input (implements the PFD), for applications where the PLL is
+to be controlled using an alternatively derived error input, a low-level API is also provided. This low-level
+API allows the Software PLL to track an arbitrary clock source which is calculated by another means such as timing of received packets
+over a communications interface.
+
+LUT Based PLL API
+-----------------
+
+The LUT based API are functions designed to be called from an audio loop. Typically the functions can take up to 210 instruction cycles when control occurs and just a few 10s of cycles when control does not occur. If run at a rate of 48 kHz then it will consume approximately 1 MIPS on average.
+
+.. doxygengroup:: sw_pll_lut
+ :content-only:
+
+SDM Based PLL API
+-----------------
+
+All SDM API items are function calls. The SDM API requires a dedicated logical core to perform the SDM calculation and periodic register write and it is expected that the user provide the fork (par) and call to the SDM.
+
+A typical design idiom is to have the task running in a loop with a timing barrier (either 1 us or 2 us depending on profile used) and a non-blocking channel poll which allows new DCO control values to be received as needed at the control loop rate. The SDM calculation and register write takes 45 instruction cycles and so with the overheads of the timing barrier and the non-blocking channel receive poll, a minimum 60 MHz logical core should be set aside for the SDM task running at 1 us period.
+This can be approximately halved it running at 2 us SDM period.
+
+The control part of the SDM SW PLL takes 75 instruction cycles when active and a few 10 s of cycles when inactive so you will need to budget around 1 MIPS for this when
+being called at 48 kHz with a control rate of one in every 512 cycles.
+
+An example of how to implement the threading, timing barrier and non-blocking channel poll can be found in ``examples/simple_sdm/simple_sw_pll_sdm.c``. A thread diagram of how this can look is shown below.
+
+
+.. figure:: ./images/sdm_threads.png
+ :width: 100%
+
+ Example Thread Diagram of SDM SW PLL
+
+
+.. doxygengroup:: sw_pll_sdm
+ :content-only:
+
diff --git a/doc/settings.json b/doc/settings.json
deleted file mode 100644
index 28c2bf8d..00000000
--- a/doc/settings.json
+++ /dev/null
@@ -1,8 +0,0 @@
-{
- "title": "XMOS SW PLL",
- "project": "SW PLL",
- "version": "1.1.0",
- "architectures": {
- "xcore.ai": ["15.2.x"]
- }
-}
diff --git a/doc/substitutions.inc b/doc/substitutions.inc
new file mode 100644
index 00000000..879f87b5
--- /dev/null
+++ b/doc/substitutions.inc
@@ -0,0 +1,3 @@
+.. |trademark| replace:: :sup:`TM`
+.. |processor| replace:: xcore.ai
+ :trim:
diff --git a/doc/substitutions.rst-inc b/doc/substitutions.rst-inc
deleted file mode 100644
index 65b3d554..00000000
--- a/doc/substitutions.rst-inc
+++ /dev/null
@@ -1,17 +0,0 @@
-.. |full_version_str| replace:: v1.1.0
-.. |tools_version| replace:: 15.2.x
-.. |I2S| replace:: I\ :sup:`2`\ S
-.. |I2C| replace:: I\ :sup:`2`\ C
-.. |trademark| replace:: :sup:`TM`
-.. |xflash manual| replace:: `*xflash Manual*`
-.. _xflash manual: https://www.xmos.ai/view/Tools-15-Documentation
-.. |XTC tools| replace:: `*XTC Tools*`
-.. _XTC tools: https://www.xmos.ai/view/Tools-15-Documentation
-.. |XMOS xCORE Programming Guide| replace:: `*XMOS xCORE Programming Guide*`
-.. _XMOS xCORE Programming Guide: https://www.xmos.ai/file/tools-user-guide
-.. |processor| replace:: xcore.ai
-.. |---| unicode:: U+02014 .. em dash
-.. |deg| unicode:: U+000B0 .. DEGREE SIGN
-.. |mgr| unicode:: U+003BC .. GREEK SMALL LETTER MU
-.. |reg| unicode:: U+000AE .. REGISTERED SIGN
- :trim:
diff --git a/doc/sw_pll.rst b/doc/sw_pll.rst
deleted file mode 100644
index 5e736420..00000000
--- a/doc/sw_pll.rst
+++ /dev/null
@@ -1,211 +0,0 @@
-How the Software PLL works
---------------------------
-
-The XCORE-AI devices come with a secondary PLL sometimes called the Application (App) PLL. This PLL
-multiplies the clock from the on-board crystal source and has a fractional register allowing very fine control
-over the multiplication and division ratios.
-
-However, it does not support an external reference clock input and so cannot natively track and lock
-to an external clock reference. This SW-PLL module is a set of scripts and firmware which enables the
-provision of an input clock which, along with a control loop, allows tracking of the external reference
-over a certain range.
-
-The range is governed by the look up table (LUT) which has a finite number of entries and consequently
-a step size which affects the output jitter performance. The index into the LUT is controlled by a
-PI controller which multiplies the error in put and integral error input by the supplied loop constants.
-An integrated wind up limiter for the integral term is nominally set at 2x the maximum LUT index
-deviation to prevent excessive overshoot where the starting input error is high.
-
-In addition to the standard API which takes a clock counting input, for applications where the PLL is
-to be controlled using a PI fed with a raw error input, a low-level API is also provided. This low-level
-API allows the Software PLL to track an arbitrary clock source which is calculated by another means.
-
-This document provides a guide to generating the LUT and configuring the available parameters to
-reach the appropriate compromise of performance and resource usage for your application.
-
-
-
-Running the PI simulation and LUT generation script
----------------------------------------------------
-
-In the ``python/sw_pll`` directory you will find two files::
-
- .
- ├── pll_calc.py
- └── sw_pll_sim.py
-
-``pll_calc.py`` is the command line script that generates the LUT. It is quite a complex to use script which requires in depth
-knowledge of the operation of the App PLL. Instead, it is recommended to use ``sw_pll_sim.py`` which calls ``pll_calc.py``
-except with a number of example PLL profiles already provided as a starting point.
-
-By running `sw_pll_sim.py` a number of operations will take place:
-
- - The ``fractions.h`` LUT include file will be generated.
- - The ``register_setup.h`` PLL configuration file will be generated.
- - A graphical view of the LUT settings ``sw_pll_range.png`` showing index vs. output frequency is generated.
- - A time domain simulation of the PI loop showing the response to steps and out of range reference inputs is run.
- - A graphical view of the simulation is saved to ``pll_step_response.png``.
- - A wave file containing a 1 kHz modulated tone for offline analysis. Note that ``ppm_shifts`` will need to be set to ``()`` otherwise it will contain the injected PPM deviations as part of the step response test.
- - A zoomed-in log FFT plot of the 1 kHz tone to see how the LUT frequency steps affect a pure tone. The same note applies as the above item.
- - A summary report of the PLL range is printed to the console.
-
-The directory listing following running of ``sw_pll_sim.py`` should look as follows::
-
- .
- ├── fractions.h
- ├── pll_calc.py
- ├── pll_step_response.png
- ├── register_setup.h
- ├── sw_pll_range.png
- ├── modulated_tone_1000Hz.wav
- ├── modulated_tone_fft_1000Hz.png
- └── sw_pll_sim.py
-
-
-A typical LUT transfer function is shown below. Note that although not perfectly regular it is monotonic and hence
-the control loop will work well with it. This is an artifact of the fractional setting steps available.
-You can also see the actual frequency oscillate very slightly over time. This is because the control loop hunts
-between two discrete fractional settings in the LUT and is expected. You may adjust the rate at which the control
-loop is called to center this noise around different frequencies or decrease the step size (larger LUT) to
-manage the amplitude of this artifact.
-
-.. image:: ./images/sw_pll_range.png
- :width: 500
-
-
-Here you can see the step response of the control loop below. You can see it track smaller step changes but for the
-larger steps it can be seen to clip and not reach the input step, which is larger than the LUT size will
-allow. The LUT size can be increased if needed to accommodate a wider range.
-
-The step response is quite fast and you can see even a very sharp change in frequency is accommodated in just
-a handful of control loop iterations.
-
-.. image:: ./images/pll_step_response.png
- :width: 500
-
-Note that each time you run ``sw_pll_sim.py`` and the ``fractions.h`` file is produced, a short report will be produced that indicates the achieved range of settings.
-Below is a typical report showing what information is summarised::
-
- $ rm -f fractions.h && python sw_pll_sim.py
- Running: lib_sw_pll/python/sw_pll/pll_calc.py -i 24.0 -a -m 80 -t 12.288 -p 6.0 -e 5 -r --fracmin 0.695 --fracmax 0.905 --header
- Available F values: [30, 32, 77, 79, 116, 118, 122, 159, 163, 165, 200, 204, 208, 245, 286, 331, 417]
- output_frequency: 12288000.0, vco_freq: 2457600000.0, F: 203, R: 1, f: 3, p: 4, OD: 1, ACD: 24, ppm: 0.0
- PLL register settings F: 203, R: 1, OD: 1, ACD: 24, f: 3, p: 4
- min_freq: 12281739Hz
- mid_freq: 12288000Hz
- max_freq: 12294286Hz
- average step size: 30.3791Hz, PPM: 2.47226
- PPM range: -509.771
- PPM range: +511.533
- LUT entries: 413 (826 bytes)
-
-
-The following section provides guidance for adjusting the LUT.
-
-How to configure the fractions table
-------------------------------------
-
-The fractions lookup table is a trade-off between PPM range and frequency step size. Frequency
-step size will affect jitter amplitude as it is the amount that the PLL will change frequency when it needs
-to adjust. Typically, the locked control loop will slowly oscillate between two values that
-straddle the target frequency, depending on input frequency.
-
-Small discontinuities in the LUT may be experienced in certain ranges, particularly close to 0.5 fractional values, so it is preferable
-to keep in the lower or upper half of the fractional range. However the LUT table is always monotonic
-and so control instability will not occur for that reason. The range of the ``sw_pll`` can be seen
-in the ``sw_pll_range.png`` image. It should be a reasonably linear response without significant
-discontinuities. If not, try moving the range towards 0.0 or 1.0 where fewer discontinuities will
-be observed.
-
-Steps to vary PPM range and frequency step size
------------------------------------------------
-
-
-1. Ascertain your target PPM range, step size and maximum tolerable table size. Each lookup value is 16b so the total size in bytes is 2 x n.
-2. Start with the given example values and run the generator to see if the above three parameters meet your needs. The values are reported by ``sw_pll_sim.py``.
-3. If you need to increase the PPM range, you may either:
- - Decrease the ``min_F`` to allow the fractional value to have a greater effect. This will also increase step size. It will not affect the LUT size.
- - Increase the range of ``fracmin`` and ``fracmax``. Try to keep the range closer to 0 or 1.0. This will decrease step size and increase LUT size.
-4. If you need to decrease the step size you may either:
- - Increase the ``min_F`` to allow the fractional value to have a greater effect. This will also reduce the PPM range. When the generation script is run the allowable F values are reported so you can tune the ``min_F`` to force use of a higher F value.
- - Increase the ``max_denom`` beyond 80. This will increase the LUT size (finer step resolution) but not affect the PPM range. Note this will increase the intrinsic jitter of the PLL hardware on chip due to the way the fractional divider works. 80 has been chosen for a reasonable tradeoff between step size and PLL intrinsic jitter and pushes this jitter beyond 40 kHz which is out of the audio band. The lowest intrinsic fractional PLL jitter freq is input frequency (normally 24 MHz) / ref divider / largest value of n.
-5. If the +/-PPM range is not symmetrical and you wish it to be, then adjust the ``fracmin`` and ``fracmax`` values around the center point that the PLL finder algorithm has found. For example if the -PPM range is to great, increase ``fracmin`` and if the +PPM range is too great, decrease the ``fracmax`` value.
-
-
-Note when the process has completed, please inspect the ``sw_pll_range.png`` output figure which shows how the fractional PLL setting affects the output frequency.
-This should be monotonic and not contain an significant discontinuities for the control loop to operate satisfactorily.
-
-Steps to tune the PI loop
--------------------------
-
-Note, in the python simulation file ``sw_pll_sim.py``, the PI constants *Kp* and *Ki* can be found in the function `run_sim()`.
-
-Typically the PID loop tuning should start with 0 *Kp* term and a small (e.g. 1.0) *Ki* term.
-
- - Decreasing the ref_to_loop_call_rate parameter will cause the control loop to execute more frequently and larger constants will be needed.
- - Try tuning *Ki* value until the desired response curve (settling time, overshoot etc.) is achieved in the ``pll_step_response.png`` output.
- - *Kp* can normally remain zero, but you may wish to add a small value to improve step response
-
-.. note::
- After changing the configuration, ensure you delete `fractions.h` otherwise the script will re-use the last calculated values. This is done to speed execution time of the script by avoiding the generation step.
-
-Example configurations
-----------------------
-
-A number of example configurations, which demonstrate the effect on PPM, step size etc. of changing various parameters, is provided in the ``sw_pll_sim.py`` file.
-Search for ``profiles`` and ``profile_choice`` in this file. Change profile choice index to select the different example profiles and run the python file again.
-
-.. list-table:: xscope throughput
- :widths: 50 50 50 50 50
- :header-rows: 1
-
- * - Output frequency MHz
- - Reference frequency kHz
- - Range +/- PPM
- - Average step size Hz
- - LUT size bytes
- * - 12.288
- - 48.0
- - 250
- - 29.3
- - 426
- * - 12.288
- - 48.0
- - 500
- - 30.4
- - 826
- * - 12.288
- - 48.0
- - 500
- - 31.0
- - 1580
- * - 24.576
- - 48.0
- - 500
- - 60.8
- - 826
- * - 24.576
- - 48.0
- - 100
- - 9.5
- - 1050
- * - 6.144
- - 16.0
- - 150
- - 30.2
- - 166
-
-Note that the PLL actually multiplies the input crystal, not the reference input clock. A change in the reference input clock only affects the control loop
-and its associated constants such as how often the PI loop is called.
-
-Transferring the results to C
------------------------------
-
-Once the LUT has been generated and simulated in Python, the values can be transferred to the firmware application. Either consult the ``sw_pll.h`` API file (below) for details or follow one of the examples in the ``/examples`` directory.
-
-lib_sw_pll API
---------------
-
-.. doxygengroup:: sw_pll_api
- :content-only:
-
diff --git a/examples/examples.cmake b/examples/examples.cmake
index 4c8785d3..5aa41fe7 100644
--- a/examples/examples.cmake
+++ b/examples/examples.cmake
@@ -1,2 +1,3 @@
-include(${CMAKE_CURRENT_LIST_DIR}/simple/simple.cmake)
-include(${CMAKE_CURRENT_LIST_DIR}/i2s_slave/i2s_slave.cmake)
+include(${CMAKE_CURRENT_LIST_DIR}/simple_lut/simple_lut.cmake)
+include(${CMAKE_CURRENT_LIST_DIR}/simple_sdm/simple_sdm.cmake)
+include(${CMAKE_CURRENT_LIST_DIR}/i2s_slave_lut/i2s_slave_lut.cmake)
diff --git a/examples/i2s_slave/i2s_slave.cmake b/examples/i2s_slave_lut/i2s_slave_lut.cmake
similarity index 62%
rename from examples/i2s_slave/i2s_slave.cmake
rename to examples/i2s_slave_lut/i2s_slave_lut.cmake
index bdb59d55..dca21145 100644
--- a/examples/i2s_slave/i2s_slave.cmake
+++ b/examples/i2s_slave_lut/i2s_slave_lut.cmake
@@ -32,10 +32,10 @@ set(APP_LINK_OPTIONS
#**********************
# Tile Targets
#**********************
-add_executable(i2s_slave)
-target_sources(i2s_slave PUBLIC ${APP_SOURCES})
-target_include_directories(i2s_slave PUBLIC ${APP_INCLUDES})
-target_compile_definitions(i2s_slave PRIVATE ${APP_COMPILE_DEFINITIONS})
-target_compile_options(i2s_slave PRIVATE ${APP_COMPILER_FLAGS})
-target_link_options(i2s_slave PRIVATE ${APP_LINK_OPTIONS})
-target_link_libraries(i2s_slave PUBLIC lib_sw_pll lib_i2s)
+add_executable(i2s_slave_lut)
+target_sources(i2s_slave_lut PUBLIC ${APP_SOURCES})
+target_include_directories(i2s_slave_lut PUBLIC ${APP_INCLUDES})
+target_compile_definitions(i2s_slave_lut PRIVATE ${APP_COMPILE_DEFINITIONS})
+target_compile_options(i2s_slave_lut PRIVATE ${APP_COMPILER_FLAGS})
+target_link_options(i2s_slave_lut PRIVATE ${APP_LINK_OPTIONS})
+target_link_libraries(i2s_slave_lut PUBLIC lib_sw_pll lib_i2s)
diff --git a/examples/i2s_slave/src/config.xscope b/examples/i2s_slave_lut/src/config.xscope
similarity index 100%
rename from examples/i2s_slave/src/config.xscope
rename to examples/i2s_slave_lut/src/config.xscope
diff --git a/examples/i2s_slave/src/fractions.h b/examples/i2s_slave_lut/src/fractions.h
similarity index 100%
rename from examples/i2s_slave/src/fractions.h
rename to examples/i2s_slave_lut/src/fractions.h
diff --git a/examples/i2s_slave/src/i2s_slave_sw_pll.c b/examples/i2s_slave_lut/src/i2s_slave_sw_pll.c
similarity index 91%
rename from examples/i2s_slave/src/i2s_slave_sw_pll.c
rename to examples/i2s_slave_lut/src/i2s_slave_sw_pll.c
index 5dc5627d..a31d8e38 100644
--- a/examples/i2s_slave/src/i2s_slave_sw_pll.c
+++ b/examples/i2s_slave_lut/src/i2s_slave_sw_pll.c
@@ -102,7 +102,7 @@ static i2s_restart_t i2s_restart_check(void *app_data){
old_mclk_pt = mclk_pt;
old_bclk_pt = bclk_pt;
- sw_pll_do_control(cb_args->sw_pll, mclk_pt, bclk_pt);
+ sw_pll_lut_do_control(cb_args->sw_pll, mclk_pt, bclk_pt);
if(cb_args->sw_pll->lock_status != cb_args->curr_lock_status){
cb_args->curr_lock_status = cb_args->sw_pll->lock_status;
@@ -175,21 +175,22 @@ void sw_pll_test(void){
printf("Initialising SW PLL\n");
sw_pll_state_t sw_pll;
- sw_pll_init(&sw_pll,
- SW_PLL_15Q16(0.0),
- SW_PLL_15Q16(1.0),
- CONTROL_LOOP_COUNT,
- PLL_RATIO,
- BCLKS_PER_LRCLK,
- frac_values_80,
- SW_PLL_NUM_LUT_ENTRIES(frac_values_80),
- APP_PLL_CTL_12288,
- APP_PLL_DIV_12288,
- APP_PLL_NOMINAL_INDEX_12288,
- PPM_RANGE);
-
-
- printf("i_windup_limit: %ld\n", sw_pll.i_windup_limit);
+ sw_pll_lut_init(&sw_pll,
+ SW_PLL_15Q16(0.0),
+ SW_PLL_15Q16(1.0),
+ SW_PLL_15Q16(0.0),
+ CONTROL_LOOP_COUNT,
+ PLL_RATIO,
+ BCLKS_PER_LRCLK,
+ frac_values_80,
+ SW_PLL_NUM_LUT_ENTRIES(frac_values_80),
+ APP_PLL_CTL_12288,
+ APP_PLL_DIV_12288,
+ APP_PLL_NOMINAL_INDEX_12288,
+ PPM_RANGE);
+
+
+ printf("i_windup_limit: %ld\n", sw_pll.pi_state.i_windup_limit);
// Initialise app_data
diff --git a/examples/i2s_slave/src/main.xc b/examples/i2s_slave_lut/src/main.xc
similarity index 100%
rename from examples/i2s_slave/src/main.xc
rename to examples/i2s_slave_lut/src/main.xc
diff --git a/examples/i2s_slave/src/xvf3800_qf60.xn b/examples/i2s_slave_lut/src/xvf3800_qf60.xn
similarity index 100%
rename from examples/i2s_slave/src/xvf3800_qf60.xn
rename to examples/i2s_slave_lut/src/xvf3800_qf60.xn
diff --git a/examples/shared/src/clock_gen.c b/examples/shared/src/clock_gen.c
new file mode 100644
index 00000000..9c7c78bb
--- /dev/null
+++ b/examples/shared/src/clock_gen.c
@@ -0,0 +1,60 @@
+// Copyright 2023 XMOS LIMITED.
+// This Software is subject to the terms of the XMOS Public Licence: Version 1.
+
+#include
+#include
+#include
+#include
+
+#include "sw_pll_common.h"
+
+#define DO_CLOCKS \
+printf("Ref Hz: %d\n", clock_rate >> 1); \
+\
+unsigned cycle_ticks_int = XS1_TIMER_HZ / clock_rate; \
+unsigned cycle_ticks_remaidner = XS1_TIMER_HZ % clock_rate; \
+unsigned carry = 0; \
+\
+period_trig += XS1_TIMER_HZ * 1; \
+unsigned time_now = hwtimer_get_time(period_tmr); \
+while(TIMER_TIMEAFTER(period_trig, time_now)) \
+{ \
+ port_out(p_clock_gen, port_val); \
+ hwtimer_wait_until(clock_tmr, time_trig); \
+ time_trig += cycle_ticks_int; \
+ carry += cycle_ticks_remaidner; \
+ if(carry >= clock_rate){ \
+ time_trig++; \
+ carry -= clock_rate; \
+ } \
+ port_val ^= 1; \
+ time_now = hwtimer_get_time(period_tmr); \
+}
+
+void clock_gen(unsigned ref_frequency, unsigned ppm_range) // Step from - to + this
+{
+ unsigned clock_rate = ref_frequency * 2; // Note double because we generate edges at this rate
+
+ unsigned clock_rate_low = (unsigned)(clock_rate * (1.0 - (float)ppm_range / 1000000.0));
+ unsigned clock_rate_high = (unsigned)(clock_rate * (1.0 + (float)ppm_range / 1000000.0));
+ unsigned step_size = (clock_rate_high - clock_rate_low) / 20;
+
+ printf("Sweep range: %d %d %d, step size: %d\n", clock_rate_low / 2, clock_rate / 2, clock_rate_high / 2, step_size);
+
+ hwtimer_t period_tmr = hwtimer_alloc();
+ unsigned period_trig = hwtimer_get_time(period_tmr);
+
+ hwtimer_t clock_tmr = hwtimer_alloc();
+ unsigned time_trig = hwtimer_get_time(clock_tmr);
+
+ port_t p_clock_gen = PORT_I2S_BCLK;
+ port_enable(p_clock_gen);
+ unsigned port_val = 1;
+
+ for(unsigned clock_rate = clock_rate_low; clock_rate <= clock_rate_high; clock_rate += 2 * step_size){
+ DO_CLOCKS
+ }
+ for(unsigned clock_rate = clock_rate_high; clock_rate > clock_rate_low; clock_rate -= 2 * step_size){
+ DO_CLOCKS
+ }
+}
\ No newline at end of file
diff --git a/examples/shared/src/clock_gen.h b/examples/shared/src/clock_gen.h
new file mode 100644
index 00000000..b2a3a475
--- /dev/null
+++ b/examples/shared/src/clock_gen.h
@@ -0,0 +1,6 @@
+// Copyright 2023 XMOS LIMITED.
+// This Software is subject to the terms of the XMOS Public Licence: Version 1.
+
+// Runs a task in a thread that produces a clock that sweeps a reference clock
+// between + and - the ppm value specified.
+void clock_gen(unsigned ref_frequency, unsigned ppm_range);
\ No newline at end of file
diff --git a/examples/shared/src/resource_setup.c b/examples/shared/src/resource_setup.c
new file mode 100644
index 00000000..f4216422
--- /dev/null
+++ b/examples/shared/src/resource_setup.c
@@ -0,0 +1,43 @@
+// Copyright 2023 XMOS LIMITED.
+// This Software is subject to the terms of the XMOS Public Licence: Version 1.
+
+#include
+#include "resource_setup.h"
+
+void setup_ref_and_mclk_ports_and_clocks(port_t p_mclk, xclock_t clk_mclk, port_t p_clock_counter, xclock_t clk_ref_clk, port_t p_ref_clk_timing)
+{
+ // Create clock from mclk port and use it to clock the p_clock_counter port.
+ clock_enable(clk_mclk);
+ port_enable(p_mclk);
+ clock_set_source_port(clk_mclk, p_mclk);
+
+ // Clock p_clock_counter from MCLK
+ port_enable(p_clock_counter);
+ port_set_clock(p_clock_counter, clk_mclk);
+
+ clock_start(clk_mclk);
+
+ // Create clock from ref_clock_port and use it to clock the p_clock_counter port.
+ clock_enable(clk_ref_clk);
+ clock_set_source_port(clk_ref_clk, p_clock_counter);
+ port_enable(p_ref_clk_timing);
+ port_set_clock(p_ref_clk_timing, clk_ref_clk);
+
+ clock_start(clk_ref_clk);
+}
+
+
+void setup_recovered_ref_clock_output(port_t p_recovered_ref_clk, xclock_t clk_recovered_ref_clk, port_t p_mclk, unsigned divider)
+{
+ // Connect clock block with divide to mclk
+ clock_enable(clk_recovered_ref_clk);
+ clock_set_source_port(clk_recovered_ref_clk, p_mclk);
+ clock_set_divide(clk_recovered_ref_clk, divider / 2);
+ printf("Divider: %u\n", divider);
+
+ // Output the divided mclk on a port
+ port_enable(p_recovered_ref_clk);
+ port_set_clock(p_recovered_ref_clk, clk_recovered_ref_clk);
+ port_set_out_clock(p_recovered_ref_clk);
+ clock_start(clk_recovered_ref_clk);
+}
\ No newline at end of file
diff --git a/examples/shared/src/resource_setup.h b/examples/shared/src/resource_setup.h
new file mode 100644
index 00000000..36b3e00f
--- /dev/null
+++ b/examples/shared/src/resource_setup.h
@@ -0,0 +1,17 @@
+// Copyright 2023 XMOS LIMITED.
+// This Software is subject to the terms of the XMOS Public Licence: Version 1.
+
+#include
+
+#pragma once
+
+// Sets up the provided resources so that we can count PLL output clocks.
+// We do this by clocking the input reference clock port with the output from the PLL
+// and its internal counter is used to count the PLL clock cycles(normal timers cannot count custom clocks)
+// It also sets up a dummy port clocked by the input reference to act as a timing barrier so that
+// the output clock count can be precisely sampled.
+void setup_ref_and_mclk_ports_and_clocks(port_t p_mclk, xclock_t clk_mclk, port_t p_clock_counter, xclock_t clk_ref_clk, port_t p_ref_clk_timing);
+
+// Sets up a divided version of the PLL output so it can visually be compared (eg. on a DSO)
+// with the input reference clock to the PLL
+void setup_recovered_ref_clock_output(port_t p_recovered_ref_clk, xclock_t clk_recovered_ref_clk, port_t p_mclk, unsigned divider);
\ No newline at end of file
diff --git a/examples/simple/simple.cmake b/examples/simple/simple.cmake
deleted file mode 100644
index 956d4558..00000000
--- a/examples/simple/simple.cmake
+++ /dev/null
@@ -1,48 +0,0 @@
-#**********************
-# Gather Sources
-#**********************
-file(GLOB_RECURSE APP_SOURCES ${CMAKE_CURRENT_LIST_DIR}/src/*.c ${CMAKE_CURRENT_LIST_DIR}/src/*.xc)
-set(APP_INCLUDES
- ${CMAKE_CURRENT_LIST_DIR}/src
-)
-
-#**********************
-# Flags
-#**********************
-set(APP_COMPILER_FLAGS
- -Os
- -g
- -report
- -fxscope
- -mcmodel=large
- -Wno-xcore-fptrgroup
- ${CMAKE_CURRENT_LIST_DIR}/src/config.xscope
- -target=XCORE-AI-EXPLORER
-)
-
-set(APP_COMPILE_DEFINITIONS
- DEBUG_PRINT_ENABLE=1
- PLATFORM_SUPPORTS_TILE_0=1
- PLATFORM_SUPPORTS_TILE_1=1
- PLATFORM_SUPPORTS_TILE_2=0
- PLATFORM_SUPPORTS_TILE_3=0
- PLATFORM_USES_TILE_0=1
- PLATFORM_USES_TILE_1=1
-)
-
-set(APP_LINK_OPTIONS
- -report
- -target=XCORE-AI-EXPLORER
- ${CMAKE_CURRENT_LIST_DIR}/src/config.xscope
-)
-
-#**********************
-# Tile Targets
-#**********************
-add_executable(simple)
-target_sources(simple PUBLIC ${APP_SOURCES})
-target_include_directories(simple PUBLIC ${APP_INCLUDES})
-target_compile_definitions(simple PRIVATE ${APP_COMPILE_DEFINITIONS})
-target_compile_options(simple PRIVATE ${APP_COMPILER_FLAGS})
-target_link_options(simple PRIVATE ${APP_LINK_OPTIONS})
-target_link_libraries(simple PUBLIC lib_sw_pll)
diff --git a/examples/simple/src/main.xc b/examples/simple/src/main.xc
deleted file mode 100644
index 8f716746..00000000
--- a/examples/simple/src/main.xc
+++ /dev/null
@@ -1,22 +0,0 @@
-// Copyright 2022-2023 XMOS LIMITED.
-// This Software is subject to the terms of the XMOS Public Licence: Version 1.
-
-#include
-#include
-
-extern void sw_pll_test(void);
-extern void clock_gen(void);
-
-int main(void)
-{
- par
- {
- on tile[0]: par {
- }
- on tile[1]: par {
- sw_pll_test();
- clock_gen();
- }
- }
- return 0;
-}
diff --git a/examples/simple/src/simple_sw_pll.c b/examples/simple/src/simple_sw_pll.c
deleted file mode 100644
index dbcc4b84..00000000
--- a/examples/simple/src/simple_sw_pll.c
+++ /dev/null
@@ -1,166 +0,0 @@
-// Copyright 2022-2023 XMOS LIMITED.
-// This Software is subject to the terms of the XMOS Public Licence: Version 1.
-
-#include
-#include
-#include
-#include
-
-#include "sw_pll.h"
-
-#define MCLK_FREQUENCY 12288000
-#define REF_FREQUENCY 48000
-#define PLL_RATIO (MCLK_FREQUENCY / REF_FREQUENCY)
-#define CONTROL_LOOP_COUNT 512
-#define PPM_RANGE 150
-
-#define APP_PLL_CTL_12288 0x0881FA03
-#define APP_PLL_DIV_12288 0x8000001E
-#define APP_PLL_NOMINAL_INDEX_12288 35
-
-//Found solution: IN 24.000MHz, OUT 12.288018MHz, VCO 3047.43MHz, RD 4, FD 507.905 (m = 19, n = 21), OD 2, FOD 31, ERR +1.50ppm
-#include "fractions.h"
-
-void setup_ref_and_mclk_ports_and_clocks(port_t p_mclk, xclock_t clk_mclk, port_t p_ref_clk_in, xclock_t clk_word_clk, port_t p_ref_clk_count)
-{
- // Create clock from mclk port and use it to clock the p_ref_clk port.
- clock_enable(clk_mclk);
- port_enable(p_mclk);
- clock_set_source_port(clk_mclk, p_mclk);
-
- // Clock p_ref_clk from MCLK
- port_enable(p_ref_clk_in);
- port_set_clock(p_ref_clk_in, clk_mclk);
-
- clock_start(clk_mclk);
-
- // Create clock from ref_clock_port and use it to clock the p_ref_clk_count port.
- clock_enable(clk_word_clk);
- clock_set_source_port(clk_word_clk, p_ref_clk_in);
- port_enable(p_ref_clk_count);
- port_set_clock(p_ref_clk_count, clk_word_clk);
-
- clock_start(clk_word_clk);
-}
-
-
-void setup_recovered_ref_clock_output(port_t p_recovered_ref_clk, xclock_t clk_recovered_ref_clk, port_t p_mclk, unsigned divider)
-{
- // Connect clock block with divide to mclk
- clock_enable(clk_recovered_ref_clk);
- clock_set_source_port(clk_recovered_ref_clk, p_mclk);
- clock_set_divide(clk_recovered_ref_clk, divider / 2);
- printf("Divider: %u\n", divider);
-
- // Output the divided mclk on a port
- port_enable(p_recovered_ref_clk);
- port_set_clock(p_recovered_ref_clk, clk_recovered_ref_clk);
- port_set_out_clock(p_recovered_ref_clk);
- clock_start(clk_recovered_ref_clk);
-}
-
-void sw_pll_test(void){
-
- // Declare mclk and refclk resources and connect up
- port_t p_mclk = PORT_MCLK_IN;
- xclock_t clk_mclk = XS1_CLKBLK_1;
- port_t p_ref_clk = PORT_I2S_LRCLK;
- xclock_t clk_word_clk = XS1_CLKBLK_2;
- port_t p_ref_clk_count = XS1_PORT_32A;
- setup_ref_and_mclk_ports_and_clocks(p_mclk, clk_mclk, p_ref_clk, clk_word_clk, p_ref_clk_count);
-
- // Make a test output to observe the recovered mclk divided down to the refclk frequency
- xclock_t clk_recovered_ref_clk = XS1_CLKBLK_3;
- port_t p_recovered_ref_clk = PORT_I2S_DAC_DATA;
- setup_recovered_ref_clock_output(p_recovered_ref_clk, clk_recovered_ref_clk, p_mclk, PLL_RATIO);
-
- sw_pll_state_t sw_pll;
- sw_pll_init(&sw_pll,
- SW_PLL_15Q16(0.0),
- SW_PLL_15Q16(1.0),
- CONTROL_LOOP_COUNT,
- PLL_RATIO,
- 0,
- frac_values_80,
- SW_PLL_NUM_LUT_ENTRIES(frac_values_80),
- APP_PLL_CTL_12288,
- APP_PLL_DIV_12288,
- APP_PLL_NOMINAL_INDEX_12288,
- PPM_RANGE);
-
- sw_pll_lock_status_t lock_status = SW_PLL_LOCKED;
-
- uint32_t max_time = 0;
- while(1)
- {
- port_in(p_ref_clk_count); // This blocks each time round the loop until it can sample input (rising edges of word clock). So we know the count will be +1 each time.
- uint16_t mclk_pt = port_get_trigger_time(p_ref_clk);// Get the port timer val from p_ref_clk (which is running from MCLK). So this is basically a 16 bit free running counter running from MCLK.
-
- uint32_t t0 = get_reference_time();
- sw_pll_do_control(&sw_pll, mclk_pt, 0);
- uint32_t t1 = get_reference_time();
- if(t1 - t0 > max_time){
- max_time = t1 - t0;
- printf("Max ticks taken: %lu\n", max_time);
- }
-
- if(sw_pll.lock_status != lock_status){
- lock_status = sw_pll.lock_status;
- const char msg[3][16] = {"UNLOCKED LOW\0", "LOCKED\0", "UNLOCKED HIGH\0"};
- printf("%s\n", msg[lock_status+1]);
- }
- }
-}
-
-#define DO_CLOCKS \
-printf("Ref Hz: %d\n", clock_rate >> 1); \
-\
-unsigned cycle_ticks_int = XS1_TIMER_HZ / clock_rate; \
-unsigned cycle_ticks_remaidner = XS1_TIMER_HZ % clock_rate; \
-unsigned carry = 0; \
-\
-period_trig += XS1_TIMER_HZ * 1; \
-unsigned time_now = hwtimer_get_time(period_tmr); \
-while(TIMER_TIMEAFTER(period_trig, time_now)) \
-{ \
- port_out(p_clock_gen, port_val); \
- hwtimer_wait_until(clock_tmr, time_trig); \
- time_trig += cycle_ticks_int; \
- carry += cycle_ticks_remaidner; \
- if(carry >= clock_rate){ \
- time_trig++; \
- carry -= clock_rate; \
- } \
- port_val ^= 1; \
- time_now = hwtimer_get_time(period_tmr); \
-}
-
-void clock_gen(void)
-{
- unsigned clock_rate = REF_FREQUENCY * 2; // Note double because we generate edges at this rate
- unsigned ppm_range = 150; // Step from - to + this
-
- unsigned clock_rate_low = (unsigned)(clock_rate * (1.0 - (float)ppm_range / 1000000.0));
- unsigned clock_rate_high = (unsigned)(clock_rate * (1.0 + (float)ppm_range / 1000000.0));
- unsigned step_size = (clock_rate_high - clock_rate_low) / 20;
-
- printf("Sweep range: %d %d %d, step size: %d\n", clock_rate_low / 2, clock_rate / 2, clock_rate_high / 2, step_size);
-
- hwtimer_t period_tmr = hwtimer_alloc();
- unsigned period_trig = hwtimer_get_time(period_tmr);
-
- hwtimer_t clock_tmr = hwtimer_alloc();
- unsigned time_trig = hwtimer_get_time(clock_tmr);
-
- port_t p_clock_gen = PORT_I2S_BCLK;
- port_enable(p_clock_gen);
- unsigned port_val = 1;
-
- for(unsigned clock_rate = clock_rate_low; clock_rate <= clock_rate_high; clock_rate += 2 * step_size){
- DO_CLOCKS
- }
- for(unsigned clock_rate = clock_rate_high; clock_rate > clock_rate_low; clock_rate -= 2 * step_size){
- DO_CLOCKS
- }
- exit(0);
-}
\ No newline at end of file
diff --git a/examples/simple_lut/simple_lut.cmake b/examples/simple_lut/simple_lut.cmake
new file mode 100644
index 00000000..7dae8196
--- /dev/null
+++ b/examples/simple_lut/simple_lut.cmake
@@ -0,0 +1,50 @@
+#**********************
+# Gather Sources
+#**********************
+file(GLOB_RECURSE APP_SOURCES ${CMAKE_CURRENT_LIST_DIR}/src/*.c
+ ${CMAKE_CURRENT_LIST_DIR}/src/*.xc
+ ${CMAKE_CURRENT_LIST_DIR}/../shared/src/*.c )
+set(APP_INCLUDES ${CMAKE_CURRENT_LIST_DIR}/src
+ ${CMAKE_CURRENT_LIST_DIR}/../shared/src
+)
+
+#**********************
+# Flags
+#**********************
+set(APP_COMPILER_FLAGS
+ -Os
+ -g
+ -report
+ -fxscope
+ -mcmodel=large
+ -Wno-xcore-fptrgroup
+ ${CMAKE_CURRENT_LIST_DIR}/src/config.xscope
+ -target=XCORE-AI-EXPLORER
+)
+
+set(APP_COMPILE_DEFINITIONS
+ DEBUG_PRINT_ENABLE=1
+ PLATFORM_SUPPORTS_TILE_0=1
+ PLATFORM_SUPPORTS_TILE_1=1
+ PLATFORM_SUPPORTS_TILE_2=0
+ PLATFORM_SUPPORTS_TILE_3=0
+ PLATFORM_USES_TILE_0=1
+ PLATFORM_USES_TILE_1=1
+)
+
+set(APP_LINK_OPTIONS
+ -report
+ -target=XCORE-AI-EXPLORER
+ ${CMAKE_CURRENT_LIST_DIR}/src/config.xscope
+)
+
+#**********************
+# Tile Targets
+#**********************
+add_executable(simple_lut)
+target_sources(simple_lut PUBLIC ${APP_SOURCES})
+target_include_directories(simple_lut PUBLIC ${APP_INCLUDES})
+target_compile_definitions(simple_lut PRIVATE ${APP_COMPILE_DEFINITIONS})
+target_compile_options(simple_lut PRIVATE ${APP_COMPILER_FLAGS})
+target_link_options(simple_lut PRIVATE ${APP_LINK_OPTIONS})
+target_link_libraries(simple_lut PUBLIC lib_sw_pll)
diff --git a/examples/simple/src/config.xscope b/examples/simple_lut/src/config.xscope
similarity index 100%
rename from examples/simple/src/config.xscope
rename to examples/simple_lut/src/config.xscope
diff --git a/examples/simple/src/fractions.h b/examples/simple_lut/src/fractions.h
similarity index 100%
rename from examples/simple/src/fractions.h
rename to examples/simple_lut/src/fractions.h
diff --git a/examples/simple_lut/src/main.xc b/examples/simple_lut/src/main.xc
new file mode 100644
index 00000000..10680418
--- /dev/null
+++ b/examples/simple_lut/src/main.xc
@@ -0,0 +1,29 @@
+// Copyright 2022-2023 XMOS LIMITED.
+// This Software is subject to the terms of the XMOS Public Licence: Version 1.
+
+#include
+#include
+#include
+
+extern void sw_pll_test(void);
+extern "C" {
+ #include "clock_gen.h"
+}
+
+
+int main(void)
+{
+ par
+ {
+ on tile[0]: par {
+ }
+ on tile[1]: par {
+ sw_pll_test();
+ {
+ clock_gen(48000, 150);
+ exit(0);
+ }
+ }
+ }
+ return 0;
+}
diff --git a/examples/simple_lut/src/simple_sw_pll.c b/examples/simple_lut/src/simple_sw_pll.c
new file mode 100644
index 00000000..b233da06
--- /dev/null
+++ b/examples/simple_lut/src/simple_sw_pll.c
@@ -0,0 +1,76 @@
+// Copyright 2022-2023 XMOS LIMITED.
+// This Software is subject to the terms of the XMOS Public Licence: Version 1.
+
+#include
+#include
+#include
+#include
+
+#include "sw_pll.h"
+#include "resource_setup.h"
+
+#define MCLK_FREQUENCY 12288000
+#define REF_FREQUENCY 48000
+#define PLL_RATIO (MCLK_FREQUENCY / REF_FREQUENCY)
+#define CONTROL_LOOP_COUNT 512
+#define PPM_RANGE 150
+
+#define APP_PLL_CTL_12288 0x0881FA03
+#define APP_PLL_DIV_12288 0x8000001E
+#define APP_PLL_NOMINAL_INDEX_12288 35
+
+//Found solution: IN 24.000MHz, OUT 12.288018MHz, VCO 3047.43MHz, RD 4, FD 507.905 (m = 19, n = 21), OD 2, FOD 31, ERR +1.50ppm
+#include "fractions.h"
+
+void sw_pll_test(void){
+
+ // Declare mclk and refclk resources and connect up
+ port_t p_mclk = PORT_MCLK_IN;
+ xclock_t clk_mclk = XS1_CLKBLK_1;
+ port_t p_clock_counter = PORT_I2S_LRCLK;
+ xclock_t clk_ref_clk = XS1_CLKBLK_2;
+ port_t p_ref_clk_timing = XS1_PORT_32A;
+ setup_ref_and_mclk_ports_and_clocks(p_mclk, clk_mclk, p_clock_counter, clk_ref_clk, p_ref_clk_timing);
+
+ // Make a test output to observe the recovered mclk divided down to the refclk frequency
+ xclock_t clk_recovered_ref_clk = XS1_CLKBLK_3;
+ port_t p_recovered_ref_clk = PORT_I2S_DAC_DATA;
+ setup_recovered_ref_clock_output(p_recovered_ref_clk, clk_recovered_ref_clk, p_mclk, PLL_RATIO);
+
+ sw_pll_state_t sw_pll;
+ sw_pll_lut_init(&sw_pll,
+ SW_PLL_15Q16(0.0),
+ SW_PLL_15Q16(1.0),
+ SW_PLL_15Q16(0.0),
+ CONTROL_LOOP_COUNT,
+ PLL_RATIO,
+ 0, /* No jitter compensation needed */
+ frac_values_80,
+ SW_PLL_NUM_LUT_ENTRIES(frac_values_80),
+ APP_PLL_CTL_12288,
+ APP_PLL_DIV_12288,
+ APP_PLL_NOMINAL_INDEX_12288,
+ PPM_RANGE);
+
+ sw_pll_lock_status_t lock_status = SW_PLL_LOCKED;
+
+ uint32_t max_time = 0;
+ while(1)
+ {
+ port_in(p_ref_clk_timing); // This blocks each time round the loop until it can sample input (rising edges of word clock). So we know the count will be +1 each time.
+ uint16_t mclk_pt = port_get_trigger_time(p_clock_counter);// Get the port timer val from p_clock_counter (which is clocked running from the PLL output).
+ uint32_t t0 = get_reference_time();
+ sw_pll_lut_do_control(&sw_pll, mclk_pt, 0);
+ uint32_t t1 = get_reference_time();
+ if(t1 - t0 > max_time){
+ max_time = t1 - t0;
+ printf("Max ticks taken: %lu\n", max_time);
+ }
+
+ if(sw_pll.lock_status != lock_status){
+ lock_status = sw_pll.lock_status;
+ const char msg[3][16] = {"UNLOCKED LOW\0", "LOCKED\0", "UNLOCKED HIGH\0"};
+ printf("%s\n", msg[lock_status+1]);
+ }
+ }
+}
diff --git a/examples/simple_sdm/simple_sdm.cmake b/examples/simple_sdm/simple_sdm.cmake
new file mode 100644
index 00000000..532d531c
--- /dev/null
+++ b/examples/simple_sdm/simple_sdm.cmake
@@ -0,0 +1,50 @@
+#**********************
+# Gather Sources
+#**********************
+file(GLOB_RECURSE APP_SOURCES ${CMAKE_CURRENT_LIST_DIR}/src/*.c
+ ${CMAKE_CURRENT_LIST_DIR}/src/*.xc
+ ${CMAKE_CURRENT_LIST_DIR}/../shared/src/*.c )
+set(APP_INCLUDES ${CMAKE_CURRENT_LIST_DIR}/src
+ ${CMAKE_CURRENT_LIST_DIR}/../shared/src
+)
+
+#**********************
+# Flags
+#**********************
+set(APP_COMPILER_FLAGS
+ -Os
+ -g
+ -report
+ -fxscope
+ -mcmodel=large
+ -Wno-xcore-fptrgroup
+ ${CMAKE_CURRENT_LIST_DIR}/src/config.xscope
+ -target=XCORE-AI-EXPLORER
+)
+
+set(APP_COMPILE_DEFINITIONS
+ DEBUG_PRINT_ENABLE=1
+ PLATFORM_SUPPORTS_TILE_0=1
+ PLATFORM_SUPPORTS_TILE_1=1
+ PLATFORM_SUPPORTS_TILE_2=0
+ PLATFORM_SUPPORTS_TILE_3=0
+ PLATFORM_USES_TILE_0=1
+ PLATFORM_USES_TILE_1=1
+)
+
+set(APP_LINK_OPTIONS
+ -report
+ -target=XCORE-AI-EXPLORER
+ ${CMAKE_CURRENT_LIST_DIR}/src/config.xscope
+)
+
+#**********************
+# Tile Targets
+#**********************
+add_executable(simple_sdm)
+target_sources(simple_sdm PUBLIC ${APP_SOURCES})
+target_include_directories(simple_sdm PUBLIC ${APP_INCLUDES})
+target_compile_definitions(simple_sdm PRIVATE ${APP_COMPILE_DEFINITIONS})
+target_compile_options(simple_sdm PRIVATE ${APP_COMPILER_FLAGS})
+target_link_options(simple_sdm PRIVATE ${APP_LINK_OPTIONS})
+target_link_libraries(simple_sdm PUBLIC lib_sw_pll)
diff --git a/examples/simple_sdm/src/config.xscope b/examples/simple_sdm/src/config.xscope
new file mode 100644
index 00000000..8ddc37b6
--- /dev/null
+++ b/examples/simple_sdm/src/config.xscope
@@ -0,0 +1,24 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/examples/simple_sdm/src/main.xc b/examples/simple_sdm/src/main.xc
new file mode 100644
index 00000000..714750a2
--- /dev/null
+++ b/examples/simple_sdm/src/main.xc
@@ -0,0 +1,33 @@
+// Copyright 2022-2023 XMOS LIMITED.
+// This Software is subject to the terms of the XMOS Public Licence: Version 1.
+
+#include
+#include
+#include
+
+extern void sw_pll_sdm_test(chanend c_sdm_control);
+extern void sdm_task(chanend c_sdm_control);
+extern "C" {
+ #include "clock_gen.h"
+}
+
+int main(void)
+{
+ chan c_sdm_control;
+
+ par
+ {
+ on tile[0]: par {
+ }
+
+ on tile[1]: par {
+ sw_pll_sdm_test(c_sdm_control);
+ sdm_task(c_sdm_control);
+ {
+ clock_gen(96000, 300);
+ exit(0);
+ }
+ }
+ }
+ return 0;
+}
diff --git a/examples/simple_sdm/src/register_setup.h b/examples/simple_sdm/src/register_setup.h
new file mode 100644
index 00000000..dc4da7f9
--- /dev/null
+++ b/examples/simple_sdm/src/register_setup.h
@@ -0,0 +1,15 @@
+/* Autogenerated SDM App PLL setup by dco_model.py using 24.576_1M profile */
+/* Input freq: 24000000
+ F: 146
+ R: 0
+ f: 4
+ p: 10
+ OD: 5
+ ACD: 5
+*/
+
+#define APP_PLL_CTL_REG 0x0A809200
+#define APP_PLL_DIV_REG 0x80000005
+#define APP_PLL_FRAC_REG 0x8000040A
+#define SW_PLL_SDM_CTRL_MID 478151
+#define SW_PLL_SDM_RATE 1000000
diff --git a/examples/simple_sdm/src/simple_sw_pll_sdm.c b/examples/simple_sdm/src/simple_sw_pll_sdm.c
new file mode 100644
index 00000000..b47249d3
--- /dev/null
+++ b/examples/simple_sdm/src/simple_sw_pll_sdm.c
@@ -0,0 +1,137 @@
+// Copyright 2022-2023 XMOS LIMITED.
+// This Software is subject to the terms of the XMOS Public Licence: Version 1.
+
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include
+
+#include "sw_pll.h"
+#include "resource_setup.h"
+
+#define MCLK_FREQUENCY 24576000
+#define REF_FREQUENCY 96000
+#define PLL_RATIO (MCLK_FREQUENCY / REF_FREQUENCY)
+#define CONTROL_LOOP_COUNT 512
+
+#include "register_setup.h"
+
+void sdm_task(chanend_t c_sdm_control){
+ printf("sdm_task\n");
+
+ const uint32_t sdm_interval = XS1_TIMER_HZ / SW_PLL_SDM_RATE; // in 10ns ticks = 1MHz
+
+ sw_pll_sdm_state_t sdm_state;
+ sw_pll_init_sigma_delta(&sdm_state);
+
+ tileref_t this_tile = get_local_tile_id();
+
+ hwtimer_t tmr = hwtimer_alloc();
+ int32_t trigger_time = hwtimer_get_time(tmr) + sdm_interval;
+ bool running = true;
+ int32_t sdm_in = 0; // Zero is an invalid number and the SDM will not write the frac reg until
+ // the first control value has been received. This avoids issues with
+ // channel lockup if two tasks (eg. init and SDM) try to write at the same
+ // time.
+
+ while(running){
+ // Poll for new SDM control value
+ SELECT_RES(
+ CASE_THEN(c_sdm_control, ctrl_update),
+ DEFAULT_THEN(default_handler)
+ )
+ {
+ ctrl_update:
+ {
+ sdm_in = chan_in_word(c_sdm_control);
+ }
+ break;
+
+ default_handler:
+ {
+ // Do nothing & fall-through
+ }
+ break;
+ }
+
+ // Wait until the timer value has been reached
+ // This implements a timing barrier and keeps
+ // the loop rate constant.
+ hwtimer_wait_until(tmr, trigger_time);
+ trigger_time += sdm_interval;
+
+ // Do not write to the frac reg until we get out first
+ // control value. This will avoid the writing of the
+ // frac reg from two different threads which may cause
+ // a channel deadlock.
+ if(sdm_in){
+ sw_pll_do_sigma_delta(&sdm_state, this_tile, sdm_in);
+ }
+ }
+}
+
+void sw_pll_send_ctrl_to_sdm_task(chanend_t c_sdm_control, int32_t dco_ctl){
+ chan_out_word(c_sdm_control, dco_ctl);
+}
+
+void sw_pll_sdm_test(chanend_t c_sdm_control){
+
+ // Declare mclk and refclk resources and connect up
+ port_t p_mclk = PORT_MCLK_IN;
+ xclock_t clk_mclk = XS1_CLKBLK_1;
+ port_t p_clock_counter = PORT_I2S_LRCLK;
+ xclock_t clk_ref_clk = XS1_CLKBLK_2;
+ port_t p_ref_clk_timing = XS1_PORT_32A;
+ setup_ref_and_mclk_ports_and_clocks(p_mclk, clk_mclk, p_clock_counter, clk_ref_clk, p_ref_clk_timing);
+
+ // Make a test output to observe the recovered mclk divided down to the refclk frequency
+ xclock_t clk_recovered_ref_clk = XS1_CLKBLK_3;
+ port_t p_recovered_ref_clk = PORT_I2S_DAC_DATA;
+ setup_recovered_ref_clock_output(p_recovered_ref_clk, clk_recovered_ref_clk, p_mclk, PLL_RATIO);
+
+ sw_pll_state_t sw_pll;
+ sw_pll_sdm_init(&sw_pll,
+ SW_PLL_15Q16(0.0),
+ SW_PLL_15Q16(32.0),
+ SW_PLL_15Q16(0.25),
+ CONTROL_LOOP_COUNT,
+ PLL_RATIO,
+ 0, /* No jitter compensation needed */
+ APP_PLL_CTL_REG,
+ APP_PLL_DIV_REG,
+ APP_PLL_FRAC_REG,
+ SW_PLL_SDM_CTRL_MID,
+ 3000 /*PPM_RANGE FOR PFD*/);
+
+ sw_pll_lock_status_t lock_status = SW_PLL_LOCKED;
+
+ uint32_t max_time = 0;
+ while(1)
+ {
+ port_in(p_ref_clk_timing); // This blocks each time round the loop until it can sample input (rising edges of word clock). So we know the count will be +1 each time.
+ uint16_t mclk_pt = port_get_trigger_time(p_clock_counter);// Get the port timer val from p_clock_counter (which is running from MCLK). So this is basically a 16 bit free running counter running from MCLK.
+
+ uint32_t t0 = get_reference_time();
+ bool ctrl_done = sw_pll_sdm_do_control(&sw_pll, mclk_pt, 0);
+ uint32_t t1 = get_reference_time();
+
+ if(ctrl_done){
+ sw_pll_send_ctrl_to_sdm_task(c_sdm_control, sw_pll.sdm_state.current_ctrl_val);
+ }
+
+ if(t1 - t0 > max_time){
+ max_time = t1 - t0;
+ printf("Max ticks taken: %lu\n", max_time);
+ }
+
+ if(sw_pll.lock_status != lock_status){
+ lock_status = sw_pll.lock_status;
+ const char msg[3][16] = {"UNLOCKED LOW\0", "LOCKED\0", "UNLOCKED HIGH\0"};
+ printf("%s\n", msg[lock_status+1]);
+ }
+ }
+}
diff --git a/index.rst b/index.rst
deleted file mode 100644
index b37815ef..00000000
--- a/index.rst
+++ /dev/null
@@ -1,8 +0,0 @@
-####################
-SW PLL DOCUMENTATION
-####################
-
-.. toctree::
- :maxdepth: 2
-
- doc/sw_pll
diff --git a/lib_sw_pll/CMakeLists.txt b/lib_sw_pll/CMakeLists.txt
index 5c5679d0..7130a7a1 100644
--- a/lib_sw_pll/CMakeLists.txt
+++ b/lib_sw_pll/CMakeLists.txt
@@ -14,7 +14,7 @@ set(XCORE_XS3A_SOURCES ${LIB_ASM_SOURCES})
set(LIB_COMPILE_FLAGS "-Os" "-g")
## Includes files
-set(LIB_PUBLIC_INCLUDES api)
+set(LIB_PUBLIC_INCLUDES api src)
set(LIB_PRIVATE_INCLUDES src)
## Gather library sources
diff --git a/lib_sw_pll/api/sw_pll.h b/lib_sw_pll/api/sw_pll.h
index ea3e646a..fe310764 100644
--- a/lib_sw_pll/api/sw_pll.h
+++ b/lib_sw_pll/api/sw_pll.h
@@ -5,107 +5,77 @@
#include
#include
+#include
#include
#include
#include
+#include
-// Helpers used in this module
-#define TIMER_TIMEAFTER(A, B) ((int)((B) - (A)) < 0) // Returns non-zero if A is after B, accounting for wrap
-#define PORT_TIMEAFTER(NOW, EVENT_TIME) ((int16_t)((EVENT_TIME) - (NOW)) < 0) // Returns non-zero if A is after B, accounting for wrap
-#define MAGNITUDE(A) (A < 0 ? -A : A) // Removes the sign of a value
+// SW_PLL Component includes
+#include "sw_pll_common.h"
+#include "sw_pll_pfd.h"
+#include "sw_pll_sdm.h"
-typedef int32_t sw_pll_15q16_t; // Type for 15.16 signed fixed point
-#define SW_PLL_NUM_FRAC_BITS 16
-#define SW_PLL_15Q16(val) ((sw_pll_15q16_t)((float)val * (1 << SW_PLL_NUM_FRAC_BITS)))
-#define SW_PLL_NUM_LUT_ENTRIES(lut_array) (sizeof(lut_array) / sizeof(lut_array[0]))
-
-typedef enum sw_pll_lock_status_t{
- SW_PLL_UNLOCKED_LOW = -1,
- SW_PLL_LOCKED = 0,
- SW_PLL_UNLOCKED_HIGH = 1
-} sw_pll_lock_status_t;
-
/**
- * \addtogroup sw_pll_api sw_pll_api
+ * \addtogroup sw_pll_lut sw_pll_lut
*
- * The public API for using the RTOS I2C slave driver.
+ * The public API for using the Software PLL.
* @{
*/
-typedef struct sw_pll_state_t{
- // User definied paramaters
- sw_pll_15q16_t Kp; // Proportional constant
- sw_pll_15q16_t Ki; // Integral constant
- int32_t i_windup_limit; // Integral term windup limit
- unsigned loop_rate_count; // How often the control loop logic runs compared to control cal rate
-
- // Internal state
- int16_t mclk_diff; // Raw difference between mclk count and expected mclk count
- uint16_t ref_clk_pt_last; // Last ref clock value
- uint32_t ref_clk_expected_inc; // Expected ref clock increment
- uint64_t ref_clk_scaling_numerator; // Used for a cheap pre-computed divide rather than runtime divide
- int32_t error_accum; // Accumulation of the raw mclk_diff term (for I)
- unsigned loop_counter; // Intenal loop counter to determine when to do control
- uint16_t mclk_pt_last; // The last mclk port timer count
- uint32_t mclk_expected_pt_inc; // Expected increment of port timer count
- uint16_t mclk_max_diff; // Maximum mclk_diff before control loop decides to skip that iteration
- sw_pll_lock_status_t lock_status; // State showing whether the PLL has locked or is under/over
- uint8_t lock_counter; // Counter used to determine lock status
- uint8_t first_loop; // Flag which indicates if the sw_pll is initialising or not
-
- const int16_t * lut_table_base; // Pointer to the base of the fractional look up table
- size_t num_lut_entries; // Number of LUT entries
- unsigned nominal_lut_idx; // Initial (mid point normally) LUT index
-
- uint16_t current_reg_val; // Last value sent to the register, used by tests
-}sw_pll_state_t;
-
-
/**
- * sw_pll initialisation function.
+ * sw_lut_pll initialisation function.
*
- * This must be called before use of sw_pll_do_control.
+ * This must be called before use of sw_pll_lut_do_control.
* Call this passing a pointer to the sw_pll_state_t stuct declared locally.
*
- * \param \c sw_pll Pointer to the struct to be initialised.
- * \param \c Kp Proportional PI constant. Use \c SW_PLL_15Q16() to convert from a float.
- * \param \c Ki Integral PI constant. Use \c SW_PLL_15Q16() to convert from a float.
- * \param \c loop_rate_count How many counts of the call to sw_pll_do_control before control is done.
- * Note this is only used by \c sw_pll_do_control. \c sw_pll_do_control_from_error
- * calls the control loop every time so this is ignored.
- * \param \c pll_ratio Integer ratio between input reference clock and the PLL output.
- * Only used by sw_pll_do_control. Don't care otherwise.
- * \param \c ref_clk_expected_inc Expected ref clock increment each time sw_pll_do_control is called.
- * Pass in zero if you are sure the mclk sampling timing is precise. This
- * will disable the scaling of the mclk count inside \c sw_pll_do_control.
- * Only used by \c sw_pll_do_control. Don't care otherwise.
- * \param \c lut_table_base Pointer to the base of the fractional PLL LUT used
- * \param \c num_lut_entries Number of entries in the LUT (half sizeof since entries are 16b)
- * \param \c app_pll_ctl_reg_val The setting of the app pll control register.
- * \param \c app_pll_div_reg_val The setting of the app pll divider register.
- * \param \c nominal_lut_idx The index into the LUT which gives the nominal output. Normally
- * close to halfway to allow symmetrical range.
- * \param \c ppm_range The pre-calculated PPM range. Used to determine the maximum deviation
- * of counted mclk before the PLL resets its state.
+ * \param sw_pll Pointer to the struct to be initialised.
+ * \param Kp Proportional PI constant. Use SW_PLL_15Q16() to convert from a float.
+ * \param Ki Integral PI constant. Use SW_PLL_15Q16() to convert from a float.
+ * \param Kii Double integral PI constant. Use SW_PLL_15Q16() to convert from a float.
+ * \param loop_rate_count How many counts of the call to sw_pll_lut_do_control before control is done.
+ * Note this is only used by sw_pll_lut_do_control. sw_pll_lut_do_control_from_error
+ * calls the control loop every time so this is ignored.
+ * \param pll_ratio Integer ratio between input reference clock and the PLL output.
+ * Only used by sw_pll_lut_do_control for the PFD. Don't care otherwise.
+ * \param ref_clk_expected_inc Expected ref clock increment each time sw_pll_lut_do_control is called.
+ * Pass in zero if you are sure the mclk sampling timing is precise. This
+ * will disable the scaling of the mclk count inside sw_pll_lut_do_control.
+ * Only used by sw_pll_lut_do_control. Don't care otherwise.
+ * \param lut_table_base Pointer to the base of the fractional PLL LUT used
+ * \param num_lut_entries Number of entries in the LUT (half sizeof since entries are 16b)
+ * \param app_pll_ctl_reg_val The setting of the app pll control register.
+ * \param app_pll_div_reg_val The setting of the app pll divider register.
+ * \param nominal_lut_idx The index into the LUT which gives the nominal output. Normally
+ * close to halfway to allow symmetrical range.
+ * \param ppm_range The pre-calculated PPM range. Used to determine the maximum deviation
+ * of counted mclk before the PLL resets its state.
+ * Note this is only used by sw_pll_lut_do_control. sw_pll_lut_do_control_from_error
+ * calls the control loop every time so this is ignored.
*
*/
-void sw_pll_init( sw_pll_state_t * const sw_pll,
- const sw_pll_15q16_t Kp,
- const sw_pll_15q16_t Ki,
- const size_t loop_rate_count,
- const size_t pll_ratio,
- const uint32_t ref_clk_expected_inc,
- const int16_t * const lut_table_base,
- const size_t num_lut_entries,
- const uint32_t app_pll_ctl_reg_val,
- const uint32_t app_pll_div_reg_val,
- const unsigned nominal_lut_idx,
- const unsigned ppm_range);
+void sw_pll_lut_init( sw_pll_state_t * const sw_pll,
+ const sw_pll_15q16_t Kp,
+ const sw_pll_15q16_t Ki,
+ const sw_pll_15q16_t Kii,
+ const size_t loop_rate_count,
+ const size_t pll_ratio,
+ const uint32_t ref_clk_expected_inc,
+ const int16_t * const lut_table_base,
+ const size_t num_lut_entries,
+ const uint32_t app_pll_ctl_reg_val,
+ const uint32_t app_pll_div_reg_val,
+ const unsigned nominal_lut_idx,
+ const unsigned ppm_range);
+
+
/**
- * sw_pll control function.
+ * sw_pll LUT version control function.
+ *
+ * It implements the PFD, controller and DCO output.
*
* This must be called periodically for every reference clock transition.
* Typically, in an audio system, this would be at the I2S or reference clock input rate.
@@ -117,55 +87,192 @@ void sw_pll_init( sw_pll_state_t * const sw_pll,
* If the precise sampling point of mclk is not easily controlled (for example in an I2S callback)
* then an additional timer count may be passed in which will scale the mclk count. See i2s_slave
* example to show how this is done. This will help reduce input jitter which, in turn, relates
- * to output jitter being a PLL.
+ * to reduced output jitter.
*
- * \param \c sw_pll Pointer to the struct to be initialised.
- * \param \c mclk_pt The 16b port timer count of mclk at the time of calling sw_pll_do_control.
- * \param \c ref_pt The 16b port timer ref ount at the time of calling \c sw_pll_do_control. This value
- * is ignored when the pll is initialised with a zero \c ref_clk_expected_inc and the
- * control loop will assume that \c mclk_pt sample timing is precise.
- *
- * \returns The lock status of the PLL. Locked or unlocked high/low. Note that
- * this value is only updated when the control loop has run.
- * The type is \c sw_pll_lock_status_t.
+ * \param sw_pll Pointer to the sw_pll state struct.
+ * \param mclk_pt The 16b port timer count of mclk at the time of calling sw_pll_lut_do_control.
+ * \param ref_pt The 16b port timer ref ount at the time of calling sw_pll_lut_do_control. This value
+ * is ignored when the pll is initialised with a zero ref_clk_expected_inc and the
+ * control loop will assume that mclk_pt sample timing is precise.
+ *
+ * \returns The lock status of the PLL. Locked or unlocked high/low. Note that
+ * this value is only updated when the control loop has run.
+ * The type is sw_pll_lock_status_t.
*/
-sw_pll_lock_status_t sw_pll_do_control(sw_pll_state_t * const sw_pll, const uint16_t mclk_pt, const uint16_t ref_pt);
+sw_pll_lock_status_t sw_pll_lut_do_control(sw_pll_state_t * const sw_pll, const uint16_t mclk_pt, const uint16_t ref_pt);
/**
* low level sw_pll control function for use as pure PLL control loop.
*
* This must be called periodically.
*
- * When this is called, the control loop will be executed every n times (set by init) and the
+ * When this is called, the control loop will be executed every time and the
* application PLL will be adjusted to minimise the error seen on the input error value.
*
- * \param \c sw_pll Pointer to the struct to be initialised.
- * \param \c error 16b signed input error value
- * \returns The lock status of the PLL. Locked or unlocked high/low. Note that
- * this value is only updated when the control loop is running.
- * The type is \c sw_pll_lock_status_t.
+ * \param sw_pll Pointer to the sw_pll state struct.
+ * \param error 16b signed input error value
+ * \returns The lock status of the PLL. Locked or unlocked high/low. Note that
+ * this value is only updated when the control loop is running.
+ * The type is sw_pll_lock_status_t.
*/
-sw_pll_lock_status_t sw_pll_do_control_from_error(sw_pll_state_t * const sw_pll, int16_t error);
+sw_pll_lock_status_t sw_pll_lut_do_control_from_error(sw_pll_state_t * const sw_pll, int16_t error);
/**
* Helper to do a partial init of the PI controller at runtime without setting the physical PLL and LUT settings.
*
- * Sets Kp, Ki and the windup limit. Note this resets the accumulator too and so state is reset.
+ * Sets Kp, Ki and the windup limits. Note this resets the PFD accumulators too and so PI controller state is reset.
*
- * \param \c sw_pll Pointer to the struct to be initialised.
- * \param \c Kp New Kp in \c sw_pll_15q16_t format.
- * \param \c Ki New Ki in \c sw_pll_15q16_t format.
- * \param \c num_lut_entries The number of elements in the sw_pll LUT.
+ * \param sw_pll Pointer to the state struct to be reset.
+ * \param Kp New Kp in sw_pll_15q16_t format.
+ * \param Ki New Ki in sw_pll_15q16_t format.
+ * \param Kii New Kii in sw_pll_15q16_t format.
+ * \param num_lut_entries The number of elements in the sw_pll LUT.
*/
-static inline void sw_pll_reset(sw_pll_state_t *sw_pll, sw_pll_15q16_t Kp, sw_pll_15q16_t Ki, size_t num_lut_entries)
+static inline void sw_pll_lut_reset(sw_pll_state_t *sw_pll, sw_pll_15q16_t Kp, sw_pll_15q16_t Ki, sw_pll_15q16_t Kii, size_t num_lut_entries)
{
- sw_pll->Kp = Kp;
- sw_pll->Ki = Ki;
- sw_pll->error_accum = 0;
+ sw_pll->pi_state.Kp = Kp;
+ sw_pll->pi_state.Ki = Ki;
+ sw_pll->pi_state.Kii = Kii;
+
+ sw_pll->pi_state.error_accum = 0;
+ sw_pll->pi_state.error_accum_accum = 0;
if(Ki){
- sw_pll->i_windup_limit = (num_lut_entries << SW_PLL_NUM_FRAC_BITS) / Ki; // Set to twice the max total error input to LUT
+ sw_pll->pi_state.i_windup_limit = (num_lut_entries << SW_PLL_NUM_FRAC_BITS) / Ki; // Set to twice the max total error input to LUT
+ }else{
+ sw_pll->pi_state.i_windup_limit = 0;
+ }
+ if(Kii){
+ sw_pll->pi_state.ii_windup_limit = (num_lut_entries << SW_PLL_NUM_FRAC_BITS) / Kii; // Set to twice the max total error input to LUT
}else{
- sw_pll->i_windup_limit = 0;
+ sw_pll->pi_state.ii_windup_limit = 0;
}
}
+
+/**@}*/ // END: addtogroup sw_pll_lut
+
+
+/**
+ * \addtogroup sw_pll_sdm sw_pll_sdm
+ *
+ * The public API for using the Software PLL.
+ * @{
+ */
+
+/**
+ * sw_pll_sdm initialisation function.
+ *
+ * This must be called before use of sw_pll_sdm_do_control or sw_pll_sdm_do_control_from_error.
+ * Call this passing a pointer to the sw_pll_state_t stuct declared locally.
+ *
+ * \param sw_pll Pointer to the struct to be initialised.
+ * \param Kp Proportional PI constant. Use SW_PLL_15Q16() to convert from a float.
+ * \param Ki Integral PI constant. Use SW_PLL_15Q16() to convert from a float.
+ * \param Kii Double integral PI constant. Use SW_PLL_15Q16() to convert from a float.
+ * \param loop_rate_count How many counts of the call to sw_pll_sdm_do_control before control is done.
+ * Note this is only used by sw_pll_sdm_do_control. sw_pll_sdm_do_control_from_error
+ * calls the control loop every time so this is ignored.
+ * \param pll_ratio Integer ratio between input reference clock and the PLL output.
+ * Only used by sw_pll_sdm_do_control in the PFD. Don't care otherwise.
+ * \param ref_clk_expected_inc Expected ref clock increment each time sw_pll_sdm_do_control is called.
+ * Pass in zero if you are sure the mclk sampling timing is precise. This
+ * will disable the scaling of the mclk count inside sw_pll_sdm_do_control.
+ * Only used by sw_pll_sdm_do_control. Don't care otherwise.
+ * \param app_pll_ctl_reg_val The setting of the app pll control register.
+ * \param app_pll_div_reg_val The setting of the app pll divider register.
+ * \param app_pll_frac_reg_val The initial setting of the app pll fractional register.
+ * \param ctrl_mid_point The nominal control value for the Sigma Delta Modulator output. Normally
+ * close to halfway to allow symmetrical range.
+ * \param ppm_range The pre-calculated PPM range. Used to determine the maximum deviation
+ * of counted mclk before the PLL resets its state. Note this is only used
+ * by sw_pll_sdm_do_control. sw_pll_sdm_do_control_from_error
+ * calls the control loop every time so this is ignored.
+ *
+ */
+void sw_pll_sdm_init(sw_pll_state_t * const sw_pll,
+ const sw_pll_15q16_t Kp,
+ const sw_pll_15q16_t Ki,
+ const sw_pll_15q16_t Kii,
+ const size_t loop_rate_count,
+ const size_t pll_ratio,
+ const uint32_t ref_clk_expected_inc,
+ const uint32_t app_pll_ctl_reg_val,
+ const uint32_t app_pll_div_reg_val,
+ const uint32_t app_pll_frac_reg_val,
+ const int32_t ctrl_mid_point,
+ const unsigned ppm_range);
+
+/**
+ * sw_pll_sdm_do_control control function.
+ *
+ * It implements the PFD and controller and generates a DCO control value for the SDM.
+ *
+ * This must be called periodically for every reference clock transition.
+ * Typically, in an audio system, this would be at the I2S or reference clock input rate.
+ * Eg. 16kHz, 48kHz ...
+ *
+ * When this is called, the control loop will be executed every n times (set by init) and the
+ * Sigma Delta Modulator control value will be set according the error seen on the mclk count value.
+ *
+ * If control is executed, TRUE is returned from the function and the value can be sent to the SDM.
+ * The most recent calculated control output value can be found written to sw_pll->sdm_state.current_ctrl_val.
+ *
+ * If the precise sampling point of mclk is not easily controlled (for example in an I2S callback)
+ * then an additional timer count may be passed in which will scale the mclk count. See i2s_slave
+ * example to show how this is done. This will help reduce input jitter which, in turn, relates
+ * to reduced output jitter.
+ *
+ * \param sw_pll Pointer to the sw_pll state struct.
+ * \param mclk_pt The 16b port timer count of mclk at the time of calling sw_pll_sdm_do_control.
+ * \param ref_pt The 16b port timer ref ount at the time of calling sw_pll_sdm_do_control. This value
+ * is ignored when the pll is initialised with a zero ref_clk_expected_inc and the
+ * control loop will assume that mclk_pt sample timing is precise.
+ *
+ * \returns Whether or not control was executed (controoled by loop_rate_count)
+ */
+bool sw_pll_sdm_do_control(sw_pll_state_t * const sw_pll, const uint16_t mclk_pt, const uint16_t ref_pt);
+
+/**
+ * low level sw_pll_sdm control function for use as pure PLL control loop.
+ *
+ * This must be called periodically.
+ *
+ * Takes the raw error input and applies the PI controller algorithm.
+ * The most recent calculated control output value can be found written to sw_pll->sdm_state.current_ctrl_val.
+ *
+ * \param sw_pll Pointer to the sw_pll state struct.
+ * \param error 16b signed input error value
+ * \returns The controller lock status
+ */
+sw_pll_lock_status_t sw_pll_sdm_do_control_from_error(sw_pll_state_t * const sw_pll, int16_t error);
+
+
+/**
+ * Use to initialise the core sigma delta modulator. Broken out as seperate API as the SDM
+ * is usually run in a dedicated thread which could be on a remote tile.
+ *
+ * \param sw_pll Pointer to the SDM state struct.
+ */
+void sw_pll_init_sigma_delta(sw_pll_sdm_state_t *sdm_state);
+
+
+/**
+ * Performs the Sigma Delta Modulation from a control input.
+ * It performs the SDM algorithm, converts the output to a fractional register setting
+ * and then writes the value to the PLL fractional register.
+ * Is typically called in a constant period fast loop and run from a dedicated thread which could be on a remote tile.
+ *
+ * NOTE: Attempting to write the PLL fractional register from more than
+ * one logical core at the same time may result in channel lock-up.
+ * Please ensure the that PLL initiaisation has completed before
+ * the SDM task writes to the register. The provided `simple_sdm` example
+ * implements a method for doing this.
+ *
+ * \param sw_pll Pointer to the SDM state struct.
+ * \param this_tile The ID of the xcore tile that is doing the write.
+ * Use get_local_tile_id() to obtain this.
+ * \param sdm_control_in Current control value.
+ */
+static inline void sw_pll_do_sigma_delta(sw_pll_sdm_state_t *sdm_state, tileref_t this_tile, int32_t sdm_control_in);
+
+/**@}*/ // END: addtogroup sw_pll_sdm
diff --git a/lib_sw_pll/module_build_info b/lib_sw_pll/module_build_info
index 56bc491b..02b9d008 100644
--- a/lib_sw_pll/module_build_info
+++ b/lib_sw_pll/module_build_info
@@ -1 +1 @@
-VERSION= 1.1.0
+VERSION= 2.0.0
diff --git a/lib_sw_pll/src/sw_pll.c b/lib_sw_pll/src/sw_pll.c
deleted file mode 100644
index f4ef7f34..00000000
--- a/lib_sw_pll/src/sw_pll.c
+++ /dev/null
@@ -1,219 +0,0 @@
-// Copyright 2022-2023 XMOS LIMITED.
-// This Software is subject to the terms of the XMOS Public Licence: Version 1.
-
-#include "sw_pll.h"
-#include
-
-#define SW_PLL_LOCK_COUNT 10 // The number of consecutive lock positive reports of the control loop before declaring we are finally locked
-#define SW_PLL_PRE_DIV_BITS 37 // Used pre-computing a divide to save on runtime div usage. Tradeoff between precision and max
-
-// Implement a delay in 100MHz timer ticks without using a timer resource
-static void blocking_delay(const uint32_t delay_ticks){
- uint32_t time_delay = get_reference_time() + delay_ticks;
- while(TIMER_TIMEAFTER(time_delay, get_reference_time()));
-}
-
-
-// Set secondary (App) PLL control register safely to work around chip bug.
-static void sw_pll_app_pll_init(const unsigned tileid,
- const uint32_t app_pll_ctl_reg_val,
- const uint32_t app_pll_div_reg_val,
- const uint16_t frac_val_nominal)
-{
- // Disable the PLL
- write_sswitch_reg(tileid, XS1_SSWITCH_SS_APP_PLL_CTL_NUM, (app_pll_ctl_reg_val & 0xF7FFFFFF));
- // Enable the PLL to invoke a reset on the appPLL.
- write_sswitch_reg(tileid, XS1_SSWITCH_SS_APP_PLL_CTL_NUM, app_pll_ctl_reg_val);
- // Must write the CTL register twice so that the F and R divider values are captured using a running clock.
- write_sswitch_reg(tileid, XS1_SSWITCH_SS_APP_PLL_CTL_NUM, app_pll_ctl_reg_val);
- // Now disable and re-enable the PLL so we get the full 5us reset time with the correct F and R values.
- write_sswitch_reg(tileid, XS1_SSWITCH_SS_APP_PLL_CTL_NUM, (app_pll_ctl_reg_val & 0xF7FFFFFF));
- write_sswitch_reg(tileid, XS1_SSWITCH_SS_APP_PLL_CTL_NUM, app_pll_ctl_reg_val);
-
- // Write the fractional-n register and set to nominal
- // We set the top bit to enable the frac-n block.
- write_sswitch_reg(tileid, XS1_SSWITCH_SS_APP_PLL_FRAC_N_DIVIDER_NUM, (0x80000000 | frac_val_nominal));
- // And then write the clock divider register to enable the output
- write_sswitch_reg(tileid, XS1_SSWITCH_SS_APP_CLK_DIVIDER_NUM, app_pll_div_reg_val);
-
- // Wait for PLL to lock.
- blocking_delay(10 * XS1_TIMER_KHZ);
-}
-
-__attribute__((always_inline))
-static inline uint16_t lookup_pll_frac(sw_pll_state_t * const sw_pll, const int32_t total_error)
-{
- const int set = (sw_pll->nominal_lut_idx - total_error); //Notice negative term for error
- unsigned int frac_index = 0;
-
- if (set < 0)
- {
- frac_index = 0;
- sw_pll->lock_counter = SW_PLL_LOCK_COUNT;
- sw_pll->lock_status = SW_PLL_UNLOCKED_LOW;
- }
- else if (set >= sw_pll->num_lut_entries)
- {
- frac_index = sw_pll->num_lut_entries - 1;
- sw_pll->lock_counter = SW_PLL_LOCK_COUNT;
- sw_pll->lock_status = SW_PLL_UNLOCKED_HIGH;
- }
- else
- {
- frac_index = set;
- if(sw_pll->lock_counter){
- sw_pll->lock_counter--;
- // Keep last unlocked status
- }
- else
- {
- sw_pll->lock_status = SW_PLL_LOCKED;
- }
- }
-
- return sw_pll->lut_table_base[frac_index];
-}
-
-
-void sw_pll_init( sw_pll_state_t * const sw_pll,
- const sw_pll_15q16_t Kp,
- const sw_pll_15q16_t Ki,
- const size_t loop_rate_count,
- const size_t pll_ratio,
- const uint32_t ref_clk_expected_inc,
- const int16_t * const lut_table_base,
- const size_t num_lut_entries,
- const uint32_t app_pll_ctl_reg_val,
- const uint32_t app_pll_div_reg_val,
- const unsigned nominal_lut_idx,
- const unsigned ppm_range)
-{
- // Get PLL started and running at nominal
- sw_pll_app_pll_init(get_local_tile_id(),
- app_pll_ctl_reg_val,
- app_pll_div_reg_val,
- lut_table_base[nominal_lut_idx]);
-
- // Setup sw_pll with supplied user paramaters
- sw_pll_reset(sw_pll, Kp, Ki, num_lut_entries);
-
- sw_pll->loop_rate_count = loop_rate_count;
- sw_pll->current_reg_val = app_pll_div_reg_val;
-
- // Setup LUT params
- sw_pll->lut_table_base = lut_table_base;
- sw_pll->num_lut_entries = num_lut_entries;
- sw_pll->nominal_lut_idx = nominal_lut_idx;
-
- // Setup general state
- sw_pll->mclk_diff = 0;
- sw_pll->ref_clk_pt_last = 0;
- sw_pll->ref_clk_expected_inc = ref_clk_expected_inc * loop_rate_count;
- if(sw_pll->ref_clk_expected_inc) // Avoid div 0 error if ref_clk compensation not used
- {
- sw_pll->ref_clk_scaling_numerator = (1ULL << SW_PLL_PRE_DIV_BITS) / sw_pll->ref_clk_expected_inc + 1; //+1 helps with rounding accuracy
- }
- sw_pll->lock_status = SW_PLL_UNLOCKED_LOW;
- sw_pll->lock_counter = SW_PLL_LOCK_COUNT;
- sw_pll->mclk_pt_last = 0;
- sw_pll->mclk_expected_pt_inc = loop_rate_count * pll_ratio;
- // Set max PPM deviation before we chose to reset the PLL state. Nominally twice the normal range.
- sw_pll->mclk_max_diff = (uint64_t)(((uint64_t)ppm_range * 2ULL * (uint64_t)pll_ratio * (uint64_t)loop_rate_count) / 1000000);
- sw_pll->loop_counter = 0;
- sw_pll->first_loop = 1;
-
- // Check we can actually support the numbers used in the maths we use
- const float calc_max = (float)0xffffffffffffffffULL / 1.1; // Add 10% headroom from ULL MAX
- const float max = (float)sw_pll->ref_clk_expected_inc
- * (float)sw_pll->ref_clk_scaling_numerator
- * (float)sw_pll->mclk_expected_pt_inc;
- // If you have hit this assert then you need to reduce loop_rate_count or possibly the PLL ratio and or MCLK frequency
- xassert(max < calc_max);
-}
-
-__attribute__((always_inline))
-static inline void sw_pll_calc_error_from_port_timers(sw_pll_state_t * const sw_pll, const uint16_t mclk_pt, const uint16_t ref_clk_pt)
-{
- uint16_t mclk_expected_pt = 0;
- // See if we are using variable loop period sampling, if so, compensate for it by scaling the expected mclk count
- if(sw_pll->ref_clk_expected_inc)
- {
- uint16_t ref_clk_expected_pt = sw_pll->ref_clk_pt_last + sw_pll->ref_clk_expected_inc;
- // This uses casting trickery to work out the difference between the timer values accounting for wrap at 65536
- int16_t ref_clk_diff = PORT_TIMEAFTER(ref_clk_pt, ref_clk_expected_pt) ? -(int16_t)(ref_clk_expected_pt - ref_clk_pt) : (int16_t)(ref_clk_pt - ref_clk_expected_pt);
- sw_pll->ref_clk_pt_last = ref_clk_pt;
-
- // This allows for wrapping of the timer when CONTROL_LOOP_COUNT is high
- // Note we use a pre-computed divide followed by a shift to replace a constant divide with a constant multiply + shift
- uint32_t mclk_expected_pt_inc = ((uint64_t)sw_pll->mclk_expected_pt_inc
- * ((uint64_t)sw_pll->ref_clk_expected_inc + ref_clk_diff)
- * sw_pll->ref_clk_scaling_numerator) >> SW_PLL_PRE_DIV_BITS;
- // Below is the line we would use if we do not pre-compute the divide. This can take a long time if we spill over 32b
- // uint32_t mclk_expected_pt_inc = sw_pll->mclk_expected_pt_inc * (sw_pll->ref_clk_expected_inc + ref_clk_diff) / sw_pll->ref_clk_expected_inc;
- mclk_expected_pt = sw_pll->mclk_pt_last + mclk_expected_pt_inc;
- }
- else // we are assuming mclk_pt is sampled precisely and needs no compoensation
- {
- mclk_expected_pt = sw_pll->mclk_pt_last + sw_pll->mclk_expected_pt_inc;
- }
-
- // This uses casting trickery to work out the difference between the timer values accounting for wrap at 65536
- sw_pll->mclk_diff = PORT_TIMEAFTER(mclk_pt, mclk_expected_pt) ? -(int16_t)(mclk_expected_pt - mclk_pt) : (int16_t)(mclk_pt - mclk_expected_pt);
-
- // Check to see if something has gone very wrong, for example ref clock stop/start. If so, reset state and keep trying
- if(MAGNITUDE(sw_pll->mclk_diff) > sw_pll->mclk_max_diff)
- {
- sw_pll->first_loop = 1;
- }
-}
-
-__attribute__((always_inline))
-inline sw_pll_lock_status_t sw_pll_do_control_from_error(sw_pll_state_t * const sw_pll, int16_t error)
-{
- sw_pll->error_accum += error; // Integral error.
- sw_pll->error_accum = sw_pll->error_accum > sw_pll->i_windup_limit ? sw_pll->i_windup_limit : sw_pll->error_accum;
- sw_pll->error_accum = sw_pll->error_accum < -sw_pll->i_windup_limit ? -sw_pll->i_windup_limit : sw_pll->error_accum;
-
- // Use long long maths to avoid overflow if ever we had a large error accum term
- int64_t error_p = ((int64_t)sw_pll->Kp * (int64_t)error);
- int64_t error_i = ((int64_t)sw_pll->Ki * (int64_t)sw_pll->error_accum);
-
- // Convert back to 32b since we are handling LUTs of around a hundred entries
- int32_t total_error = (int32_t)((error_p + error_i) >> SW_PLL_NUM_FRAC_BITS);
- sw_pll->current_reg_val = lookup_pll_frac(sw_pll, total_error);
-
- write_sswitch_reg_no_ack(get_local_tile_id(), XS1_SSWITCH_SS_APP_PLL_FRAC_N_DIVIDER_NUM, (0x80000000 | sw_pll->current_reg_val));
-
- return sw_pll->lock_status;
-}
-
-sw_pll_lock_status_t sw_pll_do_control(sw_pll_state_t * const sw_pll, const uint16_t mclk_pt, const uint16_t ref_clk_pt)
-{
- if (++sw_pll->loop_counter == sw_pll->loop_rate_count)
- {
- sw_pll->loop_counter = 0;
-
- if (sw_pll->first_loop) // First loop around so ensure state is clear
- {
- sw_pll->mclk_pt_last = mclk_pt; // load last mclk measurement with sensible data
- sw_pll->error_accum = 0;
- sw_pll->lock_counter = SW_PLL_LOCK_COUNT;
- sw_pll->lock_status = SW_PLL_UNLOCKED_LOW;
-
- sw_pll->first_loop = 0;
-
- // Do not set PLL frac as last setting probably the best. At power on we set to nominal (midway in table)
- }
- else
- {
- sw_pll_calc_error_from_port_timers(sw_pll, mclk_pt, ref_clk_pt);
- sw_pll_do_control_from_error(sw_pll, sw_pll->mclk_diff);
-
- // Save for next iteration to calc diff
- sw_pll->mclk_pt_last = mclk_pt;
-
- }
- }
-
- return sw_pll->lock_status;
-}
diff --git a/lib_sw_pll/src/sw_pll_common.h b/lib_sw_pll/src/sw_pll_common.h
new file mode 100644
index 00000000..728bf942
--- /dev/null
+++ b/lib_sw_pll/src/sw_pll_common.h
@@ -0,0 +1,107 @@
+// Copyright 2023 XMOS LIMITED.
+// This Software is subject to the terms of the XMOS Public Licence: Version 1.
+
+#pragma once
+
+// The number of consecutive lock positive reports of the control loop before declaring we are finally locked
+#define SW_PLL_LOCK_COUNT 10
+
+// Helpers used in this module
+#define TIMER_TIMEAFTER(A, B) ((int)((B) - (A)) < 0) // Returns non-zero if A is after B, accounting for wrap
+#define PORT_TIMEAFTER(NOW, EVENT_TIME) ((int16_t)((EVENT_TIME) - (NOW)) < 0) // Returns non-zero if A is after B, accounting for wrap
+#define MAGNITUDE(A) (A < 0 ? -A : A) // Removes the sign of a value
+
+typedef int32_t sw_pll_15q16_t; // Type for 15.16 signed fixed point
+
+#define SW_PLL_NUM_FRAC_BITS 16
+#define SW_PLL_15Q16(val) ((sw_pll_15q16_t)((float)val * (1 << SW_PLL_NUM_FRAC_BITS)))
+#define SW_PLL_NUM_LUT_ENTRIES(lut_array) (sizeof(lut_array) / sizeof(lut_array[0]))
+
+typedef enum sw_pll_lock_status_t{
+ SW_PLL_UNLOCKED_LOW = -1,
+ SW_PLL_LOCKED = 0,
+ SW_PLL_UNLOCKED_HIGH = 1
+} sw_pll_lock_status_t;
+
+typedef struct sw_pll_pfd_state_t{
+ int16_t mclk_diff; // Raw difference between mclk count and expected mclk count
+ uint16_t ref_clk_pt_last; // Last ref clock value
+ uint32_t ref_clk_expected_inc; // Expected ref clock increment
+ uint64_t ref_clk_scaling_numerator; // Used for a cheap pre-computed divide rather than runtime divide
+ uint16_t mclk_pt_last; // The last mclk port timer count
+ uint32_t mclk_expected_pt_inc; // Expected increment of port timer count
+ uint16_t mclk_max_diff; // Maximum mclk_diff before control loop decides to skip that iteration
+} sw_pll_pfd_state_t;
+
+typedef struct sw_pll_pi_state_t{
+ sw_pll_15q16_t Kp; // Proportional constant
+ sw_pll_15q16_t Ki; // Integral constant
+ sw_pll_15q16_t Kii; // Double integral constant
+ int32_t i_windup_limit; // Integral term windup limit
+ int32_t ii_windup_limit; // Double integral term windup limit
+ int32_t error_accum; // Accumulation of the raw mclk_diff term (for I)
+ int32_t error_accum_accum; // Accumulation of the raw mclk_diff term (for II)
+ int32_t iir_y; // Optional IIR low pass filter state
+} sw_pll_pi_state_t;
+
+typedef struct sw_pll_lut_state_t{
+ const int16_t * lut_table_base; // Pointer to the base of the fractional look up table
+ size_t num_lut_entries; // Number of LUT entries
+ unsigned nominal_lut_idx; // Initial (mid point normally) LUT index
+ uint16_t current_reg_val; // Last value sent to the register, used by tests
+} sw_pll_lut_state_t;
+
+
+typedef struct sw_pll_sdm_state_t{
+ int32_t current_ctrl_val; // The last control value calculated
+ int32_t ctrl_mid_point; // The mid point for the DCO input
+ int32_t ds_x1; // Sigma delta modulator state
+ int32_t ds_x2; // Sigma delta modulator state
+ int32_t ds_x3; // Sigma delta modulator state
+} sw_pll_sdm_state_t;
+
+/**
+ * \addtogroup sw_pll_api sw_pll_api
+ *
+ * The public API for using the RTOS I2C slave driver.
+ * @{
+ */
+
+typedef struct sw_pll_state_t{
+
+ sw_pll_lock_status_t lock_status; // State showing whether the PLL has locked or is under/over
+ uint8_t lock_counter; // Counter used to determine lock status
+ uint8_t first_loop; // Flag which indicates if the sw_pll is initialising or not
+ unsigned loop_rate_count; // How often the control loop logic runs compared to control call rate
+ unsigned loop_counter; // Intenal loop counter to determine when to do control
+
+ sw_pll_pfd_state_t pfd_state; // Phase Frequency Detector
+ sw_pll_pi_state_t pi_state; // PI(II) controller
+ sw_pll_lut_state_t lut_state; // Look Up Table based DCO
+ sw_pll_sdm_state_t sdm_state; // Sigma Delta Modulator base DCO
+
+}sw_pll_state_t;
+
+
+// This is the core PI controller code used by both SDM and LUT SW PLLs
+__attribute__((always_inline))
+inline int32_t sw_pll_do_pi_ctrl(sw_pll_state_t * const sw_pll, int16_t error)
+{
+ sw_pll->pi_state.error_accum += error; // Integral error.
+ sw_pll->pi_state.error_accum = sw_pll->pi_state.error_accum > sw_pll->pi_state.i_windup_limit ? sw_pll->pi_state.i_windup_limit : sw_pll->pi_state.error_accum;
+ sw_pll->pi_state.error_accum = sw_pll->pi_state.error_accum < -sw_pll->pi_state.i_windup_limit ? -sw_pll->pi_state.i_windup_limit : sw_pll->pi_state.error_accum;
+
+ sw_pll->pi_state.error_accum_accum += sw_pll->pi_state.error_accum; // Double integral error.
+ sw_pll->pi_state.error_accum_accum = sw_pll->pi_state.error_accum_accum > sw_pll->pi_state.ii_windup_limit ? sw_pll->pi_state.ii_windup_limit : sw_pll->pi_state.error_accum_accum;
+ sw_pll->pi_state.error_accum_accum = sw_pll->pi_state.error_accum_accum < -sw_pll->pi_state.ii_windup_limit ? -sw_pll->pi_state.ii_windup_limit : sw_pll->pi_state.error_accum_accum;
+
+ // Use long long maths to avoid overflow if ever we had a large error accum term
+ int64_t error_p = ((int64_t)sw_pll->pi_state.Kp * (int64_t)error);
+ int64_t error_i = ((int64_t)sw_pll->pi_state.Ki * (int64_t)sw_pll->pi_state.error_accum);
+ int64_t error_ii = ((int64_t)sw_pll->pi_state.Kii * (int64_t)sw_pll->pi_state.error_accum_accum);
+
+ // Convert back to 32b since we are handling LUTs of around a hundred entries
+ int32_t total_error = (int32_t)((error_p + error_i + error_ii) >> SW_PLL_NUM_FRAC_BITS);
+
+ return total_error;
+}
diff --git a/lib_sw_pll/src/sw_pll_lut.c b/lib_sw_pll/src/sw_pll_lut.c
new file mode 100644
index 00000000..62afb1da
--- /dev/null
+++ b/lib_sw_pll/src/sw_pll_lut.c
@@ -0,0 +1,157 @@
+// Copyright 2022-2023 XMOS LIMITED.
+// This Software is subject to the terms of the XMOS Public Licence: Version 1.
+
+#include "sw_pll.h"
+
+#include
+
+// Implement a delay in 100MHz timer ticks without using a timer resource
+static void blocking_delay(const uint32_t delay_ticks){
+ uint32_t time_delay = get_reference_time() + delay_ticks;
+ while(TIMER_TIMEAFTER(time_delay, get_reference_time()));
+}
+
+
+// Set secondary (App) PLL control register safely to work around chip bug.
+void sw_pll_app_pll_init(const unsigned tileid,
+ const uint32_t app_pll_ctl_reg_val,
+ const uint32_t app_pll_div_reg_val,
+ const uint16_t frac_val_nominal)
+{
+ // Disable the PLL
+ write_sswitch_reg(tileid, XS1_SSWITCH_SS_APP_PLL_CTL_NUM, (app_pll_ctl_reg_val & 0xF7FFFFFF));
+ // Enable the PLL to invoke a reset on the appPLL.
+ write_sswitch_reg(tileid, XS1_SSWITCH_SS_APP_PLL_CTL_NUM, app_pll_ctl_reg_val);
+ // Must write the CTL register twice so that the F and R divider values are captured using a running clock.
+ write_sswitch_reg(tileid, XS1_SSWITCH_SS_APP_PLL_CTL_NUM, app_pll_ctl_reg_val);
+ // Now disable and re-enable the PLL so we get the full 5us reset time with the correct F and R values.
+ write_sswitch_reg(tileid, XS1_SSWITCH_SS_APP_PLL_CTL_NUM, (app_pll_ctl_reg_val & 0xF7FFFFFF));
+ write_sswitch_reg(tileid, XS1_SSWITCH_SS_APP_PLL_CTL_NUM, app_pll_ctl_reg_val);
+
+ // Write the fractional-n register and set to nominal
+ // We set the top bit to enable the frac-n block.
+ write_sswitch_reg(tileid, XS1_SSWITCH_SS_APP_PLL_FRAC_N_DIVIDER_NUM, (0x80000000 | frac_val_nominal));
+ // And then write the clock divider register to enable the output
+ write_sswitch_reg(tileid, XS1_SSWITCH_SS_APP_CLK_DIVIDER_NUM, app_pll_div_reg_val);
+
+ // Wait for PLL to lock.
+ blocking_delay(10 * XS1_TIMER_KHZ);
+}
+
+__attribute__((always_inline))
+static inline uint16_t lookup_pll_frac(sw_pll_state_t * const sw_pll, const int32_t total_error)
+{
+ const int set = (sw_pll->lut_state.nominal_lut_idx - total_error); //Notice negative term for error
+ unsigned int frac_index = 0;
+
+ if (set < 0)
+ {
+ frac_index = 0;
+ sw_pll->lock_counter = SW_PLL_LOCK_COUNT;
+ sw_pll->lock_status = SW_PLL_UNLOCKED_LOW;
+ }
+ else if (set >= sw_pll->lut_state.num_lut_entries)
+ {
+ frac_index = sw_pll->lut_state.num_lut_entries - 1;
+ sw_pll->lock_counter = SW_PLL_LOCK_COUNT;
+ sw_pll->lock_status = SW_PLL_UNLOCKED_HIGH;
+ }
+ else
+ {
+ frac_index = set;
+ if(sw_pll->lock_counter){
+ sw_pll->lock_counter--;
+ // Keep last unlocked status
+ }
+ else
+ {
+ sw_pll->lock_status = SW_PLL_LOCKED;
+ }
+ }
+
+ return sw_pll->lut_state.lut_table_base[frac_index];
+}
+
+void sw_pll_lut_init( sw_pll_state_t * const sw_pll,
+ const sw_pll_15q16_t Kp,
+ const sw_pll_15q16_t Ki,
+ const sw_pll_15q16_t Kii,
+ const size_t loop_rate_count,
+ const size_t pll_ratio,
+ const uint32_t ref_clk_expected_inc,
+ const int16_t * const lut_table_base,
+ const size_t num_lut_entries,
+ const uint32_t app_pll_ctl_reg_val,
+ const uint32_t app_pll_div_reg_val,
+ const unsigned nominal_lut_idx,
+ const unsigned ppm_range)
+{
+ // Get PLL started and running at nominal
+ sw_pll_app_pll_init(get_local_tile_id(),
+ app_pll_ctl_reg_val,
+ app_pll_div_reg_val,
+ lut_table_base[nominal_lut_idx]);
+
+ // Setup sw_pll with supplied user paramaters
+ sw_pll_lut_reset(sw_pll, Kp, Ki, Kii, num_lut_entries);
+
+ // Setup general controller state
+ sw_pll->lock_status = SW_PLL_UNLOCKED_LOW;
+ sw_pll->lock_counter = SW_PLL_LOCK_COUNT;
+
+ sw_pll->loop_rate_count = loop_rate_count;
+ sw_pll->loop_counter = 0;
+ sw_pll->first_loop = 1;
+
+ // Setup LUT params
+ sw_pll->lut_state.current_reg_val = app_pll_div_reg_val;
+ sw_pll->lut_state.lut_table_base = lut_table_base;
+ sw_pll->lut_state.num_lut_entries = num_lut_entries;
+ sw_pll->lut_state.nominal_lut_idx = nominal_lut_idx;
+
+ // Setup PFD state
+ sw_pll_pfd_init(&(sw_pll->pfd_state), loop_rate_count, pll_ratio, ref_clk_expected_inc, ppm_range);
+}
+
+
+__attribute__((always_inline))
+inline sw_pll_lock_status_t sw_pll_lut_do_control_from_error(sw_pll_state_t * const sw_pll, int16_t error)
+{
+ int32_t total_error = sw_pll_do_pi_ctrl(sw_pll, error);
+ sw_pll->lut_state.current_reg_val = lookup_pll_frac(sw_pll, total_error);
+
+ write_sswitch_reg_no_ack(get_local_tile_id(), XS1_SSWITCH_SS_APP_PLL_FRAC_N_DIVIDER_NUM, (0x80000000 | sw_pll->lut_state.current_reg_val));
+
+ return sw_pll->lock_status;
+}
+
+sw_pll_lock_status_t sw_pll_lut_do_control(sw_pll_state_t * const sw_pll, const uint16_t mclk_pt, const uint16_t ref_clk_pt)
+{
+ if (++sw_pll->loop_counter == sw_pll->loop_rate_count)
+ {
+ sw_pll->loop_counter = 0;
+
+ if (sw_pll->first_loop) // First loop around so ensure state is clear
+ {
+ sw_pll->pfd_state.mclk_pt_last = mclk_pt; // load last mclk measurement with sensible data
+ sw_pll->pi_state.error_accum = 0;
+ sw_pll->lock_counter = SW_PLL_LOCK_COUNT;
+ sw_pll->lock_status = SW_PLL_UNLOCKED_LOW;
+
+ sw_pll->first_loop = 0;
+
+ // Do not set PLL frac as last setting probably the best. At power on we set to nominal (midway in table)
+ }
+ else
+ {
+ sw_pll_calc_error_from_port_timers(&sw_pll->pfd_state, &sw_pll->first_loop, mclk_pt, ref_clk_pt);
+ sw_pll_lut_do_control_from_error(sw_pll, sw_pll->pfd_state.mclk_diff);
+
+ // Save for next iteration to calc diff
+ sw_pll->pfd_state.mclk_pt_last = mclk_pt;
+
+ }
+ }
+
+ return sw_pll->lock_status;
+}
diff --git a/lib_sw_pll/src/sw_pll_pfd.c b/lib_sw_pll/src/sw_pll_pfd.c
new file mode 100644
index 00000000..0ea8b5a7
--- /dev/null
+++ b/lib_sw_pll/src/sw_pll_pfd.c
@@ -0,0 +1,30 @@
+// Copyright 2023 XMOS LIMITED.
+// This Software is subject to the terms of the XMOS Public Licence: Version 1.
+
+#include "sw_pll_pfd.h"
+
+void sw_pll_pfd_init(sw_pll_pfd_state_t *pfd_state,
+ const size_t loop_rate_count,
+ const size_t pll_ratio,
+ const uint32_t ref_clk_expected_inc,
+ const unsigned ppm_range)
+{
+ pfd_state->mclk_diff = 0;
+ pfd_state->ref_clk_pt_last = 0;
+ pfd_state->ref_clk_expected_inc = ref_clk_expected_inc * loop_rate_count;
+ if(pfd_state->ref_clk_expected_inc) // Avoid div 0 error if ref_clk compensation not used
+ {
+ pfd_state->ref_clk_scaling_numerator = (1ULL << SW_PLL_PFD_PRE_DIV_BITS) / pfd_state->ref_clk_expected_inc + 1; //+1 helps with rounding accuracy
+ }
+ pfd_state->mclk_pt_last = 0;
+ pfd_state->mclk_expected_pt_inc = loop_rate_count * pll_ratio;
+ // Set max PPM deviation before we chose to reset the PLL state. Nominally twice the normal range.
+ pfd_state->mclk_max_diff = (uint64_t)(((uint64_t)ppm_range * 2ULL * (uint64_t)pll_ratio * (uint64_t)loop_rate_count) / 1000000);
+ // Check we can actually support the numbers used in the maths we use
+ const float calc_max = (float)0xffffffffffffffffULL / 1.1; // Add 10% headroom from ULL MAX
+ const float max = (float)pfd_state->ref_clk_expected_inc
+ * (float)pfd_state->ref_clk_scaling_numerator
+ * (float)pfd_state->mclk_expected_pt_inc;
+ // If you have hit this assert then you need to reduce loop_rate_count or possibly the PLL ratio and or MCLK frequency
+ xassert(max < calc_max);
+}
diff --git a/lib_sw_pll/src/sw_pll_pfd.h b/lib_sw_pll/src/sw_pll_pfd.h
new file mode 100644
index 00000000..5de773ca
--- /dev/null
+++ b/lib_sw_pll/src/sw_pll_pfd.h
@@ -0,0 +1,56 @@
+// Copyright 2023 XMOS LIMITED.
+// This Software is subject to the terms of the XMOS Public Licence: Version 1.
+
+#include
+#include
+#include
+#include "sw_pll_common.h"
+
+#pragma once
+
+#define SW_PLL_PFD_PRE_DIV_BITS 37 // Used pre-computing a divide to save on runtime div usage. Tradeoff between precision and max
+
+void sw_pll_pfd_init(sw_pll_pfd_state_t *pfd_state,
+ const size_t loop_rate_count,
+ const size_t pll_ratio,
+ const uint32_t ref_clk_expected_inc,
+ const unsigned ppm_range);
+
+__attribute__((always_inline))
+static inline void sw_pll_calc_error_from_port_timers( sw_pll_pfd_state_t * const pfd,
+ uint8_t *first_loop,
+ const uint16_t mclk_pt,
+ const uint16_t ref_clk_pt)
+{
+ uint16_t mclk_expected_pt = 0;
+ // See if we are using variable loop period sampling, if so, compensate for it by scaling the expected mclk count
+ if(pfd->ref_clk_expected_inc)
+ {
+ uint16_t ref_clk_expected_pt = pfd->ref_clk_pt_last + pfd->ref_clk_expected_inc;
+ // This uses casting trickery to work out the difference between the timer values accounting for wrap at 65536
+ int16_t ref_clk_diff = PORT_TIMEAFTER(ref_clk_pt, ref_clk_expected_pt) ? -(int16_t)(ref_clk_expected_pt - ref_clk_pt) : (int16_t)(ref_clk_pt - ref_clk_expected_pt);
+ pfd->ref_clk_pt_last = ref_clk_pt;
+
+ // This allows for wrapping of the timer when CONTROL_LOOP_COUNT is high
+ // Note we use a pre-computed divide followed by a shift to replace a constant divide with a constant multiply + shift
+ uint32_t mclk_expected_pt_inc = ((uint64_t)pfd->mclk_expected_pt_inc
+ * ((uint64_t)pfd->ref_clk_expected_inc + ref_clk_diff)
+ * pfd->ref_clk_scaling_numerator) >> SW_PLL_PFD_PRE_DIV_BITS;
+ // Below is the line we would use if we do not pre-compute the divide. This can take a long time if we spill over 32b
+ // uint32_t mclk_expected_pt_inc = pfd->mclk_expected_pt_inc * (pfd->ref_clk_expected_inc + ref_clk_diff) / pfd->ref_clk_expected_inc;
+ mclk_expected_pt = pfd->mclk_pt_last + mclk_expected_pt_inc;
+ }
+ else // we are assuming mclk_pt is sampled precisely and needs no compoensation
+ {
+ mclk_expected_pt = pfd->mclk_pt_last + pfd->mclk_expected_pt_inc;
+ }
+
+ // This uses casting trickery to work out the difference between the timer values accounting for wrap at 65536
+ pfd->mclk_diff = PORT_TIMEAFTER(mclk_pt, mclk_expected_pt) ? -(int16_t)(mclk_expected_pt - mclk_pt) : (int16_t)(mclk_pt - mclk_expected_pt);
+
+ // Check to see if something has gone very wrong, for example ref clock stop/start. If so, reset state and keep trying
+ if(MAGNITUDE(pfd->mclk_diff) > pfd->mclk_max_diff)
+ {
+ *first_loop = 1;
+ }
+}
diff --git a/lib_sw_pll/src/sw_pll_sdm.c b/lib_sw_pll/src/sw_pll_sdm.c
new file mode 100644
index 00000000..d126f494
--- /dev/null
+++ b/lib_sw_pll/src/sw_pll_sdm.c
@@ -0,0 +1,129 @@
+// Copyright 2022-2023 XMOS LIMITED.
+// This Software is subject to the terms of the XMOS Public Licence: Version 1.
+
+#include "sw_pll.h"
+#include
+
+void sw_pll_sdm_init( sw_pll_state_t * const sw_pll,
+ const sw_pll_15q16_t Kp,
+ const sw_pll_15q16_t Ki,
+ const sw_pll_15q16_t Kii,
+ const size_t loop_rate_count,
+ const size_t pll_ratio,
+ const uint32_t ref_clk_expected_inc,
+ const uint32_t app_pll_ctl_reg_val,
+ const uint32_t app_pll_div_reg_val,
+ const uint32_t app_pll_frac_reg_val,
+ const int32_t ctrl_mid_point,
+ const unsigned ppm_range)
+{
+ // Get PLL started and running at nominal
+ sw_pll_app_pll_init(get_local_tile_id(),
+ app_pll_ctl_reg_val,
+ app_pll_div_reg_val,
+ (uint16_t)(app_pll_frac_reg_val & 0xffff));
+
+ // Setup sw_pll with supplied user paramaters
+ sw_pll_lut_reset(sw_pll, Kp, Ki, Kii, 0);
+ // override windup limits
+ sw_pll->pi_state.i_windup_limit = SW_PLL_SDM_UPPER_LIMIT - SW_PLL_SDM_LOWER_LIMIT;
+ sw_pll->pi_state.ii_windup_limit = SW_PLL_SDM_UPPER_LIMIT - SW_PLL_SDM_LOWER_LIMIT;
+ sw_pll->sdm_state.ctrl_mid_point = ctrl_mid_point;
+ sw_pll->pi_state.iir_y = 0;
+ sw_pll->sdm_state.current_ctrl_val = ctrl_mid_point;
+
+ // Setup general controller state
+ sw_pll->lock_status = SW_PLL_UNLOCKED_LOW;
+ sw_pll->lock_counter = SW_PLL_LOCK_COUNT;
+
+ sw_pll->loop_rate_count = loop_rate_count;
+ sw_pll->loop_counter = 0;
+ sw_pll->first_loop = 1;
+
+ // Setup PFD state
+ sw_pll_pfd_init(&(sw_pll->pfd_state), loop_rate_count, pll_ratio, ref_clk_expected_inc, ppm_range);
+}
+
+
+void sw_pll_init_sigma_delta(sw_pll_sdm_state_t *sdm_state){
+ sdm_state->ds_x1 = 0;
+ sdm_state->ds_x2 = 0;
+ sdm_state->ds_x3 = 0;
+}
+
+
+__attribute__((always_inline))
+int32_t sw_pll_sdm_post_control_proc(sw_pll_state_t * const sw_pll, int32_t error)
+{
+ // Filter some noise into DCO to reduce jitter
+ // First order IIR, make A=0.125
+ // y = y + A(x-y)
+ sw_pll->pi_state.iir_y += ((error - sw_pll->pi_state.iir_y)>>3);
+
+ int32_t dco_ctl = sw_pll->sdm_state.ctrl_mid_point + sw_pll->pi_state.iir_y;
+
+ if(dco_ctl > SW_PLL_SDM_UPPER_LIMIT){
+ dco_ctl = SW_PLL_SDM_UPPER_LIMIT;
+ sw_pll->lock_status = SW_PLL_UNLOCKED_HIGH;
+ sw_pll->lock_counter = SW_PLL_LOCK_COUNT;
+ } else if (dco_ctl < SW_PLL_SDM_LOWER_LIMIT){
+ dco_ctl = SW_PLL_SDM_LOWER_LIMIT;
+ sw_pll->lock_status = SW_PLL_UNLOCKED_LOW;
+ sw_pll->lock_counter = SW_PLL_LOCK_COUNT;
+ } else {
+ if(sw_pll->lock_counter){
+ sw_pll->lock_counter--;
+ } else {
+ sw_pll->lock_status = SW_PLL_LOCKED;
+ }
+ }
+
+ return dco_ctl;
+}
+
+
+
+__attribute__((always_inline))
+inline sw_pll_lock_status_t sw_pll_sdm_do_control_from_error(sw_pll_state_t * const sw_pll, int16_t error)
+{
+ int32_t ctrl_error = sw_pll_do_pi_ctrl(sw_pll, error);
+ sw_pll->sdm_state.current_ctrl_val = sw_pll_sdm_post_control_proc(sw_pll, ctrl_error);
+
+ return sw_pll->lock_status;
+}
+
+
+bool sw_pll_sdm_do_control(sw_pll_state_t * const sw_pll, const uint16_t mclk_pt, const uint16_t ref_clk_pt)
+{
+ bool control_done = true;
+
+ if (++sw_pll->loop_counter == sw_pll->loop_rate_count)
+ {
+ sw_pll->loop_counter = 0;
+
+ if (sw_pll->first_loop) // First loop around so ensure state is clear
+ {
+ sw_pll->pfd_state.mclk_pt_last = mclk_pt; // load last mclk measurement with sensible data
+ sw_pll->pi_state.error_accum = 0;
+ sw_pll->pi_state.iir_y = 0;
+ sw_pll->lock_counter = SW_PLL_LOCK_COUNT;
+ sw_pll->lock_status = SW_PLL_UNLOCKED_LOW;
+
+ sw_pll->first_loop = 0;
+ // Do not set current_ctrl_val as last setting probably the best. At power on we set to nominal (midway in settings)
+
+ }
+ else
+ {
+ sw_pll_calc_error_from_port_timers(&(sw_pll->pfd_state), &(sw_pll->first_loop), mclk_pt, ref_clk_pt);
+ sw_pll_sdm_do_control_from_error(sw_pll, -sw_pll->pfd_state.mclk_diff);
+
+ // Save for next iteration to calc diff
+ sw_pll->pfd_state.mclk_pt_last = mclk_pt;
+ }
+ } else {
+ control_done = false;
+ }
+
+ return control_done;
+}
diff --git a/lib_sw_pll/src/sw_pll_sdm.h b/lib_sw_pll/src/sw_pll_sdm.h
new file mode 100644
index 00000000..4860b9ea
--- /dev/null
+++ b/lib_sw_pll/src/sw_pll_sdm.h
@@ -0,0 +1,114 @@
+// Copyright 2023 XMOS LIMITED.
+// This Software is subject to the terms of the XMOS Public Licence: Version 1.
+
+#include "sw_pll.h"
+
+#pragma once
+
+#define SW_PLL_SDM_UPPER_LIMIT 980000
+#define SW_PLL_SDM_LOWER_LIMIT 60000
+
+typedef int tileref_t;
+
+
+/**
+ * low level sw_pll_calc_sigma_delta function that turns a control signal
+ * into a Sigma Delta Modulated output signal.
+ *
+ *
+ * \param sdm_state Pointer to the SDM state.
+ * \param sdm_in 32b signed input error value. Note limited range.
+ * See SW_PLL_SDM_UPPER_LIMIT and SW_PLL_SDM_LOWER_LIMIT.
+ * \returns Sigma Delta modulated signal.
+ */
+__attribute__((always_inline))
+static inline int32_t sw_pll_calc_sigma_delta(sw_pll_sdm_state_t *sdm_state, int32_t sdm_in){
+ // Third order, 9 level output delta sigma. 20 bit unsigned input.
+ int32_t sdm_out = ((sdm_state->ds_x3<<4) + (sdm_state->ds_x3<<1)) >> 13;
+ if (sdm_out > 8){
+ sdm_out = 8;
+ }
+ if (sdm_out < 0){
+ sdm_out = 0;
+ }
+ sdm_state->ds_x3 += (sdm_state->ds_x2>>5) - (sdm_out<<9) - (sdm_out<<8);
+ sdm_state->ds_x2 += (sdm_state->ds_x1>>5) - (sdm_out<<14);
+ sdm_state->ds_x1 += sdm_in - (sdm_out<<17);
+
+ return sdm_out;
+}
+
+/**
+ * low level sw_pll_sdm sw_pll_sdm_out_to_frac_reg function that turns
+ * a sigma delta output signal into a PLL fractional register setting.
+ *
+ * \param sdm_out 32b signed input value.
+ * \returns Fractional register value.
+ */
+__attribute__((always_inline))
+static inline uint32_t sw_pll_sdm_out_to_frac_reg(int32_t sdm_out){
+ // bit 31 is frac enable
+ // bits 15..8 are the f value
+ // bits 7..0 are the p value
+ // Freq - F + (f + 1)/(p + 1)
+ uint32_t frac_val = 0;
+
+ if (sdm_out == 0){
+ frac_val = 0x00000007; // step 0/8
+ }
+ else{
+ frac_val = ((sdm_out - 1) << 8) | 0x80000007; // steps 1/8 to 8/8
+ }
+
+ return frac_val;
+}
+
+/**
+ * low level sw_pll_write_frac_reg function that writes the PLL fractional
+ * register.
+ *
+ * NOTE: Attempting to write the PLL fractional register from more than
+ * one logical core at the same time may result in channel lock-up.
+ * Please ensure the that PLL initiaisation has completed before
+ * the SDM task writes to the register. The provided example
+ * implements a method for doing this.
+ *
+ * \param this_tile The ID of the xcore tile that is doing the write.
+ * \param frac_val 16b signed input error value
+ */
+__attribute__((always_inline))
+static inline void sw_pll_write_frac_reg(tileref_t this_tile, uint32_t frac_val){
+ write_sswitch_reg(this_tile, XS1_SSWITCH_SS_APP_PLL_FRAC_N_DIVIDER_NUM, frac_val);
+}
+
+
+/**
+ * Performs the Sigma Delta Modulation from a control input.
+ * It performs the SDM algorithm, converts the output to a fractional register setting
+ * and then writes the value to the PLL fractional register.
+ * Is typically called in a constant period fast loop and run from a dedicated thread which could be on a remote tile.
+ *
+ * NOTE: Attempting to write the PLL fractional register from more than
+ * one logical core at the same time may result in channel lock-up.
+ * Please ensure the that PLL initiaisation has completed before
+ * the SDM task writes to the register. The provided `simple_sdm` example
+ * implements a method for doing this.
+ *
+ * \param sw_pll Pointer to the SDM state struct.
+ * \param this_tile The ID of the xcore tile that is doing the write.
+ * Use get_local_tile_id() to obtain this.
+ * \param sdm_control_in Current control value.
+ */
+__attribute__((always_inline))
+static inline void sw_pll_do_sigma_delta(sw_pll_sdm_state_t *sdm_state, tileref_t this_tile, int32_t sdm_control_in){
+
+ int32_t sdm_out = sw_pll_calc_sigma_delta(sdm_state, sdm_control_in);
+ uint32_t frac_val = sw_pll_sdm_out_to_frac_reg(sdm_out);
+ sw_pll_write_frac_reg(this_tile, frac_val);
+}
+
+// This is here to allow access without circular dependancies in the includes
+extern void sw_pll_app_pll_init(const unsigned tileid,
+ const uint32_t app_pll_ctl_reg_val,
+ const uint32_t app_pll_div_reg_val,
+ const uint16_t frac_val_nominal);
diff --git a/python/sw_pll/analysis_tools.py b/python/sw_pll/analysis_tools.py
new file mode 100644
index 00000000..dd9be5e6
--- /dev/null
+++ b/python/sw_pll/analysis_tools.py
@@ -0,0 +1,96 @@
+# Copyright 2023 XMOS LIMITED.
+# This Software is subject to the terms of the XMOS Public Licence: Version 1.
+
+import matplotlib.pyplot as plt
+import numpy as np
+import soundfile
+from scipy.io import wavfile # soundfile has some issues writing high Fs files
+
+class audio_modulator:
+ """
+ This test helper generates a wav file with a fixed sample rate and tone frequency
+ of a certain length.
+ A method then allows sections of it to be frequency modulated by a value in Hz.
+ The modulated signal (which uses cumultaive phase to avoid discontinuites)
+ may then be plotted as an FFT to understand the SNR/THD and may also be saved
+ as a wav file.
+ """
+
+ def __init__(self, duration_s, sample_rate=48000, test_tone_hz=1000):
+ self.sample_rate = sample_rate
+ self.test_tone_hz = test_tone_hz
+
+ self.modulator = np.full(int(duration_s * sample_rate), test_tone_hz, dtype=np.float64)
+
+ def apply_frequency_deviation(self, start_s, end_s, delta_freq):
+ start_idx = int(start_s * self.sample_rate)
+ end_idx = int(end_s * self.sample_rate)
+ self.modulator[start_idx:end_idx] += delta_freq
+
+ def modulate_waveform(self):
+ # Now create the frequency modulated waveform
+ # this is designed to accumulate the phase so doesn't see discontinuities
+ # https://dsp.stackexchange.com/questions/80768/fsk-modulation-with-python
+ delta_phi = self.modulator * np.pi / (self.sample_rate / 2.0)
+ phi = np.cumsum(delta_phi)
+ self.waveform = np.sin(phi)
+
+ def save_modulated_wav(self, filename):
+ integer_output = np.int16(self.waveform * 32767)
+ # soundfile.write(filename, integer_output, int(self.sample_rate)) # This struggles with >768ksps
+ wavfile.write(filename, int(self.sample_rate), integer_output)
+
+ def plot_modulated_fft(self, filename, skip_s=None):
+ start_x = 0 if skip_s is None else int(skip_s * self.sample_rate) // 2 * 2
+ waveform = self.waveform[start_x:]
+
+ xf = np.linspace(0.0, 1.0/(2.0/self.sample_rate), waveform.size // 2)
+ N = xf.size
+ window = np.kaiser(N*2, 14)
+ waveform = waveform * window
+ yf = np.fft.fft(waveform)
+ fig, ax = plt.subplots()
+
+ # Plot a zoom in on the test
+ tone_idx = int(self.test_tone_hz / (self.sample_rate / 2) * N)
+ num_side_bins = 50
+ yf = 20 * np.log10(np.abs(yf) / N)
+ # ax.plot(xf[tone_idx - num_side_bins:tone_idx + num_side_bins], yf[tone_idx - num_side_bins:tone_idx + num_side_bins], marker='.')
+
+ # Plot the whole frequncy range from DC to nyquist
+ ax.plot(xf[:N], yf[:N], marker='.')
+ ax.set_xscale("log")
+ plt.xlim((10**1, 10**5))
+ plt.ylim((-200, 0))
+ plt.savefig(filename, dpi=150)
+
+ def load_wav(self, filename):
+ """
+ Used for testing only - load a wav into self.waveform
+ """
+ self.waveform, self.sample_rate = soundfile.read(filename)
+
+
+if __name__ == '__main__':
+ """
+ This module is not intended to be run directly. This is here for internal testing only.
+ """
+ if 0:
+ test_len = 10
+ audio = audio_modulator(test_len)
+ for time_s in range(test_len):
+ modulation_hz = 10 * (time_s - (test_len) / 2)
+ audio.apply_frequency_deviation(time_s, time_s + 1, modulation_hz)
+
+ audio.modulate_waveform()
+ audio.save_modulated_wav("modulated.wav")
+ audio.plot_modulated_fft("modulated_fft.png")
+
+ else:
+ audio = audio_modulator(1)
+ audio.load_wav("modulated_tone_1000Hz_sd_ds.wav")
+ # audio = audio_modulator(1, sample_rate=3072000)
+ # audio.modulate_waveform()
+ audio.plot_modulated_fft("modulated_tone_1000Hz_sd_ds.png")
+ # audio.save_modulated_wav("modulated.wav")
+
diff --git a/python/sw_pll/app_pll_model.py b/python/sw_pll/app_pll_model.py
new file mode 100644
index 00000000..e6c3f9ef
--- /dev/null
+++ b/python/sw_pll/app_pll_model.py
@@ -0,0 +1,287 @@
+# Copyright 2023 XMOS LIMITED.
+# This Software is subject to the terms of the XMOS Public Licence: Version 1.
+
+import subprocess
+import re
+from pathlib import Path
+from sw_pll.pll_calc import print_regs
+from contextlib import redirect_stdout
+import io
+
+register_file = "register_setup.h" # can be changed as needed. This contains the register setup params and is accessible via C in the firmware
+
+
+class app_pll_frac_calc:
+ """
+ This class uses the formulae in the XU316 datasheet to calculate the output frequency of the
+ application PLL (sometimes called secondary PLL) from the register settings provided.
+ It uses the checks specified in the datasheet to ensure the settings are valid, and will assert if not.
+ To keep the inherent jitter of the PLL output down to a minimum, it is recommended that R be kept small,
+ ideally = 0 (which equiates to 1) but reduces lock range.
+ """
+
+ frac_enable_mask = 0x80000000
+
+ def __init__(self, input_frequency, F_init, R_init, f_init, p_init, OD_init, ACD_init, verbose=False):
+ """
+ Constructor initialising a PLL instance
+ """
+ self.input_frequency = input_frequency
+ self.F = F_init
+ self.R = R_init
+ self.OD = OD_init
+ self.ACD = ACD_init
+ self.f = f_init # fractional multiplier (+1.0)
+ self.p = p_init # fractional divider (+1.0)
+ self.output_frequency = None
+ self.fractional_enable = True
+ self.verbose = verbose
+
+ self.calc_frequency()
+
+ def calc_frequency(self):
+ """
+ Calculate the output frequency based on current object settings
+ """
+ if self.verbose:
+ print(f"F: {self.F} R: {self.R} OD: {self.OD} ACD: {self.ACD} f: {self.f} p: {self.p}")
+ print(f"input_frequency: {self.input_frequency}")
+ assert self.F >= 1 and self.F <= 8191, f"Invalid F setting {self.F}"
+ assert type(self.F) is int, f"Error: F must be an INT"
+ assert self.R >= 0 and self.R <= 63, f"Invalid R setting {self.R}"
+ assert type(self.R) is int, f"Error: R must be an INT"
+ assert self.OD >= 0 and self.OD <= 7, f"Invalid OD setting {self.OD}"
+ assert type(self.OD) is int, f"Error: OD must be an INT"
+
+ intermediate_freq = self.input_frequency * (self.F + 1.0) / 2.0 / (self.R + 1.0)
+ assert intermediate_freq >= 360000000.0 and intermediate_freq <= 1800000000.0, f"Invalid VCO freq: {intermediate_freq}"
+ # print(f"intermediate_freq: {intermediate_freq}")
+
+ assert type(self.p) is int, f"Error: r must be an INT"
+ assert type(self.f) is int, f"Error: f must be an INT"
+
+ # From XU316-1024-QF60A-xcore.ai-Datasheet_22.pdf
+ if self.fractional_enable:
+ # assert self.p > self.f, "Error f is not < p: {self.f} {self.p}" # This check has been removed as Joe found it to be OK in RTL/practice
+ pll_ratio = (self.F + 1.0 + ((self.f + 1) / (self.p + 1)) ) / 2.0 / (self.R + 1.0) / (self.OD + 1.0) / (2.0 * (self.ACD + 1))
+ else:
+ pll_ratio = (self.F + 1.0) / 2.0 / (self.R + 1.0) / (self.OD + 1.0) / (2.0 * (self.ACD + 1))
+
+ self.output_frequency = self.input_frequency * pll_ratio
+
+ return self.output_frequency
+
+ def get_output_frequency(self):
+ """
+ Get last calculated frequency
+ """
+ return self.output_frequency
+
+ def update_all(self, F, R, OD, ACD, f, p):
+ """
+ Reset all App PLL vars
+ """
+ self.F = F
+ self.R = R
+ self.OD = OD
+ self.ACD = ACD
+ self.f = f
+ self.p = p
+ return self.calc_frequency()
+
+ def update_frac(self, f, p, fractional=None):
+ """
+ Update only the fractional parts of the App PLL
+ """
+ self.f = f
+ self.p = p
+ # print(f"update_frac f:{self.f} p:{self.p}")
+ if fractional is not None:
+ self.fractional_enable = fractional
+
+ return self.calc_frequency()
+
+ def update_frac_reg(self, reg):
+ """
+ Determine f and p from the register number and recalculate frequency
+ Assumes fractional is set to true
+ """
+ f = int((reg >> 8) & ((2**8)-1))
+ p = int(reg & ((2**8)-1))
+
+ self.fractional_enable = True if (reg & self.frac_enable_mask) else False
+
+ return self.update_frac(f, p)
+
+
+ def get_frac_reg(self):
+ """
+ Returns the fractional reg value from current setting
+ """
+ # print(f"get_frac_reg f:{self.f} p:{self.p}")
+ reg = self.p | (self.f << 8)
+ if self.fractional_enable:
+ reg |= self.frac_enable_mask
+
+ return reg
+
+ def gen_register_file_text(self):
+ """
+ Helper used to generate text for the register setup h file
+ """
+ text = f"/* Input freq: {self.input_frequency}\n"
+ text += f" F: {self.F}\n"
+ text += f" R: {self.R}\n"
+ text += f" f: {self.f}\n"
+ text += f" p: {self.p}\n"
+ text += f" OD: {self.OD}\n"
+ text += f" ACD: {self.ACD}\n"
+ text += "*/\n\n"
+
+ # This is a way of calling a printing function from another module and capturing the STDOUT
+ class args:
+ app = True
+ f = io.StringIO()
+ with redirect_stdout(f):
+ # in pll_calc, op_div = OD, fb_div = F, f, p, ref_div = R, fin_op_div = ACD
+ print_regs(args, self.OD + 1, [self.F + 1, self.f + 1, self.p + 1] , self.R + 1, self.ACD + 1)
+ text += f.getvalue().replace(" ", "_").replace("REG_0x", "REG 0x").replace("APP_PLL", "#define APP_PLL")
+
+ return text
+
+ # see /doc/sw_pll.rst for guidance on these settings
+def get_pll_solution(input_frequency, target_output_frequency, max_denom=80, min_F=200, ppm_max=2, fracmin=0.65, fracmax=0.95):
+ """
+ This is a wrapper function for pll_calc.py and allows it to be called programatically.
+ It contains sensible defaults for the arguments and abstracts some of the complexity away from
+ the underlying script. Configuring the PLL is not an exact science and there are many tradeoffs involved.
+ See sw_pll.rst for some of the tradeoffs involved and some example paramater sets.
+
+ Once run, this function saves two output files:
+ - fractions.h which contains the fractional term lookup table, which is guarranteed monotonic (important for PI stability)
+ - register_setup.h which contains the PLL settings in comments as well as register settings for init in the application
+
+ This function and the underlying call to pll_calc may take several seconds to complete since it searches a range
+ of possible solutions numerically.
+
+ input_frequency - The xcore clock frequency, normally the XTAL frequency
+ nominal_ref_frequency - The nominal input reference frequency
+ target_output_frequency - The nominal target output frequency
+ max_denom - (Optional) The maximum fractional denominator. See/doc/sw_pll.rst for guidance
+ min_F - (Optional) The minimum integer numerator. See/doc/sw_pll.rst for guidance
+ ppm_max - (Optional) The allowable PPM deviation for the target nominal frequency. See/doc/sw_pll.rst for guidance
+ fracmin - (Optional) The minimum fractional multiplier. See/doc/sw_pll.rst for guidance
+ fracmax - (Optional) The maximum fractional multiplier. See/doc/sw_pll.rst for guidance
+
+ """
+
+
+
+ input_frequency_MHz = input_frequency / 1000000.0
+ target_output_frequency_MHz = target_output_frequency / 1000000.0
+
+ calc_script = Path(__file__).parent/"pll_calc.py"
+
+ # input freq, app pll, max denom, output freq, min phase comp freq, max ppm error, raw, fractional range, make header
+ cmd = f"{calc_script} -i {input_frequency_MHz} -a -m {max_denom} -t {target_output_frequency_MHz} -p 6.0 -e {int(ppm_max)} -r --fracmin {fracmin} --fracmax {fracmax} --header"
+ print(f"Running: {cmd}")
+ output = subprocess.check_output(cmd.split(), text=True)
+
+ # Get each solution
+ solutions = []
+ Fs = []
+ regex = r"Found solution.+\nAPP.+\nAPP.+\nAPP.+"
+ matches = re.findall(regex, output)
+
+ for solution in matches:
+ F = int(float(re.search(r".+FD\s+(\d+.\d+).+", solution).groups()[0]))
+ solutions.append(solution)
+ Fs.append(F)
+
+ possible_Fs = sorted(set(Fs))
+ print(f"Available F values: {possible_Fs}")
+
+ # Find first solution with F greater than F
+ idx = next(x for x, val in enumerate(Fs) if val > min_F)
+ solution = matches[idx]
+
+ # Get actual PLL register bitfield settings and info
+ regex = r".+OUT (\d+\.\d+)MHz, VCO (\d+\.\d+)MHz, RD\s+(\d+), FD\s+(\d+.\d*)\s+\(m =\s+(\d+), n =\s+(\d+)\), OD\s+(\d+), FOD\s+(\d+), ERR (-*\d+.\d+)ppm.*"
+ match = re.search(regex, solution)
+
+ if match:
+ vals = match.groups()
+
+ output_frequency = (1000000.0 * float(vals[0]))
+ vco_freq = 1000000.0 * float(vals[1])
+
+ # Now convert to actual settings in register bitfields
+ F = int(float(vals[3]) - 1) # PLL integer multiplier
+ R = int(vals[2]) - 1 # PLL integer divisor
+ f = int(vals[4]) - 1 # PLL fractional multiplier
+ p = int(vals[5]) - 1 # PLL fractional divisor
+ OD = int(vals[6]) - 1 # PLL output divider
+ ACD = int(vals[7]) - 1 # PLL application clock divider
+ ppm = float(vals[8]) # PLL PPM error for requrested set frequency
+
+ assert match, f"Could not parse output of: {cmd} output: {solution}"
+
+ # Now get reg values and save to file
+ with open(register_file, "w") as reg_vals:
+ reg_vals.write(f"/* Autogenerated by {Path(__file__).name} using command:\n")
+ reg_vals.write(f" {cmd}\n")
+ reg_vals.write(f" Picked output solution #{idx}\n")
+ # reg_vals.write(f"\n{solution}\n\n") # This is verbose and contains the same info as below
+ reg_vals.write(f" Input freq: {input_frequency}\n")
+ reg_vals.write(f" F: {F}\n")
+ reg_vals.write(f" R: {R}\n")
+ reg_vals.write(f" f: {f}\n")
+ reg_vals.write(f" p: {p}\n")
+ reg_vals.write(f" OD: {OD}\n")
+ reg_vals.write(f" ACD: {ACD}\n")
+ reg_vals.write(f" Output freq: {output_frequency}\n")
+ reg_vals.write(f" VCO freq: {vco_freq} */\n")
+ reg_vals.write("\n")
+
+
+ for reg in ["APP PLL CTL REG", "APP PLL DIV REG", "APP PLL FRAC REG"]:
+ regex = rf"({reg})\s+(0[xX][A-Fa-f0-9]+)"
+ match = re.search(regex, solution)
+ if match:
+ val = match.groups()[1]
+ reg_name = reg.replace(" ", "_")
+ line = f"#define {reg_name} \t{val}\n"
+ reg_vals.write(line)
+
+
+ return output_frequency, vco_freq, F, R, f, p, OD, ACD, ppm
+
+class pll_solution:
+ """
+ Access to all the info from get_pll_solution, cleaning up temp files.
+ intended for programatic access from the tests. Creates a PLL setup and LUT and reads back the generated LUT
+ """
+ def __init__(self, *args, **kwargs):
+ self.output_frequency, self.vco_freq, self.F, self.R, self.f, self.p, self.OD, self.ACD, self.ppm = get_pll_solution(*args, **kwargs)
+ from .dco_model import lut_dco
+ dco = lut_dco("fractions.h")
+ self.lut, min_frac, max_frac = dco._read_lut_header("fractions.h")
+
+
+if __name__ == '__main__':
+ """
+ This module is not intended to be run directly. This is here for internal testing only.
+ """
+ input_frequency = 24000000
+ output_frequency = 12288000
+ print(f"get_pll_solution input_frequency: {input_frequency} output_frequency: {output_frequency}...")
+ output_frequency, vco_freq, F, R, f, p, OD, ACD, ppm = get_pll_solution(input_frequency, output_frequency)
+ print(f"got solution: \noutput_frequency: {output_frequency}\nvco_freq: {vco_freq}\nF: {F}\nR: {R}\nf: {f}\np: {p}\nOD: {OD}\nACD: {ACD}\nppm: {ppm}")
+
+ app_pll = app_pll_frac_calc(input_frequency, F, R, f, p, OD, ACD)
+ print(f"Got output frequency: {app_pll.calc_frequency()}")
+ p = 10
+ for f in range(p):
+ for frac_enable in [True, False]:
+ print(f"For f: {f} frac_enable: {frac_enable} got frequency: {app_pll.update_frac(f, p, frac_enable)}")
+
diff --git a/python/sw_pll/controller_model.py b/python/sw_pll/controller_model.py
new file mode 100644
index 00000000..17f165fe
--- /dev/null
+++ b/python/sw_pll/controller_model.py
@@ -0,0 +1,204 @@
+# Copyright 2023 XMOS LIMITED.
+# This Software is subject to the terms of the XMOS Public Licence: Version 1.
+
+from sw_pll.dco_model import lut_dco, sigma_delta_dco, lock_count_threshold
+import numpy as np
+
+
+class pi_ctrl():
+ """
+ Parent PI(I) controller class
+ """
+ def __init__(self, Kp, Ki, Kii=None, i_windup_limit=None, ii_windup_limit=None, verbose=False):
+ self.Kp = Kp
+ self.Ki = Ki
+ self.Kii = 0.0 if Kii is None else Kii
+ self.i_windup_limit = i_windup_limit
+ self.ii_windup_limit = ii_windup_limit
+
+ self.error_accum = 0.0 # Integral of error
+ self.error_accum_accum = 0.0 # Double integral of error (optional)
+ self.total_error = 0.0 # Calculated total error
+
+ self.verbose = verbose
+
+ if verbose:
+ print(f"Init sw_pll_pi_ctrl, Kp: {Kp} Ki: {Ki} Kii: {Kii}")
+
+ def _reset_controller(self):
+ """
+ Reset any accumulated state
+ """
+ self.error_accum = 0.0
+ self.error_accum_accum = 0.0
+ self.total_error = 0.0
+
+ def do_control_from_error(self, error):
+ """
+ Calculate the LUT setting from the input error
+ """
+
+ # clamp integral terms to stop them irrecoverably drifting off.
+ if self.i_windup_limit is None:
+ self.error_accum = self.error_accum + error
+ else:
+ self.error_accum = np.clip(self.error_accum + error, -self.i_windup_limit, self.i_windup_limit)
+
+ if self.ii_windup_limit is None:
+ self.error_accum_accum = self.error_accum_accum + self.error_accum
+ else:
+ self.error_accum_accum = np.clip(self.error_accum_accum + self.error_accum, -self.ii_windup_limit, self.ii_windup_limit)
+
+ error_p = self.Kp * error;
+ error_i = self.Ki * self.error_accum
+ error_ii = self.Kii * self.error_accum_accum
+
+ self.total_error = error_p + error_i + error_ii
+
+ if self.verbose:
+ print(f"error: {error} error_p: {error_p} error_i: {error_i} error_ii: {error_ii} total error: {self.total_error}")
+
+ return self.total_error
+
+
+
+##############################
+# LOOK UP TABLE IMPLEMENTATION
+##############################
+
+class lut_pi_ctrl(pi_ctrl):
+ """
+ This class instantiates a control loop instance. It takes a lookup table function which can be generated
+ from the error_from_h class which allows it use the actual pre-calculated transfer function.
+ Once instantiated, the do_control method runs the control loop.
+
+ This class forms the core of the simulator and allows the constants (K..) to be tuned to acheive the
+ desired response. The function run_sim allows for a plot of a step resopnse input which allows this
+ to be done visually.
+ """
+ def __init__(self, Kp, Ki, Kii=None, base_lut_index=None, verbose=False):
+ """
+ Create instance absed on specific control constants
+ """
+ self.dco = lut_dco()
+ self.lut_lookup_function = self.dco.get_lut()
+ lut_size = self.dco.get_lut_size()
+ self.diff = 0.0 # Most recent diff between expected and actual. Used by tests
+
+
+ # By default set the nominal LUT index to half way
+ if base_lut_index is None:
+ base_lut_index = lut_size // 2
+ self.base_lut_index = base_lut_index
+
+ # Set windup limit to the lut_size, which by default is double of the deflection from nominal
+ i_windup_limit = lut_size / Ki if Ki != 0.0 else 0.0
+ ii_windup_limit = 0.0 if Kii is None else lut_size / Kii if Kii != 0.0 else 0.0
+
+ pi_ctrl.__init__(self, Kp, Ki, Kii=Kii, i_windup_limit=i_windup_limit, ii_windup_limit=ii_windup_limit, verbose=verbose)
+
+ self.verbose = verbose
+
+ if verbose:
+ print(f"Init lut_pi_ctrl, Kp: {Kp} Ki: {Ki} Kii: {Kii}")
+
+ def get_dco_control_from_error(self, error, first_loop=False):
+ """
+ Calculate the LUT setting from the input error
+ """
+ self.diff = error # Used by tests
+
+ if first_loop:
+ pi_ctrl._reset_controller(self)
+ error = 0.0
+
+ dco_ctrl = self.base_lut_index - pi_ctrl.do_control_from_error(self, error)
+
+ return None if first_loop else dco_ctrl
+
+
+######################################
+# SIGMA DELTA MODULATOR IMPLEMENTATION
+######################################
+
+class sdm_pi_ctrl(pi_ctrl):
+ def __init__(self, mod_init, sdm_in_max, sdm_in_min, Kp, Ki, Kii=None, verbose=False):
+ """
+ Create instance absed on specific control constants
+ """
+ pi_ctrl.__init__(self, Kp, Ki, Kii=Kii, verbose=verbose)
+
+ # Low pass filter state
+ self.alpha = 0.125
+ self.iir_y = 0
+
+ # Nominal setting for SDM
+ self.initial_setting = mod_init
+
+ # Limits for SDM output
+ self.sdm_in_max = sdm_in_max
+ self.sdm_in_min = sdm_in_min
+
+ # Lock status state
+ self.lock_status = -1
+ self.lock_count = lock_count_threshold
+
+ def do_control_from_error(self, error):
+ """
+ Run the control loop. Also contains an additional
+ low passs filtering stage.
+ """
+ x = pi_ctrl.do_control_from_error(self, -error)
+ x = int(x)
+
+ # Filter noise into DCO to reduce jitter
+ # First order IIR, make A=0.125
+ # y = y + A(x-y)
+
+ # self.iir_y = int(self.iir_y + (x - self.iir_y) * self.alpha)
+ self.iir_y += (x - self.iir_y) >> 3 # This matches the firmware
+
+ sdm_in = self.initial_setting + self.iir_y
+
+
+ if sdm_in > self.sdm_in_max:
+ print(f"SDM Pos clip: {sdm_in}, {self.sdm_in_max}")
+ sdm_in = self. sdm_in_max
+ self.lock_status = 1
+ self.lock_count = lock_count_threshold
+
+ elif sdm_in < self.sdm_in_min:
+ print(f"SDM Neg clip: {sdm_in}, {self.sdm_in_min}")
+ sdm_in = self.sdm_in_min
+ self.lock_status = -1
+ self.lock_count = lock_count_threshold
+
+ else:
+ if self.lock_count > 0:
+ self.lock_count -= 1
+ else:
+ self.lock_status = 0
+
+ return sdm_in, self.lock_status
+
+
+if __name__ == '__main__':
+ """
+ This module is not intended to be run directly. This is here for internal testing only.
+ """
+ Kp = 1.0
+ Ki = 0.1
+ Kii = 0.0
+
+ sw_pll = lut_pi_ctrl(Kp, Ki, Kii=Kii, verbose=True)
+ for error_input in range(-10, 20):
+ dco_ctrl = sw_pll.do_control_from_error(error_input)
+
+ mod_init = (sigma_delta_dco.sdm_in_max + sigma_delta_dco.sdm_in_min) / 2
+ Kp = 0.0
+ Ki = 0.1
+ Kii = 0.1
+
+ sw_pll = sdm_pi_ctrl(mod_init, sigma_delta_dco.sdm_in_max, sigma_delta_dco.sdm_in_min, Kp, Ki, Kii=Kii, verbose=True)
+ for error_input in range(-10, 20):
+ dco_ctrl, lock_status = sw_pll.do_control_from_error(error_input)
diff --git a/python/sw_pll/dco_model.py b/python/sw_pll/dco_model.py
new file mode 100644
index 00000000..a08d6339
--- /dev/null
+++ b/python/sw_pll/dco_model.py
@@ -0,0 +1,399 @@
+# Copyright 2023 XMOS LIMITED.
+# This Software is subject to the terms of the XMOS Public Licence: Version 1.
+
+from sw_pll.app_pll_model import register_file, app_pll_frac_calc
+import matplotlib.pyplot as plt
+import numpy as np
+import os
+import re
+from pathlib import Path
+
+"""
+This file contains implementations of digitally controlled oscillators.
+It uses the app_pll_model underneath to turn a control signal into a
+calculated output frequency.
+
+It currently contains two implementations of DCO:
+
+- A lookup table version which is efficient in computation and offers
+ a range of frequencies based on a pre-calculated look up table (LUT)
+- A Sigma Delta Modulator which typically uses a dedicated thread to
+ run the modulator but results in lower noise in the audio spectrum
+"""
+
+
+lock_status_lookup = {-1 : "UNLOCKED LOW", 0 : "LOCKED", 1 : "UNLOCKED HIGH"}
+lock_count_threshold = 10
+
+##############################
+# LOOK UP TABLE IMPLEMENTATION
+##############################
+
+class lut_dco:
+ """
+ This class parses a pre-generated fractions.h file and builds a lookup table so that the values can be
+ used by the sw_pll simulation. It may be used directly but is generally used a sub class of error_to_pll_output_frequency.
+ """
+
+ def __init__(self, header_file = "fractions.h", verbose=False): # fixed header_file name by pll_calc.py
+ """
+ Constructor for the LUT DCO. Reads the pre-calculated header filed and produces the LUT which contains
+ the pll fractional register settings (16b) for each of the entries. Also a
+ """
+
+ self.lut, self.min_frac, self.max_frac = self._read_lut_header(header_file)
+ input_freq, F, R, f, p, OD, ACD = self._parse_register_file(register_file)
+ self.app_pll = app_pll_frac_calc(input_freq, F, R, f, p, OD, ACD)
+
+ self.last_output_frequency = self.app_pll.update_frac_reg(self.lut[self.get_lut_size() // 2] | app_pll_frac_calc.frac_enable_mask)
+ self.lock_status = -1
+ self.lock_count = lock_count_threshold
+
+ def _read_lut_header(self, header_file):
+ """
+ read and parse the pre-written LUT
+ """
+ if not os.path.exists(header_file):
+ assert False, f"Please initialize a lut_dco to produce a parsable header file {header_file}"
+
+ with open(header_file) as hdr:
+ header = hdr.readlines()
+ min_frac = 1.0
+ max_frac = 0.0
+ for line in header:
+ regex_ne = fr"frac_values_?\d*\[(\d+)].*"
+ match = re.search(regex_ne, line)
+ if match:
+ num_entries = int(match.groups()[0])
+ # print(f"num_entries: {num_entries}")
+ lut = np.zeros(num_entries, dtype=np.uint16)
+
+ regex_fr = r"0x([0-9A-F]+).+Index:\s+(\d+).+=\s(0.\d+)"
+ match = re.search(regex_fr, line)
+ if match:
+ reg, idx, frac = match.groups()
+ reg = int(reg, 16)
+ idx = int(idx)
+ frac = float(frac)
+ min_frac = frac if frac < min_frac else min_frac
+ max_frac = frac if frac > max_frac else max_frac
+ lut[idx] = reg
+
+ # print(f"min_frac: {min_frac} max_frac: {max_frac}")
+ return lut, min_frac, max_frac
+
+ def _parse_register_file(self, register_file):
+ """
+ This method reads the pre-saved register setup comments from get_pll_solution and parses them into parameters that
+ can be used for later simulation.
+ """
+ if not os.path.exists(register_file):
+ assert False, f"Please initialize a lut_dco to produce a parsable register setup file {register_file}"
+
+ with open(register_file) as rf:
+ reg_file = rf.read().replace('\n', '')
+ input_freq = int(re.search(r".+Input freq:\s+(\d+).+", reg_file).groups()[0])
+ F = int(re.search(r".+F:\s+(\d+).+", reg_file).groups()[0])
+ R = int(re.search(r".+R:\s+(\d+).+", reg_file).groups()[0])
+ f = int(re.search(r".+f:\s+(\d+).+", reg_file).groups()[0])
+ p = int(re.search(r".+p:\s+(\d+).+", reg_file).groups()[0])
+ OD = int(re.search(r".+OD:\s+(\d+).+", reg_file).groups()[0])
+ ACD = int(re.search(r".+ACD:\s+(\d+).+", reg_file).groups()[0])
+
+ return input_freq, F, R, f, p, OD, ACD
+
+ def get_lut(self):
+ """
+ Return the look up table
+ """
+ return self.lut
+
+ def get_lut_size(self):
+ """
+ Return the size of look up table
+ """
+ return np.size(self.lut)
+
+ def print_stats(self, target_output_frequency):
+ """
+ Returns a summary of the LUT range and steps.
+ """
+ lut = self.get_lut()
+ steps = np.size(lut)
+
+ register = int(lut[0])
+ min_freq = self.app_pll.update_frac_reg(register | app_pll_frac_calc.frac_enable_mask)
+
+ register = int(lut[steps // 2])
+ mid_freq = self.app_pll.update_frac_reg(register | app_pll_frac_calc.frac_enable_mask)
+
+ register = int(lut[-1])
+ max_freq = self.app_pll.update_frac_reg(register | app_pll_frac_calc.frac_enable_mask)
+
+ ave_step_size = (max_freq - min_freq) / steps
+
+ print(f"LUT min_freq: {min_freq:.0f}Hz")
+ print(f"LUT mid_freq: {mid_freq:.0f}Hz")
+ print(f"LUT max_freq: {max_freq:.0f}Hz")
+ print(f"LUT entries: {steps} ({steps*2} bytes)")
+ print(f"LUT average step size: {ave_step_size:.6}Hz, PPM: {1e6 * ave_step_size/mid_freq:.6}")
+ print(f"PPM range: {1e6 * (1 - target_output_frequency / min_freq):.6}")
+ print(f"PPM range: +{1e6 * (max_freq / target_output_frequency - 1):.6}")
+
+ return min_freq, mid_freq, max_freq, steps
+
+
+ def plot_freq_range(self):
+ """
+ Generates a plot of the frequency range of the LUT and
+ visually shows the spacing of the discrete frequencies
+ that it can produce.
+ """
+
+ frequencies = []
+ for step in range(self.get_lut_size()):
+ register = int(self.lut[step])
+ self.app_pll.update_frac_reg(register | app_pll_frac_calc.frac_enable_mask)
+ frequencies.append(self.app_pll.get_output_frequency())
+
+ plt.clf()
+ plt.plot(frequencies, color='green', marker='.', label='frequency')
+ plt.title('PLL fractional range', fontsize=14)
+ plt.xlabel(f'LUT index', fontsize=14)
+ plt.ylabel('Frequency', fontsize=10)
+ plt.legend(loc="upper right")
+ plt.grid(True)
+ # plt.show()
+ plt.savefig("lut_dco_range.png", dpi=150)
+
+ def get_frequency_from_dco_control(self, dco_ctrl):
+ """
+ given a set_point, a LUT, and an APP_PLL, calculate the frequency
+ """
+
+ if dco_ctrl is None:
+ return self.last_output_frequency, self.lock_status
+
+ num_entries = self.get_lut_size()
+
+ set_point = int(dco_ctrl)
+ if set_point < 0:
+ set_point = 0
+ self.lock_status = -1
+ self.lock_count = lock_count_threshold
+ elif set_point >= num_entries:
+ set_point = num_entries - 1
+ self.lock_status = 1
+ self.lock_count = lock_count_threshold
+ else:
+ set_point = set_point
+ if self.lock_count > 0:
+ self.lock_count -= 1
+ else:
+ self.lock_status = 0
+
+ register = int(self.lut[set_point])
+
+ output_frequency = self.app_pll.update_frac_reg(register | app_pll_frac_calc.frac_enable_mask)
+ self.last_output_frequency = output_frequency
+ return output_frequency, self.lock_status
+
+
+
+######################################
+# SIGMA DELTA MODULATOR IMPLEMENTATION
+######################################
+
+class sdm:
+ """
+ Experimental - taken from lib_xua synchronous branch
+ Third order, 9 level output delta sigma. 20 bit unsigned input.
+ """
+ # Limits for SDM modulator for stability
+ sdm_in_max = 980000
+ sdm_in_min = 60000
+
+ def __init__(self):
+ # Delta sigma modulator state
+ self.sdm_x1 = 0
+ self.sdm_x2 = 0
+ self.sdm_x3 = 0
+
+ # # generalized version without fixed point shifts. WIP!!
+ # # takes a Q20 number from 60000 to 980000 (or 0.0572 to 0.934)
+ # # This is work in progress - the integer model matches the firmware better
+ # def do_sigma_delta(self, sdm_in):
+ # if sdm_in > self.sdm_in_max:
+ # print(f"SDM Pos clip: {sdm_in}, {self.sdm_in_max}")
+ # sdm_in = self. sdm_in_max
+ # self.lock_status = 1
+
+ # elif sdm_in < self.sdm_in_min:
+ # print(f"SDM Neg clip: {sdm_in}, {self.sdm_in_min}")
+ # sdm_in = self.sdm_in_min
+ # self.lock_status = -1
+
+ # else:
+ # self.lock_status = 0
+
+ # sdm_out = int(self.sdm_x3 * 0.002197265625)
+
+ # if sdm_out > 8:
+ # sdm_out = 8
+ # if sdm_out < 0:
+ # sdm_out = 0
+
+ # self.sdm_x3 += int((self.sdm_x2 * 0.03125) - (sdm_out * 768))
+ # self.sdm_x2 += int((self.sdm_x1 * 0.03125) - (sdm_out * 16384))
+ # self.sdm_x1 += int(sdm_in - (sdm_out * 131072))
+
+ # return int(sdm_out), self.lock_status
+
+ def do_sigma_delta_int(self, sdm_in):
+ # takes a Q20 number from 60000 to 980000 (or 0.0572 to 0.934)
+ # Third order, 9 level output delta sigma. 20 bit unsigned input.
+ sdm_in = int(sdm_in)
+
+ sdm_out = ((self.sdm_x3<<4) + (self.sdm_x3<<1)) >> 13
+
+ if sdm_out > 8:
+ sdm_out = 8
+ if sdm_out < 0:
+ sdm_out = 0
+
+ self.sdm_x3 += (self.sdm_x2>>5) - (sdm_out<<9) - (sdm_out<<8)
+ self.sdm_x2 += (self.sdm_x1>>5) - (sdm_out<<14)
+ self.sdm_x1 += sdm_in - (sdm_out<<17)
+
+ return sdm_out
+
+
+class sigma_delta_dco(sdm):
+ """
+ DCO based on the sigma delta modulator
+ PLL solution profiles depending on target output clock
+
+ These are designed to work with a SDM either running at
+ 1MHz:
+ - 10ps jitter 100Hz-40kHz with very low freq noise floor -100dBc
+ or 500kHz:
+ - 50ps jitter 100Hz-40kHz with low freq noise floor -93dBc.
+
+ """
+
+ profiles = {"24.576_1M": {"input_freq":24000000, "F":int(147.455 - 1), "R":1 - 1, "f":5 - 1, "p":11 - 1, "OD":6 - 1, "ACD":6 - 1, "output_frequency":24.576e6, "mod_init":478151, "sdm_rate":1000000},
+ "22.5792_1M": {"input_freq":24000000, "F":int(135.474 - 1), "R":1 - 1, "f":9 - 1, "p":19 - 1, "OD":6 - 1, "ACD":6 - 1, "output_frequency":22.5792e6, "mod_init":498283, "sdm_rate":1000000},
+ "24.576_500k": {"input_freq":24000000, "F":int(278.529 - 1), "R":2 - 1, "f":9 - 1, "p":17 - 1, "OD":2 - 1, "ACD":17 - 1, "output_frequency":24.576e6, "mod_init":553648, "sdm_rate":500000},
+ "22.5792_500k": {"input_freq":24000000, "F":int(293.529 - 1), "R":2 - 1, "f":9 - 1, "p":17 - 1, "OD":3 - 1, "ACD":13 - 1, "output_frequency":22.5792e6, "mod_init":555326, "sdm_rate":500000}
+ }
+
+
+ def __init__(self, profile):
+ """
+ Create a sigmal delta DCO targetting either 24.576 or 22.5792MHz
+ """
+ self.profile = profile
+ self.p_value = 8 # 8 frac settings + 1 non frac setting
+
+ input_freq, F, R, f, p, OD, ACD, _, _, _ = list(self.profiles[profile].values())
+
+ self.app_pll = app_pll_frac_calc(input_freq, F, R, f, p, OD, ACD)
+ self.sdm_out = 0
+ self.f = 0
+
+ sdm.__init__(self)
+
+ def _sdm_out_to_freq(self, sdm_out):
+ """
+ Translate the SDM steps to register settings
+ """
+ if sdm_out == 0:
+ # Step 0
+ self.f = 0
+ return self.app_pll.update_frac(self.f, self.p_value - 1, False)
+ else:
+ # Steps 1 to 8 inclusive
+ self.f = sdm_out - 1
+ return self.app_pll.update_frac(self.f, self.p_value - 1, True)
+
+ def do_modulate(self, input):
+ """
+ Input a control value and output a SDM signal
+ """
+ # self.sdm_out, lock_status = sdm.do_sigma_delta(self, input)
+ self.sdm_out = sdm.do_sigma_delta_int(self, input)
+
+ frequency = self._sdm_out_to_freq(self.sdm_out)
+
+ return frequency
+
+ def print_stats(self):
+ """
+ Returns a summary of the SDM range and steps.
+ """
+
+ steps = self.p_value + 1 # +1 we have frac off state
+ min_freq = self._sdm_out_to_freq(0)
+ max_freq = self._sdm_out_to_freq(self.p_value)
+ target_output_frequency = self.profiles[self.profile]["output_frequency"]
+
+
+ ave_step_size = (max_freq - min_freq) / steps
+
+ print(f"SDM min_freq: {min_freq:.0f}Hz")
+ print(f"SDM max_freq: {max_freq:.0f}Hz")
+ print(f"SDM steps: {steps}")
+ print(f"PPM range: {1e6 * (1 - target_output_frequency / min_freq):.6}")
+ print(f"PPM range: +{1e6 * (max_freq / target_output_frequency - 1):.6}")
+
+ return min_freq, max_freq, steps
+
+
+ def plot_freq_range(self):
+ """
+ Generates a plot of the frequency range of the LUT and
+ visually shows the spacing of the discrete frequencies
+ that it can produce.
+ """
+
+ frequencies = []
+ for step in range(self.p_value + 1): # +1 since p value is +1 in datasheet
+ frequencies.append(self._sdm_out_to_freq(step))
+
+ plt.clf()
+ plt.plot(frequencies, color='green', marker='.', label='frequency')
+ plt.title('PLL fractional range', fontsize=14)
+ plt.xlabel(f'SDM step', fontsize=14)
+ plt.ylabel('Frequency', fontsize=10)
+ plt.legend(loc="upper right")
+ plt.grid(True)
+ # plt.show()
+ plt.savefig("sdm_dco_range.png", dpi=150)
+
+ def write_register_file(self):
+ with open(register_file, "w") as reg_vals:
+ reg_vals.write(f"/* Autogenerated SDM App PLL setup by {Path(__file__).name} using {self.profile} profile */\n")
+ reg_vals.write(self.app_pll.gen_register_file_text())
+ reg_vals.write(f"#define SW_PLL_SDM_CTRL_MID {self.profiles[self.profile]['mod_init']}\n")
+ reg_vals.write(f"#define SW_PLL_SDM_RATE {self.profiles[self.profile]['sdm_rate']}\n")
+ reg_vals.write("\n\n")
+
+ return register_file
+
+
+if __name__ == '__main__':
+ """
+ This module is not intended to be run directly. This is here for internal testing only.
+ """
+ dco = lut_dco()
+ print(f"LUT size: {dco.get_lut_size()}")
+ dco.plot_freq_range()
+ dco.print_stats(12288000)
+
+ sdm_dco = sigma_delta_dco("24.576_1M")
+ sdm_dco.write_register_file()
+ sdm_dco.print_stats()
+ sdm_dco.plot_freq_range()
+ for i in range(30):
+ output_frequency = sdm_dco.do_modulate(500000)
+ # print(i, output_frequency)
diff --git a/python/sw_pll/pfd_model.py b/python/sw_pll/pfd_model.py
new file mode 100644
index 00000000..6ddddee3
--- /dev/null
+++ b/python/sw_pll/pfd_model.py
@@ -0,0 +1,60 @@
+# Copyright 2023 XMOS LIMITED.
+# This Software is subject to the terms of the XMOS Public Licence: Version 1.
+
+class port_timer_pfd():
+ def __init__(self, nominal_output_hz, nominal_control_rate_hz, ppm_range=1000):
+ self.output_count_last = 0.0 # Integer value of last output_clock_count
+ self.first_loop = True
+ self.ppm_range = ppm_range
+ self.expected_output_clock_count_inc = nominal_output_hz / nominal_control_rate_hz
+
+ def get_error(self, output_clock_count_float, period_fraction=1.0):
+
+ """
+ Calculate frequency error from the port output_count taken at the ref clock time.
+ Note it uses a floating point input clock count to make simulation easier. This
+ handles fractional counts and carries them properly.
+
+ If the time of sampling the output_count is not precisely 1.0 x the ref clock time,
+ you may pass a fraction to allow for a proportional value using period_fraction. This is optional.
+ """
+
+ output_count_int = int(output_clock_count_float) # round down to nearest int to match hardware
+ output_count_inc = output_count_int - self.output_count_last
+ output_count_inc = output_count_inc / period_fraction
+
+ expected_output_clock_count = self.output_count_last + self.expected_output_clock_count_inc
+
+ error = output_count_inc - int(self.expected_output_clock_count_inc)
+
+ # Apply out of range detection so that the controller ignores startup or missed control loops (as per C)
+ if abs(error) > (self.ppm_range / 1e6) * self.expected_output_clock_count_inc:
+ # print("PFD FIRST LOOP", abs(error), (self.ppm_range / 10e6) * self.expected_output_clock_count_inc)
+ self.first_loop = True
+ else:
+ self.first_loop = False
+
+ self.output_count_last = output_count_int
+
+ return error, self.first_loop
+
+
+
+if __name__ == '__main__':
+ """
+ This module is not intended to be run directly. This is here for internal testing only.
+ """
+
+ nominal_output_hz = 12288000
+ nominal_control_rate_hz = 93.75
+ expected_output_clock_inc = nominal_output_hz / nominal_control_rate_hz
+
+ pfd = port_timer_pfd(nominal_output_hz, nominal_control_rate_hz)
+
+ output_clock_count_float = 0.0
+ for output_hz in range(nominal_output_hz - 1000, nominal_output_hz + 1000, 10):
+ output_clock_count_float += output_hz / nominal_output_hz * expected_output_clock_inc
+ error = pfd.get_error(output_clock_count_float)
+ print(f"actual output Hz: {output_hz} output_clock_count: {output_clock_count_float} error: {error}")
+
+
diff --git a/python/sw_pll/sw_pll_sim.py b/python/sw_pll/sw_pll_sim.py
index 30c92776..62a0d928 100644
--- a/python/sw_pll/sw_pll_sim.py
+++ b/python/sw_pll/sw_pll_sim.py
@@ -1,654 +1,299 @@
-# Copyright 2022-2023 XMOS LIMITED.
+# Copyright 2023 XMOS LIMITED.
# This Software is subject to the terms of the XMOS Public Licence: Version 1.
-import numpy as np
+from sw_pll.app_pll_model import get_pll_solution
+from sw_pll.pfd_model import port_timer_pfd
+from sw_pll.dco_model import lut_dco, sigma_delta_dco, lock_status_lookup
+from sw_pll.controller_model import lut_pi_ctrl, sdm_pi_ctrl
+from sw_pll.analysis_tools import audio_modulator
import matplotlib.pyplot as plt
-import subprocess
-import re
-import os
-from pathlib import Path
-import soundfile
+import numpy as np
-header_file = "fractions.h" # fixed name by pll_calc.py
-register_file = "register_setup.h" # can be changed as needed
+def plot_simulation(freq_log, target_freq_log, real_time_log, name="sw_pll_tracking.png"):
+ plt.clf()
+ plt.plot(real_time_log, freq_log, color='red', marker='.', label='actual frequency')
+ plt.plot(real_time_log, target_freq_log, color='blue', marker='.', label='target frequency')
+ plt.title('PLL tracking', fontsize=14)
+ plt.xlabel(f'Time in seconds', fontsize=10)
+ plt.ylabel('Frequency', fontsize=10)
+ plt.legend(loc="upper right")
+ plt.grid(True)
+ # plt.show()
+ plt.savefig(name, dpi=150)
-class app_pll_frac_calc:
- """
- This class uses the formula in the XU316 datasheet to calculate the output frequency of the
- application PLL (sometimes called secondary PLL) from the register settings provided.
- It uses the checks specified in the datasheet to ensure the settings are valid, and will assert if not.
- To keep the inherent jitter of the PLL output down to a minimum, it is recommended that R be kept small,
- ideally = 0 (which equiates to 1) but reduces lock range.
- """
- def __init__(self, input_frequency, F_init, R_init, OD_init, ACD_init, f_init, r_init, verbose=False):
- self.input_frequency = input_frequency
- self.F = F_init
- self.R = R_init
- self.OD = OD_init
- self.ACD = ACD_init
- self.f = f_init # fractional multiplier (+1.0)
- self.p = r_init # fractional fivider (+1.0)
- self.output_frequency = None
- self.lock_status_state = 0
- self.verbose = verbose
-
- self.calc_frequency()
-
- def calc_frequency(self):
- if self.verbose:
- print(f"F: {self.F} R: {self.R} OD: {self.OD} ACD: {self.ACD} f: {self.f} p: {self.p}")
- print(f"input_frequency: {self.input_frequency}")
- assert self.F >= 1 and self.F <= 8191, f"Invalid F setting {self.F}"
- assert type(self.F) is int, f"Error: F must be an INT"
- assert self.R >= 0 and self.R <= 63, f"Invalid R setting {self.R}"
- assert type(self.R) is int, f"Error: R must be an INT"
- assert self.OD >= 0 and self.OD <= 7, f"Invalid OD setting {self.OD}"
- assert type(self.OD) is int, f"Error: OD must be an INT"
-
- intermediate_freq = self.input_frequency * (self.F + 1.0) / 2.0 / (self.R + 1.0)
- assert intermediate_freq >= 360000000.0 and intermediate_freq <= 1800000000.0, f"Invalid VCO freq: {intermediate_freq}"
- # print(f"intermediate_freq: {intermediate_freq}")
-
- assert type(self.p) is int, f"Error: r must be an INT"
- assert type(self.f) is int, f"Error: f must be an INT"
-
- assert self.p > self.f, "Error f is not < p: {self.f} {self.p}"
-
- # From XU316-1024-QF60A-xcore.ai-Datasheet_22.pdf
- self.output_frequency = self.input_frequency * (self.F + 1.0 + ((self.f + 1) / (self.p + 1)) ) / 2.0 / (self.R + 1.0) / (self.OD + 1.0) / (2.0 * (self.ACD + 1))
-
- return self.output_frequency
-
- def get_output_frequency(self):
- return self.output_frequency
-
- def update_pll_all(self, F, R, OD, ACD, f, p):
- self.F = F
- self.R = R
- self.OD = OD
- self.ACD = ACD
- self.f = f
- self.p = p
- self.calc_frequency()
-
- def update_pll_frac(self, f, p):
- self.f = f
- self.p = p
- self.calc_frequency()
-
- def update_pll_frac_reg(self, reg):
- """determine f and p from the register number and recalculate frequency"""
- f = int((reg >> 8) & ((2**8)-1))
- p = int(reg & ((2**8)-1))
- self.update_pll_frac(f, p)
-
-class parse_lut_h_file():
- """
- This class parses a pre-generated fractions.h file and builds a lookup table so that the values can be
- used by the sw_pll simulation. It may be used directly but is generally used a sub class of error_to_pll_output_frequency.
- """
- def __init__(self, header_file, verbose=False):
- with open(header_file) as hdr:
- header = hdr.readlines()
- min_frac = 1.0
- max_frac = 0.0
- for line in header:
- regex_ne = fr"frac_values_?\d*\[(\d+)].*"
- match = re.search(regex_ne, line)
- if match:
- num_entries = int(match.groups()[0])
- # print(f"num_entries: {num_entries}")
- lut = np.zeros(num_entries, dtype=np.uint16)
-
- regex_fr = r"0x([0-9A-F]+).+Index:\s+(\d+).+=\s(0.\d+)"
- match = re.search(regex_fr, line)
- if match:
- reg, idx, frac = match.groups()
- reg = int(reg, 16)
- idx = int(idx)
- frac = float(frac)
- min_frac = frac if frac < min_frac else min_frac
- max_frac = frac if frac > max_frac else max_frac
- lut[idx] = reg
-
- # print(f"min_frac: {min_frac} max_frac: {max_frac}")
-
- self.lut_reg = lut
- self.min_frac = min_frac
- self.max_frac = max_frac
-
- def get_lut(self):
- return self.lut_reg
-
- def get_lut_size(self):
- return np.size(self.lut_reg)
-
-def get_frequency_from_error(error, lut, pll:app_pll_frac_calc):
- """given an error, a lut, and a pll, calculate the frequency"""
- num_entries = np.size(lut)
-
- set_point = int(error) # Note negative term for neg feedback
- if set_point < 0:
- set_point = 0
- lock_status = -1
- elif set_point >= num_entries:
- set_point = num_entries - 1
- lock_status = 1
- else:
- set_point = set_point
- lock_status = 0
-
- register = int(lut[set_point])
- pll.update_pll_frac_reg(register)
-
- return pll.get_output_frequency(), lock_status
-
-class error_to_pll_output_frequency(app_pll_frac_calc, parse_lut_h_file):
- """
- This super class combines app_pll_frac_calc and parse_lut_h_file and provides a way of inputting the eror signal and
- providing an output frequency for a given set of PLL configuration parameters. It includes additonal methods for
- turning the LUT register settings parsed by parse_lut_h_file into fractional values which can be fed into app_pll_frac_calc.
- It also contains information reporting methods which provide the range and step sizes of the PLL configuration as well as
- plotting the transfer function from error to frequncy so the linearity and regularity the transfer function can be observed.
- """
+##############################
+# LOOK UP TABLE IMPLEMENTATION
+##############################
- def __init__(self, header_file, input_frequency, F_init, R_init, OD_init, ACD_init, f_init, p_init, verbose=False):
- self.app_pll_frac_calc = app_pll_frac_calc.__init__(self, input_frequency, F_init, R_init, OD_init, ACD_init, f_init, p_init, verbose=False)
- self.parse_lut_h_file = parse_lut_h_file.__init__(self, header_file, verbose=False)
- self.verbose = verbose
-
- def reg_to_frac(self, register):
- f = (register & 0xff00) >> 8
- p = register & 0xff
-
- return f, p
-
- def get_output_frequency_from_error(self, error):
- lut = self.get_lut()
-
- return get_frequency_from_error(error, lut, self)
-
- def get_stats(self):
- lut = self.get_lut()
- steps = np.size(lut)
-
- register = int(lut[0])
- f, p = self.reg_to_frac(register)
- self.update_pll_frac(f, p)
- min_freq = self.get_output_frequency()
-
- register = int(lut[steps // 2])
- f, p = self.reg_to_frac(register)
- self.update_pll_frac(f, p)
- mid_freq = self.get_output_frequency()
-
- register = int(lut[-1])
- f, p = self.reg_to_frac(register)
- self.update_pll_frac(f, p)
- max_freq = self.get_output_frequency()
-
- return min_freq, mid_freq, max_freq, steps
-
- def plot_freq_range(self):
- lut = self.get_lut()
- steps = np.size(lut)
-
- frequencies = []
- for step in range(steps):
- register = int(lut[step])
- f, p = self.reg_to_frac(register)
- self.update_pll_frac(f, p)
- frequencies.append(self.get_output_frequency())
-
- plt.clf()
- plt.plot(frequencies, color='green', marker='.', label='frequency')
- plt.title('PLL fractional range', fontsize=14)
- plt.xlabel(f'LUT index', fontsize=14)
- plt.ylabel('Frequency', fontsize=10)
- plt.legend(loc="upper right")
- plt.grid(True)
- # plt.show()
- plt.savefig("sw_pll_range.png", dpi=150)
-
-def parse_register_file(register_file):
- """
- This helper function reads the pre-saved register setup comments from get_pll_solution and parses them into parameters that
- can be used for the simulation.
+class sim_sw_pll_lut:
"""
+ Complete SW PLL simulation class which contains all of the components including
+ Phase Frequency Detector, Controller and Digitally Controlled Oscillator using
+ a Look Up Table method.
+ """
+ def __init__( self,
+ target_output_frequency,
+ nominal_nominal_control_rate_frequency,
+ Kp,
+ Ki,
+ Kii=None):
+ """
+ Init a Lookup Table based SW_PLL instance
+ """
- with open(register_file) as rf:
- reg_file = rf.read().replace('\n', '')
- F = int(re.search(".+F:\s+(\d+).+", reg_file).groups()[0])
- R = int(re.search(".+R:\s+(\d+).+", reg_file).groups()[0])
- f = int(re.search(".+f:\s+(\d+).+", reg_file).groups()[0])
- p = int(re.search(".+p:\s+(\d+).+", reg_file).groups()[0])
- OD = int(re.search(".+OD:\s+(\d+).+", reg_file).groups()[0])
- ACD = int(re.search(".+ACD:\s+(\d+).+", reg_file).groups()[0])
+ self.pfd = port_timer_pfd(target_output_frequency, nominal_nominal_control_rate_frequency)
+ self.controller = lut_pi_ctrl(Kp, Ki, Kii=Kii, verbose=False)
+ self.dco = lut_dco(verbose=False)
- return F, R, f, p, OD, ACD
+ self.target_output_frequency = target_output_frequency
+ self.time = 0.0
+ self.control_time_inc = 1 / nominal_nominal_control_rate_frequency
+ def do_control_loop(self, output_clock_count, period_fraction=1.0, verbose=False):
+ """
+ This should be called once every control period.
+ output_clock_count is fed into the PDF and period_fraction is an optional jitter
+ reduction term where the control period is not exact, but can be compensated for.
+ """
- # see /doc/sw_pll.rst for guidance on these settings
-def get_pll_solution(input_frequency, target_output_frequency, max_denom=80, min_F=200, ppm_max=2, fracmin=0.65, fracmax=0.95):
- """
- This is a wrapper function for pll_calc.py and allows it to be called programatically.
- It contains sensible defaults for the arguments and abstracts some of the complexity away from
- the underlying script. Configuring the PLL is not an exact science and there are many tradeoffs involved.
- See sw_pll.rst for some of the tradeoffs involved and some example paramater sets.
+ error, first_loop = self.pfd.get_error(output_clock_count, period_fraction=period_fraction)
+ dco_ctl = self.controller.get_dco_control_from_error(error, first_loop=first_loop)
+ output_frequency, lock_status = self.dco.get_frequency_from_dco_control(dco_ctl)
+ if first_loop: # We cannot claim to be locked if the PFD sees an error
+ lock_status = -1
- Once run, this function saves two output files:
- - fractions.h which contains the fractional term lookup table, which is guarranteed monotonic (important for PI stability)
- - register_setup.h which contains the PLL settings in comments as well as register settings for init in the application
+ if verbose:
+ print(f"Raw error: {error}")
+ print(f"dco_ctl: {dco_ctl}")
+ print(f"Output_frequency: {output_frequency}")
+ print(f"Lock status: {lock_status_lookup[lock_status]}")
- This function and the underlying call to pll_calc may take several seconds to complete since it searches a range
- of possible solutions numerically.
- """
- input_frequency_MHz = input_frequency / 1000000.0
- target_output_frequency_MHz = target_output_frequency / 1000000.0
-
- calc_script = Path(__file__).parent/"pll_calc.py"
-
- # input freq, app pll, max denom, output freq, min phase comp freq, max ppm error, raw, fractional range, make header
- cmd = f"{calc_script} -i {input_frequency_MHz} -a -m {max_denom} -t {target_output_frequency_MHz} -p 6.0 -e {int(ppm_max)} -r --fracmin {fracmin} --fracmax {fracmax} --header"
- print(f"Running: {cmd}")
- output = subprocess.check_output(cmd.split(), text=True)
-
- # Get each solution
- solutions = []
- Fs = []
- regex = r"Found solution.+\nAPP.+\nAPP.+\nAPP.+"
- matches = re.findall(regex, output)
-
- for solution in matches:
- F = int(float(re.search(".+FD\s+(\d+.\d+).+", solution).groups()[0]))
- solutions.append(solution)
- Fs.append(F)
-
- possible_Fs = sorted(set(Fs))
- print(f"Available F values: {possible_Fs}")
-
- # Find first solution with F greater than F
- idx = next(x for x, val in enumerate(Fs) if val > min_F)
- solution = matches[idx]
-
- # Get actual PLL register bitfield settings and info
- regex = r".+OUT (\d+\.\d+)MHz, VCO (\d+\.\d+)MHz, RD\s+(\d+), FD\s+(\d+.\d*)\s+\(m =\s+(\d+), n =\s+(\d+)\), OD\s+(\d+), FOD\s+(\d+), ERR (-*\d+.\d+)ppm.*"
- match = re.search(regex, solution)
-
- if match:
- vals = match.groups()
-
- output_frequency = (1000000.0 * float(vals[0]))
- vco_freq = 1000000.0 * float(vals[1])
-
- # Now convert to actual settings in register bitfields
- F = int(float(vals[3]) - 1) # PLL integer multiplier
- R = int(vals[2]) - 1 # PLL integer divisor
- f = int(vals[4]) - 1 # PLL fractional multiplier
- p = int(vals[5]) - 1 # PLL fractional divisor
- OD = int(vals[6]) - 1 # PLL output divider
- ACD = int(vals[7]) - 1 # PLL application clock divider
- ppm = float(vals[8]) # PLL PPM error for requrested set frequency
-
- assert match, f"Could not parse output of: {cmd} output: {solution}"
-
- # Now get reg values and save to file
- with open(register_file, "w") as reg_vals:
- reg_vals.write(f"/* Autogenerated by {Path(__file__).name} using command:\n")
- reg_vals.write(f" {cmd}\n")
- reg_vals.write(f" Picked output solution #{idx}\n")
- # reg_vals.write(f"\n{solution}\n\n") # This is verbose and contains the same info as below
- reg_vals.write(f" F: {F}\n")
- reg_vals.write(f" R: {R}\n")
- reg_vals.write(f" f: {f}\n")
- reg_vals.write(f" p: {p}\n")
- reg_vals.write(f" OD: {OD}\n")
- reg_vals.write(f" ACD: {ACD}\n")
- reg_vals.write(f" Output freq: {output_frequency}\n")
- reg_vals.write(f" VCO freq: {vco_freq} */\n")
- reg_vals.write("\n")
-
-
- for reg in ["APP PLL CTL REG", "APP PLL DIV REG", "APP PLL FRAC REG"]:
- regex = rf"({reg})\s+(0[xX][A-Fa-f0-9]+)"
- match = re.search(regex, solution)
- if match:
- val = match.groups()[1]
- reg_name = reg.replace(" ", "_")
- line = f"#define {reg_name} \t{val}\n"
- reg_vals.write(line)
-
-
- return output_frequency, vco_freq, F, R, f, p, OD, ACD, ppm
-
-class pll_solution:
- """
- Access to all the info from get_pll_solution, cleaning up temp files.
- intended for programatic access from the tests
- """
- def __init__(self, *args, **kwargs):
- try:
- self.output_frequency, self.vco_freq, self.F, self.R, self.f, self.p, self.OD, self.ACD, self.ppm = get_pll_solution(*args, **kwargs)
- self.lut = parse_lut_h_file("fractions.h")
- finally:
- Path("fractions.h").unlink(missing_ok=True)
- Path("register_setup.h").unlink(missing_ok=True)
-
-class sw_pll_ctrl:
- """
- This class instantiates a control loop instance. It takes a lookup table function which can be generated
- from the error_from_h class which allows it use the actual pre-calculated transfer function.
- Once instantiated, the do_control method runs the control loop.
+ return output_frequency, lock_status
- This class forms the core of the simulator and allows the constants (K..) to be tuned to acheive the
- desired response. The function run_sim allows for a plot of a step resopnse input which allows this
- to be done visually.
- """
- lock_status_lookup = {-1 : "UNLOCKED LOW", 0 : "LOCKED", 1 : "UNLOCKED HIGH"}
- def __init__(self, target_output_frequency, lut_lookup_function, lut_size, multiplier, ref_to_loop_call_rate, Kp, Ki, init_output_count=0, init_ref_clk_count=0, base_lut_index=None, verbose=False):
- self.lut_lookup_function = lut_lookup_function
- self.multiplier = multiplier
- self.ref_to_loop_call_rate = ref_to_loop_call_rate
- self.ref_clk_count = init_output_count # Integer as we run this loop based on the ref clock input count
- self.output_count_old = init_output_count # Integer
- self.expected_output_count_inc_float = multiplier * ref_to_loop_call_rate
- self.expected_output_count_float = 0.0
+def run_lut_sw_pll_sim():
+ """
+ Test program / example showing how to run the simulator object
+ """
- if base_lut_index is None:
- base_lut_index = lut_size // 2
- self.base_lut_index = base_lut_index
+ # Example profiles to produce typical frequencies seen in audio systems. ALl assume 24MHz input clock to the hardware PLL.
+ profiles = [
+ # 0 - 12.288MHz with 48kHz ref (note also works with 16kHz ref), +-250PPM, 29.3Hz steps, 426B LUT size
+ {"nominal_ref_frequency":48000.0, "target_output_frequency":12288000, "max_denom":80, "min_F":200, "ppm_max":5, "fracmin":0.843, "fracmax":0.95},
+ # 1 - 12.288MHz with 48kHz ref (note also works with 16kHz ref), +-500PPM, 30.4Hz steps, 826B LUT size
+ {"nominal_ref_frequency":48000.0, "target_output_frequency":12288000, "max_denom":80, "min_F":200, "ppm_max":5, "fracmin":0.695, "fracmax":0.905},
+ # 2 - 24.576MHz with 48kHz ref (note also works with 16kHz ref), +-1000PPM, 31.9Hz steps, 1580B LUT size
+ {"nominal_ref_frequency":48000.0, "target_output_frequency":12288000, "max_denom":90, "min_F":140, "ppm_max":5, "fracmin":0.49, "fracmax":0.81},
+ # 3 - 24.576MHz with 48kHz ref (note also works with 16kHz ref), +-100PPM, 9.5Hz steps, 1050B LUT size
+ {"nominal_ref_frequency":48000.0, "target_output_frequency":24576000, "max_denom":120, "min_F":400, "ppm_max":5, "fracmin":0.764, "fracmax":0.884},
+ # 4 - 6.144MHz with 16kHz ref, +-200PPM, 30.2Hz steps, 166B LUT size
+ {"nominal_ref_frequency":16000.0, "target_output_frequency":6144000, "max_denom":40, "min_F":400, "ppm_max":5, "fracmin":0.635, "fracmax":0.806},
+ ]
+
+ profile_used = 1
+ profile = profiles[profile_used]
+
+ nominal_output_hz = profile["target_output_frequency"]
+
+ # This generates the needed header files read later by sim_sw_pll_lut
+ # 12.288MHz with 48kHz ref (note also works with 16kHz ref), +-500PPM, 30.4Hz steps, 826B LUT size
+ get_pll_solution(24000000, nominal_output_hz, max_denom=80, min_F=200, ppm_max=5, fracmin=0.695, fracmax=0.905)
+
+ output_frequency = nominal_output_hz
+ nominal_control_rate_hz = profile["nominal_ref_frequency"] / 512
+ simulation_iterations = 100
+ Kp = 0.0
+ Ki = 1.0
+ Kii = 0.0
- self.Kp = Kp
- self.Ki = Ki
+ sw_pll = sim_sw_pll_lut(nominal_output_hz, nominal_control_rate_hz, Kp, Ki, Kii=Kii)
+ output_clock_count = 0
- self.diff = 0.0 #Most recent diff between expected and actual
- self.error_accum = 0.0 #Integral of error
- self.error = 0.0 #total error
+ test_tone_hz = 1000
+ audio = audio_modulator(simulation_iterations * 1 / nominal_control_rate_hz, sample_rate=48000, test_tone_hz=test_tone_hz)
- self.i_windup_limit = lut_size / Ki if Ki != 0.0 else 0.0
+
+ freq_log = []
+ target_freq_log = []
+ real_time_log = []
+ real_time = 0.0
+ period_fraction = 1.0
- self.last_output_frequency = target_output_frequency
+ ppm_shift = +50
- self.verbose = verbose
+ for loop in range(simulation_iterations):
+ output_frequency, lock_status = sw_pll.do_control_loop(output_clock_count, period_fraction=period_fraction, verbose=False)
- if verbose:
- print(f"Init sw_pll_ctrl, target_output_frequency: {target_output_frequency} ref_to_loop_call_rate: {ref_to_loop_call_rate}, Kp: {Kp} Ki: {Ki}")
+ # Now work out how many output clock counts this translates to
+ measured_clock_count_inc = output_frequency / nominal_control_rate_hz * (1 - ppm_shift / 1e6)
- def get_expected_output_count_inc(self):
- return self.expected_output_count_inc_float
+ # Add some jitter to the output_count to test jitter compensation
+ jitter_amplitude = 100 # measured in output clock counts
+ clock_count_sampling_jitter = jitter_amplitude * (np.random.sample() - 0.5)
+ period_fraction = (measured_clock_count_inc + clock_count_sampling_jitter) * measured_clock_count_inc
- def get_error(self):
- return self.error
+ output_clock_count += measured_clock_count_inc * period_fraction
+ real_time_log.append(real_time)
+ target_output_frequency = nominal_output_hz * (1 + ppm_shift / 1e6)
+ target_freq_log.append(target_output_frequency)
+ freq_log.append(output_frequency)
- def do_control_from_error(self, error):
- """ Calculate the actual output frequency from raw input error term.
- """
- self.diff = error # Used by tests
+ time_inc = 1 / nominal_control_rate_hz
+ scaled_frequency_shift = test_tone_hz * (output_frequency - target_output_frequency) / target_output_frequency
+ audio.apply_frequency_deviation(real_time, real_time + time_inc, scaled_frequency_shift)
- # clamp integral terms to stop them irrecoverably drifting off.
- self.error_accum = np.clip(self.error_accum + error, -self.i_windup_limit, self.i_windup_limit)
+ real_time += time_inc
- error_p = self.Kp * error;
- error_i = self.Ki * self.error_accum
- self.error = error_p + error_i
+ plot_simulation(freq_log, target_freq_log, real_time_log, "tracking_lut.png")
+
+ audio.modulate_waveform()
+ audio.save_modulated_wav("modulated_tone_1000Hz_lut.wav")
+ audio.plot_modulated_fft("modulated_fft_lut.png", skip_s=real_time / 2) # skip so we ignore the inital lock period
- if self.verbose:
- print(f"diff: {error} error_p: {error_p}({self.Kp}) error_i: {error_i}({self.Ki}) total error: {self.error}")
- print(f"expected output_count: {self.expected_output_count_inc_float} actual output_count: {output_count_inc} error: {self.error}")
- actual_output_frequency, lock_status = self.lut_lookup_function(self.base_lut_index - self.error)
- return actual_output_frequency, lock_status
+######################################
+# SIGMA DELTA MODULATOR IMPLEMENTATION
+######################################
- def do_control(self, output_count_float, period_fraction=1.0):
+class sim_sw_pll_sd:
+ """
+ Complete SW PLL simulation class which contains all of the components including
+ Phase Frequency Detector, Controller and Digitally Controlled Oscillator using
+ a Sigma Delta Modulator method.
+ """
- """ Calculate the actual output frequency from the input output_count taken at the ref clock time.
- If the time of sampling the output_count is not precisely 1.0 x the ref clock time,
- you may pass a fraction to allow for a proportional value using period_fraction. This is optional.
+ def __init__( self,
+ target_output_frequency,
+ nominal_nominal_control_rate_frequency,
+ Kp,
+ Ki,
+ Kii=None):
+ """
+ Init a Sigma Delta Modulator based SW_PLL instance
"""
- if 0 == output_count_float:
- return self.lut_lookup_function(self.base_lut_index)
-
- output_count_int = int(output_count_float)
- output_count_inc = output_count_int - self.output_count_old
- output_count_inc = output_count_inc / period_fraction
-
- self.expected_output_count_float = self.output_count_old + self.expected_output_count_inc_float
- self.output_count_old = output_count_int
-
- self.ref_clk_count += self.ref_to_loop_call_rate
- error = output_count_inc - int(self.expected_output_count_inc_float)
- actual_output_frequency, lock_status = self.do_control_from_error(error)
+ self.pfd = port_timer_pfd(target_output_frequency, nominal_nominal_control_rate_frequency, ppm_range=3000)
+ self.dco = sigma_delta_dco("24.576_1M")
+ self.controller = sdm_pi_ctrl( (self.dco.sdm_in_max + self.dco.sdm_in_min) / 2,
+ self.dco.sdm_in_max,
+ self.dco.sdm_in_min,
+ Kp,
+ Ki,
+ Kii)
- return actual_output_frequency, lock_status
+ self.target_output_frequency = target_output_frequency
+ self.time = 0.0
+ self.control_time_inc = 1 / nominal_nominal_control_rate_frequency
-class audio_modulator:
- def __init__(self, duration_s, sample_rate=48000, test_tone_hz=1000):
- self.sample_rate = sample_rate
- self.test_tone_hz = test_tone_hz
+ self.control_setting = (self.controller.sdm_in_max + self.controller.sdm_in_min) / 2 # Mid way
- # First generate arrays for FM modulation
- self.each_sample_number = np.linspace(0, duration_s, int(sample_rate * duration_s))
- self.carrier = 2 * np.pi * self.each_sample_number * test_tone_hz
- # Blank array with 0Hz modulation
- k = 2 * np.pi # modulation constant - amplitude of 1.0 = 1Hz deviation
- self.modulator = k * self.each_sample_number
+ def do_control_loop(self, output_clock_count, verbose=False):
+ """
+ Run the control loop (which runs at a tiny fraction of the SDM rate)
+ This should be called once every control period.
- def apply_frequency_deviation(self, start_s, end_s, delta_freq):
- start_idx = int(start_s * self.sample_rate)
- end_idx = int(end_s * self.sample_rate)
- self.modulator[start_idx:end_idx] = self.modulator[start_idx:end_idx] + delta_freq
+ output_clock_count is fed into the PDF and period_fraction is an optional jitter
+ reduction term where the control period is not exact, but can be compensated for.
+ """
+ error, first_loop = self.pfd.get_error(output_clock_count)
+ ctrl_output, lock_status = self.controller.do_control_from_error(error)
+ self.control_setting = ctrl_output
- def get_modulated_waveform(self):
- # Now create the frequency modulated waveform
- waveform = np.cos(self.carrier + self.modulator)
+ if verbose:
+ print(f"Raw error: {error}")
+ print(f"ctrl_output: {ctrl_output}")
+ print(f"Lock status: {lock_status_lookup[lock_status]}")
- return waveform
+ return self.control_setting
- def save_modulated_wav(self, filename, waveform):
- integer_output = np.int16(waveform * 32767)
- soundfile.write(filename, integer_output, int(self.sample_rate))
+ def do_sigma_delta(self):
+ """
+ Run the SDM which needs to be run constantly at the SDM rate.
+ See DCO (dco_model) for details
+ """
+ frequncy = self.dco.do_modulate(self.control_setting)
- def plot_modulated_fft(self, filename, waveform):
- xf = np.linspace(0.0, 1.0/(2.0/self.sample_rate), self.each_sample_number.size//2)
- N = xf.size
- window = np.kaiser(N*2, 14)
- waveform = waveform * window
- yf = np.fft.fft(waveform)
- fig, ax = plt.subplots()
-
- # Plot a zoom in on the test
- tone_idx = int(self.test_tone_hz / (self.sample_rate / 2) * N)
- num_side_bins = 50
- yf = 20 * np.log10(np.abs(yf) / N)
- # ax.plot(xf[tone_idx - num_side_bins:tone_idx + num_side_bins], yf[tone_idx - num_side_bins:tone_idx + num_side_bins], marker='.')
-
- # Plot the whole frequncy range from DC to nyquist
- ax.plot(xf[:N], yf[:N], marker='.')
- ax.set_xscale("log")
- plt.savefig(filename, dpi=150)
+ return frequncy
-def run_sim(target_output_frequency, nominal_ref_frequency, lut_lookup_function, lut_size, verbose=False):
+def run_sd_sw_pll_sim():
"""
- This function uses the sw_pll_ctrl and passed lut_lookup_function to run a simulation of the response
- of the sw_pll to changes in input reference frequency.
- A plot of the simulation is generated to allow visual inspection and tuning.
+ Test program / example showing how to run the simulator object
"""
-
- # PI loop control constants
- Kp = 0.0
- Ki = 1.0
-
- ref_frequency = nominal_ref_frequency
- sw_pll = sw_pll_ctrl(target_output_frequency, lut_lookup_function, lut_size, multiplier, ref_to_loop_call_rate, Kp, Ki, verbose=False)
+ nominal_output_hz = 24576000
+ nominal_control_rate_hz = 100
+ nominal_sd_rate_hz = 1e6
+ output_frequency = nominal_output_hz
- output_count_end_float = 0.0
- real_time = 0.0
- actual_output_frequency = target_output_frequency
-
- last_count = 0
-
- freq_log = []
- target_log = []
+ simulation_iterations = 1000000
+ Kp = 0.0
+ Ki = 32.0
+ Kii = 0.25
- simulation_iterations = 1500
+ sw_pll = sim_sw_pll_sd(nominal_output_hz, nominal_control_rate_hz, Kp, Ki, Kii=Kii)
+ sw_pll.dco.write_register_file()
- # Move the reference frequency about - iteration count, PPM change
- ppm_shifts = ((250, 300), (500, 150), (800, -200), (1300, 0))
- # ppm_shifts = () # Straight run with no PPM deviation
+ output_clock_count = 0
test_tone_hz = 1000
- audio = audio_modulator(simulation_iterations * ref_to_loop_call_rate / ref_frequency, sample_rate = ref_frequency, test_tone_hz = test_tone_hz)
-
- for count in range(simulation_iterations):
- output_count_start_float = output_count_end_float
- output_count_float_inc = actual_output_frequency / ref_frequency * ref_to_loop_call_rate
-
- # Add some jitter to the output_count to test jitter compensation
- # output_sample_jitter = 0
- output_sample_jitter = 100 * (np.random.sample() - 0.5)
- output_count_end_float += output_count_float_inc + output_sample_jitter
- # Compensate for the jitter
- period_fraction = (output_count_float_inc + output_sample_jitter) / output_count_float_inc
-
- # print(f"output_count_float_inc: {output_count_float_inc}, period_fraction: {period_fraction}, ratio: {output_count_float_inc / period_fraction}")
-
- actual_output_frequency, lock_status = sw_pll.do_control(output_count_end_float, period_fraction = period_fraction)
- # lock_status = 0
-
- # Helpers for the tone modulation
- time_in_s = lambda count: count * ref_to_loop_call_rate / ref_frequency
- freq_shift = lambda actual_output_frequency, target_output_frequency, test_tone_hz: (actual_output_frequency / target_output_frequency - 1) * test_tone_hz
- audio.apply_frequency_deviation(time_in_s(count), time_in_s(count + 1), freq_shift(actual_output_frequency, target_output_frequency, test_tone_hz))
-
-
- # print(freq_shift(actual_output_frequency, target_output_frequency, test_tone_hz))
+ audio = audio_modulator(simulation_iterations * 1 / nominal_sd_rate_hz, sample_rate=6144000, test_tone_hz=test_tone_hz)
- if verbose:
- print(f"Loop: count: {count}, time: {real_time}, actual_output_frequency: {actual_output_frequency}, lock_status: {sw_pll_ctrl.lock_status_lookup[lock_status]}")
-
-
- freq_log.append(actual_output_frequency)
- target_log.append(ref_frequency * multiplier)
+ freq_log = []
+ target_freq_log = []
+ real_time_log = []
+ real_time = 0.0
- real_time += ref_to_loop_call_rate / ref_frequency
+ ppm_shift = +50
+ # For working out when to do control calls
+ control_time_inc = 1 / nominal_control_rate_hz
+ control_time_trigger = control_time_inc
- # A number of events where the input reference is stepped
- ppm_adjust = lambda f, ppm: f * (1 + (ppm / 1000000))
- for ppm_shift in ppm_shifts:
- (change_at_count, ppm) = ppm_shift
- if count == change_at_count:
- ref_frequency = ppm_adjust(nominal_ref_frequency, ppm)
+ for loop in range(simulation_iterations):
+ output_frequency = sw_pll.do_sigma_delta()
- plt.clf()
- plt.plot(freq_log, color='red', marker='.', label='actual frequency')
- plt.plot(target_log, color='blue', marker='.', label='target frequency')
- plt.title('PLL tracking', fontsize=14)
- plt.xlabel(f'loop_cycle {ref_to_loop_call_rate}', fontsize=14)
- plt.ylabel('Frequency', fontsize=10)
- plt.legend(loc="upper right")
- plt.grid(True)
- # plt.show()
- plt.savefig("pll_step_response.png", dpi=150)
-
- # Generate fft of modulated test tone
- audio.plot_modulated_fft(f"modulated_tone_fft_{test_tone_hz}Hz.png", audio.get_modulated_waveform())
- audio.save_modulated_wav(f"modulated_tone_{test_tone_hz}Hz.wav", audio.get_modulated_waveform())
-
-
-"""
-ref_to_loop_call_rate - Determines how often to call the control loop in terms of ref clocks
-xtal_frequency - The xcore clock frequency
-nominal_ref_frequency - The nominal input reference frequency
-target_output_frequency - The nominal target output frequency
-max_denom - (Optional) The maximum fractional denominator. See/doc/sw_pll.rst for guidance
-min_F - (Optional) The minimum integer numerator. See/doc/sw_pll.rst for guidance
-ppm_max - (Optional) The allowable PPM deviation for the target nominal frequency. See/doc/sw_pll.rst for guidance
-fracmin - (Optional) The minimum fractional multiplier. See/doc/sw_pll.rst for guidance
-fracmax - (Optional) The maximum fractional multiplier. See/doc/sw_pll.rst for guidance
-"""
-
-ref_to_loop_call_rate = 512
-xtal_frequency = 24000000
-profile_choice = 0
-
-# Example profiles to produce typical frequencies seen in audio systems
-profiles = [
- # 0 - 12.288MHz with 48kHz ref (note also works with 16kHz ref), +-250PPM, 29.3Hz steps, 426B LUT size
- {"nominal_ref_frequency":48000.0, "target_output_frequency":12288000, "max_denom":80, "min_F":200, "ppm_max":5, "fracmin":0.843, "fracmax":0.95},
- # 1 - 12.288MHz with 48kHz ref (note also works with 16kHz ref), +-500PPM, 30.4Hz steps, 826B LUT size
- {"nominal_ref_frequency":48000.0, "target_output_frequency":12288000, "max_denom":80, "min_F":200, "ppm_max":5, "fracmin":0.695, "fracmax":0.905},
- # 2 - 12.288MHz with 48kHz ref (note also works with 16kHz ref), +-500PPM, 30.4Hz steps, 826B LUT size
- {"nominal_ref_frequency":48000.0, "target_output_frequency":12288000, "max_denom":80, "min_F":200, "ppm_max":5, "fracmin":0.695, "fracmax":0.905},
- # 3 - 24.576MHz with 48kHz ref (note also works with 16kHz ref), +-1000PPM, 31.9Hz steps, 1580B LUT size
- {"nominal_ref_frequency":48000.0, "target_output_frequency":12288000, "max_denom":90, "min_F":140, "ppm_max":5, "fracmin":0.49, "fracmax":0.81},
- # 4 - 24.576MHz with 48kHz ref (note also works with 16kHz ref), +-100PPM, 9.5Hz steps, 1050B LUT size
- {"nominal_ref_frequency":48000.0, "target_output_frequency":24576000, "max_denom":120, "min_F":400, "ppm_max":5, "fracmin":0.764, "fracmax":0.884},
- # 5 - 6.144MHz with 16kHz ref, +-200PPM, 30.2Hz steps, 166B LUT size
- {"nominal_ref_frequency":16000.0, "target_output_frequency":6144000, "max_denom":40, "min_F":400, "ppm_max":5, "fracmin":0.635, "fracmax":0.806},
- ]
+ # Log results
+ freq_log.append(output_frequency)
+ target_output_frequency = nominal_output_hz * (1 + ppm_shift / 1e6)
+ target_freq_log.append(target_output_frequency)
+ real_time_log.append(real_time)
+ # Modulate tone
+ sdm_time_inc = 1 / nominal_sd_rate_hz
+ scaled_frequency_shift = test_tone_hz * (output_frequency - target_output_frequency) / target_output_frequency
+ audio.apply_frequency_deviation(real_time, real_time + sdm_time_inc, scaled_frequency_shift)
+ # Accumulate the real number of output clocks
+ output_clock_count += output_frequency / nominal_sd_rate_hz * (1 - ppm_shift / 1e6)
-if __name__ == '__main__':
- """
- This script checks to see if PLL settings have already been generated, if not, generates them.
- It then uses these settings to generate a LUT and control loop instance.
- A set of step functions in input reference frequencies are then generated and the
- response of the sw_pll to these changes is logged and then plotted.
- """
+ # Check for control loop run ready
+ if real_time > control_time_trigger:
+ control_time_trigger += control_time_inc
- profile_used = profiles[profile_choice]
+ # Now work out how many output clock counts this translates to
+ sw_pll.do_control_loop(output_clock_count)
- # Make a list of the correct args for get_pll_solution
- get_pll_solution_args = {"input_frequency":xtal_frequency}
- get_pll_solution_args.update(profile_used)
- del get_pll_solution_args["nominal_ref_frequency"]
- get_pll_solution_args = list(get_pll_solution_args.values())
+ real_time += sdm_time_inc
- # Extract the required vals from the profile
- target_output_frequency = profile_used["target_output_frequency"]
- nominal_ref_frequency = profile_used["nominal_ref_frequency"]
- multiplier = target_output_frequency / nominal_ref_frequency
- # input_frequency, target_output_frequency, max_denom=80, min_F=200, ppm_max=2, fracmin=0.65, fracmax=0.95
+ plot_simulation(freq_log, target_freq_log, real_time_log, "tracking_sdm.png")
- # Use pre-caclulated saved values if they exist, otherwise generate new ones
- if not os.path.exists(header_file) or not os.path.exists(register_file):
- output_frequency, vco_freq, F, R, f, p, OD, ACD, ppm = get_pll_solution(*get_pll_solution_args)
- print(f"output_frequency: {output_frequency}, vco_freq: {vco_freq}, F: {F}, R: {R}, f: {f}, p: {p}, OD: {OD}, ACD: {ACD}, ppm: {ppm}")
- else:
- F, R, f, p, OD, ACD = parse_register_file(register_file)
- print(f"Using pre-calculated settings read from {header_file} and {register_file}:")
+ audio.modulate_waveform()
+ audio.save_modulated_wav("modulated_tone_1000Hz_sdm.wav")
+ audio.plot_modulated_fft("modulated_fft_sdm.png", skip_s=real_time / 2) # skip so we ignore the inital lock period
- print(f"PLL register settings F: {F}, R: {R}, OD: {OD}, ACD: {ACD}, f: {f}, p: {p}")
- # Instantiate controller
- error_from_h = error_to_pll_output_frequency(header_file, xtal_frequency, F, R, OD, ACD, f, p, verbose=False)
- error_from_h.plot_freq_range()
-
- min_freq, mid_freq, max_freq, steps = error_from_h.get_stats()
- step_size = ((max_freq - min_freq) / steps)
-
- print(f"min_freq: {min_freq:.0f}Hz")
- print(f"mid_freq: {mid_freq:.0f}Hz")
- print(f"max_freq: {max_freq:.0f}Hz")
- print(f"average step size: {step_size:.6}Hz, PPM: {1e6 * step_size/mid_freq:.6}")
- print(f"PPM range: {1e6 * (1 - target_output_frequency / min_freq):.6}")
- print(f"PPM range: +{1e6 * (max_freq / target_output_frequency - 1):.6}")
- print(f"LUT entries: {steps} ({steps*2} bytes)")
-
- run_sim(target_output_frequency, nominal_ref_frequency, error_from_h.get_output_frequency_from_error, error_from_h.get_lut_size(), verbose=False)
+if __name__ == '__main__':
+ run_lut_sw_pll_sim()
+ run_sd_sw_pll_sim() # Note this will overwrite the "register_setup.h" file generated by run_lut_sw_pll_sim
+
\ No newline at end of file
diff --git a/requirements.txt b/requirements.txt
index 097d778e..c8599821 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -4,4 +4,4 @@
pytest
pandas
soundfile
-
+scipy
diff --git a/settings.yml b/settings.yml
new file mode 100644
index 00000000..6de98920
--- /dev/null
+++ b/settings.yml
@@ -0,0 +1,19 @@
+---
+################################
+# Settings file for docs build #
+################################
+
+project: SW_PLL
+version: 2.0.0
+documentation:
+ title: Software PLL
+ root_doc: doc/index.rst
+ exclude_patterns_path: doc/exclude-patterns.inc
+ substitutions_path: doc/substitutions.inc
+ doxygen_projects:
+ SW_PLL:
+ doxyfile_path: doc/Doxyfile.inc
+ pdfs:
+ doc/index:
+ pdf_title: '{{project}} Programming Guide \newline'
+ pdf_filename: '{{project}}_programming_guide_v{{version}}'
diff --git a/setup.py b/setup.py
index 2235bc7a..a89967a6 100644
--- a/setup.py
+++ b/setup.py
@@ -4,7 +4,7 @@
setup(
name="sw_pll",
- version="1.1.0",
+ version="2.0.0",
packages=["sw_pll"],
package_dir={
"": "python"
diff --git a/tests/test_app/CMakeLists.txt b/tests/test_app/CMakeLists.txt
index 2e6b903c..617bdc27 100644
--- a/tests/test_app/CMakeLists.txt
+++ b/tests/test_app/CMakeLists.txt
@@ -7,6 +7,7 @@ target_compile_options(
test_app
PUBLIC
-g
+ -Os
-report
-fxscope
-target=XCORE-AI-EXPLORER
diff --git a/tests/test_app/main.c b/tests/test_app/main.c
index b10ee53e..219e694f 100644
--- a/tests/test_app/main.c
+++ b/tests/test_app/main.c
@@ -3,7 +3,7 @@
///
/// Application to call the control loop with the parameters fully
/// controllable by an external application. This app expects the
-/// sw_pll_init parameters on the commannd line. These will be integers
+/// sw_pll_lut_init parameters on the commannd line. These will be integers
/// for lut_table_base, skip the parameter in the list and append the whole
/// lut to the command line
///
@@ -27,10 +27,12 @@ int main(int argc, char** argv) {
int i = 1;
- float kp = atoi(argv[i++]);
+ float kp = atof(argv[i++]);
fprintf(stderr, "kp\t\t%f\n", kp);
- float ki = atoi(argv[i++]);
+ float ki = atof(argv[i++]);
fprintf(stderr, "ki\t\t%f\n", ki);
+ float kii = atof(argv[i++]);
+ fprintf(stderr, "kii\t\t%f\n", kii);
size_t loop_rate_count = atoi(argv[i++]);
fprintf(stderr, "loop_rate_count\t\t%d\n", loop_rate_count);
size_t pll_ratio = atoi(argv[i++]);
@@ -64,18 +66,19 @@ int main(int argc, char** argv) {
fprintf(stderr, "\n");
sw_pll_state_t sw_pll;
- sw_pll_init( &sw_pll,
- SW_PLL_15Q16(kp),
- SW_PLL_15Q16(ki),
- loop_rate_count,
- pll_ratio,
- ref_clk_expected_inc,
- lut_table_base,
- num_lut_entries,
- app_pll_ctl_reg_val,
- app_pll_div_reg_val,
- nominal_lut_idx,
- ppm_range);
+ sw_pll_lut_init( &sw_pll,
+ SW_PLL_15Q16(kp),
+ SW_PLL_15Q16(ki),
+ SW_PLL_15Q16(kii),
+ loop_rate_count,
+ pll_ratio,
+ ref_clk_expected_inc,
+ lut_table_base,
+ num_lut_entries,
+ app_pll_ctl_reg_val,
+ app_pll_div_reg_val,
+ nominal_lut_idx,
+ ppm_range);
for(;;) {
@@ -101,11 +104,11 @@ int main(int argc, char** argv) {
sscanf(read_buf, "%hu %hu", &mclk_pt, &ref_pt);
fprintf(stderr, "%hu %hu\n", mclk_pt, ref_pt);
uint32_t t0 = get_reference_time();
- sw_pll_lock_status_t s = sw_pll_do_control(&sw_pll, mclk_pt, ref_pt);
+ sw_pll_lock_status_t s = sw_pll_lut_do_control(&sw_pll, mclk_pt, ref_pt);
uint32_t t1 = get_reference_time();
// xsim doesn't support our register and the val that was set gets
// dropped
- printf("%i %x %hd %ld %u %lu\n", s, sw_pll.current_reg_val, sw_pll.mclk_diff, sw_pll.error_accum, sw_pll.first_loop, t1 - t0);
+ printf("%i %x %hd %ld %ld %u %lu\n", s, sw_pll.lut_state.current_reg_val, sw_pll.pfd_state.mclk_diff, sw_pll.pi_state.error_accum, sw_pll.pi_state.error_accum_accum, sw_pll.first_loop, t1 - t0);
}
}
diff --git a/tests/test_app/readme.txt b/tests/test_app/readme.txt
deleted file mode 100644
index e69de29b..00000000
diff --git a/tests/test_app_low_level_api/CMakeLists.txt b/tests/test_app_low_level_api/CMakeLists.txt
index 4d7cda58..e465f00d 100644
--- a/tests/test_app_low_level_api/CMakeLists.txt
+++ b/tests/test_app_low_level_api/CMakeLists.txt
@@ -7,6 +7,7 @@ target_compile_options(
test_app_low_level_api
PUBLIC
-g
+ -Os
-report
-fxscope
-target=XCORE-AI-EXPLORER
diff --git a/tests/test_app_low_level_api/main.c b/tests/test_app_low_level_api/main.c
index 447859ec..1cc2f77e 100644
--- a/tests/test_app_low_level_api/main.c
+++ b/tests/test_app_low_level_api/main.c
@@ -3,7 +3,7 @@
///
/// Application to call the control loop with the parameters fully
/// controllable by an external application. This app expects the
-/// sw_pll_init parameters on the commannd line. These will be integers
+/// sw_pll_lut_init parameters on the commannd line. These will be integers
/// for lut_table_base, skip the parameter in the list and append the whole
/// lut to the command line
///
@@ -27,10 +27,12 @@ int main(int argc, char** argv) {
int i = 1;
- float kp = atoi(argv[i++]);
+ float kp = atof(argv[i++]);
fprintf(stderr, "kp\t\t%f\n", kp);
- float ki = atoi(argv[i++]);
+ float ki = atof(argv[i++]);
fprintf(stderr, "ki\t\t%f\n", ki);
+ float kii = atof(argv[i++]);
+ fprintf(stderr, "kii\t\t%f\n", kii);
size_t loop_rate_count = atoi(argv[i++]);
fprintf(stderr, "loop_rate_count\t\t%d\n", loop_rate_count);
size_t pll_ratio = atoi(argv[i++]);
@@ -64,18 +66,19 @@ int main(int argc, char** argv) {
fprintf(stderr, "\n");
sw_pll_state_t sw_pll;
- sw_pll_init( &sw_pll,
- SW_PLL_15Q16(kp),
- SW_PLL_15Q16(ki),
- loop_rate_count,
- pll_ratio,
- ref_clk_expected_inc,
- lut_table_base,
- num_lut_entries,
- app_pll_ctl_reg_val,
- app_pll_div_reg_val,
- nominal_lut_idx,
- ppm_range);
+ sw_pll_lut_init( &sw_pll,
+ SW_PLL_15Q16(kp),
+ SW_PLL_15Q16(ki),
+ SW_PLL_15Q16(kii),
+ loop_rate_count,
+ pll_ratio,
+ ref_clk_expected_inc,
+ lut_table_base,
+ num_lut_entries,
+ app_pll_ctl_reg_val,
+ app_pll_div_reg_val,
+ nominal_lut_idx,
+ ppm_range);
for(;;) {
@@ -99,12 +102,13 @@ int main(int argc, char** argv) {
int16_t error;
sscanf(read_buf, "%hu", &error);
fprintf(stderr, "%hu\n", error);
+
uint32_t t0 = get_reference_time();
- sw_pll_lock_status_t s = sw_pll_do_control_from_error(&sw_pll, error);
+ sw_pll_lock_status_t s = sw_pll_lut_do_control_from_error(&sw_pll, error);
uint32_t t1 = get_reference_time();
// xsim doesn't support our register and the val that was set gets
// dropped
- printf("%i %x %hd %ld %u %lu\n", s, sw_pll.current_reg_val, error, sw_pll.error_accum, sw_pll.first_loop, t1 - t0);
+ printf("%i %x %hd %ld %ld %u %lu\n", s, sw_pll.lut_state.current_reg_val, error, sw_pll.pi_state.error_accum, sw_pll.pi_state.error_accum_accum, sw_pll.first_loop, t1 - t0);
}
}
diff --git a/tests/test_app_low_level_api/readme.txt b/tests/test_app_low_level_api/readme.txt
deleted file mode 100644
index e69de29b..00000000
diff --git a/tests/test_app_sdm_ctrl/CMakeLists.txt b/tests/test_app_sdm_ctrl/CMakeLists.txt
new file mode 100644
index 00000000..163104e6
--- /dev/null
+++ b/tests/test_app_sdm_ctrl/CMakeLists.txt
@@ -0,0 +1,24 @@
+cmake_minimum_required(VERSION 3.21.0)
+
+add_executable(test_app_sdm_ctrl EXCLUDE_FROM_ALL main.c)
+
+
+target_compile_options(
+ test_app_sdm_ctrl
+ PUBLIC
+ -g
+ -Os
+ -report
+ -fxscope
+ -target=XCORE-AI-EXPLORER
+)
+
+target_link_options(
+ test_app_sdm_ctrl
+ PUBLIC
+ -report
+ -target=XCORE-AI-EXPLORER
+ -fcmdline-buffer-bytes=10000 # support for command line params
+)
+
+target_link_libraries(test_app_sdm_ctrl PUBLIC lib_sw_pll)
diff --git a/tests/test_app_sdm_ctrl/main.c b/tests/test_app_sdm_ctrl/main.c
new file mode 100644
index 00000000..f76a9ed9
--- /dev/null
+++ b/tests/test_app_sdm_ctrl/main.c
@@ -0,0 +1,149 @@
+// Copyright 2023 XMOS LIMITED.
+// This Software is subject to the terms of the XMOS Public Licence: Version 1.
+///
+/// Application to call the control loop with the parameters fully
+/// controllable by an external application. This app expects the
+/// sw_pll_init parameters on the commannd line. These will be integers
+/// for lut_table_base, skip the parameter in the list and append the whole
+/// lut to the command line
+///
+/// After init, the app will expect 2 integers to come in over stdin, These
+/// are the mclk_pt and ref_pt. It will then run control and print out the
+/// locked state and register value.
+///
+///
+///
+#include "xs1.h"
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#define IN_LINE_SIZE 1000
+
+extern int32_t sw_pll_sdm_post_control_proc(sw_pll_state_t * const sw_pll, int32_t error);
+
+
+DECLARE_JOB(control_task, (int, char**, chanend_t));
+void control_task(int argc, char** argv, chanend_t c_sdm_control) {
+
+ int i = 1;
+
+ float kp = atof(argv[i++]);
+ fprintf(stderr, "kp\t\t%f\n", kp);
+ float ki = atof(argv[i++]);
+ fprintf(stderr, "ki\t\t%f\n", ki);
+ float kii = atof(argv[i++]);
+ fprintf(stderr, "kii\t\t%f\n", kii);
+ size_t loop_rate_count = atoi(argv[i++]);
+ fprintf(stderr, "loop_rate_count\t\t%d\n", loop_rate_count);
+ size_t pll_ratio = atoi(argv[i++]);
+ fprintf(stderr, "pll_ratio\t\t%d\n", pll_ratio);
+ uint32_t ref_clk_expected_inc = atoi(argv[i++]);
+ fprintf(stderr, "ref_clk_expected_inc\t\t%lu\n", ref_clk_expected_inc);
+ uint32_t app_pll_ctl_reg_val = atoi(argv[i++]);
+ fprintf(stderr, "app_pll_ctl_reg_val\t\t%lu\n", app_pll_ctl_reg_val);
+ uint32_t app_pll_div_reg_val = atoi(argv[i++]);
+ fprintf(stderr, "app_pll_div_reg_val\t\t%lu\n", app_pll_div_reg_val);
+ uint32_t app_pll_frac_reg_val = atoi(argv[i++]);
+ fprintf(stderr, "app_pll_frac_reg_val\t\t%lu\n", app_pll_frac_reg_val);
+ int32_t ctrl_mid_point = atoi(argv[i++]);
+ fprintf(stderr, "ctrl_mid_point\t\t%ld\n", ctrl_mid_point);
+ unsigned ppm_range = atoi(argv[i++]);
+ fprintf(stderr, "ppm_range\t\t%d\n", ppm_range);
+ unsigned target_output_frequency = atoi(argv[i++]);
+ fprintf(stderr, "target_output_frequency\t\t%d\n", target_output_frequency);
+
+ if(i != argc) {
+ fprintf(stderr, "wrong number of params sent to main.c in xcore test app\n");
+ exit(1);
+ }
+
+ sw_pll_state_t sw_pll;
+
+ sw_pll_sdm_init(&sw_pll,
+ SW_PLL_15Q16(kp),
+ SW_PLL_15Q16(ki),
+ SW_PLL_15Q16(kii),
+ loop_rate_count,
+ pll_ratio,
+ ref_clk_expected_inc,
+ app_pll_ctl_reg_val,
+ app_pll_div_reg_val,
+ app_pll_frac_reg_val,
+ ctrl_mid_point,
+ ppm_range);
+
+
+ for(;;) {
+ char read_buf[IN_LINE_SIZE];
+ int len = 0;
+ for(;;) {
+ int val = fgetc(stdin);
+ if(EOF == val) {
+ exit(0);
+ }
+ if('\n' == val) {
+ read_buf[len] = 0;
+ break;
+ }
+ else {
+ read_buf[len++] = val;
+ }
+ }
+
+ int16_t mclk_diff;
+ sscanf(read_buf, "%hd", &mclk_diff);
+
+ uint32_t t0 = get_reference_time();
+ int32_t error = sw_pll_do_pi_ctrl(&sw_pll, -mclk_diff);
+ int32_t dco_ctl = sw_pll_sdm_post_control_proc(&sw_pll, error);
+ uint32_t t1 = get_reference_time();
+
+ printf("%ld %ld %d %lu\n", error, dco_ctl, sw_pll.lock_status, t1 - t0);
+ }
+}
+
+DECLARE_JOB(sdm_dummy, (chanend_t));
+void sdm_dummy(chanend_t c_sdm_control){
+ int running = 1;
+
+ int ds_in = 0;
+ while(running){
+ // Poll for new SDM control value
+ SELECT_RES(
+ CASE_THEN(c_sdm_control, ctrl_update),
+ DEFAULT_THEN(default_handler)
+ )
+ {
+ ctrl_update:
+ {
+ ds_in = chan_in_word(c_sdm_control);
+ fprintf(stderr, "%d\n", ds_in);
+ }
+ break;
+
+ default_handler:
+ {
+ // Do nothing & fall-through
+ }
+ break;
+ }
+ }
+}
+
+
+int main(int argc, char** argv) {
+
+ channel_t c_sdm_control = chan_alloc();
+
+ PAR_JOBS(PJOB(control_task, (argc, argv, c_sdm_control.end_a)),
+ PJOB(sdm_dummy, (c_sdm_control.end_a)));
+
+ return 0;
+}
\ No newline at end of file
diff --git a/tests/test_app_sdm_dco/CMakeLists.txt b/tests/test_app_sdm_dco/CMakeLists.txt
new file mode 100644
index 00000000..edace81f
--- /dev/null
+++ b/tests/test_app_sdm_dco/CMakeLists.txt
@@ -0,0 +1,24 @@
+cmake_minimum_required(VERSION 3.21.0)
+
+add_executable(test_app_sdm_dco EXCLUDE_FROM_ALL main.c)
+
+
+target_compile_options(
+ test_app_sdm_dco
+ PUBLIC
+ -g
+ -Os
+ -report
+ -fxscope
+ -target=XCORE-AI-EXPLORER
+)
+
+target_link_options(
+ test_app_sdm_dco
+ PUBLIC
+ -report
+ -target=XCORE-AI-EXPLORER
+ -fcmdline-buffer-bytes=10000 # support for command line params
+)
+
+target_link_libraries(test_app_sdm_dco PUBLIC lib_sw_pll)
diff --git a/tests/test_app_sdm_dco/main.c b/tests/test_app_sdm_dco/main.c
new file mode 100644
index 00000000..0dab4979
--- /dev/null
+++ b/tests/test_app_sdm_dco/main.c
@@ -0,0 +1,60 @@
+// Copyright 2023 XMOS LIMITED.
+// This Software is subject to the terms of the XMOS Public Licence: Version 1.
+///
+/// Application to call the control loop with the parameters fully
+/// controllable by an external application. This app expects the
+/// sw_pll_init parameters on the commannd line. These will be integers
+/// for lut_table_base, skip the parameter in the list and append the whole
+/// lut to the command line
+///
+/// After init, the app will expect 2 integers to come in over stdin, These
+/// are the mclk_pt and ref_pt. It will then run control and print out the
+/// locked state and register value.
+///
+///
+///
+#include "xs1.h"
+#include
+#include
+#include
+#include
+#include
+#include
+
+#define IN_LINE_SIZE 1000
+
+int main(int argc, char** argv) {
+
+ sw_pll_sdm_state_t sdm_state;
+ sw_pll_init_sigma_delta(&sdm_state);
+
+ for(;;) {
+ char read_buf[IN_LINE_SIZE];
+ int len = 0;
+ for(;;) {
+ int val = fgetc(stdin);
+ if(EOF == val) {
+ return 0;
+ }
+ if('\n' == val) {
+ read_buf[len] = 0;
+ break;
+ }
+ else {
+ read_buf[len++] = val;
+ }
+ }
+
+ int32_t ds_in;
+ sscanf(read_buf, "%ld", &ds_in);
+ // fprintf(stderr, "%ld\n", ds_in);
+
+ // calc new ds_out and then wait to write
+ uint32_t t0 = get_reference_time();
+ int32_t ds_out = sw_pll_calc_sigma_delta(&sdm_state, ds_in);
+ uint32_t frac_val = sw_pll_sdm_out_to_frac_reg(ds_out);
+ uint32_t t1 = get_reference_time();
+
+ printf("%ld %lu %lu\n", ds_out, frac_val, t1 - t0);
+ }
+}
diff --git a/tests/test_lib_sw_pll.py b/tests/test_lib_sw_pll.py
index 2fe002d4..0179c37f 100644
--- a/tests/test_lib_sw_pll.py
+++ b/tests/test_lib_sw_pll.py
@@ -14,13 +14,10 @@
import numpy as np
import copy
+from sw_pll.app_pll_model import pll_solution, app_pll_frac_calc
+from sw_pll.sw_pll_sim import sim_sw_pll_lut
+
from typing import Any
-from sw_pll.sw_pll_sim import (
- pll_solution,
- app_pll_frac_calc,
- sw_pll_ctrl,
- get_frequency_from_error,
-)
from dataclasses import dataclass, asdict
from subprocess import Popen, PIPE
from itertools import product
@@ -28,13 +25,13 @@
from matplotlib import pyplot as plt
DUT_XE = Path(__file__).parent / "../build/tests/test_app/test_app.xe"
-DUT_XE_LOW_LEVEL = Path(__file__).parent / "../build/tests/test_app_low_level_api/test_app_low_level_api.xe"
BIN_PATH = Path(__file__).parent/"bin"
@dataclass
class DutArgs:
kp: float
ki: float
+ kii: float
loop_rate_count: int
pll_ratio: int
ref_clk_expected_inc: int
@@ -53,21 +50,18 @@ def __init__(self, args: DutArgs, pll):
self.pll = pll
self.args = DutArgs(**asdict(args)) # copies the values
self.lut = self.args.lut
- self.args.lut = len(self.lut.get_lut())
- self.ctrl = sw_pll_ctrl(
+ self.args.lut = len(self.lut)
+ nominal_control_rate_hz = args.target_output_frequency / args.pll_ratio / args.loop_rate_count
+ self.ctrl = sim_sw_pll_lut(
args.target_output_frequency,
- self.lut_func,
- len(self.lut.get_lut()),
- args.loop_rate_count,
- args.pll_ratio,
+ nominal_control_rate_hz,
args.kp,
args.ki,
- base_lut_index=args.nominal_lut_idx,
- )
+ Kii=args.kii )
def lut_func(self, error):
"""Sim requires a function to provide access to the LUT. This is that"""
- return get_frequency_from_error(error, self.lut.get_lut(), self.pll)
+ return get_frequency_from_error(error, self.lut, self.pll)
def __enter__(self):
"""support context manager"""
@@ -80,17 +74,18 @@ def do_control(self, mclk_pt, _ref_pt):
"""
Execute control using simulator
"""
- f, l = self.ctrl.do_control(mclk_pt)
+ f, l = self.ctrl.do_control_loop(mclk_pt)
- return l, f, self.ctrl.diff, self.ctrl.error_accum, 0, 0
+ return l, f, self.ctrl.controller.diff, self.ctrl.controller.error_accum, self.ctrl.controller.error_accum_accum, 0, 0
def do_control_from_error(self, error):
"""
Execute control using simulator
"""
- f, l = self.ctrl.do_control_from_error(error)
+ dco_ctl = self.ctrl.controller.get_dco_control_from_error(error)
+ f, l = self.ctrl.dco.get_frequency_from_dco_control(dco_ctl)
- return l, f, self.ctrl.diff, self.ctrl.error_accum, 0, 0
+ return l, f, self.ctrl.controller.diff, self.ctrl.controller.error_accum, self.ctrl.controller.error_accum_accum, 0, 0
class Dut:
"""
@@ -102,8 +97,9 @@ def __init__(self, args: DutArgs, pll, xe_file=DUT_XE):
self.args = DutArgs(**asdict(args)) # copies the values
self.args.kp = self.args.kp
self.args.ki = self.args.ki
- lut = self.args.lut.get_lut()
- self.args.lut = len(args.lut.get_lut())
+ self.args.kii = self.args.kii
+ lut = self.args.lut
+ self.args.lut = len(args.lut)
# concatenate the parameters to the init function and the whole lut
# as the command line parameters to the xe.
list_args = [*(str(i) for i in asdict(self.args).values())] + [
@@ -132,27 +128,27 @@ def __exit__(self, *_):
def do_control(self, mclk_pt, ref_pt):
"""
- returns lock_state, reg_val, mclk_diff, error_acum, first_loop, ticks
+ returns lock_state, reg_val, mclk_diff, error_acum, error_acum_acum, first_loop, ticks
"""
self._process.stdin.write(f"{mclk_pt % 2**16} {ref_pt % 2**16}\n")
self._process.stdin.flush()
- locked, reg, diff, acum, first_loop, ticks = self._process.stdout.readline().strip().split()
+ locked, reg, diff, acum, acum_acum, first_loop, ticks = self._process.stdout.readline().strip().split()
- self.pll.update_pll_frac_reg(int(reg, 16))
- return int(locked), self.pll.get_output_frequency(), int(diff), int(acum), int(first_loop), int(ticks)
+ self.pll.update_frac_reg(int(reg, 16) | app_pll_frac_calc.frac_enable_mask)
+ return int(locked), self.pll.get_output_frequency(), int(diff), int(acum), int(acum_acum), int(first_loop), int(ticks)
def do_control_from_error(self, error):
"""
- returns lock_state, reg_val, mclk_diff, error_acum, first_loop, ticks
+ returns lock_state, reg_val, mclk_diff, error_acum, error_acum_acum, first_loop, ticks
"""
self._process.stdin.write(f"{error % 2**16}\n")
self._process.stdin.flush()
- locked, reg, diff, acum, first_loop, ticks = self._process.stdout.readline().strip().split()
+ locked, reg, diff, acum, acum_acum, first_loop, ticks = self._process.stdout.readline().strip().split()
- self.pll.update_pll_frac_reg(int(reg, 16))
- return int(locked), self.pll.get_output_frequency(), int(diff), int(acum), int(first_loop), int(ticks)
+ self.pll.update_frac_reg(int(reg, 16) | app_pll_frac_calc.frac_enable_mask)
+ return int(locked), self.pll.get_output_frequency(), int(diff), int(acum), int(acum_acum), int(first_loop), int(ticks)
def close(self):
@@ -217,11 +213,12 @@ def basic_test_vector(request, solution_12288, bin_dir):
loop_rate_count = 1
# Generate init parameters
- start_reg = sol.lut.get_lut()[0]
+ start_reg = sol.lut[0]
args = DutArgs(
target_output_frequency=target_mclk_f,
kp=0.0,
ki=1.0,
+ kii=0.0,
loop_rate_count=loop_rate_count, # copied from ed's setup in 3800
# have to call 512 times to do 1
# control update
@@ -234,15 +231,15 @@ def basic_test_vector(request, solution_12288, bin_dir):
# directly into the lut index. therefore the "ppm_range" or max
# allowable diff must be at least as big as the LUT. *2 used here
# to allow recovery from out of range values.
- ppm_range=int(len(sol.lut.get_lut()) * 2),
+ ppm_range=int(len(sol.lut) * 2),
lut=sol.lut,
)
- pll = app_pll_frac_calc(xtal_freq, sol.F, sol.R, sol.OD, sol.ACD, 1, 2)
+ pll = app_pll_frac_calc(xtal_freq, sol.F, sol.R, 1, 2, sol.OD, sol.ACD)
frequency_lut = []
- for reg in sol.lut.get_lut():
- pll.update_pll_frac_reg(reg)
+ for reg in sol.lut:
+ pll.update_frac_reg(reg | app_pll_frac_calc.frac_enable_mask)
frequency_lut.append(pll.get_output_frequency())
frequency_range_frac = (frequency_lut[-1] - frequency_lut[0])/frequency_lut[0]
@@ -251,7 +248,7 @@ def basic_test_vector(request, solution_12288, bin_dir):
plt.savefig(bin_dir/f"lut-{name}.png")
plt.close()
- pll.update_pll_frac_reg(start_reg)
+ pll.update_frac_reg(start_reg | app_pll_frac_calc.frac_enable_mask)
input_freqs = {
"perfect": target_ref_f,
@@ -274,6 +271,7 @@ def basic_test_vector(request, solution_12288, bin_dir):
"actual_diff": [],
"clk_diff": [],
"clk_diff_i": [],
+ "clk_diff_ii": [],
"first_loop": [],
"ticks": []
}
@@ -295,7 +293,7 @@ def basic_test_vector(request, solution_12288, bin_dir):
loop_time = ref_pt_per_loop / ref_f
mclk_count = loop_time * mclk_f
mclk_pt = mclk_pt + mclk_count
- locked, mclk_f, e, ea, fl, ticks = dut.do_control(int(mclk_pt), int(ref_pt))
+ locked, mclk_f, e, ea, eaa, fl, ticks = dut.do_control(int(mclk_pt), int(ref_pt))
results["target"].append(ref_f * (target_mclk_f / target_ref_f))
results["ref_f"].append(ref_f)
@@ -308,6 +306,7 @@ def basic_test_vector(request, solution_12288, bin_dir):
results["clk_diff"].append(e)
results["actual_diff"].append(mclk_count - (ref_pt_per_loop * (target_mclk_f/target_ref_f)))
results["clk_diff_i"].append(ea)
+ results["clk_diff_ii"].append(eaa)
results["first_loop"].append(fl)
results["ticks"].append(ticks)
@@ -324,6 +323,11 @@ def basic_test_vector(request, solution_12288, bin_dir):
plt.savefig(bin_dir/f"basic-test-vector-{name}-error-acum.png")
plt.close()
+ plt.figure()
+ df[["target", "clk_diff_ii"]].plot(secondary_y=["target"])
+ plt.savefig(bin_dir/f"basic-test-vector-{name}-error-acum-acum.png")
+ plt.close()
+
plt.figure()
df[["exp_mclk_count", "mclk_count"]].plot()
plt.savefig(bin_dir/f"basic-test-vector-{name}-counts.png")
@@ -336,7 +340,7 @@ def basic_test_vector(request, solution_12288, bin_dir):
df.to_csv(bin_dir/f"basic-test-vector-{name}.csv")
- with open(bin_dir/f"timing-report.txt", "a") as tr:
+ with open(bin_dir/f"timing-report-lut.txt", "a") as tr:
max_ticks = int(df[["ticks"]].max())
tr.write(f"{name} max ticks: {max_ticks}\n")
@@ -368,6 +372,7 @@ def test_lock_lost(basic_test_vector, test_f):
this_df = df[df["ref_f"] == input_freqs[test_f]]
not_locked_df = this_df[this_df["locked"] != 0]
+
assert not not_locked_df.empty, "Expected lock to be lost when out of range"
first_not_locked = not_locked_df.index[0]
after_not_locked = this_df[first_not_locked:]["locked"] != 0
@@ -414,113 +419,3 @@ def test_locked_values_within_desirable_ppm(basic_test_vector, test_f):
assert not test_df.empty, "No locked values found, expected some"
max_diff = (test_df["mclk"] - test_df["target"]).abs().max()
assert max_diff < max_f_step, "Frequency oscillating more that expected when locked"
-
-
-def test_low_level_equivalence(solution_12288, bin_dir):
- """
- Simple low level test of equivalence using do_control_from_error
- Feed in random numbers into but C and Python DUTs and see if we get the same results
- """
-
- _, xtal_freq, target_mclk_f, sol = solution_12288
-
-
- # every sample to speed things up.
- loop_rate_count = 1
- target_ref_f = 48000
-
- # Generate init parameters
- start_reg = sol.lut.get_lut()[0]
- lut_size = len(sol.lut.get_lut())
-
- args = DutArgs(
- target_output_frequency=target_mclk_f,
- kp=0.0,
- ki=1.0,
- loop_rate_count=loop_rate_count, # copied from ed's setup in 3800
- # have to call 512 times to do 1
- # control update
- pll_ratio=int(target_mclk_f / target_ref_f),
- ref_clk_expected_inc=0,
- app_pll_ctl_reg_val=0,
- app_pll_div_reg_val=start_reg,
- nominal_lut_idx=0, # start low so there is some control to do
- # with ki of 1 and the other values 0, the diff value translates
- # directly into the lut index. therefore the "ppm_range" or max
- # allowable diff must be at least as big as the LUT. *2 used here
- # to allow recovery from out of range values.
- ppm_range=int(lut_size * 2),
- lut=sol.lut,
- )
-
- pll = app_pll_frac_calc(xtal_freq, sol.F, sol.R, sol.OD, sol.ACD, 1, 2)
-
- frequency_lut = []
-
- pll.update_pll_frac_reg(start_reg)
-
- input_errors = np.random.randint(-lut_size // 2, lut_size // 2, size = 40)
- print(f"input_errors: {input_errors}")
-
- result_categories = {
- "mclk": [],
- "locked": [],
- "time": [],
- "clk_diff": [],
- "clk_diff_i": [],
- "first_loop": [],
- "ticks": []
- }
- names = ["C", "Python"]
- duts = [Dut(args, pll, xe_file=DUT_XE_LOW_LEVEL), SimDut(args, pll)]
-
- results = {}
- for name in names:
- results[name] = copy.deepcopy(result_categories)
-
- for dut, name in zip(duts, names):
- _, mclk_f, *_ = dut.do_control_from_error(0)
-
- locked = -1
- time = 0
- print(f"Running: {name}")
- for input_error in input_errors:
-
- locked, mclk_f, e, ea, fl, ticks = dut.do_control_from_error(input_error)
-
- results[name]["mclk"].append(mclk_f)
- results[name]["time"].append(time)
- results[name]["locked"].append(locked)
- results[name]["clk_diff"].append(e)
- results[name]["clk_diff_i"].append(ea)
- results[name]["first_loop"].append(fl)
- results[name]["ticks"].append(ticks)
- time += 1
-
- # print(name, time, input_error, mclk_f)
-
- # Plot mclk output dut vs dut
- duts = list(results.keys())
- for dut in duts:
- mclk = results[dut]["mclk"]
- times = results[dut]["time"]
- clk_diff = results[dut]["clk_diff"]
- clk_diff_i = results[dut]["clk_diff_i"]
- locked = results[dut]["locked"]
-
- plt.plot(mclk, label=dut)
-
- plt.legend(loc="upper left")
- plt.xlabel("Iteration")
- plt.ylabel("mclk")
- plt.savefig(bin_dir/f"c-vs-python-low-level-equivalence-mclk.png")
- plt.close()
-
- # Check for equivalence
- for compare_item in ["mclk", "clk_diff", "clk_diff_i"]:
- C = results["C"][compare_item]
- Python = results["Python"][compare_item]
- assert np.allclose(C, Python), f"Error in low level equivalence checking of: {compare_item}"
-
- print("TEST PASSED!")
-
diff --git a/tests/test_lib_sw_pll_equiv.py b/tests/test_lib_sw_pll_equiv.py
new file mode 100644
index 00000000..e713b0d5
--- /dev/null
+++ b/tests/test_lib_sw_pll_equiv.py
@@ -0,0 +1,127 @@
+# Copyright 2023 XMOS LIMITED.
+# This Software is subject to the terms of the XMOS Public Licence: Version 1.
+
+import pytest
+import numpy as np
+import copy
+
+from sw_pll.app_pll_model import pll_solution, app_pll_frac_calc
+from sw_pll.sw_pll_sim import sim_sw_pll_lut
+
+from test_lib_sw_pll import SimDut, Dut, DutArgs, solution_12288, bin_dir
+
+from pathlib import Path
+from matplotlib import pyplot as plt
+
+DUT_XE_LOW_LEVEL = Path(__file__).parent / "../build/tests/test_app_low_level_api/test_app_low_level_api.xe"
+BIN_PATH = Path(__file__).parent/"bin"
+
+
+def test_low_level_equivalence(solution_12288, bin_dir):
+ """
+ Simple low level test of equivalence using do_control_from_error
+ Feed in random numbers into C and Python DUTs and see if we get the same results
+ """
+
+ _, xtal_freq, target_mclk_f, sol = solution_12288
+
+
+ # every sample to speed things up.
+ loop_rate_count = 1
+ target_ref_f = 48000
+
+ # Generate init parameters
+ start_reg = sol.lut[0]
+ lut_size = len(sol.lut)
+
+ args = DutArgs(
+ target_output_frequency=target_mclk_f,
+ kp=0.0,
+ ki=2.0,
+ kii=1.0, # NOTE WE SPECIFICALLY ENABLE KII in this test as it is not tested elsewhere
+ loop_rate_count=loop_rate_count,
+ pll_ratio=int(target_mclk_f / target_ref_f),
+ ref_clk_expected_inc=0,
+ app_pll_ctl_reg_val=0,
+ app_pll_div_reg_val=start_reg,
+ nominal_lut_idx=lut_size//2,
+ ppm_range=int(lut_size * 2),
+ lut=sol.lut,
+ )
+
+ pll = app_pll_frac_calc(xtal_freq, sol.F, sol.R, 1, 2, sol.OD, sol.ACD)
+
+ pll.update_frac_reg(start_reg | app_pll_frac_calc.frac_enable_mask)
+
+ input_errors = np.random.randint(-lut_size // 10, lut_size // 10, size = 40)
+ print(f"input_errors: {input_errors}")
+
+ result_categories = {
+ "mclk": [],
+ "locked": [],
+ "time": [],
+ "clk_diff": [],
+ "clk_diff_i": [],
+ "clk_diff_ii": [],
+ "first_loop": [],
+ "ticks": []
+ }
+ names = ["C", "Python"]
+ duts = [Dut(args, pll, xe_file=DUT_XE_LOW_LEVEL), SimDut(args, pll)]
+
+ results = {}
+ for name in names:
+ results[name] = copy.deepcopy(result_categories)
+
+ for dut, name in zip(duts, names):
+ _, mclk_f, *_ = dut.do_control_from_error(0)
+
+ locked = -1
+ time = 0
+ print(f"Running: {name}")
+ for input_error in input_errors:
+
+ locked, mclk_f, e, ea, eaa, fl, ticks = dut.do_control_from_error(input_error)
+
+ results[name]["mclk"].append(mclk_f)
+ results[name]["time"].append(time)
+ results[name]["locked"].append(locked)
+ results[name]["clk_diff"].append(e)
+ results[name]["clk_diff_i"].append(ea)
+ results[name]["clk_diff_ii"].append(eaa)
+ results[name]["first_loop"].append(fl)
+ results[name]["ticks"].append(ticks)
+ time += 1
+
+ # print(name, time, input_error, mclk_f)
+
+ # Plot mclk output dut vs dut
+ duts = list(results.keys())
+ for dut in duts:
+ mclk = results[dut]["mclk"]
+ times = results[dut]["time"]
+ clk_diff = results[dut]["clk_diff"]
+ clk_diff_i = results[dut]["clk_diff_i"]
+ clk_diff_ii = results[dut]["clk_diff_ii"]
+ locked = results[dut]["locked"]
+
+ plt.plot(mclk, label=dut)
+
+ plt.legend(loc="upper left")
+ plt.xlabel("Iteration")
+ plt.ylabel("mclk")
+ plt.savefig(bin_dir/f"c-vs-python-low-level-equivalence-mclk.png")
+ plt.close()
+
+ # Check for equivalence
+ for compare_item in ["clk_diff", "clk_diff_i", "clk_diff_ii", "mclk"]:
+ C = results["C"][compare_item]
+ Python = results["Python"][compare_item]
+ print("***", compare_item)
+ for c, p in zip(C, Python):
+ print(c, p)
+ print()
+ assert np.allclose(C, Python), f"Error in low level equivalence checking of: {compare_item}"
+
+ print("TEST PASSED!")
+
diff --git a/tests/test_sdm_ctrl_equiv.py b/tests/test_sdm_ctrl_equiv.py
new file mode 100644
index 00000000..3dda415a
--- /dev/null
+++ b/tests/test_sdm_ctrl_equiv.py
@@ -0,0 +1,171 @@
+# Copyright 2023 XMOS LIMITED.
+# This Software is subject to the terms of the XMOS Public Licence: Version 1.
+
+import pytest
+import numpy as np
+import copy
+from typing import Any
+from dataclasses import dataclass, asdict
+from pathlib import Path
+from matplotlib import pyplot as plt
+from subprocess import Popen, PIPE
+import re
+
+
+# from sw_pll.app_pll_model import app_pll_frac_calc
+from sw_pll.dco_model import sigma_delta_dco
+from sw_pll.controller_model import sdm_pi_ctrl
+from test_lib_sw_pll import bin_dir
+
+
+DUT_XE_SDM_CTRL = Path(__file__).parent / "../build/tests/test_app_sdm_ctrl/test_app_sdm_ctrl.xe"
+
+@dataclass
+class DutSDMCTRLArgs:
+ kp: float
+ ki: float
+ kii: float
+ loop_rate_count: int
+ pll_ratio: int
+ ref_clk_expected_inc: int
+ app_pll_ctl_reg_val: int
+ app_pll_div_reg_val: int
+ app_pll_frac_reg_val: int
+ ctrl_mid_point: int
+ ppm_range: int
+ target_output_frequency: int
+
+
+class Dut_SDM_CTRL:
+ """
+ run controller in xsim and provide access to the sdm function
+ """
+
+ def __init__(self, args:DutSDMCTRLArgs, xe_file=DUT_XE_SDM_CTRL):
+ self.args = DutSDMCTRLArgs(**asdict(args)) # copies the values
+ # concatenate the parameters to the init function and the whole lut
+ # as the command line parameters to the xe.
+ list_args = [*(str(i) for i in asdict(self.args).values())]
+
+ cmd = ["xsim", "--args", str(xe_file), *list_args]
+
+ print(" ".join(cmd))
+
+ self._process = Popen(
+ cmd,
+ stdin=PIPE,
+ stdout=PIPE,
+ encoding="utf-8",
+ )
+
+ def __enter__(self):
+ """support context manager"""
+ return self
+
+ def __exit__(self, *_):
+ """support context manager"""
+ self.close()
+
+ def do_control(self, mclk_diff):
+ """
+ returns sigma delta out, calculated frac val, lock status and timing
+ """
+ self._process.stdin.write(f"{mclk_diff}\n")
+ self._process.stdin.flush()
+
+ from_dut = self._process.stdout.readline().strip()
+ # print(f"from_dut: {from_dut}")
+ error, dco_ctrl, locked, ticks = from_dut.split()
+
+ return int(error), int(dco_ctrl), int(locked), int(ticks)
+
+ def close(self):
+ """Send EOF to xsim and wait for it to exit"""
+ self._process.stdin.close()
+ self._process.wait()
+
+
+def read_register_file(reg_file):
+ with open(reg_file) as rf:
+ text = "".join(rf.readlines())
+ regex = r".+APP_PLL_CTL_REG 0[xX]([0-9a-fA-F]+)\n.+APP_PLL_DIV_REG 0[xX]([0-9a-fA-F]+)\n.+APP_PLL_FRAC_REG 0[xX]([0-9a-fA-F]+)\n.+SW_PLL_SDM_CTRL_MID (\d+)"
+ match = re.search(regex, text)
+
+ app_pll_ctl_reg_val, app_pll_div_reg_val, app_pll_frac_reg_val, ctrl_mid_point = match.groups()
+
+ return int(app_pll_ctl_reg_val, 16), int(app_pll_div_reg_val, 16), int(app_pll_frac_reg_val, 16), int(ctrl_mid_point)
+
+
+def test_sdm_ctrl_equivalence(bin_dir):
+ """
+ Simple low level test of equivalence using do_control_from_error
+ Feed in random numbers into C and Python DUTs and see if we get the same results
+ """
+
+ available_profiles = list(sigma_delta_dco.profiles.keys())
+
+ with open(bin_dir/f"timing-report-sdm-ctrl.txt", "a") as tr:
+
+ for profile_used in available_profiles:
+ profile = sigma_delta_dco.profiles[profile_used]
+ target_output_frequency = profile["output_frequency"]
+ ctrl_mid_point = profile["mod_init"]
+ ref_frequency = 48000
+ ref_clk_expected_inc = 0
+
+ Kp = 0.0
+ Ki = 32.0
+ Kii = 0.0
+
+ ctrl_sim = sdm_pi_ctrl(ctrl_mid_point, sigma_delta_dco.sdm_in_max, sigma_delta_dco.sdm_in_min, Kp, Ki)
+
+ dco = sigma_delta_dco(profile_used)
+ dco.print_stats()
+ register_file = dco.write_register_file()
+ app_pll_ctl_reg_val, app_pll_div_reg_val, app_pll_frac_reg_val, read_ctrl_mid_point = read_register_file(register_file)
+
+ assert ctrl_mid_point == read_ctrl_mid_point, f"ctrl_mid_point doesn't match: {ctrl_mid_point} {read_ctrl_mid_point}"
+
+ args = DutSDMCTRLArgs(
+ kp = Kp,
+ ki = Ki,
+ kii = Kii,
+ loop_rate_count = 1,
+ pll_ratio = target_output_frequency / ref_frequency,
+ ref_clk_expected_inc = ref_clk_expected_inc,
+ app_pll_ctl_reg_val = app_pll_ctl_reg_val,
+ app_pll_div_reg_val = app_pll_div_reg_val,
+ app_pll_frac_reg_val = app_pll_frac_reg_val,
+ ctrl_mid_point = ctrl_mid_point,
+ ppm_range = 1000,
+ target_output_frequency = target_output_frequency
+ )
+
+
+ ctrl_dut = Dut_SDM_CTRL(args)
+
+ max_ticks = 0
+
+ for i in range(50):
+ mclk_diff = np.random.randint(-10, 10)
+
+ # Run through the model
+ dco_ctl_sim, lock_status_sim = ctrl_sim.do_control_from_error(mclk_diff)
+ error_sim = ctrl_sim.total_error
+
+ # Run through the firmware
+ error_dut, dco_ctl_dut, lock_status_dut, ticks = ctrl_dut.do_control(mclk_diff)
+
+ print(f"SIM: {mclk_diff} {error_sim} {dco_ctl_sim} {lock_status_sim}")
+ print(f"DUT: {mclk_diff} {error_dut} {dco_ctl_dut} {lock_status_dut} {ticks}\n")
+
+ max_ticks = ticks if ticks > max_ticks else max_ticks
+
+ assert error_sim == error_dut
+ assert dco_ctl_sim == dco_ctl_dut
+ assert lock_status_sim == lock_status_dut
+
+ tr.write(f"SDM Control {profile_used} max ticks: {max_ticks}\n")
+
+ print(f"{profile_used} TEST PASSED!")
+
diff --git a/tests/test_sdm_dco_equiv.py b/tests/test_sdm_dco_equiv.py
new file mode 100644
index 00000000..fa8e84f6
--- /dev/null
+++ b/tests/test_sdm_dco_equiv.py
@@ -0,0 +1,120 @@
+# Copyright 2023 XMOS LIMITED.
+# This Software is subject to the terms of the XMOS Public Licence: Version 1.
+
+import pytest
+import numpy as np
+import copy
+from typing import Any
+from dataclasses import dataclass, asdict
+from pathlib import Path
+from matplotlib import pyplot as plt
+from subprocess import Popen, PIPE
+
+from sw_pll.dco_model import sigma_delta_dco
+
+from test_lib_sw_pll import bin_dir
+
+
+DUT_XE_SDM_DCO = Path(__file__).parent / "../build/tests/test_app_sdm_dco/test_app_sdm_dco.xe"
+
+@dataclass
+class DutSDMDCOArgs:
+ dummy: int
+
+
+class Dut_SDM_DCO:
+ """
+ run DCO in xsim and provide access to the sdm function
+ """
+
+ def __init__(self, pll, args:DutSDMDCOArgs, xe_file=DUT_XE_SDM_DCO):
+ self.args = DutSDMDCOArgs(**asdict(args)) # copies the values
+ # concatenate the parameters to the init function and the whole lut
+ # as the command line parameters to the xe.
+ list_args = [*(str(i) for i in asdict(self.args).values())]
+
+ cmd = ["xsim", "--args", str(xe_file), *list_args]
+
+ print(" ".join(cmd))
+
+ self.pll = pll.app_pll
+ self._process = Popen(
+ cmd,
+ stdin=PIPE,
+ stdout=PIPE,
+ encoding="utf-8",
+ )
+
+ def __enter__(self):
+ """support context manager"""
+ return self
+
+ def __exit__(self, *_):
+ """support context manager"""
+ self.close()
+
+ def do_modulate(self, sdm_in):
+ """
+ returns sigma delta out, calculated frac val and timing
+ """
+ self._process.stdin.write(f"{sdm_in}\n")
+ self._process.stdin.flush()
+
+ from_dut = self._process.stdout.readline().strip()
+ sdm_out, frac_val, ticks = from_dut.split()
+
+ frac_val = int(frac_val)
+ frequency = self.pll.update_frac_reg(frac_val)
+
+ return int(sdm_out), int(frac_val), frequency, int(ticks)
+
+ def close(self):
+ """Send EOF to xsim and wait for it to exit"""
+ self._process.stdin.close()
+ self._process.wait()
+
+def test_sdm_dco_equivalence(bin_dir):
+ """
+ Simple low level test of equivalence using do_modulate
+ Feed in a sweep of DCO control vals into C and Python DUTs and see if we get the same results
+ """
+
+ args = DutSDMDCOArgs(
+ dummy = 0
+ )
+
+ available_profiles = list(sigma_delta_dco.profiles.keys())
+
+ with open(bin_dir/f"timing-report-sdm-dco.txt", "a") as tr:
+
+ for profile in available_profiles:
+
+ dco_sim = sigma_delta_dco(profile)
+ dco_sim.write_register_file()
+
+ dco_sim.print_stats()
+
+ dut_pll = sigma_delta_dco(profile)
+ dco_dut = Dut_SDM_DCO(dut_pll, args)
+
+ max_ticks = 0
+
+ for sdm_in in np.linspace(dco_sim.sdm_in_min, dco_sim.sdm_in_max, 100):
+ frequency_sim = dco_sim.do_modulate(sdm_in)
+ frac_reg_sim = dco_sim.app_pll.get_frac_reg()
+
+ print(f"SIM: {sdm_in} {dco_sim.sdm_out} {frac_reg_sim:#x} {frequency_sim}")
+
+ sdm_out_dut, frac_reg_dut, frequency_dut, ticks = dco_dut.do_modulate(sdm_in)
+ print(f"DUT: {sdm_in} {sdm_out_dut} {frac_reg_dut:#x} {frequency_dut} {ticks}\n")
+
+ max_ticks = ticks if ticks > max_ticks else max_ticks
+
+ assert dco_sim.sdm_out == sdm_out_dut
+ assert frac_reg_sim == frac_reg_dut
+ assert frequency_sim == frequency_dut
+
+ tr.write(f"SDM DCO {profile} max ticks: {max_ticks}\n")
+
+ print(f"{profile} TEST PASSED!")
+
diff --git a/tools/ci/checkout-submodules.sh b/tools/ci/checkout-submodules.sh
index bd16abb5..e51e6427 100755
--- a/tools/ci/checkout-submodules.sh
+++ b/tools/ci/checkout-submodules.sh
@@ -22,11 +22,11 @@ rm -rf modules
mkdir -p modules
pushd modules
-clone fwk_core git@github.com:xmos/fwk_core.git 9e4f6196386995e2d7786b376091404638055639
-clone fwk_io git@github.com:xmos/fwk_io.git 6b3275cbe4e39abce3b6e822655732767a62740d
+clone fwk_core git@github.com:xmos/fwk_core.git v1.0.2
+clone fwk_io git@github.com:xmos/fwk_io.git v3.3.0
clone infr_scripts_py git@github.com:xmos/infr_scripts_py.git 1d767cbe89a3223da7a4e27c283fb96ee2a279c9
-clone infr_apps git@github.com:xmos/infr_apps.git 8bc62324b19a1ab32b1e5a5e262f40f710f9f5c1
+clone infr_apps git@github.com:xmos/infr_apps.git 8bc62324b19a1ab32b1e5a5e262f40f710f9f5c1
pip install -e infr_apps -e infr_scripts_py
popd
diff --git a/tools/ci/do-ci-build.sh b/tools/ci/do-ci-build.sh
new file mode 100755
index 00000000..9d59c4e8
--- /dev/null
+++ b/tools/ci/do-ci-build.sh
@@ -0,0 +1,8 @@
+#! /usr/bin/env bash
+#
+# build stuff
+
+set -ex
+
+cmake -B build -DCMAKE_TOOLCHAIN_FILE=modules/fwk_io/xmos_cmake_toolchain/xs3a.cmake
+cmake --build build --target all --target test_app --target test_app_low_level_api --target test_app_sdm_dco --target test_app_sdm_ctrl --target simple_lut --target simple_sdm --target i2s_slave_lut -j$(nproc)
diff --git a/tools/ci/do-ci-tests.sh b/tools/ci/do-ci-tests.sh
new file mode 100755
index 00000000..773b094b
--- /dev/null
+++ b/tools/ci/do-ci-tests.sh
@@ -0,0 +1,11 @@
+#! /usr/bin/env bash
+#
+# test stuff
+
+set -ex
+
+pushd tests
+pytest --junitxml=results.xml -rA -v --durations=0 -o junit_logging=all
+ls bin
+popd
+
diff --git a/tools/ci/do-ci.sh b/tools/ci/do-ci.sh
deleted file mode 100755
index 8c9e91e2..00000000
--- a/tools/ci/do-ci.sh
+++ /dev/null
@@ -1,14 +0,0 @@
-#! /usr/bin/env bash
-#
-# build and test stuff
-
-set -ex
-
-cmake -B build -DCMAKE_TOOLCHAIN_FILE=modules/fwk_io/xmos_cmake_toolchain/xs3a.cmake
-cmake --build build --target all --target test_app --target test_app_low_level_api --target simple --target i2s_slave -j$(nproc)
-
-pushd tests
-pytest --junitxml=results.xml -rA -v --durations=0 -o junit_logging=all
-ls bin
-popd
-
diff --git a/tools/ci/do-model-examples.sh b/tools/ci/do-model-examples.sh
new file mode 100755
index 00000000..07cfa755
--- /dev/null
+++ b/tools/ci/do-model-examples.sh
@@ -0,0 +1,10 @@
+#! /usr/bin/env bash
+#
+# test stuff
+
+set -ex
+
+pushd python/sw_pll
+python sw_pll_sim.py
+popd
+