Merge branch 'main' into dev

This commit is contained in:
gab-k committed 2024-01-03 12:05:45 +01:00
commit 577bc5dd5c
11 files changed
+3540 -495

No files matched your search

@@ -0,0 +1,38 @@
# This starter workflow is for a CMake project running on a single platform. There is a different starter workflow if you need cross-platform coverage.
# See: https://github.com/actions/starter-workflows/blob/main/ci/cmake-multi-platform.yml
name: CMake on a single platform
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
env:
# Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.)
BUILD_TYPE: Debug
jobs:
build:
# The CMake configure and build commands are platform agnostic and should work equally well on Windows or Mac.
# You can convert this to a matrix build if you need cross-platform coverage.
# See: https://docs.github.com/en/free-pro-team@latest/actions/learn-github-actions/managing-complex-workflows#using-a-build-matrix
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: install build packages
run: sudo apt-get update && sudo apt-get install cmake gcc-arm-none-eabi libnewlib-arm-none-eabi libstdc++-arm-none-eabi-newlib
- name: get sdk
run: cd /tmp && git clone https://github.com/raspberrypi/pico-sdk.git && echo "PICO_SDK_PATH=/tmp/pico-sdk" >> $GITHUB_ENV
- name: Configure CMake
# Configure CMake in a 'build' subdirectory. `CMAKE_BUILD_TYPE` is only required if you are using a single-configuration generator such as make.
# See https://cmake.org/cmake/help/latest/variable/CMAKE_BUILD_TYPE.html?highlight=cmake_build_type
run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}}
- name: Build
# Build your program with the given configuration
run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}}
+41
View File
@@ -0,0 +1,41 @@
# This is a basic workflow to help you get started with Actions
name: Doxygen Action
# Controls when the action will run. Triggers the workflow on push or pull request
# events but only for the master branch
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
# This workflow contains a single job called "build"
build:
# The type of runner that the job will run on
runs-on: ubuntu-latest
# Steps represent a sequence of tasks that will be executed as part of the job
steps:
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- uses: actions/checkout@v2
- name: Doxygen Action
uses: mattnotmitt/doxygen-action@v1.1.0
with:
# Path to Doxyfile
doxyfile-path: "./Doxyfile" # default is ./Doxyfile
# Working directory
working-directory: "." # default is .
- name: Deploy
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
# Default Doxyfile build documentation to html directory.
# Change the directory if changes in Doxyfile
publish_dir: ./html
+4
View File
@@ -2,6 +2,10 @@
.vscode
.idea
# Doxygen generated files
html
latex
# Build folders
build
cmake-build-debug
+9 -8
View File
@@ -1,7 +1,7 @@
#pragma once
#define CV_ARRAY_SIZE 512
// All CVs are 8-bit numbers ranging from (0 - 255)dec ≙ (0b00000000 - 0b11111111)bin ≙ (0x00 - 0xFF)hex
// Note : CV_1 ≙ index 0, CV_2 ≙ index 1, CV_3 ≙ index 2, ...
// All CVs are 8-bit numbers ranging from (0 - 255)dec = (0b00000000 - 0b11111111)bin = (0x00 - 0xFF)hex
// Note : CV_1 = index 0, CV_2 = index 1, CV_3 = index 2, ...
uint8_t CV_ARRAY_DEFAULT [CV_ARRAY_SIZE] = {
0b00000011, //CV_1 - Basic address - CV_1 = 0 and CV_1 > 127 are not valid - Default = 3
@@ -14,6 +14,7 @@ uint8_t CV_ARRAY_DEFAULT [CV_ARRAY_SIZE] = {
0b01100100, //CV_5 - V_max - Default = 100*16
0b00111111, //CV_6 - V_mid - Default = 63*16
0b00000001, //CV_7 - Version no. (read-only)
// Writing a value of 8 to CV_8 resets all CV values to the default values in CV.h
0b00001101, //CV_8 - Manufacturer (13 = Public Domain & Do-It-Yourself Decoders) (read-only)
0b10010110, //CV_9 - PWM frequency in Hz = CV_9*100+10000 - Default = (150*100+10000)Hz = 25kHz
0b00000001, //CV_10 -
@@ -59,20 +60,20 @@ uint8_t CV_ARRAY_DEFAULT [CV_ARRAY_SIZE] = {
0b00000000, //CV_45 -
0b00000000, //CV_46 -
// Speed controller - Configuration ////////////////////////////////////////////////////////////////////////////////
0b00110010, //CV_47 - Feed-forward gain k_ff ≙ CV_47/10000 Default = 50 -> 0.005 //
0b00110010, //CV_47 - Feed-forward gain k_ff = CV_47/10000 Default = 50 -> 0.005 //
0b00001010, //CV_48 - PID Control low pass filter time constant (tau) in ms //
0b00000101, //CV_49 - PID Control sampling time t in ms //
0b00011001, //CV_50 - PID Control I_Factor ≙ CV_50/10 Default = 25 -> 2.5 //
0b00110010, //CV_51 - PID Control D_Factor ≙ CV_51/10000 Default = 50 -> 0.005 //
0b01100100, //CV_52 - PID Integral Limit positive ≙ CV_52*10 Default = 100 -> +1000 //
0b01100100, //CV_53 - PID Integral Limit negative ≙ CV_53*(-10) Default = 100 -> -1000 //
0b00011001, //CV_50 - PID Control I_Factor = CV_50/10 Default = 25 -> 2.5 //
0b00110010, //CV_51 - PID Control D_Factor = CV_51/10000 Default = 50 -> 0.005 //
0b01100100, //CV_52 - PID Integral Limit positive = CV_52*10 Default = 100 -> +1000 //
0b01100100, //CV_53 - PID Integral Limit negative = CV_53*(-10) Default = 100 -> -1000 //
0b00000111, //CV_54 - k_p @ x0 - High Byte (Bits 8-15) divided by 100 //
0b11010000, //CV_55 - k_p @ x0 - Low Byte (Bits 0-7) Default = 2000 -> 20 //
0b00000000, //CV_56 - k_p @ x1 - High Byte (Bits 8-15) divided by 100 //
0b11111010, //CV_57 - k_p @ x1 - Low Byte (Bits 0-7) Default = 250 -> 2.5 //
0b00000000, //CV_58 - k_p @ x2 - High Byte (Bits 8-15) divided by 100 //
0b10010110, //CV_59 - k_p @ x2 - Low Byte (Bits 0-7) Default = 150 -> 1.5 //
0b00001101, //CV_60 - x_1 shift in % ≙ CV_60/255 //
0b00001101, //CV_60 - x_1 shift in % = CV_60/255 //
// V_EMF Measurement Configuration //////////////////////////////////////////////////////////////////////////////////
0b01100100, //CV_61 - V_EMF Total amount of Measurement Iterations - Default = 100 iterations //
0b01100100, //CV_62 - V_EMF Delay before Measuring - Default = 100us //
+2894
View File
File diff suppressed because it is too large. Load diff
+273 -287
View File
@@ -5,46 +5,47 @@
//////////////////////////
#include "core0.h"
// XIP_BASE + FLASH_TARGET_OFFSET = "0x101FF000" <- This address need to be smaller than __flash_binary_end stored in RP2040-Decoder.elf.map
const uint8_t *CV_ARRAY_FLASH = (const uint8_t *) (XIP_BASE + FLASH_TARGET_OFFSET);
uint64_t input_bit_buffer = 0;
uint16_t level_table[32] = {0};
absolute_time_t falling_edge_time,rising_edge_time;
absolute_time_t falling_edge_time, rising_edge_time;
// Function returns average of values deviating less than twice the standard deviation from original average
float two_std_dev(const float arr[], uint32_t length){
float two_std_dev(const float arr[], const uint32_t length) {
// Calculate arithmetic average
float sum = 0;
for (uint32_t i = 0; i < length; ++i) {
sum += arr[i];
}
float x_avg = sum / (float)length;
const float x_avg = sum / (float)length;
// Calculate sample variance and sampled standard deviation
sum = 0;
for (uint32_t i = 0; i < length; ++i) {
sum += (arr[i]-x_avg)*(arr[i]-x_avg);
sum += (arr[i] - x_avg) * (arr[i] - x_avg);
}
float variance = sum / (float)(length-1);
float std_dev = sqrtf(variance);
const float variance = sum / (float)(length-1);
const float std_dev = sqrtf(variance);
// Sum every element that is within two times the sampled standard deviation and compute new average
sum = 0;
uint32_t counter = 0;
for (uint32_t i = 0; i < length; ++i) {
float diff = fabsf(arr[i]-x_avg);
if ( diff < std_dev*2.0f ){
const float diff = fabsf(arr[i] - x_avg);
if ( diff < std_dev * 2.0f ){
sum += arr[i];
counter++;
}
}
return sum / (float)counter;
return sum / (float) counter;
}
// Measures constant adc offset and programs the offset into flash
void adc_offset_adjustment(uint32_t n){
void adc_offset_adjustment(const uint32_t n) {
LOG(1, "adc_offset_adjustment");
float offsets_fwd[n];
@@ -57,8 +58,8 @@ void adc_offset_adjustment(uint32_t n){
// Measure n times in "reverse direction" (GPIO 28)
adc_select_input(2);
adc_run(true);
for (uint32_t i = 0; i < n; i++) {
offsets_rev[i] = (float)adc_fifo_get_blocking();
for (uint32_t i = 0; i < n; i++) {
offsets_rev[i] = (float) adc_fifo_get_blocking();
}
adc_run(false);
adc_fifo_drain();
@@ -67,17 +68,17 @@ void adc_offset_adjustment(uint32_t n){
// Measure n times in "forward direction" (GPIO 29)
adc_select_input(3);
adc_run(true);
for (uint32_t i = 0; i < n; i++) {
offsets_fwd[i] = (float)adc_fifo_get_blocking();
for (uint32_t i = 0; i < n; i++) {
offsets_fwd[i] = (float) adc_fifo_get_blocking();
}
adc_run(false);
adc_fifo_drain();
// Find overall average discarding outliers in measurement
float offset_avg_fwd = two_std_dev(offsets_fwd, n);
float offset_avg_rev = two_std_dev(offsets_rev, n);
float overall_avg = (offset_avg_fwd+offset_avg_rev)/2;
uint8_t offset = (uint8_t)roundf(overall_avg);
const float offset_avg_fwd = two_std_dev(offsets_fwd, n);
const float offset_avg_rev = two_std_dev(offsets_rev, n);
const float overall_avg = (offset_avg_fwd + offset_avg_rev) / 2;
const uint8_t offset = (uint8_t) roundf(overall_avg);
LOG(1, "new adc offset CV[171] (%f): (uint8_t)%d\n", overall_avg, offset);
@@ -93,7 +94,7 @@ void adc_offset_adjustment(uint32_t n){
// Confirmation after writing or verifying a CV
// Works by creating a spike in current consumption, this is detected by the command station
void acknowledge() {
uint16_t max_lvl = _125M/(CV_ARRAY_FLASH[8]*100+10000);
const uint16_t max_lvl = _125M / (CV_ARRAY_FLASH[8] * 100 + 10000);
pwm_set_gpio_level(MOTOR_FWD_PIN, max_lvl);
busy_wait_ms(3);
pwm_set_gpio_level(MOTOR_FWD_PIN, 0);
@@ -104,9 +105,9 @@ void acknowledge() {
// When bit matches sent byte -> acknowledge()
void verify_cv_bit(uint16_t cv_address,bool bit_val, uint8_t bit_pos) {
uint8_t mask = 0b00000001;
bool res = ( (CV_ARRAY_FLASH[cv_address] >> bit_pos) &mask ) == bit_val;
void verify_cv_bit(const uint16_t cv_address, const bool bit_val, const uint8_t bit_pos) {
const uint8_t mask = 0b00000001;
const bool res = ((CV_ARRAY_FLASH[cv_address] >> bit_pos) & mask) == bit_val;
if (res) {
acknowledge();
}
@@ -114,13 +115,13 @@ void verify_cv_bit(uint16_t cv_address,bool bit_val, uint8_t bit_pos) {
// When byte matches sent byte -> acknowledge()
void verify_cv_byte(uint16_t cv_address, uint8_t cv_data){
void verify_cv_byte(const uint16_t cv_address, const uint8_t cv_data) {
if (CV_ARRAY_FLASH[cv_address] == cv_data) acknowledge();
}
// CV writing function first erases necessary amount of blocks in flash and then rewrites to flash
void regular_cv_write(uint16_t cv_index, uint8_t cv_data){
void regular_cv_write(const uint16_t cv_index, const uint8_t cv_data) {
uint8_t CV_ARRAY_TEMP[CV_ARRAY_SIZE];
memcpy(CV_ARRAY_TEMP, CV_ARRAY_FLASH, sizeof(CV_ARRAY_TEMP));
CV_ARRAY_TEMP[cv_index] = cv_data;
@@ -131,14 +132,16 @@ void regular_cv_write(uint16_t cv_index, uint8_t cv_data){
// There are some exceptions to writing CVs - e.g. writing to a read only CV is not valid - this gets handled here
void write_cv_handler(uint16_t cv_index, uint8_t cv_data){
void write_cv_handler(const uint16_t cv_index, const uint8_t cv_data) {
switch (cv_index) {
case 0: //CV_1
// CV_1 => Value = 0 is not allowed
if (cv_data == 0 || cv_data > 127)
if (cv_data == 0 || cv_data > 127) {
break;
else
regular_cv_write(cv_index,cv_data);
}
else {
regular_cv_write(cv_index, cv_data);
}
break;
case 6: //CV_7
// Read only (CV_7 - Version no.)
@@ -151,7 +154,7 @@ void write_cv_handler(uint16_t cv_index, uint8_t cv_data){
case 7: //CV_8
// Read only (CV_8 - Manufacturer ID)
// Reset all CVs to Default (CV_8; Value = 8)
if (cv_data == 8){
if (cv_data == 8) {
LOG(1, "reset of flash triggered via cv8 => 8\n");
flash_range_erase(FLASH_TARGET_OFFSET, FLASH_SECTOR_SIZE);
flash_range_program(FLASH_TARGET_OFFSET, CV_ARRAY_DEFAULT, FLASH_PAGE_SIZE * 2);
@@ -159,93 +162,97 @@ void write_cv_handler(uint16_t cv_index, uint8_t cv_data){
break;
// CV_17 must have a value between 11000000->(192dec) and 11100111->(231dec) inclusive
// CV_17 == 192 && CV_18 == 0 -> Address = 0 is also not valid and therefore shall not be set
case 16: //CV_17
if ( (cv_data < 192 || cv_data > 231) || (CV_ARRAY_FLASH[17] == 0 && cv_data == 192) )
case 16: //CV_17
if ((cv_data < 192 || cv_data > 231) || (CV_ARRAY_FLASH[17] == 0 && cv_data == 192)) {
break;
else
regular_cv_write(cv_index,cv_data);
}
regular_cv_write(cv_index, cv_data);
break;
case 17: //CV_18
if(CV_ARRAY_FLASH[16] == 192 && cv_data == 0)
case 17: //CV_18
if(CV_ARRAY_FLASH[16] == 192 && cv_data == 0){
break;
else
regular_cv_write(cv_index,cv_data);
}
regular_cv_write(cv_index, cv_data);
break;
// CV_31 & CV_32 Index high byte isn't implemented and shall not be set
// CV_31 & CV_32 Index high byte isn't implemented and shall not be set
case 30: //CV_31
case 31: //CV_32
break;
// Regular CV write is carried out
// Regular CV write is carried out
default:
regular_cv_write(cv_index,cv_data);
regular_cv_write(cv_index, cv_data);
}
}
// CV Programming function resets core1 and evaluates the type of programming instruction (e.g. write byte)
void program_mode(uint8_t number_of_bytes, const uint8_t * const byte_array) {
void program_mode(const uint8_t number_of_bytes, const uint8_t *const byte_array) {
//First check for valid programming command ("address" 112-127)
if (byte_array[number_of_bytes - 1]<128 && byte_array[number_of_bytes - 1]>111) {
uint8_t instruction_type_mask = 0b00001100;
uint8_t instruction_type = instruction_type_mask & byte_array[number_of_bytes - 1];
uint8_t cv_address_ms_bits_mask = 0b00000011;
uint16_t cv_address_ms_bits = cv_address_ms_bits_mask & byte_array[number_of_bytes - 1];
uint16_t cv_address = byte_array[number_of_bytes - 2] + (cv_address_ms_bits << 8);
if (byte_array[number_of_bytes - 1] < 128 && byte_array[number_of_bytes - 1] > 111) {
const uint8_t instruction_type_mask = 0b00001100;
const uint8_t instruction_type = instruction_type_mask & byte_array[number_of_bytes - 1];
const uint8_t cv_address_ms_bits_mask = 0b00000011;
const uint16_t cv_address_ms_bits = cv_address_ms_bits_mask & byte_array[number_of_bytes - 1];
const uint16_t cv_address = byte_array[number_of_bytes - 2] + (cv_address_ms_bits << 8);
// Before accessing flash, timers and interrupts need to be disabled and core1 needs to be shut down.
if(pid_control_timer.pool)
alarm_pool_destroy(pid_control_timer.pool);
if(speed_helper_timer.pool)
alarm_pool_destroy(speed_helper_timer.pool);
// Before accessing flash, timers and interrupts need to be disabled and core1 needs to be shut down.
if (pid_control_timer.pool) {
alarm_pool_destroy(pid_control_timer.pool);
}
if (speed_helper_timer.pool) {
alarm_pool_destroy(speed_helper_timer.pool);
}
multicore_reset_core1();
uint32_t saved_interrupts = save_and_disable_interrupts();
multicore_reset_core1();
const uint32_t saved_interrupts = save_and_disable_interrupts();
if (instruction_type == 0b000001000) {
// Verify CV bit instruction
if (instruction_type == 0b000001000) {
uint8_t bit_pos_mask = 0b00000111;
uint8_t bit_pos = bit_pos_mask&byte_array[number_of_bytes - 3];
uint8_t bit_val_mask = 0b00000001;
uint8_t bit_val_uint = (byte_array[number_of_bytes - 3]>>3) & bit_val_mask;
bool bit_val = bit_val_uint;
verify_cv_bit(cv_address, bit_val, bit_pos);
}
const uint8_t bit_pos_mask = 0b00000111;
const uint8_t bit_pos = bit_pos_mask & byte_array[number_of_bytes - 3];
const uint8_t bit_val_mask = 0b00000001;
const uint8_t bit_val_uint = (byte_array[number_of_bytes - 3] >> 3) & bit_val_mask;
const bool bit_val = bit_val_uint;
verify_cv_bit(cv_address, bit_val, bit_pos);
}
else if (instruction_type == 0b000000100) {
// Verify CV byte instruction
else if (instruction_type == 0b000000100) {
uint8_t cv_data = byte_array[number_of_bytes - 3];
verify_cv_byte(cv_address, cv_data);
}
const uint8_t cv_data = byte_array[number_of_bytes - 3];
verify_cv_byte(cv_address, cv_data);
}
else if (instruction_type == 0b000001100) {
// Write CV byte instruction
else if (instruction_type == 0b000001100) {
uint8_t cv_data = byte_array[number_of_bytes - 3];
write_cv_handler(cv_address, cv_data);
}
const uint8_t cv_data = byte_array[number_of_bytes - 3];
write_cv_handler(cv_address, cv_data);
}
// Restore interrupts
restore_interrupts(saved_interrupts);
busy_wait_ms(5);
// Restore interrupts
restore_interrupts(saved_interrupts);
// TODO: verify core1 launch...
multicore_launch_core1(core1_entry);
// TODO: Check busy wait necessity
busy_wait_ms(5);
}
}
// Set outputs according to configuration (PWM on/off, PWM duty cycle/level, ...)
void set_outputs(uint32_t functions_to_set_bitmask) {
void set_outputs(const uint32_t functions_to_set_bitmask) {
// Get outputs with pwm enabled and preset outputs_to_set_PWM variable with resulting GPIO Bitmask
uint32_t PWM_enabled_outputs = get_32bit_CV(111);
const uint32_t PWM_enabled_outputs = get_32bit_CV(111);
uint32_t outputs_to_set_PWM = PWM_enabled_outputs;
// Get enabled output configuration corresponding to set functions and direction
uint32_t outputs_to_set = 0;
uint32_t temp_mask = 1;
for (uint8_t i = 0; i < 32; i++) {
if (temp_mask & functions_to_set_bitmask ){
bool dir = get_direction(0);
outputs_to_set |= get_32bit_CV(i * 8 + 260 - 4 * dir);
if (temp_mask & functions_to_set_bitmask) {
const bool direction = get_direction_of_speed_step(speed_step_target);
outputs_to_set |= get_32bit_CV(i * 8 + 260 - 4 * direction);
}
temp_mask<<=1;
temp_mask <<= 1;
}
outputs_to_set_PWM &= outputs_to_set; // Outputs with PWM to be enabled
outputs_to_set &= ~outputs_to_set_PWM; // Outputs without PWM to be enabled
@@ -256,43 +263,47 @@ void set_outputs(uint32_t functions_to_set_bitmask) {
// Set PWM enabled outputs to desired level
temp_mask = 1;
for (uint8_t i = 0; i < 32; ++i) {
if(temp_mask & outputs_to_set_PWM){
if (temp_mask & outputs_to_set_PWM) {
pwm_set_gpio_level(i, level_table[i]);
pwm_gpio_to_channel(i);
pwm_gpio_to_slice_num(i);
}
else if (temp_mask & PWM_enabled_outputs){
pwm_set_gpio_level(i,0);
else if (temp_mask & PWM_enabled_outputs) {
pwm_set_gpio_level(i, 0);
}
temp_mask<<=1;
temp_mask <<= 1;
}
}
// Update functions F0 - F31 when function command is received or in case of direction change
void update_active_functions(uint32_t new_function_bitmask, uint8_t clr_bit_ind, bool direction_change) {
void update_active_functions(uint32_t new_function_bitmask, const uint8_t clr_bit_ind, const bool direction_change) {
static uint32_t active_functions;
static uint32_t prev_active_func;
// Outputs depend on direction
// In case of a direction change every output needs to be set according to configuration for the other direction
if (direction_change) set_outputs(active_functions);
// In case of a change in active functions only the function group corresponding to the instruction is considered
// Check for changes and set outputs accordingly
else{
// Outputs depend on direction, therefore on direction change outputs need to be set as configured for the other direction.
if (direction_change) {
// In case of a direction change every output needs to be set according to configuration for the other direction
set_outputs(active_functions);
}
else {
// TODO: improve explanation here...
// In case of a change in active functions only the function group corresponding to the instruction is considered
// Check for changes and set outputs accordingly
new_function_bitmask &= ~(clr_bit_arr[clr_bit_ind]); // Clear every bit except bits corresponding to group of functions
active_functions &= clr_bit_arr[clr_bit_ind]; // Clear bits corresponding to group of functions
active_functions |= new_function_bitmask; // Write bits corresponding to group of functions
uint32_t changes = active_functions ^ prev_active_func; // Checks for changes from previous state
if(changes) set_outputs(active_functions);
const uint32_t changes = active_functions ^ prev_active_func; // Checks for changes from previous state
if (changes) {
set_outputs(active_functions);
}
prev_active_func = active_functions;
}
}
// Bitwise XOR for all Bytes -> Successful result is: "0000 0000"
bool error_detection(int8_t number_of_bytes, const uint8_t * const byte_array) {
// Bitwise XOR for all Bytes -> when result is: "0000 0000" error check is passed.
bool error_detection(const int8_t number_of_bytes, const uint8_t *const byte_array) {
uint8_t xor_byte = 0;
for (int i = 0; i < number_of_bytes; i++) {
xor_byte = xor_byte ^ byte_array[i];
@@ -302,105 +313,103 @@ bool error_detection(int8_t number_of_bytes, const uint8_t * const byte_array) {
// Check for long address. Function returns true for long address.
bool is_long_address(uint8_t number_of_bytes, const uint8_t * const byte_array) {
if ((byte_array[number_of_bytes - 1]>>6) == 0b00000011) return true;
bool is_long_address(uint8_t const number_of_bytes, const uint8_t *const byte_array) {
if ((byte_array[number_of_bytes - 1] >> 6) == 0b00000011) {
return true;
}
return false;
}
// First checks for idle package and then evaluates address included in byte_array[]
bool address_evaluation(uint8_t number_of_bytes,const uint8_t * const byte_array) {
// Check for Idle Package
if (byte_array[number_of_bytes - 1] == 255)
{
// First checks for idle message and then evaluates address included in byte_array[] which contains the received DCC message
bool address_evaluation(const uint8_t number_of_bytes, const uint8_t *const byte_array) {
// Check for idle message
if (byte_array[number_of_bytes - 1] == 255) {
return false;
}
// Long/extended address decoder configuration (CV_29 Bit5)
bool CV_29_bit5 = (CV_ARRAY_FLASH[28]&0b00100000)>>5;
const bool CV_29_bit5 = (CV_ARRAY_FLASH[28] & 0b00100000) >> 5;
uint16_t read_address;
// Decoder configured to receive long/extended address
if (CV_29_bit5){
// Package received does contain a long address -> Check for accordance
if (is_long_address(number_of_bytes, byte_array))
{
// Check if decoder is configured to receive long/extended address (CV_29 Bit5 set)
if (CV_29_bit5) {
// Check DCC message for long address format
if (is_long_address(number_of_bytes, byte_array)) {
// DCC message received has long address format
// start of transmission -> address_byte_1 -> address_byte_0 -> ... -> end of transmission
uint16_t address_byte_1 = (byte_array[number_of_bytes - 1]) - 192; // Remove long address identifier bits
uint16_t address_byte_0 = (byte_array[number_of_bytes - 2]);
const uint16_t address_byte_1 = (byte_array[number_of_bytes - 1]) - 192; // Remove long address identifier bits
const uint16_t address_byte_0 = (byte_array[number_of_bytes - 2]);
read_address = (address_byte_1 << 8) + address_byte_0;
uint16_t long_address = get_16bit_CV(16) & 0x3FFF; // &Mask to remove long address identifier bits
const uint16_t long_address = get_16bit_CV(16) & 0x3FFF; // &Mask to remove long address identifier bits
return (long_address == read_address);
}
// Package received does not contain a long address
else return false;
else {
// DCC message received does not have long address format
return false;
}
}
// Short address decoder configuration (CV_29 Bit5)
else
{
// Short Address Package
else {
// Else decoder is configured to receive short address (CV_29 Bit5 not set)
// Short address message:
// start of transmission -> address_byte_0 -> ... -> end of transmission
read_address = (byte_array[number_of_bytes - 1]);
return (CV_ARRAY_FLASH[0] == read_address);
read_address = byte_array[number_of_bytes - 1];
return CV_ARRAY_FLASH[0] == read_address;
}
}
// Evaluate the type of instruction
void instruction_evaluation(uint8_t number_of_bytes,const uint8_t * const byte_array) {
void instruction_evaluation(const uint8_t number_of_bytes, const uint8_t *const byte_array) {
// start of transmission -> ... -> command_byte_n -> ... -> command_byte_0 -> ... -> end of transmission
// The position of command bytes depend on whether the address is long or not
uint8_t command_byte_n;
uint8_t command_byte_start_index;
if (is_long_address(number_of_bytes,byte_array)) {
if (is_long_address(number_of_bytes, byte_array)) {
command_byte_start_index = number_of_bytes - 3;
}
else {
command_byte_start_index = number_of_bytes - 2;
}
command_byte_n = byte_array[command_byte_start_index];
const uint8_t command_byte_n = byte_array[command_byte_start_index];
//0011-1111 (128 Speed Step Control) - 2 Byte length
if (command_byte_n == 0b00111111){
static bool prev_dir;
uint32_t speed_step = byte_array[command_byte_start_index - 1];
// LOG(1, "new speed %d", speed_step);
multicore_fifo_push_blocking(speed_step);
// LOG(1, " submitted to list");
// In case of a direction change, functions need to be updated because functions might depend on direction state
if (get_direction(0) != prev_dir) {
update_active_functions(0,0,true);
prev_dir = get_direction(0);
if (command_byte_n == 0b00111111) {
// 0011-1111 (128 Speed Step Control) - 2 Byte length
speed_step_target_prev = speed_step_target;
speed_step_target = byte_array[command_byte_start_index - 1];
// Check for direction change
const bool direction_changed = get_direction_of_speed_step(speed_step_target) !=
get_direction_of_speed_step(speed_step_target_prev);
// In case of a direction change, functions need to be updated because functions depend on direction
if (direction_changed) {
update_active_functions(0, 0, true);
}
}
// 10XX-XXXX (Function Group Instruction)
else if (command_byte_n >> 6 == 0b00000010){
else if (command_byte_n >> 6 == 0b00000010) {
// 10XX-XXXX (Function Group Instruction)
switch (command_byte_n >> 4) {
case 0b00001011: // F5-F8
update_active_functions((command_byte_n << 5),1,false);
update_active_functions((command_byte_n << 5), 1, false);
break;
case 0b00001010: // F9-F12
update_active_functions((command_byte_n << 9),2,false);
update_active_functions((command_byte_n << 9), 2, false);
break;
default: // F0-F4
update_active_functions((((command_byte_n & 0b00001111) << 1) + ((command_byte_n & 0b00010000) >> 4)),0,false);
update_active_functions((((command_byte_n & 0b00001111) << 1) + ((command_byte_n & 0b00010000) >> 4)), 0, false);
break;
}
}
//Feature Expansion Instruction 110X-XXXX
else if (command_byte_n >> 5 == 0b00000110) {
//Feature Expansion Instruction 110X-XXXX
switch (command_byte_n) {
case 0b11011110: // F13-F20
update_active_functions((byte_array[command_byte_start_index - 1] << 13),3,false);
update_active_functions((byte_array[command_byte_start_index - 1] << 13), 3, false);
break;
case 0b11011111: // F21-F28
update_active_functions((byte_array[command_byte_start_index - 1] << 21),4,false);
update_active_functions((byte_array[command_byte_start_index - 1] << 21), 4, false);
break;
case 0b11011000: // F29-F31
update_active_functions((byte_array[command_byte_start_index - 1] << 29),5,false);
update_active_functions((byte_array[command_byte_start_index - 1] << 29), 5, false);
break;
default:
break;
@@ -409,32 +418,38 @@ void instruction_evaluation(uint8_t number_of_bytes,const uint8_t * const byte_a
}
// Check for reset package - When reset package is found stop the motor and disable all functions
bool reset_package_check(uint8_t number_of_bytes,const uint8_t * const byte_array){
if (byte_array[number_of_bytes-1] == 0b00000000 && byte_array[number_of_bytes-2] == 0b00000000){
uint32_t speed_step = 1;
multicore_fifo_push_blocking(speed_step); // Emergency Stop
// Check for reset message - When reset message is found, stop the motor and disable all functions.
bool reset_message_check(const uint8_t number_of_bytes, const uint8_t *const byte_array) {
if (byte_array[number_of_bytes - 1] == 0b00000000 && byte_array[number_of_bytes - 2] == 0b00000000) {
const bool direction = get_direction_of_speed_step(speed_step_target);
// Set previous speed step target to current speed step target
speed_step_target_prev = speed_step_target;
// Set speed step target to emergency stop speed step ( 1 for Reverse direction / 129 for forward direction)
// for details see get_direction_of_speed_step() doxygen comment in "shared.h"
speed_step_target = 1 + 128*direction;
update_active_functions(0,0,0); // Disables all functions
return true;
}
else return false;
return false;
}
// Checks for valid package - looking for correct preamble
int8_t check_for_package() { //returns number of bytes if valid bit-pattern is found. Otherwise -1 is returned.
uint64_t package3Masked = input_bit_buffer & PACKAGE_MASK_3_BYTES;
if (package3Masked == PACKAGE_3_BYTES) return 3;
uint64_t package4Masked = input_bit_buffer & PACKAGE_MASK_4_BYTES;
if (package4Masked == PACKAGE_4_BYTES) return 4;
uint64_t package5Masked = input_bit_buffer & PACKAGE_MASK_5_BYTES;
if (package5Masked == PACKAGE_5_BYTES) return 5;
return -1;
// Checks for valid message - looking for correct preamble using bitmasks
// returns number of bytes if valid bit-pattern is found. Otherwise -1 is returned.
int8_t verify_dcc_message() {
int8_t number_of_bytes = -1;
const uint64_t masked_message_3_bytes = input_bit_buffer & MESSAGE_MASK_3_BYTES;
if (masked_message_3_bytes == MESSAGE_3_BYTES) number_of_bytes = 3;
const uint64_t masked_message_4_bytes = input_bit_buffer & MESSAGE_MASK_4_BYTES;
if (masked_message_4_bytes == MESSAGE_4_BYTES) number_of_bytes = 4;
const uint64_t masked_message_5_bytes = input_bit_buffer & MESSAGE_MASK_5_BYTES;
if (masked_message_5_bytes == MESSAGE_5_BYTES) number_of_bytes = 5;
return number_of_bytes;
}
//start of transmission -> byte_n(address byte) -> ... -> byte_0(error detection byte) -> end of transmission
void bits_to_byte_array(int8_t number_of_bytes,uint8_t byte_array[]) {
void bits_to_byte_array(const int8_t number_of_bytes, uint8_t byte_array[]) {
for (uint8_t i = 0; i < number_of_bytes; i++) {
byte_array[i] = input_bit_buffer >> (i * 9 + 1);
}
@@ -442,35 +457,29 @@ void bits_to_byte_array(int8_t number_of_bytes,uint8_t byte_array[]) {
// Sequence of bits gets evaluated
void evaluation(){
static bool core1_launched = false;
static bool reset_package_flag;
int8_t number_of_bytes = check_for_package();
// number_of_bytes contains the amount of bytes when the package is valid, otherwise -1
void evaluate_message() {
static bool reset_message_flag;
// Check if input buffer contains a valid dcc message
const int8_t number_of_bytes = verify_dcc_message();
// number_of_bytes contains the amount of bytes when the message is valid, otherwise -1
if (number_of_bytes != -1) {
// Split data into 8Bit array
uint8_t byte_array[SIZE_BYTE_ARRAY] = {0};
bits_to_byte_array(number_of_bytes,byte_array);
bits_to_byte_array(number_of_bytes, byte_array);
// Check for errors
if (error_detection(number_of_bytes,byte_array)) {
if (error_detection(number_of_bytes, byte_array)) {
// Check for matching address
if (address_evaluation(number_of_bytes,byte_array)) {
reset_package_flag = false;
if (!core1_launched){
multicore_launch_core1(core1_entry);
// Wait for pid.direction pointer via multicore fifo also signalizing that core1 initialization is finished.
get_direction((bool *) multicore_fifo_pop_blocking());
core1_launched = true;
}
instruction_evaluation(number_of_bytes,byte_array);
if (address_evaluation(number_of_bytes, byte_array)) {
reset_message_flag = false;
instruction_evaluation(number_of_bytes, byte_array);
}
// When previous packet was a reset package -> enter program mode
else if (reset_package_flag) {
program_mode(number_of_bytes,byte_array);
else if (reset_message_flag) {
// When previous packet was a reset message -> enter program mode
program_mode(number_of_bytes, byte_array);
}
// Check for reset package and set flag when reset package is received
else {
reset_package_flag = reset_package_check(number_of_bytes,byte_array);
// Check for reset message and set flag when reset message is received
reset_message_flag = reset_message_check(number_of_bytes, byte_array);
}
}
}
@@ -478,7 +487,7 @@ void evaluation(){
// DCC-Signal (GPIO 21) rising edge interrupt
void track_signal_rise(unsigned int gpio, long unsigned int events) {
void track_signal_rise(const unsigned int gpio, const long unsigned int events) {
// Save current timer value
rising_edge_time = get_absolute_time();
// Disable rising edge interrupt and enable falling edge interrupt
@@ -488,188 +497,163 @@ void track_signal_rise(unsigned int gpio, long unsigned int events) {
// DCC-Signal (GPIO 21) falling edge interrupt
void track_signal_fall(unsigned int gpio, long unsigned int events) {
void track_signal_fall( const unsigned int gpio, const long unsigned int events) {
// Save current timer value
falling_edge_time = get_absolute_time();
// Time difference is equal to the time the signal was in a logical high state
int64_t time_logical_high = absolute_time_diff_us(rising_edge_time,falling_edge_time);
const int64_t time_logical_high = absolute_time_diff_us(rising_edge_time, falling_edge_time);
// When logical high was longer than 87us write 0 bit into buffer otherwise 1
bool bit;
if(time_logical_high > 87) bit = 0;
if (time_logical_high > 87) bit = 0;
else bit = 1;
input_bit_buffer <<= 1;
input_bit_buffer |= bit;
// evaluate sequence of bits saved in buffer
evaluation();
evaluate_message();
// Disable falling edge interrupt and enable rising edge interrupt
gpio_set_irq_enabled_with_callback(DCC_INPUT_PIN, GPIO_IRQ_EDGE_FALL, false, &track_signal_fall);
gpio_set_irq_enabled_with_callback(DCC_INPUT_PIN, GPIO_IRQ_EDGE_RISE, true, &track_signal_rise);
}
// Output initialization function - Configures pwm frequency and clock divider according to CV_111 - CV_171
void init_outputs(){
void init_outputs() {
gpio_init_mask(GPIO_ALLOWED_OUTPUTS);
gpio_set_dir_out_masked(GPIO_ALLOWED_OUTPUTS); // Note: This might also disable UART on GPIO0 & GPIO1
uint32_t PWM_enabled_outputs = get_32bit_CV(111) & GPIO_ALLOWED_OUTPUTS;
uint32_t slice, channel;
uint16_t wrap, level;
uint8_t clock_divider;
const uint32_t PWM_enabled_outputs = get_32bit_CV(111) & GPIO_ALLOWED_OUTPUTS;
uint32_t mask = 1;
for (uint8_t i = 0; i < 32; ++i) {
if (PWM_enabled_outputs & mask){
slice = pwm_gpio_to_slice_num(i);
channel = pwm_gpio_to_channel(i); // Channel A = "0"; Channel B = "1"
wrap = get_16bit_CV(115 + 7*slice);
level = get_16bit_CV(118 + 7*slice + 2*channel);
clock_divider = CV_ARRAY_FLASH[117+7*slice] + 1;
gpio_set_function(i,GPIO_FUNC_PWM);
pwm_set_wrap(slice,wrap);
pwm_set_gpio_level(i,0);
if (PWM_enabled_outputs & mask) {
const uint32_t slice = pwm_gpio_to_slice_num(i);
const uint32_t channel = pwm_gpio_to_channel(i); // Channel A = "0"; Channel B = "1"
const uint16_t wrap = get_16bit_CV(115 + 7 * slice);
const uint16_t level = get_16bit_CV(118 + 7 * slice + 2 * channel);
const uint8_t clock_divider = CV_ARRAY_FLASH[117 + 7 * slice] + 1;
gpio_set_function(i, GPIO_FUNC_PWM);
pwm_set_wrap(slice, wrap);
pwm_set_gpio_level(i, 0);
level_table[i] = level;
pwm_set_clkdiv_int_frac(slice,clock_divider,0);
pwm_set_enabled(slice,true);
pwm_set_clkdiv_int_frac(slice, clock_divider, 0);
pwm_set_enabled(slice, true);
}
mask<<=1;
mask <<= 1;
}
}
// Measures "base" pwm duty cycle needed to overcome friction
uint16_t measure_base_pwm(bool direction, uint8_t iterations){
uint16_t measure_base_pwm(const bool direction, const uint8_t iterations) {
uint gpio;
if (direction) gpio = MOTOR_FWD_PIN;
else gpio = MOTOR_REV_PIN;
float level_arr[iterations];
for (int i = 0; i < iterations; ++i) {
uint16_t max_level = _125M/(CV_ARRAY_FLASH[8]*100+10000);
uint16_t level = max_level/20;
const uint16_t max_level = _125M / (CV_ARRAY_FLASH[8] * 100 + 10000);
uint16_t level = max_level / 20;
LOG(3, "iteration %d: maxlevel %d level %d\n", i, max_level, level);
float measurement;
do {
pwm_set_gpio_level(gpio, level);
busy_wait_ms(30);
level += max_level/500;
level += max_level / 500;
measurement = measure(CV_ARRAY_FLASH[60],
CV_ARRAY_FLASH[61],
CV_ARRAY_FLASH[62],
CV_ARRAY_FLASH[63],
direction);
LOG(3, "level %d measurement %f loop-cond: %f\n", level, measurement, measurement-(float)CV_ARRAY_FLASH[171]);
LOG(3, "level %d measurement %f loop-cond: %f\n", level, measurement, measurement - (float) CV_ARRAY_FLASH[171]);
if (level > max_level) {
// Abort measurement and write default value of 0 to flash
LOG(1, "measure_base_pwm: abort measurement and return 0\n");
return 0;
}
} while((measurement - (float)CV_ARRAY_FLASH[171]) < 5.0f);
LOG(3, "level_arr[%d] = %f\n", i, level);
level_arr[i] = (float)level;
} while ((measurement - (float) CV_ARRAY_FLASH[171]) < 5.0f);
LOG(3, "level_arr[%d] = %d\n", i, level);
level_arr[i] = (float) level;
busy_wait_ms(100);
}
// Find and return overall average discarding outliers in measurement - multiply with 0.9
float retVal = 0.9f*two_std_dev(level_arr,5);
LOG(1, "measure_base_pwm: %d(%f)\n", (uint16_t)retVal, retVal);
return (uint16_t)(retVal);
const float retVal = 0.9f * two_std_dev(level_arr, 5);
LOG(1, "measure_base_pwm: %d(%f)\n", (uint16_t) retVal, retVal);
return (uint16_t) retVal;
}
// Check for flash memory factory condition and adc offset setup
// When factory condition is found the CV_ARRAY_DEFAULT will be written into flash
// When ADC Setup is not configured run adc offset adjustment function and write adc offset into flash
void cv_setup_check(){
void cv_setup_check() {
// Check for flash factory setting and set CV_FLASH_ARRAY to default values when factory condition ("0xFF") is found.
if ( CV_ARRAY_FLASH[64] == 0xFF ){
if (CV_ARRAY_FLASH[64] == 0xFF) {
LOG(1, "found cv[64] equals to 0xff, reseting CVs (and CV[8] = 8)\n");
uint8_t arr[4] = {125,8,7,124};
program_mode(4,arr); //reset to CV_ARRAY_DEFAULT (write CV_8 = 8)
const uint8_t arr[4] = {125, 8, 7, 124};
program_mode(4, arr); //reset to CV_ARRAY_DEFAULT (write CV_8 = 8)
}
// Check for adc offset setup
if ( CV_ARRAY_FLASH[171] == 0xFF ){
// Check for existing ADC offset setup
if (CV_ARRAY_FLASH[171] == 0xFF) {
// Write a value of 7 to read-only CV_7 in order to trigger a ADC offset measurement
LOG(1, "found cv[171] equals to 0xff, adc offset adjstments (and cr[7] = 7)\n");
uint8_t arr[4] = {125,7,6,124};
program_mode(4,arr); //ADC offset adjustment (write CV_7 = 7)
const uint8_t arr[4] = {125, 7, 6, 124};
program_mode(4, arr); // ADC offset adjustment (write CV_7 = 7)
}
// Check for base PWM configuration - used for feed-forward
// Forward Direction
if (get_16bit_CV(175) == 0){
if (get_16bit_CV(175) == 0) {
LOG(1, "found cv[175] equals to 0, forward direction\n");
uint16_t base_pwm_fwd = measure_base_pwm(true,10);
uint8_t base_pwm_fwd_high_byte = base_pwm_fwd>>8;
uint8_t base_pwm_fwd_low_byte = base_pwm_fwd&0x00FF;
uint8_t arr0[4] = {125,base_pwm_fwd_high_byte,175,124};
program_mode(4,arr0);
uint8_t arr1[4] = {125,base_pwm_fwd_low_byte,176,124};
program_mode(4,arr1);
const uint16_t base_pwm_fwd = measure_base_pwm(true, 10);
const uint8_t base_pwm_fwd_high_byte = base_pwm_fwd >> 8;
const uint8_t base_pwm_fwd_low_byte = base_pwm_fwd & 0x00FF;
const uint8_t arr0[4] = {125, base_pwm_fwd_high_byte, 175, 124};
program_mode(4, arr0);
const uint8_t arr1[4] = {125, base_pwm_fwd_low_byte, 176, 124};
program_mode(4, arr1);
}
// Reverse Direction
if (get_16bit_CV(177) == 0){
if (get_16bit_CV(177) == 0) {
LOG(1, "found cv[177] equals to 0, reverse direction\n");
uint16_t base_pwm_rev = measure_base_pwm(false,10);
uint8_t base_pwm_rev_high_byte = base_pwm_rev>>8;
uint8_t base_pwm_rev_low_byte = base_pwm_rev&0x00FF;
uint8_t arr0[4] = {125,base_pwm_rev_high_byte,177,124};
program_mode(4,arr0);
uint8_t arr1[4] = {125,base_pwm_rev_low_byte,178,124};
program_mode(4,arr1);
const uint16_t base_pwm_rev = measure_base_pwm(false, 10);
const uint8_t base_pwm_rev_high_byte = base_pwm_rev >> 8;
const uint8_t base_pwm_rev_low_byte = base_pwm_rev & 0x00FF;
const uint8_t arr0[4] = {125, base_pwm_rev_high_byte, 177, 124};
program_mode(4, arr0);
const uint8_t arr1[4] = {125, base_pwm_rev_low_byte, 178, 124};
program_mode(4, arr1);
}
LOG(1, "int_lim_max %d\n", CV_ARRAY_FLASH[51]);
LOG(1, "int_lim_min %d\n", CV_ARRAY_FLASH[52]);
}
// This function ensures that the direction pointer can only be written once.
// After first initialization this function can be called with arbitrary input to get the current direction
bool get_direction(bool *direction_ptr){
static bool set_flag;
static bool *dir_ptr;
if(!set_flag) {
if (direction_ptr == NULL){
LOG(0, "Error! Direction pointer argument is NULL-pointer!\n")
}
else {
set_flag = true;
dir_ptr = direction_ptr;
}
}
return *dir_ptr;
}
// Motor PWM initialization
void init_motor_pwm(uint8_t gpio) {
uint16_t wrap_counter = (_125M/(CV_ARRAY_FLASH[8]*100+10000)) - 1;
uint32_t slice_num = pwm_gpio_to_slice_num(gpio);
pwm_set_clkdiv_int_frac(slice_num,CV_ARRAY_FLASH[173],0);
void init_motor_pwm(const uint8_t gpio) {
// Set GPIO pin to PWM functionality
gpio_set_function(gpio, GPIO_FUNC_PWM);
// Set wrap counter value saved in CV
const uint16_t wrap_counter = (_125M / (CV_ARRAY_FLASH[8] * 100 + 10000)) - 1;
const uint32_t slice_num = pwm_gpio_to_slice_num(gpio);
pwm_set_clkdiv_int_frac(slice_num, CV_ARRAY_FLASH[173], 0);
pwm_set_wrap(slice_num, wrap_counter);
pwm_set_gpio_level(gpio,0);
// Set initial level to 0
pwm_set_gpio_level(gpio, 0);
// Enable PWM
pwm_set_enabled(slice_num, true);
LOG(2, "init motor(%d): wrapCounter %d clkdiv %d\n", gpio, wrap_counter, CV_ARRAY_FLASH[173]);
}
// Main initialization - GPIO Config / ADC Config
void init_gpio_adc(){
if(gpio_get_function(MOTOR_FWD_PIN) != 4){
gpio_set_function(MOTOR_FWD_PIN, GPIO_FUNC_PWM);
gpio_set_function(MOTOR_REV_PIN, GPIO_FUNC_PWM);
adc_init();
adc_gpio_init(FWD_V_EMF_ADC_PIN);
adc_gpio_init(REV_V_EMF_ADC_PIN);
adc_fifo_setup(true,false,0,false,false);
}
void init_adc() {
// Initialize ADC
adc_init();
// Set ADC GPIO pins to ADC functionality
adc_gpio_init(FWD_V_EMF_ADC_PIN);
adc_gpio_init(REV_V_EMF_ADC_PIN);
// Configure ADC FIFO
adc_fifo_setup(true, false, 0, false, false);
}
int main() {
stdio_init_all();
LOG(1, "\n\n======\ncore0 init\n");
init_gpio_adc();
LOG(1, "init motor pwms\n");
LOG(1, "Init motor PWM\n");
init_motor_pwm(MOTOR_FWD_PIN);
init_motor_pwm(MOTOR_REV_PIN);
LOG(1, "Init ADC")
init_adc();
LOG(1, "check cvs\n");
cv_setup_check();
LOG(1, "init outputs\n");
@@ -680,5 +664,7 @@ int main() {
gpio_pull_up(DCC_INPUT_PIN);
gpio_set_irq_enabled_with_callback(DCC_INPUT_PIN, GPIO_IRQ_EDGE_RISE, true, &track_signal_rise);
LOG(1, "core0 done\n");
while (1);
busy_wait_ms(100);
multicore_launch_core1(core1_entry);
while (true);
}
+78 -20
View File
@@ -1,19 +1,19 @@
//////////////////////////
// RP2040-Decoder //
// Gabriel Koppenstein //
// core0.h //
//////////////////////////
/*!
*
* \file core0.h
* Used exclusively by core0
*
*/
#pragma once
#include "shared.h"
#include "CV.h"
#define SIZE_BYTE_ARRAY 5
#define PACKAGE_3_BYTES 0b11111111110000000000000000000000000001
#define PACKAGE_MASK_3_BYTES 0b11111111111000000001000000001000000001
#define PACKAGE_4_BYTES 0b11111111110000000000000000000000000000000000001
#define PACKAGE_MASK_4_BYTES 0b11111111111000000001000000001000000001000000001
#define PACKAGE_5_BYTES 0b11111111110000000000000000000000000000000000000000000001
#define PACKAGE_MASK_5_BYTES 0b11111111111000000001000000001000000001000000001000000001
#define MESSAGE_3_BYTES 0b11111111110000000000000000000000000001
#define MESSAGE_MASK_3_BYTES 0b11111111111000000001000000001000000001
#define MESSAGE_4_BYTES 0b11111111110000000000000000000000000000000000001
#define MESSAGE_MASK_4_BYTES 0b11111111111000000001000000001000000001000000001
#define MESSAGE_5_BYTES 0b11111111110000000000000000000000000000000000000000000001
#define MESSAGE_MASK_5_BYTES 0b11111111111000000001000000001000000001000000001000000001
const uint32_t clr_bit_arr[6] = {
0b11111111111111111111111111100000, // Clear Bits 0-4 (F0-F4)
0b11111111111111111111111000011111, // Clear Bits 5-8 (F5-F8)
@@ -29,7 +29,7 @@ void acknowledge();
void verify_cv_bit(uint16_t cv_address,bool bit_val, uint8_t bit_pos);
void verify_cv_byte(uint16_t cv_address, uint8_t cv_data);
void regular_cv_write(uint16_t cv_index, uint8_t cv_data);
void write_cv_handler(uint16_t cv_index, uint8_t cv_data);
//void write_cv_handler(uint16_t cv_index, uint8_t cv_data);
#define ProgramInstrVerifyBit 0b10
@@ -37,22 +37,80 @@ void write_cv_handler(uint16_t cv_index, uint8_t cv_data);
#define ProgramInstrWriteByte 0b11
#define ProgramCmd(instr, adrmsbits) ((instr<<2) | (adrmsbits))
/*!
* \brief CV Programming mode function
* Used on entering programming mode in order to write CV values to persistent flash memory or verify/read bits/bytes from flash. <br>
* Refers to NMRA Standard 9.2.3 ("Service Mode Programming") or RCN-216<br>
*
* Procedure:
* 1. Checks for valid programming command
* 2. Disables core1 timers
* 3. Resets core1
* 4. Saves interrupts
* 5. Evaluates the type of programming instruction Write byte / Verify byte / Verify bit and runs corresponding function
* 6. Restores interrupts
* 7. Launch core1
*
* \param number_of_bytes Number of bytes in byte_array[]
* \param byte_array Pointer to byte_array[]
*/
void program_mode(uint8_t number_of_bytes, const uint8_t byte_array[]);
void set_outputs(uint32_t functions_to_set_bitmask);
void update_active_functions(uint32_t byte, uint8_t clr_bit_ind,bool direction_change);
bool error_detection(int8_t number_of_bytes, const uint8_t byte_array[]);
void update_active_functions(uint32_t new_function_bitmask, uint8_t clr_bit_ind, bool direction_change);
bool error_detection(int8_t number_of_bytes, const uint8_t * byte_array);
bool is_long_address(uint8_t number_of_bytes, const uint8_t byte_array[]);
bool address_evaluation(uint8_t number_of_bytes,const uint8_t byte_array[]);
void instruction_evaluation(uint8_t number_of_bytes,const uint8_t byte_array[]);
bool reset_package_check(uint8_t number_of_bytes,const uint8_t byte_array[]);
int8_t check_for_package();
bool reset_message_check(uint8_t number_of_bytes, const uint8_t *const byte_array);
int8_t verify_dcc_message();
void bits_to_byte_array(int8_t number_of_bytes,uint8_t byte_array[]);
void evaluation();
void evaluate_message();
void track_signal_rise(unsigned int gpio, long unsigned int events);
void track_signal_fall(unsigned int gpio, long unsigned int events);
/*!
* \brief Output initialization function
*
* Initializes all allowed GPIO outputs as outputs <br>
* Sets PWM functionality for GPIOs configured as PWM pins CV_112 - CV_115 (see CV.h for reference) <br>
* PWM frequency and clock divider are configured according to CV_116 - CV_171 (see CV.h for reference) <br>
*/
void init_outputs();
/*!
* \brief Measures base pwm duty cycles at which the motor barely starts moving.
*
* Function starts with 1/20 of the maximum duty cycle then increases the duty cycle by 1/500 of the maximum until
* the motor movement can be measured. This is done for the specified amount of iterations.
* The array with raw measurements values is then passed to two_std_dev() in order to detect outliers and
* calculate the average.An additional correction factor is applied and the overall measurement result is then
* returned. In case no motor movement could be measured a value of 0 is returned and normally written to flash,
* indicating a pending calibration next time the decoder starts, rerunning the calibration.
* \param direction Specifies direction which is to be measured
* \param iterations Specifies the amount of iterations the measurement is to be repeated and averaged out over
* \return Measurement
*/
uint16_t measure_base_pwm(bool direction, uint8_t iterations);
/*!
* \brief Checks various CV values in order to detect factory condition or pending calibrations
*
* Procedure:
* 1. Check for flash memory factory condition when found write default values specified in CV.h to flash memory
* 2. Check for existing ADC offset setup when not found write 7 to read-only CV_7 in order to trigger a ADC offset measurement/calibration
* 3. Check for base PWM configuration/calibration, run calibration when none is found
*/
void cv_setup_check();
bool get_direction(bool *direction_ptr);
/*!
* \brief Function initializes motor PWM for pin specified
* \param gpio GPIO pin
*/
void init_motor_pwm(uint8_t gpio);
void init_gpio_adc();
/*!
* \brief Initializes ADC
*
* Function initializes ADC, corresponding GPIO pins and ADC FIFO
*/
void init_adc();
+139 -158
View File
@@ -5,83 +5,73 @@
//////////////////////////
#include "core1.h"
struct repeating_timer pid_control_timer,speed_helper_timer;
struct repeating_timer pid_control_timer, speed_helper_timer;
// Update speed_step_target, end_target_index and direction on receiving data from core0
void update_speed_dir(pid_params *pid, uint32_t speed_step_target){
pid->speed_step_target = speed_step_target;
// When CV_29 Bit 0 is set direction is reversed
bool reverse_dir = CV_ARRAY_FLASH[28] & 0b00000001;
// Forward
if(speed_step_target > 127) {
pid->direction = true^reverse_dir;
if (pid->speed_step_target == 128)
pid->end_target_index = 0;
else
pid->end_target_index = (pid->speed_step_target-129);
}
// Reverse
else {
pid->direction = false^reverse_dir;
if (pid->speed_step_target == 0)
pid->end_target_index = 0;
else
pid->end_target_index = (pid->speed_step_target-1);
// Get speed_step_table_index depending on speed_step
uint8_t get_speed_step_table_index_of_speed_step(uint8_t speed_step) {
// Clear direction information in bit7
speed_step = speed_step & 0b01111111;
// Check for Stop or Emergency Stop speed step
if (speed_step == 0 || speed_step == 1) {
return 0;
}
// In any other case i.e. speed steps 1 to 126:
return speed_step-1;
}
// This function gets called every x milliseconds where x is CV_175.
// The purpose of this function is to implement a time delay in acceleration or deceleration
bool speed_helper(struct repeating_timer *t) {
bool speed_helper(struct repeating_timer *const t) {
// pid->setpoint only gets adjusted when the speed_helper_counter is equal to the accel_rate/decel_rate
// -> Time for 1 Speed Step := (speed_helper timer delay)*(accel_rate) or CV_175*CV_3 or CV_175*CV_4
pid_params *pid = (pid_params *)(t->user_data);
uint8_t accel_rate = CV_ARRAY_FLASH[2];
uint8_t decel_rate = CV_ARRAY_FLASH[3];
static bool prev_dir;
pid_params *const pid = (pid_params *) (t->user_data);
const uint8_t accel_rate = CV_ARRAY_FLASH[2];
const uint8_t decel_rate = CV_ARRAY_FLASH[3];
static uint8_t speed_helper_counter;
static uint8_t speed_table_index;
// Emergency Stop
if (pid->speed_step_target == 129 || pid->speed_step_target==1) {
// Get speed_step_table_end_index corresponding to current speed_step_target
const uint8_t speed_step_table_end_index = get_speed_step_table_index_of_speed_step(speed_step_target);
const bool direction_changed = get_direction_of_speed_step(speed_step_target) !=
get_direction_of_speed_step(speed_step_target_prev);
if (pid->speed_step_target == 129 || pid->speed_step_target == 1) {
// Emergency Stop
speed_table_index = 0;
speed_helper_counter = 0;
pid->setpoint = pid->speed_table[speed_table_index];
}
// Acceleration
else if (pid->end_target_index > speed_table_index && speed_helper_counter == accel_rate) {
if(!accel_rate) speed_table_index = pid->end_target_index; // directly accelerate to end target speed
else if (speed_step_table_end_index > speed_table_index && speed_helper_counter == accel_rate) {
// Acceleration
if (!accel_rate) speed_table_index = speed_step_table_end_index; // directly accelerate to end target speed
else speed_table_index++;
pid->setpoint = pid->speed_table[speed_table_index];
speed_helper_counter = 0;
}
// Deceleration
else if (pid->end_target_index < speed_table_index && speed_helper_counter == decel_rate) {
if(!decel_rate) speed_table_index = pid->end_target_index; // directly decelerate to end target speed
else if (speed_step_table_end_index < speed_table_index && speed_helper_counter == decel_rate) {
// Deceleration
if (!decel_rate) speed_table_index = speed_step_table_end_index; // directly decelerate to end target speed
else speed_table_index--;
pid->setpoint = pid->speed_table[speed_table_index];
speed_helper_counter = 0;
}
// Change of direction while decelerating -> jump to most recent speed_step without delay (other direction)
else if (pid->direction != prev_dir){
speed_table_index = pid->end_target_index;
else if (direction_changed) {
// Change of direction while decelerating -> jump to most recent speed_step without delay (other direction)
speed_table_index = speed_step_table_end_index;
pid->setpoint = pid->speed_table[speed_table_index];
speed_helper_counter = 0;
}
// Acceleration/Deceleration "scheduled"
else if (pid->end_target_index != speed_table_index) speed_helper_counter++;
// Target reached -> Reset Counter
else speed_helper_counter = 0;
// Save prev speed_helper direction - not to be confused with pid->prev_direction
prev_dir = pid->direction;
else if (speed_step_table_end_index != speed_table_index) {
// Acceleration/Deceleration "scheduled"
speed_helper_counter++;
}
else {
// Target reached -> Reset Counter
speed_helper_counter = 0;
}
// return true to schedule the repeating timer again
return true;
@@ -89,14 +79,14 @@ bool speed_helper(struct repeating_timer *t) {
// Helper function to adjust pwm level/duty cycle.
void adjust_pwm_level(uint16_t level, pid_params *pid) {
// Forward
if (pid->direction) {
void adjust_pwm_level(const uint16_t level) {
if (get_direction_of_speed_step(speed_step_target)) {
// Forward
pwm_set_gpio_level(MOTOR_REV_PIN, 0);
pwm_set_gpio_level(MOTOR_FWD_PIN, level);
}
// Reverse
else {
// Reverse
pwm_set_gpio_level(MOTOR_FWD_PIN, 0);
pwm_set_gpio_level(MOTOR_REV_PIN, level);
}
@@ -104,74 +94,73 @@ void adjust_pwm_level(uint16_t level, pid_params *pid) {
// Update feed-forward slope/gradient for both directions
void update_m(pid_params *pid){
pid->m_fwd = (pid->y_2_fwd-pid->y_1_fwd)/(pid->x_2_fwd-pid->x_1_fwd);
pid->m_rev = (pid->y_2_rev-pid->y_1_rev)/(pid->x_2_rev-pid->x_1_rev);
void update_m(pid_params *const pid) {
pid->m_fwd = (pid->y_2_fwd - pid->y_1_fwd) / (pid->x_2_fwd - pid->x_1_fwd);
pid->m_rev = (pid->y_2_rev - pid->y_1_rev) / (pid->x_2_rev - pid->x_1_rev);
}
// Update feedforward function value y_2 in both directions
void update_y(pid_params *pid,float i){
// Forward
if(pid->direction) {
pid->y_2_fwd += i*pid->k_ff;
void update_y(pid_params *const pid, const float i) {
if (get_direction_of_speed_step(speed_step_target)) {
// Forward
pid->y_2_fwd += i * pid->k_ff;
// Limit y_2_fwd
if(pid->y_2_fwd > pid->max_output) pid->y_2_fwd = pid->max_output;
else if(pid->y_2_fwd < pid->y_1_fwd) pid->y_2_fwd = pid->y_1_fwd;
if (pid->y_2_fwd > pid->max_output) pid->y_2_fwd = pid->max_output;
else if (pid->y_2_fwd < pid->y_1_fwd) pid->y_2_fwd = pid->y_1_fwd;
}
// Reverse
else{
pid->y_2_rev += i*pid->k_ff;
else {
// Reverse
pid->y_2_rev += i * pid->k_ff;
// Limit y_2_rev
if(pid->y_2_rev > pid->max_output) pid->y_2_rev = pid->max_output;
else if(pid->y_2_rev < pid->y_1_rev) pid->y_2_rev = pid->y_1_rev;
if (pid->y_2_rev > pid->max_output) pid->y_2_rev = pid->max_output;
else if (pid->y_2_rev < pid->y_1_rev) pid->y_2_rev = pid->y_1_rev;
}
update_m(pid);
}
// Returns feedforward value corresponding to current setpoint
float get_ff_val(pid_params *pid){
float get_ff_val(const pid_params *const pid) {
float val;
// Forward
if(pid->direction){
val = pid->m_fwd*((float)pid->setpoint-pid->x_1_fwd)+pid->y_1_fwd;
if (get_direction_of_speed_step(speed_step_target)) {
// Forward
val = pid->m_fwd * ((float) pid->setpoint - pid->x_1_fwd) + pid->y_1_fwd;
}
// Reverse
else{
val = pid->m_rev*((float)pid->setpoint-pid->x_1_rev)+pid->y_1_rev;
else {
// Reverse
val = pid->m_rev * ((float) pid->setpoint - pid->x_1_rev) + pid->y_1_rev;
}
return val;
}
// Returns proportional gain value corresponding to current setpoint
float get_kp(pid_params *pid){
float sp = (float)pid->setpoint;
if (sp < pid->k_p_x_1){
float get_kp(const pid_params *const pid) {
const float sp = (float) pid->setpoint;
if (sp < pid->k_p_x_1) {
return pid->k_p_m_1 * sp + pid->k_p_y_0;
}
else{
return pid->k_p_m_2 * (sp - pid->k_p_x_1) + pid->k_p_y_1;
}
return pid->k_p_m_2 * (sp - pid->k_p_x_1) + pid->k_p_y_1;
}
// PID controller function gets called every x milliseconds where x is CV_49 aka sampling time (pid->t)
bool pid_control(struct repeating_timer *t){
bool pid_control(struct repeating_timer *const t) {
// Cast (void *) to (pid_params *)
pid_params *pid = (pid_params *)(t->user_data);
pid_params *const pid = (pid_params *) (t->user_data);
// Acceleration from standstill or change in direction -> reset previous derivative, error and integral parts
if((!pid->setpoint_prev && !pid->setpoint) || (pid->direction != pid->direction_prev)){
const bool direction_changed = get_direction_of_speed_step(speed_step_target) !=
get_direction_of_speed_step(speed_step_target_prev);
if ((!pid->setpoint_prev && !pid->setpoint) || direction_changed) {
pid->d_prev = 0.0f;
pid->i_prev = 0.0f;
pid->e_prev = 0.0f;
}
// Get feed-forward and proportional gain values
float feed_fwd = get_ff_val(pid);
const float feed_fwd = get_ff_val(pid);
pid->k_p = get_kp(pid);
// Measure BEMF voltage and compute error
@@ -179,44 +168,56 @@ bool pid_control(struct repeating_timer *t){
pid->msr_delay_in_us,
pid->l_side_arr_cutoff,
pid->r_side_arr_cutoff,
pid->direction);
float e = (float)pid->setpoint - (pid->measurement - pid->adc_offset);
get_direction_of_speed_step(speed_step_target));
const float measurement_corrected = pid->measurement - pid->adc_offset;
const float e = (float) pid->setpoint - measurement_corrected;
// Proportional part, integral part and derivative part (including digital low-pass-filter with time constant tau)
float p = pid->k_p * e;
float i = pid->ci_0*(e + pid->e_prev) + pid->i_prev;
float d = pid->cd_0*(pid->measurement-pid->measurement_prev)+pid->cd_1*pid->d_prev;
const float p = pid->k_p * e;
float i = pid->ci_0 * (e + pid->e_prev) + pid->i_prev;
const float d = pid->cd_0 * (pid->measurement - pid->measurement_prev) + pid->cd_1 * pid->d_prev;
// Check for limits on the integral part
if (i > pid->int_lim_max)i = pid->int_lim_max;
else if (i < pid->int_lim_min)i = pid->int_lim_min;
if (i > pid->int_lim_max) {
i = pid->int_lim_max;
}
else if (i < pid->int_lim_min) {
i = pid->int_lim_min;
}
// Sum feed forward + all controller terms (p+i+d). Limit Output from 0% to 100% duty cycle
float output = feed_fwd+p+i+d;
if (output < 0 || !pid->setpoint) output = 0.0f;
else if (output > pid->max_output) output = pid->max_output;
float output = feed_fwd + p + i + d;
if (output < 0 || !pid->setpoint) {
output = 0.0f;
}
else if (output > pid->max_output) {
output = pid->max_output;
}
if(LOGLEVEL >= 1) {
if (LOGLEVEL >= 1) {
static int counter = 0;
counter++;
if(counter > 100) {
if (counter > 100) {
LOG(1, "pid error(%f) output(%f)\n", e, output);
counter = 0;
counter = 0;
}
}
// Set PWM Level and discard results in adc fifo
adjust_pwm_level((uint16_t)roundf(output),pid);
adjust_pwm_level((uint16_t) roundf(output));
adc_fifo_drain();
// Check for High or Low Integrator values -> Update x,y values of feedforward function
if( (output < pid->max_output && output > pid->max_output/2) && ((i > pid->int_lim_max/2) || (i < pid->int_lim_min/2)) ) update_y(pid,i);
if ((output < pid->max_output && output > pid->max_output / 2) &&
((i > pid->int_lim_max / 2) || (i < pid->int_lim_min / 2))) {
update_y(pid, i);
}
// Save previous error, integrator, differentiator, direction, setpoint and measured value also sum error to e_sum
pid->e_prev = e;
pid->i_prev = i;
pid->d_prev = d;
pid->direction_prev = pid->direction;
pid->setpoint_prev = pid->setpoint;
pid->measurement_prev = pid->measurement;
@@ -226,9 +227,9 @@ bool pid_control(struct repeating_timer *t){
// PID controller and measurement parameter, and speed_table initialization
void init_pid(pid_params *pid){
void init_pid(pid_params *const pid) {
// Measurement variables initialization
pid->adc_offset = (float)CV_ARRAY_FLASH[171];
pid->adc_offset = (float) CV_ARRAY_FLASH[171];
pid->msr_total_iterations = CV_ARRAY_FLASH[60];
pid->msr_delay_in_us = CV_ARRAY_FLASH[61];
pid->l_side_arr_cutoff = CV_ARRAY_FLASH[62];
@@ -236,41 +237,41 @@ void init_pid(pid_params *pid){
// Speed table initialization
// Calculate speed setpoint table according to V_min, V_max and V_mid CVs
double v_min = (double)CV_ARRAY_FLASH[1];
double v_mid = (double)CV_ARRAY_FLASH[5]*16;
double v_max = (double)CV_ARRAY_FLASH[4]*16;
const double v_min = (double) CV_ARRAY_FLASH[1];
const double v_mid = (double) CV_ARRAY_FLASH[5] * 16;
const double v_max = (double) CV_ARRAY_FLASH[4] * 16;
LOG(1, "speedtable min(%f) mid(%f) max(%f)\n", v_min, v_mid, v_max);
double delta_x = 63;
double m_1 = (v_mid-v_min)/delta_x;
double m_2 = (v_max-v_mid)/delta_x;
const double delta_x = 63;
const double m_1 = (v_mid - v_min) / delta_x;
const double m_2 = (v_max - v_mid) / delta_x;
pid->speed_table[0] = 0;
for (uint8_t i = 1; i < 64; ++i) {
pid->speed_table[i] = (uint16_t)lround(m_1*(i-1)+v_min);
pid->speed_table[i] = (uint16_t) lround(m_1 * (i - 1) + v_min);
}
for (uint8_t i = 64; i < 127; ++i) {
pid->speed_table[i] = (uint16_t)lround(m_2*(i-63)+v_mid);
pid->speed_table[i] = (uint16_t) lround(m_2 * (i - 63) + v_mid);
}
// Controller constants initialization
pid->k_i = (float)CV_ARRAY_FLASH[49]/10;
pid->k_d = (float)CV_ARRAY_FLASH[50]/10000;
pid->tau = (float)CV_ARRAY_FLASH[47]/1000;
pid->t = (float)CV_ARRAY_FLASH[48]/1000;
pid->ci_0 = (pid->k_i*pid->t)/2;
pid->cd_0 = -(2*pid->k_d)/(2*pid->tau+pid->t);
pid->cd_1 = (2*pid->tau-pid->t)/(2*pid->tau+pid->t);
pid->int_lim_max = 10*(float)CV_ARRAY_FLASH[51];
pid->int_lim_min = -10*(float)CV_ARRAY_FLASH[52];
pid->k_ff = (float)CV_ARRAY_FLASH[46]/10000;
pid->max_output = (float)(_125M/(CV_ARRAY_FLASH[8]*100+10000));
pid->k_i = (float) CV_ARRAY_FLASH[49] / 10;
pid->k_d = (float) CV_ARRAY_FLASH[50] / 10000;
pid->tau = (float) CV_ARRAY_FLASH[47] / 1000;
pid->t = (float) CV_ARRAY_FLASH[48] / 1000;
pid->ci_0 = (pid->k_i * pid->t) / 2;
pid->cd_0 = -(2 * pid->k_d) / (2 * pid->tau + pid->t);
pid->cd_1 = (2 * pid->tau - pid->t) / (2 * pid->tau + pid->t);
pid->int_lim_max = 10 * (float) CV_ARRAY_FLASH[51];
pid->int_lim_min = -10 * (float) CV_ARRAY_FLASH[52];
pid->k_ff = (float) CV_ARRAY_FLASH[46] / 10000;
pid->max_output = (float) (_125M / (CV_ARRAY_FLASH[8] * 100 + 10000));
pid->x_1_rev = 0.0f;
pid->x_1_fwd = 0.0f;
pid->y_1_fwd = (float)get_16bit_CV(175);
pid->y_1_rev = (float)get_16bit_CV(177);
pid->x_2_rev = (float)pid->speed_table[126];
pid->x_2_fwd = (float)pid->speed_table[126];
pid->y_1_fwd = (float) get_16bit_CV(175);
pid->y_1_rev = (float) get_16bit_CV(177);
pid->x_2_rev = (float) pid->speed_table[126];
pid->x_2_fwd = (float) pid->speed_table[126];
// Controller variables initialization
pid->y_2_fwd = pid->max_output;
@@ -280,58 +281,38 @@ void init_pid(pid_params *pid){
pid->e_prev = 0.0f;
pid->i_prev = 0.0f;
pid->d_prev = 0.0f;
pid->direction = false;
pid->direction_prev = false;
pid->speed_step_target = 0;
pid->setpoint = 0;
// Gain scheduling initialization
pid->k_p_x_1_shift = (float)CV_ARRAY_FLASH[59] / 255.0f;
pid->k_p_x_1 = (float)pid->speed_table[126] * pid->k_p_x_1_shift;
pid->k_p_x_2 = (float)pid->speed_table[126] * (1.0f - pid->k_p_x_1_shift);
pid->k_p_y_0 = (float)get_16bit_CV(53) / 100.0f;
pid->k_p_y_1 = (float)get_16bit_CV(55) / 100.0f;
pid->k_p_y_2 = (float)get_16bit_CV(57) / 100.0f;
pid->k_p_x_1_shift = (float) CV_ARRAY_FLASH[59] / 255.0f;
pid->k_p_x_1 = (float) pid->speed_table[126] * pid->k_p_x_1_shift;
pid->k_p_x_2 = (float) pid->speed_table[126] * (1.0f - pid->k_p_x_1_shift);
pid->k_p_y_0 = (float) get_16bit_CV(53) / 100.0f;
pid->k_p_y_1 = (float) get_16bit_CV(55) / 100.0f;
pid->k_p_y_2 = (float) get_16bit_CV(57) / 100.0f;
pid->k_p_m_1 = (pid->k_p_y_1 - pid->k_p_y_0) / pid->k_p_x_1;
pid->k_p_m_2 = (pid->k_p_y_2 - pid->k_p_y_1) / pid->k_p_x_2;
update_m(pid);
}
void core1_entry() {
LOG(1, "core1 init...\n");
pid_params pid_parameters;
pid_params *pid = &pid_parameters;
init_pid(pid);
alarm_pool_add_repeating_timer_ms(alarm_pool_create(0,1),
alarm_pool_add_repeating_timer_ms(alarm_pool_create(0, 1),
CV_ARRAY_FLASH[48],
pid_control,
pid,
&pid_control_timer);
irq_set_priority(0,0x00); // 0x00 = highest priority
alarm_pool_add_repeating_timer_ms(alarm_pool_create(1,1),
// Set TIMER_IRQ_0 to highest priority of 0x00
irq_set_priority(TIMER_IRQ_0, 0x00);
alarm_pool_add_repeating_timer_ms(alarm_pool_create(1, 1),
CV_ARRAY_FLASH[174],
speed_helper,
pid,
&speed_helper_timer);
// Send direction pointer for access and to let core0 know that core1 is done with initialization,
// Note: Pointer will be cast into uint32_t and then back into bool * on core0 (Both 32-Bit Datatype).
// This is done only to accommodate the correct data type associated with multicore_fifo_push_blocking().
multicore_fifo_push_blocking((uint32_t) &(pid->direction));
uint64_t packet_timeout_threshold_in_us = CV_ARRAY_FLASH[10]*1000000;
absolute_time_t time_last_update = get_absolute_time();
// printf("core1 done\n");
while (1){
// Check for time difference between last packet and current time (Packet Timeout)
absolute_time_t current_time = get_absolute_time();
if (absolute_time_diff_us(time_last_update,current_time) > packet_timeout_threshold_in_us){
update_speed_dir(pid,1 + 128*pid->direction); // Emergency stop on timeout
}
// If core0 sends new speed data to core1 speed_step_target and direction variables get updated
if(multicore_fifo_rvalid()) {
update_speed_dir(pid, multicore_fifo_pop_blocking());
time_last_update = get_absolute_time();
}
}
LOG(1, "core1 done\n");
while (true);
}
+11 -13
View File
@@ -1,8 +1,9 @@
//////////////////////////
// RP2040-Decoder //
// Gabriel Koppenstein //
// core1.h //
//////////////////////////
/*!
*
* \file core1.h
* Used exclusively by core1
*
*/
#pragma once
#include "shared.h"
@@ -46,11 +47,8 @@ typedef struct pid_params{
float m_rev; // Slope reverse direction
uint16_t speed_table[127]; // Array with setpoint values corresponding to every speed step
uint32_t speed_step_target; // End target speed step
uint16_t end_target_index; // Index for speed table array corresponding to end target speed step
uint32_t setpoint; // Current setpoint
uint32_t setpoint_prev; // Previous setpoint
bool direction; // Current Direction
bool direction_prev; // Previous Direction
// Measurement Variables
float measurement; // Newest Measurement value
float adc_offset; // ADC offset value
@@ -60,12 +58,12 @@ typedef struct pid_params{
uint8_t r_side_arr_cutoff; // Discarded samples (right side)
}pid_params;
void update_speed_dir(pid_params *pid, uint32_t speed_step_target);
uint8_t get_speed_step_table_index_of_speed_step(uint8_t speed_step);
bool speed_helper(struct repeating_timer *t);
void adjust_pwm_level(uint16_t level, pid_params *pid);
void adjust_pwm_level(uint16_t level);
void update_m(pid_params *pid);
void update_y(pid_params *pid,float i);
float get_ff_val(pid_params *pid);
float get_kp(pid_params *pid);
float get_ff_val(const pid_params *pid);
float get_kp(const pid_params *pid);
bool pid_control(struct repeating_timer *t);
void init_pid(pid_params *pid);
void init_pid( pid_params * pid);
+9 -2
View File
@@ -6,8 +6,10 @@
#include "shared.h"
// Functions in shared.c can be accessed by both cores
uint8_t speed_step_target = 0;
uint8_t speed_step_target_prev = 0;
// Functions in shared.c can be accessed by both cores
// Measures Back-EMF voltage (proportional to the rotational speed of the motor) on GPIO 28 and GPIO 29 respectively (depending on direction)
float measure(uint8_t total_iterations,
uint8_t measurement_delay_us,
@@ -60,4 +62,9 @@ uint16_t get_16bit_CV (uint16_t CV_start_index){
uint8_t byte_1 = CV_ARRAY_FLASH[CV_start_index];
uint8_t byte_0 = CV_ARRAY_FLASH[CV_start_index+1];
return (byte_0) + (byte_1<<8);
}
}
bool get_direction_of_speed_step(uint8_t speed_step){
// Shift by 7 Bytes to move bit7 into bit0 position and return
return speed_step >> 7;
}
+44 -7
View File
@@ -1,8 +1,9 @@
//////////////////////////
// RP2040-Decoder //
// Gabriel Koppenstein //
// shared.h //
//////////////////////////
/*!
*
* \file shared.h
* Used by both cores
*
*/
#pragma once
#include "string.h"
@@ -13,7 +14,6 @@
#include "hardware/pwm.h"
#include "hardware/adc.h"
#include "hardware/flash.h"
#include "hardware/irq.h"
// here you can enable printf debugging (needs extra soldering and you have to enable uart in the cmake configuration)
@@ -27,7 +27,7 @@
#define LOGLEVEL 0
#define LOG(level, ...) { if(level <= LOGLEVEL) {printf(__VA_ARGS__);}}
// Constant Value of 125 x 10⁶
// Constant Value of 125 x 10^6
#define _125M 125000000
// GPIO used for DCC-Signal, Motor PWM or ADC
@@ -58,7 +58,12 @@
extern repeating_timer_t pid_control_timer;
extern repeating_timer_t speed_helper_timer;
extern const uint8_t *CV_ARRAY_FLASH;
extern uint8_t speed_step_target;
extern uint8_t speed_step_target_prev;
void core1_entry();
void write_cv_handler(uint16_t cv_index, uint8_t cv_data);
float measure(uint8_t total_iterations,
uint8_t measurement_delay_us,
uint8_t l_side_arr_cutoff,
@@ -66,3 +71,35 @@ float measure(uint8_t total_iterations,
bool direction);
uint32_t get_32bit_CV (uint16_t CV_start_index);
uint16_t get_16bit_CV (uint16_t CV_start_index);
/*!
* @brief Get direction
* Function calculates direction.Direction is based on speed_step byte. <br>
* Refers to "128 Speed Control" - NMRA Standard 9.2.1 section 2.3.2.1 or RCN-212 section 2.2.2. <br>
*
* The following speed steps exist:
* * DEC | BIN | DIRECTION | DEFINITION
* * 000 | 0000 0000 | Reverse | STOP
* * 001 | 0000 0001 | Reverse | EMERGENCY STOP
* * 002 | 0000 0010 | Reverse | Speed step 001 (Lowest speed)
* * 003 | 0000 0011 | Reverse | Speed step 002
* * 004 | 0000 0100 | Reverse | Speed step 003
* * ... | .... .... | Reverse | .....
* * ... | .... .... | Reverse | .....
* * ... | .... .... | Reverse | .....
* * 126 | 0111 1110 | Reverse | Speed step 125
* * 127 | 0111 1111 | Reverse | Speed step 126 (Full speed)
* * 128 | 1000 0000 | Forward | STOP
* * 129 | 1000 0001 | Forward | EMERGENCY STOP
* * 130 | 1000 0010 | Forward | Speed step 001 (Lowest speed)
* * 131 | 1000 0011 | Forward | Speed step 002
* * 132 | 1000 0100 | Forward | Speed step 003
* * ... | .... .... | Forward | .....
* * ... | .... .... | Forward | .....
* * ... | .... .... | Forward | .....
* * 254 | 1111 1110 | Forward | Speed step 125
* * 255 | 1111 1111 | Forward | Speed step 126 (Full speed)
*
* @param speed_step speed step byte
* @return direction; false for reverse; true for forward;
*/
bool get_direction_of_speed_step(uint8_t speed_step);