Update docs

This commit is contained in:
gab-k committed 2024-11-27 21:59:54 +01:00
1 parent 72bd29ddbc
commit c0f61511ce
9 files changed
+562 -8

No files matched your search

+8
View File
@@ -0,0 +1,8 @@
Hardware
=================
.. toctree::
:maxdepth: 2
:caption: Contents:
hw_description
@@ -0,0 +1,133 @@
Hardware Description
====================
Overview
--------
.. image:: https://github.com/1nct/RP2040-Decoder/blob/main/docs/svg/Block_Diagram.svg
:alt: Block Diagram
The above block diagram gives a general overview regarding the operation of components. For better illustration it has been divided into four functional blocks. Furthermore, these functional blocks can be subdivided and will be explained below.
* **Input Stage**
- DCC Signal Level Shift
- Bridge Rectifier & Voltage Regulator
* **Motor Driver**
- Motor Driver
- Back EMF measurement (ADC)
* **General Purpose**
- GPIO
- Auxiliary output
* **Microcontroller**
- Flash memory
- Crystal oscillator
Characteristics
---------------
.. table:: Characteristics table
:widths: auto
===================================================== ============================= ========= ========= =====
Parameter Symbol Minimum Maximum Unit
===================================================== ============================= ========= ========= =====
Absolute max. DCC Input Voltage V\ :sub:`DCC`\ -25 +25 V
Absolute max. GPIO Voltage\ :sup:`(0)`\ V\ :sub:`PIN`\ -0.5 3.3+0.5 V
Input Voltage High\ :sup:`(0)`\ V\ :sub:`IH`\ 2.145 3.6 V
Input Voltage Low\ :sup:`(0)`\ V\ :sub:`IL`\ 0 1.155 V
Total GPIO Current\ :sup:`(0)`\ I\ :sub:`IOVDD`\ 50 mA
Absolute max. motor output current\ :sup:`(1)`\ I\ :sub:`MOTOR`\ 2.8 A
Absolute max. auxiliary output current \ :sup:`(2)`\ I\ :sub:`AUX`\ 400 mA
===================================================== ============================= ========= ========= =====
(0): According to: `RP2040 Datasheet <https://datasheets.raspberrypi.com/rp2040/rp2040-datasheet.pdf>`_ (assuming V\ :sub:`DD`\ = 3.3V)
(1): According to: `BDR6133 Datasheet <https://datasheet.lcsc.com/lcsc/2101211904_Bardeen-Micro--BDR6133_C2687793.pdf>`_
(2): According to: `T2N7002BK Datasheet <https://datasheet.lcsc.com/lcsc/1810271831_TOSHIBA-T2N7002BK-LM_C146372.pdf>`_
Input Stage
-----------
.. image:: https://github.com/1nct/RP2040-Decoder/blob/main/docs/svg/Input_Stage.svg
:alt: Input Stage
D1 Rectifies the DCC square-wave into +V, the amplitude is not critical as long as it's within the 25V limit. The rectified voltage +V is then provided to the 3.3V voltage regulator (U1) and to the motor driver (U2).
The MOSFET on the right effectively translates the rather high DCC voltage to a suitable level for the microcontroller to process. When Q1 is turned off GPIO21 is pulled high by the RP2040 internal pull-up resistor, as soon as Q1 gets turned on (V<sub>GS</sub> > V<sub>GS,th</sub>), GPIO21 gets pulled to GND potential. R1 and R2 ensure that V<sub>GS</sub> doesn't exceed ±20V.
Motor Driver
------------
.. image:: https://github.com/1nct/RP2040-Decoder/blob/main/docs/svg/Motor_Driver.svg
:alt: Motor Driver
The Motor Driver is a complete H-Bridge IC specifically made for DC-Motors.
In order to control the motor, it is necessary to measure the back-EMF. This is done by the ADC, which measures at Points ADC_EMF_A and ADC_EMF_B respectively. The two resistors are used as a voltage divider.
Auxiliary Output
----------------
.. image:: https://github.com/1nct/RP2040-Decoder/blob/main/docs/svg/Aux_Outputs.svg
:alt: Auxiliary Output
Switching of loads up to a maximum of about ~400mA can be done using four N-Channel MOSFETs. They are switching on the low-side, which means the load effectively gets connected to GND potential as the transistor starts to conduct. GPIO24 - GPIO27 are used.
GPIO
-----
To switch lighter loads, six soldering pads on the back side of the PCB are connected to GPIO0 - GPIO5 pins. Although not implemented yet, they could theoretically be used as inputs as well (e.g., Reed switch).
Microcontroller
---------------
.. image:: https://github.com/1nct/RP2040-Decoder/blob/main/docs/svg/Microcontroller.svg
:alt: Microcontroller
The Microcontroller needs a crystal oscillator to function properly. External flash memory is also needed as it holds the configuration variables and the program itself. R3 & C14 are used to filter ADC_AVDD (ADC Reference Voltage).
Complete Schematic
------------------
.. image:: https://github.com/1nct/RP2040-Decoder/blob/main/docs/svg/RP2040-Decoder.svg
:alt: Complete Schematic
BOM & Alternative Parts
------------------------
.. table:: BOM
:widths: auto
===================================================== ============================= ==================================== ============================= ===================== =========================
Ref Quantity Value Component Type Component Name Footprint
===================================================== ============================= ==================================== ============================= ===================== =========================
C1, C2, C5, C6, C14 5 10u Ceramic Capacitor / 0603_1608Metric
C3, C4, C7, C8, C9, C10, C11, C12, C13, C15 10 100n Ceramic Capacitor / 0603_1608Metric
C16, C17 2 33p Ceramic Capacitor / 0603_1608Metric
D1 1 V\ :sub:`RMS`\=40V, I\ :sub:`F`\=2A Bridge Rectifier KMB24F MBS (TO-269AA)
Q1, Q2, Q3, Q4, Q5 5 V\ :sub:`DS`\=60V, I\ :sub:`D`\=0.4A N-Channel MOSFET T2N7002BK SOT-23
R1, R2, R5, R6 4 6k8 Resistor / 0603_1608Metric
R3 1 200 Resistor / 0603_1608Metric
R7, R8, R9 3 1k Resistor / 0603_1608Metric
U1 1 V\ :sub:`OUT`\=3.3V Low Dropout Voltage Regulator HT7533S SOT-23
U2 1 I=2.8A H-Bridge Driver BDR6133 SOIC-8
U3 1 64Mb Flash Memory W25Q64JVSSIQ SOIC-8
U4 1 / Microcontroller RP2040 QFN-56-1EP_7x7mm_P0.4mm
Y1 1 f=12MHz Crystal Oscillator X322512MSB4SI Crystal_SMD_3225-4Pin_3.2x2.5mm
===================================================== ============================= ==================================== ============================= ===================== =========================
NOTE: Keep capacitor V\ :sub:`max`\ in mind!
Alternatives for BDR6133:
--------------------------
* `PT5126A-S-TP <https://lcsc.com/product-detail/Motor-Driver-ICs_PTC-Princeton-Tech-PT5126A-S-TP_C162093.html>`_
* `PT2476 <https://lcsc.com/product-detail/Motor-Driver-ICs_PTC-Princeton-Tech-PT2476_C481903.html>`_
Alternative for HT7533S:
------------------------
* `GS7533-33TR3 <https://www.lcsc.com/product-detail/Linear-Voltage-Regulators-LDO_Gainsil-GS7533-33TR3_C7427372.html>`_
@@ -0,0 +1,108 @@
# Hardware Description
## Overview
![Block Diagram](https://github.com/1nct/RP2040-Decoder/blob/main/docs/svg/Block_Diagram.svg)
The above block diagram gives a general overview regarding the operation of components. For better illustration it has been divided into four functional blocks. Furthermore these functional blocks can be subdivided and will be explained below.
* Input Stage
- DCC Signal Level Shift
- Bridge Rectifier & Voltage Regulator
* Motor Driver
- Motor Driver
- Back EMF measurement (ADC)
* General Purpose
- GPIO
- Auxillary output
* Microcontroller
- Flash memory
- Crystal oscillator
## Characteristics
| Parameter | Symbol | Minimum | Maximum | Unit |
| ----------------------------------------------------- | -------------- | ------- | -------- | ---- |
| Absolute max. DCC Input Voltage | V<sub>DCC</sub> | -25 | +25 | V |
| Absolute max. GPIO Voltage<sup>(0)</sup> | V<sub>PIN</sub> | -0.5 | 3.3+0.5 | V |
| Input Voltage High<sup>(0)</sup> | V<sub>IH</sub> | 2.145 | 3.6 | V |
| Input Voltage Low<sup>(0)</sup> | V<sub>IL</sub> | 0 | 1.155 | V |
| Total GPIO Current<sup>(0)</sup> | I<sub>IOVDD_MAX</sub>| | 50 | mA |
| Absolute max. motor output current<sup>(1)</sup> | I<sub>MOTOR</sub> | | 2.8 | A |
| Absolute max. auxillary output current<sup>(2)</sup> | I<sub>AUX</sub> | | 400 | mA |
(0): According to: [RP2040 Datasheet](https://datasheets.raspberrypi.com/rp2040/rp2040-datasheet.pdf) (assuming V<sub>DD</sub> = 3.3V)
(1): According to: [BDR6133 Datasheet](https://datasheet.lcsc.com/lcsc/2101211904_Bardeen-Micro--BDR6133_C2687793.pdf)
(2): According to: [T2N7002BK Datasheet](https://datasheet.lcsc.com/lcsc/1810271831_TOSHIBA-T2N7002BK-LM_C146372.pdf)
## Input Stage
![Input Stage](https://github.com/1nct/RP2040-Decoder/blob/main/docs/svg/Input_Stage.svg)
D1 Rectifies the DCC square-wave into +V, the amplitude is not critical as long as its within the 25V limit. The rectified voltage +V is then provided to the 3.3V voltage regulator (U1) and to the motor driver (U2).
The MOSFET on the right effectively translates the rather high DCC voltage to a suitable level for the microcontroller to process. When Q1 is turned off GPIO21 is pulled high by the RP2040 internal pull-up resistor, as soon as Q1 gets turned on (V<sub>GS</sub> > V<sub>GS,th</sub>), GPIO21 gets pulled to GND potential. R1 and R2 ensure that V<sub>GS</sub> doesnt exceed ±20V.
## Motor Driver
![Motor Driver](https://github.com/1nct/RP2040-Decoder/blob/main/docs/svg/Motor_Driver.svg)
The Motor Driver is a complete H-Bridge IC specifically made for DC-Motors.
In order to control the motor, it is necessary to measure the back-EMF. This is done by the ADC which measures at Points ADC_EMF_A and ADC_EMF_B respectively. The two resistors are used as a voltage divider.
## Auxillary Output
![Auxillary Output](https://github.com/1nct/RP2040-Decoder/blob/main/docs/svg/Aux_Outputs.svg)
Switching of loads up to a maximum of about ~400mA can be done using four N-Channel MOSFETS. They are switching on the low-side which means the load effectively gets connected to GND potential as the transistor starts to conduct. GPIO24 - GPIO27 are used.
## GPIO
To switch lighter loads six soldering pads on the back side of the PCB are connected to GPIO0 - GPIO5 pins . Although not implemented yet they could theoretically be used as inputs as well (e.g. Reed switch).
## Microcontroller
![Microcontroller](https://github.com/1nct/RP2040-Decoder/blob/main/docs/svg/Microcontroller.svg)
The Microcontroller needs a crystal oscillator to function properly. External flash memory is also needed as it holds the configuration variables and the program itself. R3 & C14 are used to filter ADC_AVDD (ADC Reference Voltage).
## Complete Schematic
![Complete schematic](https://github.com/1nct/RP2040-Decoder/blob/main/docs/svg/RP2040-Decoder.svg)
BOM & Alternative Parts
--------------------------
| Ref | Quantity | Value | Component Type | Component Name | Footprint |
| ----------------------------------------------------- | -------------- | ------- | -------- | ---- |---- |
| C1, C2, C5, C6, C14 | 5 | 10u | Ceramic Capacitor | / | 0603_1608Metric |
| C3, C4, C7, C8, C9, C10, C11, C12, C13, C15 | 10 | 100n | Ceramic Capacitor | / | 0603_1608Metric |
| C16, C17 | 2 | 33p | Ceramic Capacitor | / | 0603_1608Metric |
| D1 | 1 | V<sub>RMS</sub> = 40V , I<sub>F</sub> = 2A | Bridge Rectifier | KMB24F | MBS (TO-269AA) |
| Q1, Q2, Q3, Q4, Q5 | 5 | V<sub>DS</sub> = 60V , I<sub>D</sub> = 0.4A | N-Channel MOSFET |T2N7002BK | SOT-23 |
| R1, R2, R5, R6 | 4 | 6k8 | Resistor | / | 0603_1608Metric |
| R3 | 1 | 200 | Resistor | / | 0603_1608Metric |
| R7, R8, R9 | 3 | 1k | Resistor | / | 0603_1608Metric |
| U1 | 1 | V<sub>OUT</sub> = 3.3V | Low Dropout Voltage Regulator | HT7533S | SOT-23 |
| U2 | 1 | I = 2.8A | H-Bridge driver | BDR6133 | SOIC-8 |
| U3 | 1 | 64Mb | Serial Flash Memory | W25Q64JVSSIQ | SOIC-8 |
| U4 | 1 | / | Raspberry Pi RP2040 Microcontroller | RP2040 | QFN-56-1EP_7x7mm_P0.4mm |
| Y1 | 1 | f = 12MHz | Crystal Oscillator | X322512MSB4SI | Crystal_SMD_3225-4Pin_3.2x2.5mm |
NOTE: Keep capacitor V<sub>max</sub> in mind!
Alternatives for BDR6133:
[PT5126A-S-TP](https://lcsc.com/product-detail/Motor-Driver-ICs_PTC-Princeton-Tech-PT5126A-S-TP_C162093.html)
[PT2476](https://lcsc.com/product-detail/Motor-Driver-ICs_PTC-Princeton-Tech-PT2476_C481903.html)
Alternative for HT7533S:
[GS7533-33TR3](https://www.lcsc.com/product-detail/Linear-Voltage-Regulators-LDO_Gainsil-GS7533-33TR3_C7427372.html)
+6 -8
View File
@@ -3,17 +3,15 @@
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
RP2040-Decoder documentation
RP2040-Decoder Documentation
============================
Add your content using ``reStructuredText`` syntax. See the
`reStructuredText <https://www.sphinx-doc.org/en/master/usage/restructuredtext/index.html>`_
documentation for details.
.. toctree::
:maxdepth: 2
:caption: Contents:
getting_started/getting_started
software/header_files
other/getting_started
hardware/hw
software/sw
other/CV_list
other/troubleshooting
+202
View File
@@ -0,0 +1,202 @@
# Configuration Variables (CV)
## Note
CV.h contains default values for every CV. When your board is still "factory new" these values are automatically written into flash. CV_65 == 255 indicates a factory condition and resets all CVs to default. Alternatively to reset all CVs to default a value of 8 can be written to CV8. Also note that index 0 in the CV array corresponds with CV_1, index 1 corresponds with CV_2 and so forth. This list only contains CVs that are in use.
## Speed step configuration
![Speed Table](https://github.com/gab-k/RP2040-Decoder/blob/main/docs/svg/speed_table.svg)
* V_min = CV_2
* V_mid = CV_6 * 16
* V_max = CV_5 * 16
The illustration above shows how the speed steps can be configured using the corresponding CVs. The red * represents V_min which is always at speed step 1, the green * shows V_mid at speed step 64 and the blue * shows V_max at speed step 126.
## CV List
### CV_1 - Basic address
Short DCC address
### CV_2 - V_min
Min motor voltage/speed
### CV_3 - Acceleration rate
CV_3*CV_175 = Time for one discrete speed step change in ms
### CV_4 - Deceleration rate
CV_4*CV_175 = Time for one discrete speed step change in ms
### CV_5 - V_max
Max motor voltage/speed - V_max = CV_5 * 16
### CV_6 - V_mid
Mid motor voltage/speed - V_max = CV_6 * 16
### CV_7 - Version No. (Read-Only)
Rev 0.3 = 1
Writing a value of 7 triggers am ADC offset adjustment.
### CV_8 - Manufacturer (Read-Only)
Default = "13" = Public Domain & Do-It-Yourself Decoders
Writing a value of 8 resets all CV values to the default values in CV.h.
This will also happen if CV_65 == "255" == "0xFF".
### CV_9 - Motor PWM Frequency
f in Hz = CV_9 * 100 + 10000
### CV_11 - Packet timeout
If no package is received for x seconds (x = CV_11) the decoder will automatically stop the motor (Emergency Stop).
### CV_12 - Permitted operating modes
Currently DCC Digital mode is the only supported mode.
### CV_17 & CV_18 - 14-Bit extended/long address
Address is only used if bit5 has a value of "1" in CV_29.
![Long Address](https://github.com/gab-k/RP2040-Decoder/blob/main/docs/svg/Long_address.svg)
Bit15 and bit14 which correspond to bit7 and bit6 of CV_17 are always "1". CV_17 = "192" & CV_18 = "0" is also not a valid address. Otherwise the valid value range of CV_17 ranges from "192" to "231" and "0" to "255" for CV_18 respectively.
### CV_29 - Decoder Configuration
Bit0 is used to reverse direction i.e. "0" = normal, "1" = reverse.
Bit5 switches between basic and extended addressing modes i.e. "0" = basic address, "1" = extended address.
The other 6 bits are currently not in use and therefore irrelevant.
### CV_31 & CV_32 - Extended CV pointer (Read-Only)
Not in use.
### CV_47 - Feed-forward gain k_ff
k_ff defines the correction behavior with regard to the y2 variable. High values for k_ff lead to a faster change in the variable. Values for k_ff that are too high can lead to oscillations.
k_ff = CV_47/10000
### CV_48 - Filter time constant (tau) in ms
The time constant tau characterizes the low-pass filter which is connected downstream in the D component of the PID controller
### CV_49 - PID Control sampling time t in ms
Every t seconds the pid_control() function gets called to compute the new control output
### CV_50 - PID Control I Factor
Integral gain factor of the PID-Controller
### CV_51 - PID Control D Factor
Derivative gain factor of the PID-Controller
### CV_52 & CV_53 - PID Integral Limits
Maximum and minimum integral part values
### CV_54 & CV_55 - Gain scheduling config k_p @ x0
CV_54 - High Byte -- CV_55 - Low Byte
### CV_56 & CV_57 - Gain scheduling config k_p @ x1
CV_56 - High Byte -- CV_57 - Low Byte
### CV_58 & CV_59 - Gain scheduling config k_p @ x2
CV_58 - High Byte -- CV_59 - Low Byte
### CV_60 - Gain scheduling config x1 shift percentage
Determines position of x1 in percent -> x1 shift in % ≙ CV_60/255
### CV_61 - Measurement Iterations
Total amount of BEMF-Voltage measurement iterations
### CV_62 - Measurement Delay
BEMF-Voltage measurement delay
### CV_63 & CV_64 - Measurement array cutoffs
CV_63 determines how many elements from the left side (beginning with index 0) of the array will be discarded while CV_64 determines how many elements from the right side (beginning from highest index) will be discarded.
### CV_65 - New flash variable
Each Byte of the factory new flash chip should have a inital state of "0xFF". This will be checked for in the beginning of core0.c (see cv_setup_check()). When CV_65 == "255" == "0xFF" the default config (CV.h) will be written to flash. Alternatively a reset to default can be done by either writing "8" to CV_8 or writing "255" to CV_65 which then triggers a reset on startup.
### CV_112, CV_113, CV_114, CV_115 - GPIO PWM Configuration
PWM enabled "1" - PWM disabled "0"
### CV_116 to CV_171 - PWM Slice configuration
![GPIO Slices](https://github.com/gab-k/RP2040-Decoder/blob/main/docs/svg/GPIO_slices.svg)
Every slice controls two independent output channels, duty cycle from 0% to 100% inclusive and can be configured with several parameters:
* Wrap (16Bit): Sets the slice time period of x cycles - effectively determining the frequency
* Clock Divider: Additional clock divider
* Level Channel A / Level Channel B - (16Bit each): Determining how many of the x cycles the signal is at a high level - effectively determining the duty cycle
To see which CVs correspond to which slice and channel, it is advisable to use CV.h as a reference
The PWM-frequency is calculated as follows: f<sub>PWM</sub> = 125 MHz / [ (CV<sub>clk_div</sub> + 1) * (CV<sub>wrap</sub> + 1) ]
The duty-cycle can be calculated as follows: D = CV<sub>Level</sub> / CV<sub>wrap</sub> + 1
**Example configuration - (AUX2: PWM-Frequency f<sub>PWM</sub> = 10kHz; Duty-cycle D = 20%):**
AUX1 => GPIO25 => Slice 4 / Channel B => Wrap: CV_144 & CV_145; Clock-divider: CV_146; Level(B): CV_149 & CV_150
=> f<sub>PWM</sub> = 10kHz = 125 MHz / [ (0 + 1) * (12499 + 1) ];
=> CV_144 = 110000, CV_145 = 11010011, CV_146 = 0; --- (Note: "12499<sub>dec</sub>" = "11000011010011<sub>bin</sub>")
=> CV<sub>Level</sub> = CV_149 & CV_150 = D * (CV<sub>wrap</sub> + 1) = 0.2 * 12500 = 2500
=> CV_149 = 1001, CV_150 = 11000100; --- (Note: "2500<sub>dec</sub>" = "100111000100<sub>bin</sub>")
Another configuration which also achieves 10kHz and D = 20% would be CV<sub>clk_div</sub> = 10, CV<sub>wrap</sub> = 1249, CV<sub>Level</sub> = 250.
A more detailed explanation regarding PWM can be found in the [RP2040-Datasheet - Chapter 4.5](https://datasheets.raspberrypi.com/rp2040/rp2040-datasheet.pdf).
### CV_172 - ADC Offset
If CV_172 = "0xFF" = "255" there will be a measurement procedure on startup
### CV_173 - ADC offset measurement cycles
Determines how many ADC offset measurement iterations are done.
### CV_174 - Additional motor-PWM clock divider.
Additional Clock Divider - works the same as any GPIO clock divider
### CV_175 - speed_helper timer delay
This timer delay can be used to change the time between two speed steps. So basically an additional option to adjust the deceleration and acceleration rate.
### CV_176, CV_177, CV_178, CV_179 - Base PWM Level used in feed-forward control
CV_176 - High Byte forward -- CV_177 - Low Byte forward -- CV_178 - High Byte reverse -- CV_179 - Low Byte reverse
These values are equivalent to y1(forward) and y1(reverse) mentioned [here](https://github.com/gab-k/RP2040-Decoder/wiki/Software-description#feed-forward). Writing "0" to all four CVs schedules a new calibration on startup.
### CV_257 to CV_512 - Function Mapping CVs
The switching status of the outputs depends both on the function instruction received and on the current direction of travel. That means you can, for example, use a function to switch two or more outputs or, as is usual with headlights, switch them depending on the direction of travel. For configuration, 32 bits (corresponding to the GPIOs) are available for each function in each direction of travel.
@@ -0,0 +1,14 @@
# Troubleshooting
To narrow down the issue when your decoder is not working as expected, you can do the following:
Check the power supply of the decoder:
* +3V3 to GND should be 3.3V
* +V to GND should be somewhere in the range of around +10V to +20V
* If you dont measure the correct voltages, try to [measure Track Voltage](https://dccwiki.com/Measuring_Track_Voltage)
Check your motor:
* Desolder your motor and try the motor with a analog power supply 0...+-16V to check if the motor is working or not (desolder the wires because the decoder doesn't like voltage on these pins!)
Reset:
* Try to reset the decoder by writing a value of 8 to CV8 (beware, this will reset the complete CV memory!)
+9
View File
@@ -0,0 +1,9 @@
Software
=================
.. toctree::
:maxdepth: 2
:caption: Contents:
sw_description
header_files
@@ -0,0 +1,82 @@
# Software Description
## Overview
The Software is structured as follows:
* Core0.c
- DCC package detection & decoding
- Programming mode (Modify and read CVs on programming track)
- ADC-Offset measurement
- Feed-forward base PWM measurement
* Core1.c
- PID motor controller
* CV.h
- Default configuration variables
Conveniently The Raspberry Pi Foundation provides a well documented [SDK](https://datasheets.raspberrypi.com/pico/raspberry-pi-pico-c-sdk.pdf) for the RP2040. The SDK provides abstraction to a higher level and therefore there is no need to access any registers directly. Everything is written using the SDK so hopefully the code is easier to understand. In the following, the motor control and the decoding of the DCC signals will be explained.
## Motor control overview
![Block Diagram](https://github.com/1nct/RP2040-Decoder/blob/main/docs/svg/Block_Diagram_Control.svg)
***
**Block diagram - Motor control**
The above block diagram in essence describes the functionality of the control loop. While the central component is the PID controller, there is an additional block called [Feed-forward](https://en.wikipedia.org/wiki/Feed_forward_(control)) that has an impact on the control output variable. The Feed-forward block adds an additional offset to the output depending on the setpoint, this is done to achieve better control. A more detailed explanation regarding Feed-forward can be found below. The speed helper block is corresponding to the speed_helper() function which delays changing the setpoint according to the configured deceleration/acceleration rates.
## PID Controller
![PID Controller](https://github.com/gab-k/RP2040-Decoder/blob/main/docs/svg/Block_Diagram_PID.svg)
The block diagram above shows the PID controller in the s-domain. The derivative part contains an additional digital low pass filter used to filter out high-frequency noise.
Output = E * (K<sub>P</sub> + K<sub>I</sub>/s + (K<sub>D</sub>*s)/(sτ+1)) = P + I + D
* P = E * K<sub>P</sub>
* I = E * K<sub>I</sub>/s
* D = E * (K<sub>D</sub>*s)/(sτ+1)
The continuous-time system representation can now be transformed into a discrete-time representation using [bilinear transform](https://en.wikipedia.org/wiki/Bilinear_transform) [ s = 2*(z-1) / T<sub>s</sub>*(z+1) ].
This results in the following difference equations which are then implemented in software:
* p<sub>n</sub> = K<sub>P</sub> * e<sub>n</sub>
* i<sub>n</sub> = 0.5K<sub>I</sub> * (e<sub>n</sub> + e<sub>n-1</sub>) + i<sub>n-1</sub>
* d<sub>n</sub> = [ 2K<sub>D</sub> * (e<sub>n</sub> - e<sub>n-1</sub>) + (2τ - T<sub>s</sub>) * d<sub>n-1</sub> ] / [ 2τ + T<sub>s</sub>]
=> output<sub>n</sub> = p<sub>n</sub> + i<sub>n</sub> + d<sub>n</sub>
Also note that instead of using derivative of error, derivative on measurement is used. This is done to prevent a high derivative part in the event of a large change in setpoint.
### Gain scheduling
![K_P](https://github.com/gab-k/RP2040-Decoder/blob/main/docs/svg/adaptive_kp.svg)
Another aspect to consider is the implementation of [gain scheduling](https://en.wikipedia.org/wiki/Gain_scheduling). K<sub>P</sub> is a function of the current setpoint. Often it is favorable to have a higher proportional gain K<sub>P</sub> for slow speeds, achieving better control results. The illustration above shows the default setting for K<sub>P</sub>. CV_54 & CV_55 are used to set K<sub>P</sub> @ x<sub>0</sub>, CV_56 & CV_57 for K<sub>P</sub> @ x<sub>1</sub> and CV_58 & CV_59 for K<sub>P</sub> @ x<sub>2</sub>. Additionally CV_60 is used to shift x<sub>1</sub> from the leftmost point (0% = 0/255) to the rightmost point (100% = 255/255).
### Feed-forward
![Feed-forward](https://github.com/gab-k/RP2040-Decoder/blob/main/docs/svg/feed_forward.svg)
To achieve better control [Feed-forward](https://en.wikipedia.org/wiki/Feed_forward_(control)) is used. On startup the decoder will check for a configuration regarding Feed-forward control - when no configuration is found the decoder automatically runs a calibration to establish a base pwm level (y<sub>1</sub>) for both directions. The base pwm level (y<sub>1</sub>) will vary depending on load, motor and voltage on the tracks and can be configured with CV_176 - CV_179. If the setpoint is greater than the threshold, y<sub>2</sub> is corrected automatically when i<sub>n</sub> reaches 0.5i<sub>min</sub> or 0.5i<sub>max</sub>. CV_47 can be used to set how sensitive this correction is.
### Back-EMF voltage measurement
To provide a feedback signal which is proportional to the motor speed the ADC is used to measure the [Back-EMF voltage](https://en.wikipedia.org/wiki/Counter-electromotive_force). The measurement works by setting the PWM duty cycle to 0%, waiting for a certain delay time (CV_62) and then measuring x times (x = CV_63). While measuring the array with measurement values are being sorted using insertion sort. Afterwards y elements (y = CV_63) from the left (lowest values) and z elements (z = CV_64) from the right (highest values) will be dismissed to mitigate the impact of potential outliers in measurement. The average value of the remaining values will be computed and fed back into the control algorithm. Considering default settings (100us delay, 100 samples, ~2µs sampling time) the complete measurement run including averaging takes about 0.3ms to 0.35ms which effectively reduces the maximum possible duty cycle to about 93% to 94%.
## DCC signal decoding
The detection of the DCC signal works by looking at every rising and falling edge and calculating the time between them. When the time between rising and falling edge is greater than 87μs then this is equivalent to "0", else "1" - This value then gets shifted into a 64-Bit variable.
Decoding is done after every falling edge. It starts with an error detection which when not passed will dismiss the received command. Then the address will be decoded and compared to the address stored in the configuration. If the address matches the command/instruction will be decoded.
Only a few instructions are currently implemented, only 128 speed step instructions are supported.
**Implemented instructions:**
* 0011-1111 - (128 Speed Step Control) - 2 Byte length
* 10XX-XXXX - (Function Group Instruction) (F0 - F12)
* 110X-XXXX - Expansion Instruction (F13 - F31)
All DCC instructions can be found in Section 9.2, 9.2.1 and 9.2.1.1 of the [NMRA Communications Standard ](https://www.nmra.org/index-nmra-standards-and-recommended-practices)