id
int64
0
877k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
66
repo_stars
int64
94
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
11 values
repo_extraction_date
stringclasses
197 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
1,540,119
globals.h
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/globals.h
/** @file * Global defines, macros, struct definitions (@ref statuses, @ref config2, @ref config4, config*), extern-definitions (for globally accessible vars). * * ### Note on configuration struct layouts * * Once the struct members have been assigned to certain "role" (in certain SW version), they should not be "moved around" * as the structs are stored onto EEPROM as-is and the offset and size of member needs to remain constant. Also removing existing struct members * would disturb layouts. Because of this a certain amount unused old members will be left into the structs. For the storage related reasons also the * bit fields are defined in byte-size (or multiple of ...) chunks. * * ### Config Structs and 2D, 3D Tables * * The config* structures contain information coming from tuning SW (e.g. TS) for 2D and 3D tables, where looked up value is not a result of direct * array lookup, but from interpolation algorithm. Because of standard, reusable interpolation routines associated with structs table2D and table3D, * the values from config are copied from config* structs to table2D (table3D destined configurations are not stored in config* structures). * * ### Board choice * There's a C-preprocessor based "#if defined" logic present in this header file based on the Arduino IDE compiler set CPU * (+board?) type, e.g. `__AVR_ATmega2560__`. This respectively drives (withi it's "#if defined ..." block): * - The setting of various BOARD_* C-preprocessor variables (e.g. BOARD_MAX_ADC_PINS) * - Setting of BOARD_H (Board header) file (e.g. "board_avr2560.h"), which is later used to include the header file * - Seems Arduino ide implicitly compiles and links respective .ino file (by it's internal build/compilation rules) (?) * - Setting of CPU (?) CORE_* variables (e.g. CORE_AVR), that is used across codebase to distinguish CPU. */ #ifndef GLOBALS_H #define GLOBALS_H #include <Arduino.h> #include "table2d.h" #include "table3d.h" #include <assert.h> #include "src/FastCRC/FastCRC.h" #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega2561__) #define BOARD_MAX_DIGITAL_PINS 54 //digital pins +1 #define BOARD_MAX_IO_PINS 70 //digital pins + analog channels + 1 #define BOARD_MAX_ADC_PINS 15 //Number of analog pins #ifndef LED_BUILTIN #define LED_BUILTIN 13 #endif #define CORE_AVR #define BOARD_H "board_avr2560.h" #define INJ_CHANNELS 4 #define IGN_CHANNELS 5 #if defined(__AVR_ATmega2561__) //This is a workaround to avoid having to change all the references to higher ADC channels. We simply define the channels (Which don't exist on the 2561) as being the same as A0-A7 //These Analog inputs should never be used on any 2561 board definition (Because they don't exist on the MCU), so it will not cause any issues #define A8 A0 #define A9 A1 #define A10 A2 #define A11 A3 #define A12 A4 #define A13 A5 #define A14 A6 #define A15 A7 #endif //#define TIMER5_MICROS #elif defined(CORE_TEENSY) #if defined(__MK64FX512__) || defined(__MK66FX1M0__) #define CORE_TEENSY35 #define BOARD_H "board_teensy35.h" #define BOARD_MAX_ADC_PINS 22 //Number of analog pins #elif defined(__IMXRT1062__) #define CORE_TEENSY41 #define BOARD_H "board_teensy41.h" #define BOARD_MAX_ADC_PINS 17 //Number of analog pins #endif #define INJ_CHANNELS 8 #define IGN_CHANNELS 8 #elif defined(STM32_MCU_SERIES) || defined(ARDUINO_ARCH_STM32) || defined(STM32) #define CORE_STM32 #define BOARD_MAX_ADC_PINS NUM_ANALOG_INPUTS-1 //Number of analog pins from core. #if defined(STM32F407xx) //F407 can do 8x8 STM32F401/STM32F411 not #define INJ_CHANNELS 8 #define IGN_CHANNELS 8 #else #define INJ_CHANNELS 4 #define IGN_CHANNELS 5 #endif //Select one for EEPROM,the default is EEPROM emulation on internal flash. //#define SRAM_AS_EEPROM /*Use 4K battery backed SRAM, requires a 3V continuous source (like battery) connected to Vbat pin */ //#define USE_SPI_EEPROM PB0 /*Use M25Qxx SPI flash */ //#define FRAM_AS_EEPROM /*Use FRAM like FM25xxx, MB85RSxxx or any SPI compatible */ #ifndef word #define word(h, l) ((h << 8) | l) //word() function not defined for this platform in the main library #endif #if defined(ARDUINO_BLUEPILL_F103C8) || defined(ARDUINO_BLUEPILL_F103CB) \ || defined(ARDUINO_BLACKPILL_F401CC) || defined(ARDUINO_BLACKPILL_F411CE) //STM32 Pill boards #ifndef NUM_DIGITAL_PINS #define NUM_DIGITAL_PINS 35 #endif #ifndef LED_BUILTIN #define LED_BUILTIN PB1 //Maple Mini #endif #elif defined(STM32F407xx) #ifndef NUM_DIGITAL_PINS #define NUM_DIGITAL_PINS 75 #endif #endif #if defined(STM32_CORE_VERSION) #define BOARD_H "board_stm32_official.h" #else #define CORE_STM32_GENERIC #define BOARD_H "board_stm32_generic.h" #endif //Specific mode for Bluepill due to its small flash size. This disables a number of strings from being compiled into the flash #if defined(MCU_STM32F103C8) || defined(MCU_STM32F103CB) #define SMALL_FLASH_MODE #endif #define BOARD_MAX_DIGITAL_PINS NUM_DIGITAL_PINS #define BOARD_MAX_IO_PINS NUM_DIGITAL_PINS #if __GNUC__ < 7 //Already included on GCC 7 extern "C" char* sbrk(int incr); //Used to freeRam #endif #ifndef digitalPinToInterrupt inline uint32_t digitalPinToInterrupt(uint32_t Interrupt_pin) { return Interrupt_pin; } //This isn't included in the stm32duino libs (yet) #endif #elif defined(__SAMD21G18A__) #define BOARD_H "board_samd21.h" #define CORE_SAMD21 #define CORE_SAM #define INJ_CHANNELS 4 #define IGN_CHANNELS 4 #elif defined(__SAMC21J18A__) #define BOARD_H "board_samc21.h" #define CORE_SAMC21 #define CORE_SAM #elif defined(__SAME51J19A__) #define BOARD_H "board_same51.h" #define CORE_SAME51 #define CORE_SAM #define INJ_CHANNELS 8 #define IGN_CHANNELS 8 #else #error Incorrect board selected. Please select the correct board (Usually Mega 2560) and upload again #endif //This can only be included after the above section #include BOARD_H //Note that this is not a real file, it is defined in globals.h. //Handy bitsetting macros #define BIT_SET(a,b) ((a) |= (1U<<(b))) #define BIT_CLEAR(a,b) ((a) &= ~(1U<<(b))) #define BIT_CHECK(var,pos) !!((var) & (1U<<(pos))) #define BIT_TOGGLE(var,pos) ((var)^= 1UL << (pos)) #define BIT_WRITE(var, pos, bitvalue) ((bitvalue) ? BIT_SET((var), (pos)) : bitClear((var), (pos))) #define interruptSafe(c) (noInterrupts(); {c} interrupts();) //Wraps any code between nointerrupt and interrupt calls #define MS_IN_MINUTE 60000 #define US_IN_MINUTE 60000000 //Define the load algorithm #define LOAD_SOURCE_MAP 0 #define LOAD_SOURCE_TPS 1 #define LOAD_SOURCE_IMAPEMAP 2 //Define bit positions within engine variable #define BIT_ENGINE_RUN 0 // Engine running #define BIT_ENGINE_CRANK 1 // Engine cranking #define BIT_ENGINE_ASE 2 // after start enrichment (ASE) #define BIT_ENGINE_WARMUP 3 // Engine in warmup #define BIT_ENGINE_ACC 4 // in acceleration mode (TPS accel) #define BIT_ENGINE_DCC 5 // in deceleration mode #define BIT_ENGINE_MAPACC 6 // MAP acceleration mode #define BIT_ENGINE_MAPDCC 7 // MAP deceleration mode //Define masks for Status1 #define BIT_STATUS1_INJ1 0 //inj1 #define BIT_STATUS1_INJ2 1 //inj2 #define BIT_STATUS1_INJ3 2 //inj3 #define BIT_STATUS1_INJ4 3 //inj4 #define BIT_STATUS1_DFCO 4 //Deceleration fuel cutoff #define BIT_STATUS1_BOOSTCUT 5 //Fuel component of MAP based boost cut out #define BIT_STATUS1_TOOTHLOG1READY 6 //Used to flag if tooth log 1 is ready #define BIT_STATUS1_TOOTHLOG2READY 7 //Used to flag if tooth log 2 is ready (Log is not currently used) //Define masks for spark variable #define BIT_SPARK_HLAUNCH 0 //Hard Launch indicator #define BIT_SPARK_SLAUNCH 1 //Soft Launch indicator #define BIT_SPARK_HRDLIM 2 //Hard limiter indicator #define BIT_SPARK_SFTLIM 3 //Soft limiter indicator #define BIT_SPARK_BOOSTCUT 4 //Spark component of MAP based boost cut out #define BIT_SPARK_ERROR 5 // Error is detected #define BIT_SPARK_IDLE 6 // idle on #define BIT_SPARK_SYNC 7 // Whether engine has sync or not #define BIT_SPARK2_FLATSH 0 //Flat shift hard cut #define BIT_SPARK2_FLATSS 1 //Flat shift soft cut #define BIT_SPARK2_SPARK2_ACTIVE 2 #define BIT_SPARK2_UNUSED4 3 #define BIT_SPARK2_UNUSED5 4 #define BIT_SPARK2_UNUSED6 5 #define BIT_SPARK2_UNUSED7 6 #define BIT_SPARK2_UNUSED8 7 #define BIT_TIMER_1HZ 0 #define BIT_TIMER_4HZ 1 #define BIT_TIMER_10HZ 2 #define BIT_TIMER_15HZ 3 #define BIT_TIMER_30HZ 4 #define BIT_TIMER_1KHZ 7 #define BIT_STATUS3_RESET_PREVENT 0 //Indicates whether reset prevention is enabled #define BIT_STATUS3_NITROUS 1 #define BIT_STATUS3_FUEL2_ACTIVE 2 #define BIT_STATUS3_VSS_REFRESH 3 #define BIT_STATUS3_HALFSYNC 4 //shows if there is only sync from primary trigger, but not from secondary. #define BIT_STATUS3_NSQUIRTS1 5 #define BIT_STATUS3_NSQUIRTS2 6 #define BIT_STATUS3_NSQUIRTS3 7 #define BIT_STATUS4_WMI_EMPTY 0 //Indicates whether the WMI tank is empty #define BIT_STATUS4_VVT1_ERROR 1 //VVT1 cam angle within limits or not #define BIT_STATUS4_VVT2_ERROR 2 //VVT2 cam angle within limits or not #define BIT_STATUS4_FAN 3 //Fan Status #define BIT_STATUS4_BURNPENDING 4 #define BIT_STATUS4_STAGING_ACTIVE 5 #define BIT_STATUS4_COMMS_COMPAT 6 #define BIT_STATUS4_ALLOW_LEGACY_COMMS 7 #define BIT_AIRCON_REQUEST 0 //Indicates whether the A/C button is pressed #define BIT_AIRCON_COMPRESSOR 1 //Indicates whether the A/C compressor is running #define BIT_AIRCON_RPM_LOCKOUT 2 //Indicates the A/C is locked out due to the RPM being too high/low, or the post-high/post-low-RPM "stand-down" lockout period #define BIT_AIRCON_TPS_LOCKOUT 3 //Indicates the A/C is locked out due to high TPS, or the post-high-TPS "stand-down" lockout period #define BIT_AIRCON_TURNING_ON 4 //Indicates the A/C request is on (i.e. A/C button pressed), the lockouts are off, however the start delay has not yet elapsed. This gives the idle up time to kick in before the compressor. #define BIT_AIRCON_CLT_LOCKOUT 5 //Indicates the A/C is locked out either due to high coolant temp. #define BIT_AIRCON_FAN 6 //Indicates whether the A/C fan is running #define BIT_AIRCON_UNUSED8 7 #define VALID_MAP_MAX 1022 //The largest ADC value that is valid for the MAP sensor #define VALID_MAP_MIN 2 //The smallest ADC value that is valid for the MAP sensor #ifndef UNIT_TEST #define TOOTH_LOG_SIZE 127 #else #define TOOTH_LOG_SIZE 1 #endif #define O2_CALIBRATION_PAGE 2U #define IAT_CALIBRATION_PAGE 1U #define CLT_CALIBRATION_PAGE 0U // note the sequence of these defines which refernce the bits used in a byte has moved when the third trigger & engine cycle was incorporated #define COMPOSITE_LOG_PRI 0 #define COMPOSITE_LOG_SEC 1 #define COMPOSITE_LOG_THIRD 2 #define COMPOSITE_LOG_TRIG 3 #define COMPOSITE_LOG_SYNC 4 #define COMPOSITE_ENGINE_CYCLE 5 #define EGO_TYPE_OFF 0 #define EGO_TYPE_NARROW 1 #define EGO_TYPE_WIDE 2 #define INJ_TYPE_PORT 0 #define INJ_TYPE_TBODY 1 #define INJ_PAIRED 0 #define INJ_SEMISEQUENTIAL 1 #define INJ_BANKED 2 #define INJ_SEQUENTIAL 3 #define INJ_PAIR_13_24 0 #define INJ_PAIR_14_23 1 #define OUTPUT_CONTROL_DIRECT 0 #define OUTPUT_CONTROL_MC33810 10 #define IGN_MODE_WASTED 0 #define IGN_MODE_SINGLE 1 #define IGN_MODE_WASTEDCOP 2 #define IGN_MODE_SEQUENTIAL 3 #define IGN_MODE_ROTARY 4 #define SEC_TRIGGER_SINGLE 0 #define SEC_TRIGGER_4_1 1 #define SEC_TRIGGER_POLL 2 #define SEC_TRIGGER_5_3_2 3 #define ROTARY_IGN_FC 0 #define ROTARY_IGN_FD 1 #define ROTARY_IGN_RX8 2 #define BOOST_MODE_SIMPLE 0 #define BOOST_MODE_FULL 1 #define EN_BOOST_CONTROL_BARO 0 #define EN_BOOST_CONTROL_FIXED 1 #define WMI_MODE_SIMPLE 0 #define WMI_MODE_PROPORTIONAL 1 #define WMI_MODE_OPENLOOP 2 #define WMI_MODE_CLOSEDLOOP 3 #define HARD_CUT_FULL 0 #define HARD_CUT_ROLLING 1 #define EVEN_FIRE 0 #define ODD_FIRE 1 #define EGO_ALGORITHM_SIMPLE 0 #define EGO_ALGORITHM_PID 2 #define STAGING_MODE_TABLE 0 #define STAGING_MODE_AUTO 1 #define NITROUS_OFF 0 #define NITROUS_STAGE1 1 #define NITROUS_STAGE2 2 #define NITROUS_BOTH 3 #define PROTECT_CUT_OFF 0 #define PROTECT_CUT_IGN 1 #define PROTECT_CUT_FUEL 2 #define PROTECT_CUT_BOTH 3 #define PROTECT_IO_ERROR 7 #define AE_MODE_TPS 0 #define AE_MODE_MAP 1 #define AE_MODE_MULTIPLIER 0 #define AE_MODE_ADDER 1 #define KNOCK_MODE_OFF 0 #define KNOCK_MODE_DIGITAL 1 #define KNOCK_MODE_ANALOG 2 #define FUEL2_MODE_OFF 0 #define FUEL2_MODE_MULTIPLY 1 #define FUEL2_MODE_ADD 2 #define FUEL2_MODE_CONDITIONAL_SWITCH 3 #define FUEL2_MODE_INPUT_SWITCH 4 #define SPARK2_MODE_OFF 0 #define SPARK2_MODE_MULTIPLY 1 #define SPARK2_MODE_ADD 2 #define SPARK2_MODE_CONDITIONAL_SWITCH 3 #define SPARK2_MODE_INPUT_SWITCH 4 #define FUEL2_CONDITION_RPM 0 #define FUEL2_CONDITION_MAP 1 #define FUEL2_CONDITION_TPS 2 #define FUEL2_CONDITION_ETH 3 #define SPARK2_CONDITION_RPM 0 #define SPARK2_CONDITION_MAP 1 #define SPARK2_CONDITION_TPS 2 #define SPARK2_CONDITION_ETH 3 #define RESET_CONTROL_DISABLED 0 #define RESET_CONTROL_PREVENT_WHEN_RUNNING 1 #define RESET_CONTROL_PREVENT_ALWAYS 2 #define RESET_CONTROL_SERIAL_COMMAND 3 #define OPEN_LOOP_BOOST 0 #define CLOSED_LOOP_BOOST 1 #define SOFT_LIMIT_FIXED 0 #define SOFT_LIMIT_RELATIVE 1 #define VVT_MODE_ONOFF 0 #define VVT_MODE_OPEN_LOOP 1 #define VVT_MODE_CLOSED_LOOP 2 #define VVT_LOAD_MAP 0 #define VVT_LOAD_TPS 1 #define MULTIPLY_MAP_MODE_OFF 0 #define MULTIPLY_MAP_MODE_BARO 1 #define MULTIPLY_MAP_MODE_100 2 #define FOUR_STROKE 0 #define TWO_STROKE 1 #define GOING_LOW 0 #define GOING_HIGH 1 #define MAX_RPM 18000 /**< The maximum rpm that the ECU will attempt to run at. It is NOT related to the rev limiter, but is instead dictates how fast certain operations will be allowed to run. Lower number gives better performance */ #define BATTV_COR_MODE_WHOLE 0 #define BATTV_COR_MODE_OPENTIME 1 #define INJ1_CMD_BIT 0 #define INJ2_CMD_BIT 1 #define INJ3_CMD_BIT 2 #define INJ4_CMD_BIT 3 #define INJ5_CMD_BIT 4 #define INJ6_CMD_BIT 5 #define INJ7_CMD_BIT 6 #define INJ8_CMD_BIT 7 #define IGN1_CMD_BIT 0 #define IGN2_CMD_BIT 1 #define IGN3_CMD_BIT 2 #define IGN4_CMD_BIT 3 #define IGN5_CMD_BIT 4 #define IGN6_CMD_BIT 5 #define IGN7_CMD_BIT 6 #define IGN8_CMD_BIT 7 #define ENGINE_PROTECT_BIT_RPM 0 #define ENGINE_PROTECT_BIT_MAP 1 #define ENGINE_PROTECT_BIT_OIL 2 #define ENGINE_PROTECT_BIT_AFR 3 #define ENGINE_PROTECT_BIT_COOLANT 4 #define CALIBRATION_TABLE_SIZE 512 ///< Calibration table size for CLT, IAT, O2 #define CALIBRATION_TEMPERATURE_OFFSET 40 /**< All temperature measurements are stored offset by 40 degrees. This is so we can use an unsigned byte (0-255) to represent temperature ranges from -40 to 215 */ #define OFFSET_FUELTRIM 127 ///< The fuel trim tables are offset by 128 to allow for -128 to +128 values #define OFFSET_IGNITION 40 ///< Ignition values from the main spark table are offset 40 degrees downwards to allow for negative spark timing #define SERIAL_BUFFER_THRESHOLD 32 ///< When the serial buffer is filled to greater than this threshold value, the serial processing operations will be performed more urgently in order to avoid it overflowing. Serial buffer is 64 bytes long, so the threshold is set at half this as a reasonable figure #define LOGGER_CSV_SEPARATOR_SEMICOLON 0 #define LOGGER_CSV_SEPARATOR_COMMA 1 #define LOGGER_CSV_SEPARATOR_TAB 2 #define LOGGER_CSV_SEPARATOR_SPACE 3 #define LOGGER_DISABLED 0 #define LOGGER_CSV 1 #define LOGGER_BINARY 2 #define LOGGER_RATE_1HZ 0 #define LOGGER_RATE_4HZ 1 #define LOGGER_RATE_10HZ 2 #define LOGGER_RATE_30HZ 3 #define LOGGER_FILENAMING_OVERWRITE 0 #define LOGGER_FILENAMING_DATETIME 1 #define LOGGER_FILENAMING_SEQENTIAL 2 extern const char TSfirmwareVersion[] PROGMEM; extern const byte data_structure_version; //This identifies the data structure when reading / writing. Now in use: CURRENT_DATA_VERSION (migration on-the fly) ? extern struct table3d16RpmLoad fuelTable; //16x16 fuel map extern struct table3d16RpmLoad fuelTable2; //16x16 fuel map extern struct table3d16RpmLoad ignitionTable; //16x16 ignition map extern struct table3d16RpmLoad ignitionTable2; //16x16 ignition map extern struct table3d16RpmLoad afrTable; //16x16 afr target map extern struct table3d8RpmLoad stagingTable; //8x8 fuel staging table extern struct table3d8RpmLoad boostTable; //8x8 boost map extern struct table3d8RpmLoad boostTableLookupDuty; //8x8 boost map extern struct table3d8RpmLoad vvtTable; //8x8 vvt map extern struct table3d8RpmLoad vvt2Table; //8x8 vvt map extern struct table3d8RpmLoad wmiTable; //8x8 wmi map typedef table3d6RpmLoad trimTable3d; extern trimTable3d trim1Table; //6x6 Fuel trim 1 map extern trimTable3d trim2Table; //6x6 Fuel trim 2 map extern trimTable3d trim3Table; //6x6 Fuel trim 3 map extern trimTable3d trim4Table; //6x6 Fuel trim 4 map extern trimTable3d trim5Table; //6x6 Fuel trim 5 map extern trimTable3d trim6Table; //6x6 Fuel trim 6 map extern trimTable3d trim7Table; //6x6 Fuel trim 7 map extern trimTable3d trim8Table; //6x6 Fuel trim 8 map extern struct table3d4RpmLoad dwellTable; //4x4 Dwell map extern struct table2D taeTable; //4 bin TPS Acceleration Enrichment map (2D) extern struct table2D maeTable; extern struct table2D WUETable; //10 bin Warm Up Enrichment map (2D) extern struct table2D ASETable; //4 bin After Start Enrichment map (2D) extern struct table2D ASECountTable; //4 bin After Start duration map (2D) extern struct table2D PrimingPulseTable; //4 bin Priming pulsewidth map (2D) extern struct table2D crankingEnrichTable; //4 bin cranking Enrichment map (2D) extern struct table2D dwellVCorrectionTable; //6 bin dwell voltage correction (2D) extern struct table2D injectorVCorrectionTable; //6 bin injector voltage correction (2D) extern struct table2D injectorAngleTable; //4 bin injector timing curve (2D) extern struct table2D IATDensityCorrectionTable; //9 bin inlet air temperature density correction (2D) extern struct table2D baroFuelTable; //8 bin baro correction curve (2D) extern struct table2D IATRetardTable; //6 bin ignition adjustment based on inlet air temperature (2D) extern struct table2D idleTargetTable; //10 bin idle target table for idle timing (2D) extern struct table2D idleAdvanceTable; //6 bin idle advance adjustment table based on RPM difference (2D) extern struct table2D CLTAdvanceTable; //6 bin ignition adjustment based on coolant temperature (2D) extern struct table2D rotarySplitTable; //8 bin ignition split curve for rotary leading/trailing (2D) extern struct table2D flexFuelTable; //6 bin flex fuel correction table for fuel adjustments (2D) extern struct table2D flexAdvTable; //6 bin flex fuel correction table for timing advance (2D) extern struct table2D flexBoostTable; //6 bin flex fuel correction table for boost adjustments (2D) extern struct table2D fuelTempTable; //6 bin fuel temperature correction table for fuel adjustments (2D) extern struct table2D knockWindowStartTable; extern struct table2D knockWindowDurationTable; extern struct table2D oilPressureProtectTable; extern struct table2D wmiAdvTable; //6 bin wmi correction table for timing advance (2D) extern struct table2D coolantProtectTable; //6 bin coolant temperature protection table for engine protection (2D) extern struct table2D fanPWMTable; //These are for the direct port manipulation of the injectors, coils and aux outputs extern volatile PORT_TYPE *inj1_pin_port; extern volatile PINMASK_TYPE inj1_pin_mask; extern volatile PORT_TYPE *inj2_pin_port; extern volatile PINMASK_TYPE inj2_pin_mask; extern volatile PORT_TYPE *inj3_pin_port; extern volatile PINMASK_TYPE inj3_pin_mask; extern volatile PORT_TYPE *inj4_pin_port; extern volatile PINMASK_TYPE inj4_pin_mask; extern volatile PORT_TYPE *inj5_pin_port; extern volatile PINMASK_TYPE inj5_pin_mask; extern volatile PORT_TYPE *inj6_pin_port; extern volatile PINMASK_TYPE inj6_pin_mask; extern volatile PORT_TYPE *inj7_pin_port; extern volatile PINMASK_TYPE inj7_pin_mask; extern volatile PORT_TYPE *inj8_pin_port; extern volatile PINMASK_TYPE inj8_pin_mask; extern volatile PORT_TYPE *ign1_pin_port; extern volatile PINMASK_TYPE ign1_pin_mask; extern volatile PORT_TYPE *ign2_pin_port; extern volatile PINMASK_TYPE ign2_pin_mask; extern volatile PORT_TYPE *ign3_pin_port; extern volatile PINMASK_TYPE ign3_pin_mask; extern volatile PORT_TYPE *ign4_pin_port; extern volatile PINMASK_TYPE ign4_pin_mask; extern volatile PORT_TYPE *ign5_pin_port; extern volatile PINMASK_TYPE ign5_pin_mask; extern volatile PORT_TYPE *ign6_pin_port; extern volatile PINMASK_TYPE ign6_pin_mask; extern volatile PORT_TYPE *ign7_pin_port; extern volatile PINMASK_TYPE ign7_pin_mask; extern volatile PORT_TYPE *ign8_pin_port; extern volatile PINMASK_TYPE ign8_pin_mask; extern volatile PORT_TYPE *tach_pin_port; extern volatile PINMASK_TYPE tach_pin_mask; extern volatile PORT_TYPE *pump_pin_port; extern volatile PINMASK_TYPE pump_pin_mask; extern volatile PORT_TYPE *flex_pin_port; extern volatile PINMASK_TYPE flex_pin_mask; extern volatile PORT_TYPE *triggerPri_pin_port; extern volatile PINMASK_TYPE triggerPri_pin_mask; extern volatile PORT_TYPE *triggerSec_pin_port; extern volatile PINMASK_TYPE triggerSec_pin_mask; extern volatile PORT_TYPE *triggerThird_pin_port; extern volatile PINMASK_TYPE triggerThird_pin_mask; extern byte triggerInterrupt; extern byte triggerInterrupt2; extern byte triggerInterrupt3; //These need to be here as they are used in both speeduino.ino and scheduler.ino extern byte channelInjEnabled; extern int ignition1EndAngle; extern int ignition2EndAngle; extern int ignition3EndAngle; extern int ignition4EndAngle; extern int ignition5EndAngle; extern int ignition6EndAngle; extern int ignition7EndAngle; extern int ignition8EndAngle; extern int ignition1StartAngle; extern int ignition2StartAngle; extern int ignition3StartAngle; extern int ignition4StartAngle; extern int ignition5StartAngle; extern int ignition6StartAngle; extern int ignition7StartAngle; extern int ignition8StartAngle; extern bool initialisationComplete; //Tracks whether the setup() function has run completely extern byte fpPrimeTime; //The time (in seconds, based on currentStatus.secl) that the fuel pump started priming extern uint8_t softLimitTime; //The time (in 0.1 seconds, based on seclx10) that the soft limiter started extern volatile uint16_t mainLoopCount; extern unsigned long revolutionTime; //The time in uS that one revolution would take at current speed (The time tooth 1 was last seen, minus the time it was seen prior to that) extern volatile unsigned long timer5_overflow_count; //Increments every time counter 5 overflows. Used for the fast version of micros() extern volatile unsigned long ms_counter; //A counter that increments once per ms extern uint16_t fixedCrankingOverride; extern bool clutchTrigger; extern bool previousClutchTrigger; extern volatile uint32_t toothHistory[TOOTH_LOG_SIZE]; extern volatile uint8_t compositeLogHistory[TOOTH_LOG_SIZE]; extern volatile bool fpPrimed; //Tracks whether or not the fuel pump priming has been completed yet extern volatile bool injPrimed; //Tracks whether or not the injector priming has been completed yet extern volatile unsigned int toothHistoryIndex; extern unsigned long currentLoopTime; /**< The time (in uS) that the current mainloop started */ extern volatile uint16_t ignitionCount; /**< The count of ignition events that have taken place since the engine started */ //The below shouldn't be needed and probably should be cleaned up, but the Atmel SAM (ARM) boards use a specific type for the trigger edge values rather than a simple byte/int #if defined(CORE_SAMD21) extern PinStatus primaryTriggerEdge; extern PinStatus secondaryTriggerEdge; extern PinStatus tertiaryTriggerEdge; #else extern byte primaryTriggerEdge; extern byte secondaryTriggerEdge; extern byte tertiaryTriggerEdge; #endif extern int CRANK_ANGLE_MAX; extern int CRANK_ANGLE_MAX_IGN; extern int CRANK_ANGLE_MAX_INJ; ///< The number of crank degrees that the system track over. 360 for wasted / timed batch and 720 for sequential extern volatile uint32_t runSecsX10; /**< Counter of seconds since cranking commenced (similar to runSecs) but in increments of 0.1 seconds */ extern volatile uint32_t seclx10; /**< Counter of seconds since powered commenced (similar to secl) but in increments of 0.1 seconds */ extern volatile byte HWTest_INJ; /**< Each bit in this variable represents one of the injector channels and it's HW test status */ extern volatile byte HWTest_INJ_50pc; /**< Each bit in this variable represents one of the injector channels and it's 50% HW test status */ extern volatile byte HWTest_IGN; /**< Each bit in this variable represents one of the ignition channels and it's HW test status */ extern volatile byte HWTest_IGN_50pc; /**< Each bit in this variable represents one of the ignition channels and it's 50% HW test status */ extern byte maxIgnOutputs; /**< Used for rolling rev limiter to indicate how many total ignition channels should currently be firing */ extern byte resetControl; ///< resetControl needs to be here (as global) because using the config page (4) directly can prevent burning the setting extern volatile byte TIMER_mask; extern volatile byte LOOP_TIMER; //These functions all do checks on a pin to determine if it is already in use by another (higher importance) function #define pinIsInjector(pin) ( ((pin) == pinInjector1) || ((pin) == pinInjector2) || ((pin) == pinInjector3) || ((pin) == pinInjector4) || ((pin) == pinInjector5) || ((pin) == pinInjector6) || ((pin) == pinInjector7) || ((pin) == pinInjector8) ) #define pinIsIgnition(pin) ( ((pin) == pinCoil1) || ((pin) == pinCoil2) || ((pin) == pinCoil3) || ((pin) == pinCoil4) || ((pin) == pinCoil5) || ((pin) == pinCoil6) || ((pin) == pinCoil7) || ((pin) == pinCoil8) ) //#define pinIsOutput(pin) ( pinIsInjector((pin)) || pinIsIgnition((pin)) || ((pin) == pinFuelPump) || ((pin) == pinFan) || ((pin) == pinAirConComp) || ((pin) == pinAirConFan)|| ((pin) == pinVVT_1) || ((pin) == pinVVT_2) || ( ((pin) == pinBoost) && configPage6.boostEnabled) || ((pin) == pinIdle1) || ((pin) == pinIdle2) || ((pin) == pinTachOut) || ((pin) == pinStepperEnable) || ((pin) == pinStepperStep) ) #define pinIsSensor(pin) ( ((pin) == pinCLT) || ((pin) == pinIAT) || ((pin) == pinMAP) || ((pin) == pinTPS) || ((pin) == pinO2) || ((pin) == pinBat) || (((pin) == pinFlex) && (configPage2.flexEnabled != 0)) ) //#define pinIsUsed(pin) ( pinIsSensor((pin)) || pinIsOutput((pin)) || pinIsReserved((pin)) ) /** The status struct with current values for all 'live' variables. * In current version this is 64 bytes. Instantiated as global currentStatus. * int *ADC (Analog-to-digital value / count) values contain the "raw" value from AD conversion, which get converted to * unit based values in similar variable(s) without ADC part in name (see sensors.ino for reading of sensors). */ struct statuses { volatile bool hasSync; /**< Flag for crank/cam position being known by decoders (See decoders.ino). This is used for sanity checking e.g. before logging tooth history or reading some sensors and computing readings. */ uint16_t RPM; ///< RPM - Current Revs per minute byte RPMdiv100; ///< RPM value scaled (divided by 100) to fit a byte (0-255, e.g. 12000 => 120) long longRPM; ///< RPM as long int (gets assigned to / maintained in statuses.RPM as well) int mapADC; int baroADC; long MAP; ///< Manifold absolute pressure. Has to be a long for PID calcs (Boost control) int16_t EMAP; ///< EMAP ... (See @ref config6.useEMAP for EMAP enablement) int16_t EMAPADC; byte baro; ///< Barometric pressure is simply the initial MAP reading, taken before the engine is running. Alternatively, can be taken from an external sensor byte TPS; /**< The current TPS reading (0% - 100%). Is the tpsADC value after the calibration is applied */ byte tpsADC; /**< byte (valued: 0-255) representation of the TPS. Downsampled from the original 10-bit (0-1023) reading, but before any calibration is applied */ int16_t tpsDOT; /**< TPS delta over time. Measures the % per second that the TPS is changing. Note that is signed value, because TPSdot can be also negative */ byte TPSlast; /**< The previous TPS reading */ int16_t mapDOT; /**< MAP delta over time. Measures the kpa per second that the MAP is changing. Note that is signed value, because MAPdot can be also negative */ volatile int rpmDOT; /**< RPM delta over time (RPM increase / s ?) */ byte VE; /**< The current VE value being used in the fuel calculation. Can be the same as VE1 or VE2, or a calculated value of both. */ byte VE1; /**< The VE value from fuel table 1 */ byte VE2; /**< The VE value from fuel table 2, if in use (and required conditions are met) */ byte O2; /**< Primary O2 sensor reading */ byte O2_2; /**< Secondary O2 sensor reading */ int coolant; /**< Coolant temperature reading */ int cltADC; int IAT; /**< Inlet air temperature reading */ int iatADC; int batADC; int O2ADC; int O2_2ADC; int dwell; ///< dwell (coil primary winding/circuit on) time (in ms * 10 ? See @ref correctionsDwell) volatile int16_t actualDwell; ///< actual dwell time if new ignition mode is used (in uS) byte dwellCorrection; /**< The amount of correction being applied to the dwell time (in unit ...). */ byte battery10; /**< The current BRV in volts (multiplied by 10. Eg 12.5V = 125) */ int8_t advance; /**< The current advance value being used in the spark calculation. Can be the same as advance1 or advance2, or a calculated value of both */ int8_t advance1; /**< The advance value from ignition table 1 */ int8_t advance2; /**< The advance value from ignition table 2 */ uint16_t corrections; /**< The total current corrections % amount */ uint16_t AEamount; /**< The amount of acceleration enrichment currently being applied. 100=No change. Varies above 255 */ byte egoCorrection; /**< The amount of closed loop AFR enrichment currently being applied */ byte wueCorrection; /**< The amount of warmup enrichment currently being applied */ byte batCorrection; /**< The amount of battery voltage enrichment currently being applied */ byte iatCorrection; /**< The amount of inlet air temperature adjustment currently being applied */ byte baroCorrection; /**< The amount of correction being applied for the current baro reading */ byte launchCorrection; /**< The amount of correction being applied if launch control is active */ byte flexCorrection; /**< Amount of correction being applied to compensate for ethanol content */ byte fuelTempCorrection; /**< Amount of correction being applied to compensate for fuel temperature */ int8_t flexIgnCorrection;/**< Amount of additional advance being applied based on flex. Note the type as this allows for negative values */ byte afrTarget; /**< Current AFR Target looked up from AFR target table (x10 ? See @ref afrTable)*/ byte CLIdleTarget; /**< The target idle RPM (when closed loop idle control is active) */ bool idleUpActive; /**< Whether the externally controlled idle up is currently active */ bool CTPSActive; /**< Whether the externally controlled closed throttle position sensor is currently active */ volatile byte ethanolPct; /**< Ethanol reading (if enabled). 0 = No ethanol, 100 = pure ethanol. Eg E85 = 85. */ volatile int8_t fuelTemp; unsigned long AEEndTime; /**< The target end time used whenever AE (acceleration enrichment) is turned on */ volatile byte status1; ///< Status bits (See BIT_STATUS1_* defines on top of this file) volatile byte spark; ///< Spark status/control indicator bits (launch control, boost cut, spark errors, See BIT_SPARK_* defines) volatile byte spark2; ///< Spark 2 ... (See also @ref config10 spark2* members and BIT_SPARK2_* defines) uint8_t engine; ///< Engine status bits (See BIT_ENGINE_* defines on top of this file) unsigned int PW1; ///< In uS unsigned int PW2; ///< In uS unsigned int PW3; ///< In uS unsigned int PW4; ///< In uS unsigned int PW5; ///< In uS unsigned int PW6; ///< In uS unsigned int PW7; ///< In uS unsigned int PW8; ///< In uS volatile byte runSecs; /**< Counter of seconds since cranking commenced (Maxes out at 255 to prevent overflow) */ volatile byte secl; /**< Counter incrementing once per second. Will overflow after 255 and begin again. This is used by TunerStudio to maintain comms sync */ volatile uint32_t loopsPerSecond; /**< A performance indicator showing the number of main loops that are being executed each second */ bool launchingSoft; /**< Indicator showing whether soft launch control adjustments are active */ bool launchingHard; /**< Indicator showing whether hard launch control adjustments are active */ uint16_t freeRAM; unsigned int clutchEngagedRPM; /**< The RPM at which the clutch was last depressed. Used for distinguishing between launch control and flat shift */ bool flatShiftingHard; volatile uint32_t startRevolutions; /**< A counter for how many revolutions have been completed since sync was achieved. */ uint16_t boostTarget; byte testOutputs; ///< Test Output bits (only first bit used/tested ?) bool testActive; // Not in use ? Replaced by testOutputs ? uint16_t boostDuty; ///< Boost Duty percentage value * 100 to give 2 points of precision byte idleLoad; ///< Either the current steps or current duty cycle for the idle control uint16_t canin[16]; ///< 16bit raw value of selected canin data for channels 0-15 uint8_t current_caninchannel = 0; /**< Current CAN channel, defaults to 0 */ uint16_t crankRPM = 400; /**< The actual cranking RPM limit. This is derived from the value in the config page, but saves us multiplying it every time it's used (Config page value is stored divided by 10) */ volatile byte status3; ///< Status bits (See BIT_STATUS3_* defines on top of this file) int16_t flexBoostCorrection; /**< Amount of boost added based on flex */ byte nitrous_status; byte nSquirts; ///< Number of injector squirts per cycle (per injector) byte nChannels; /**< Number of fuel and ignition channels. */ int16_t fuelLoad; int16_t fuelLoad2; int16_t ignLoad; int16_t ignLoad2; bool fuelPumpOn; /**< Indicator showing the current status of the fuel pump */ volatile byte syncLossCounter; byte knockRetard; bool knockActive; bool toothLogEnabled; byte compositeTriggerUsed; // 0 means composite logger disabled, 2 means use secondary input (1st cam), 3 means use tertiary input (2nd cam), 4 means log both cams together int16_t vvt1Angle; //Has to be a long for PID calcs (CL VVT control) byte vvt1TargetAngle; long vvt1Duty; //Has to be a long for PID calcs (CL VVT control) uint16_t injAngle; byte ASEValue; uint16_t vss; /**< Current speed reading. Natively stored in kph and converted to mph in TS if required */ bool idleUpOutputActive; /**< Whether the idle up output is currently active */ byte gear; /**< Current gear (Calculated from vss) */ byte fuelPressure; /**< Fuel pressure in PSI */ byte oilPressure; /**< Oil pressure in PSI */ byte engineProtectStatus; byte fanDuty; byte wmiPW; volatile byte status4; ///< Status bits (See BIT_STATUS4_* defines on top of this file) int16_t vvt2Angle; //Has to be a long for PID calcs (CL VVT control) byte vvt2TargetAngle; long vvt2Duty; //Has to be a long for PID calcs (CL VVT control) byte outputsStatus; byte TS_SD_Status; //TunerStudios SD card status byte airConStatus; }; /** Page 2 of the config - mostly variables that are required for fuel. * These are "non-live" EFI setting, engine and "system" variables that remain fixed once sent * (and stored to e.g. EEPROM) from configuration/tuning SW (from outside by USBserial/bluetooth). * Contains a lots of *Min, *Max (named) variables to constrain values to sane ranges. * See the ini file for further reference. * */ struct config2 { byte aseTaperTime; byte aeColdPct; //AE cold clt modifier % byte aeColdTaperMin; //AE cold modifier, taper start temp (full modifier, was ASE in early versions) byte aeMode : 2; /**< Acceleration Enrichment mode. 0 = TPS, 1 = MAP. Values 2 and 3 reserved for potential future use (ie blended TPS / MAP) */ byte battVCorMode : 1; byte SoftLimitMode : 1; byte useTachoSweep : 1; byte aeApplyMode : 1; ///< Acceleration enrichment calc mode: 0 = Multiply | 1 = Add (AE_MODE_ADDER) byte multiplyMAP : 2; ///< MAP value processing: 0 = off, 1 = div by currentStatus.baro, 2 = div by 100 (to gain usable value) byte wueValues[10]; ///< Warm up enrichment array (10 bytes, transferred to @ref WUETable) byte crankingPct; ///< Cranking enrichment (See @ref config10, updates.ino) byte pinMapping; ///< The board / ping mapping number / id to be used (See: @ref setPinMapping in init.ino) byte tachoPin : 6; ///< Custom pin setting for tacho output (if != 0, override copied to pinTachOut, which defaults to board assigned tach pin) byte tachoDiv : 2; ///< Whether to change the tacho speed ("half speed tacho" ?) byte tachoDuration; //The duration of the tacho pulse in mS byte maeThresh; /**< The MAPdot threshold that must be exceeded before AE is engaged */ byte taeThresh; /**< The TPSdot threshold that must be exceeded before AE is engaged */ byte aeTime; byte taeMinChange; /**< The minimum change in TPS that must be made before AE is engaged */ byte maeMinChange; /**< The minimum change in MAP that must be made before AE is engaged */ //Display config bits byte displayB1 : 4; //23 byte displayB2 : 4; byte reqFuel; //24 byte divider; byte injTiming : 1; ///< Injector timing (aka. injector staging) 0=simultaneous, 1=alternating byte crkngAddCLTAdv : 1; byte includeAFR : 1; //< Enable AFR compensation ? (See also @ref config2.incorporateAFR) byte hardCutType : 1; byte ignAlgorithm : 3; byte indInjAng : 1; byte injOpen; ///< Injector opening time (ms * 10) uint16_t injAng[4]; //config1 in ini byte mapSample : 2; ///< MAP sampling method (0=Instantaneous, 1=Cycle Average, 2=Cycle Minimum, 4=Ign. event average, See sensors.ino) byte strokes : 1; ///< Engine cycle type: four-stroke (0) / two-stroke (1) byte injType : 1; ///< Injector type 0=Port (INJ_TYPE_PORT), 1=Throttle Body / TBI (INJ_TYPE_TBODY) byte nCylinders : 4; ///< Number of cylinders //config2 in ini byte fuelAlgorithm : 3;///< Fuel algorithm - 0=Manifold pressure/MAP (LOAD_SOURCE_MAP, default, proven), 1=Throttle/TPS (LOAD_SOURCE_TPS), 2=IMAP/EMAP (LOAD_SOURCE_IMAPEMAP) byte fixAngEnable : 1; ///< Whether fixed/locked timing is enabled (0=disable, 1=enable, See @ref configPage4.FixAng) byte nInjectors : 4; ///< Number of injectors //config3 in ini byte engineType : 1; ///< Engine crank/ign phasing type: 0=even fire, 1=odd fire byte flexEnabled : 1; ///< Enable Flex fuel sensing (pin / interrupt) byte legacyMAP : 1; ///< Legacy MAP reading behaviour byte baroCorr : 1; // Unused ? byte injLayout : 2; /**< Injector Layout - 0=INJ_PAIRED (number outputs == number cyls/2, timed over 1 crank rev), 1=INJ_SEMISEQUENTIAL (like paired, but number outputs == number cyls, only for 4 cyl), 2=INJ_BANKED (2 outputs are used), 3=INJ_SEQUENTIAL (number outputs == number cyls, timed over full cycle, 2 crank revs) */ byte perToothIgn : 1; ///< Experimental / New ignition mode ... (?) (See decoders.ino) byte dfcoEnabled : 1; ///< Whether or not DFCO (deceleration fuel cut-off) is turned on byte aeColdTaperMax; ///< AE cold modifier, taper end temp (no modifier applied, was primePulse in early versions) byte dutyLim; byte flexFreqLow; //Lowest valid frequency reading from the flex sensor byte flexFreqHigh; //Highest valid frequency reading from the flex sensor byte boostMaxDuty; byte tpsMin; byte tpsMax; int8_t mapMin; //Must be signed uint16_t mapMax; byte fpPrime; ///< Time (In seconds) that the fuel pump should be primed for on power up byte stoich; ///< Stoichiometric ratio (x10, so e.g. 14.7 => 147) uint16_t oddfire2; ///< The ATDC angle of channel 2 for oddfire uint16_t oddfire3; ///< The ATDC angle of channel 3 for oddfire uint16_t oddfire4; ///< The ATDC angle of channel 4 for oddfire byte idleUpPin : 6; byte idleUpPolarity : 1; byte idleUpEnabled : 1; byte idleUpAdder; byte aeTaperMin; byte aeTaperMax; byte iacCLminValue; byte iacCLmaxValue; byte boostMinDuty; int8_t baroMin; //Must be signed uint16_t baroMax; int8_t EMAPMin; //Must be signed uint16_t EMAPMax; byte fanWhenOff : 1; ///< Allow running fan with engine off: 0 = Only run fan when engine is running, 1 = Allow even with engine off byte fanWhenCranking : 1; ///< Set whether the fan output will stay on when the engine is cranking (0=force off, 1=allow on) byte useDwellMap : 1; ///< Setting to change between fixed dwell value and dwell map (0=Fixed value from @ref configPage4.dwellRun, 1=Use @ref dwellTable) byte fanEnable : 2; ///< Fan mode. 0=Off, 1=On/Off, 2=PWM byte rtc_mode : 2; // Unused ? byte incorporateAFR : 1; ///< Enable AFR target (stoich/afrtgt) compensation in PW calculation byte asePct[4]; ///< Afterstart enrichment values (%) byte aseCount[4]; ///< Afterstart enrichment cycles. This is the number of ignition cycles that the afterstart enrichment % lasts for byte aseBins[4]; ///< Afterstart enrichment temperatures (x-axis) for (target) enrichment values byte primePulse[4];//Priming pulsewidth values (mS, copied to @ref PrimingPulseTable) byte primeBins[4]; //Priming temperatures (source,x-axis) byte CTPSPin : 6; byte CTPSPolarity : 1; byte CTPSEnabled : 1; byte idleAdvEnabled : 2; byte idleAdvAlgorithm : 1; byte idleAdvDelay : 5; byte idleAdvRPM; byte idleAdvTPS; byte injAngRPM[4]; byte idleTaperTime; byte dfcoDelay; byte dfcoMinCLT; //VSS Stuff byte vssMode : 2; ///< VSS (Vehicle speed sensor) mode (0=none, 1=CANbus, 2,3=Interrupt driven) byte vssPin : 6; ///< VSS (Vehicle speed sensor) pin number uint16_t vssPulsesPerKm; ///< VSS (Vehicle speed sensor) pulses per Km byte vssSmoothing; uint16_t vssRatio1; uint16_t vssRatio2; uint16_t vssRatio3; uint16_t vssRatio4; uint16_t vssRatio5; uint16_t vssRatio6; byte idleUpOutputEnabled : 1; byte idleUpOutputInv : 1; byte idleUpOutputPin : 6; byte tachoSweepMaxRPM; byte primingDelay; byte iacTPSlimit; byte iacRPMlimitHysteresis; int8_t rtc_trim; byte idleAdvVss; byte mapSwitchPoint; byte canBMWCluster : 1; byte canVAGCluster : 1; byte enableCluster1 : 1; byte enableCluster2 : 1; byte vssAuxCh : 4; byte decelAmount; #if defined(CORE_AVR) }; #else } __attribute__((__packed__)); //The 32 bit systems require all structs to be fully packed #endif /** Page 4 of the config - variables required for ignition and rpm/crank phase /cam phase decoding. * See the ini file for further reference. */ struct config4 { int16_t triggerAngle; ///< Angle (ATDC) when tooth No:1 on the primary wheel sends signal (-360 to +360 deg.) int8_t FixAng; ///< Fixed Ignition angle value (enabled by @ref configPage2.fixAngEnable, copied to ignFixValue, Negative values allowed, See corrections.ino) int8_t CrankAng; ///< Fixed start-up/cranking ignition angle (See: corrections.ino) byte TrigAngMul; ///< Multiplier for non evenly divisible tooth counts. byte TrigEdge : 1; ///< Primary (RPM1) Trigger Edge - 0 - RISING, 1 = FALLING (Copied from this config to primaryTriggerEdge) byte TrigSpeed : 1; ///< Primary (RPM1) Trigger speed - 0 = crank speed (CRANK_SPEED), 1 = cam speed (CAM_SPEED), See decoders.ino byte IgInv : 1; ///< Ignition signal invert (?) (GOING_LOW=0 (default by init.ino) / GOING_HIGH=1 ) byte TrigPattern : 5; ///< Decoder configured (DECODER_MISSING_TOOTH, DECODER_BASIC_DISTRIBUTOR, DECODER_GM7X, ... See init.ino) byte TrigEdgeSec : 1; ///< Secondary (RPM2) Trigger Edge (See RPM1) byte fuelPumpPin : 6; ///< Fuel pump pin (copied as override to pinFuelPump, defaults to board default, See: init.ino) byte useResync : 1; byte sparkDur; ///< Spark duration in ms * 10 byte trigPatternSec : 7; ///< Mode for Missing tooth secondary trigger - 0=single tooth cam wheel (SEC_TRIGGER_SINGLE), 1=4-1 (SEC_TRIGGER_4_1) or 2=poll level mode (SEC_TRIGGER_POLL) byte PollLevelPolarity : 1; //for poll level cam trigger. Sets if the cam trigger is supposed to be high or low for revolution one. uint8_t bootloaderCaps; //Capabilities of the bootloader over stock. e.g., 0=Stock, 1=Reset protection, etc. byte resetControlConfig : 2; /** Which method of reset control to use - 0=Disabled (RESET_CONTROL_DISABLED), 1=Prevent When Running (RESET_CONTROL_PREVENT_WHEN_RUNNING), 2=Prevent Always (RESET_CONTROL_PREVENT_ALWAYS), 3=Serial Command (RESET_CONTROL_SERIAL_COMMAND) - Copied to resetControl (See init.ino, utilities.ino) */ byte resetControlPin : 6; byte StgCycles; //The number of initial cycles before the ignition should fire when first cranking byte boostType : 1; ///< Boost Control type: 0=Open loop (OPEN_LOOP_BOOST), 1=closed loop (CLOSED_LOOP_BOOST) byte useDwellLim : 1; //Whether the dwell limiter is off or on byte sparkMode : 3; /** Ignition/Spark output mode - 0=Wasted spark (IGN_MODE_WASTED), 1=single channel (IGN_MODE_SINGLE), 2=Wasted COP (IGN_MODE_WASTEDCOP), 3=Sequential (IGN_MODE_SEQUENTIAL), 4=Rotary (IGN_MODE_ROTARY) */ byte triggerFilter : 2; //The mode of trigger filter being used (0=Off, 1=Light (Not currently used), 2=Normal, 3=Aggressive) byte ignCranklock : 1; //Whether or not the ignition timing during cranking is locked to a CAS (crank) pulse. Only currently valid for Basic distributor and 4G63. byte dwellCrank; ///< Dwell time whilst cranking byte dwellRun; ///< Dwell time whilst running byte triggerTeeth; ///< The full count of teeth on the trigger wheel if there were no gaps byte triggerMissingTeeth; ///< The size of the tooth gap (ie number of missing teeth) byte crankRPM; ///< RPM below which the engine is considered to be cranking byte floodClear; ///< TPS (raw adc count? % ?) value that triggers flood clear mode (No fuel whilst cranking, See @ref correctionFloodClear()) byte SoftRevLim; ///< Soft rev limit (RPM/100) byte SoftLimRetard; ///< Amount soft limit (ignition) retard (degrees) byte SoftLimMax; ///< Time the soft limit can run (units 0.1S) byte HardRevLim; ///< Hard rev limit (RPM/100) byte taeBins[4]; ///< TPS based acceleration enrichment bins (Unit: %/s) byte taeValues[4]; ///< TPS based acceleration enrichment rates (Unit: % to add), values matched to thresholds of taeBins byte wueBins[10]; ///< Warmup Enrichment bins (Values are in @ref configPage2.wueValues OLD:configTable1) byte dwellLimit; byte dwellCorrectionValues[6]; ///< Correction table for dwell vs battery voltage byte iatRetBins[6]; ///< Inlet Air Temp timing retard curve bins (Unit: ...) byte iatRetValues[6]; ///< Inlet Air Temp timing retard curve values (Unit: ...) byte dfcoRPM; ///< RPM at which DFCO turns off/on at byte dfcoHyster; //Hysteris RPM for DFCO byte dfcoTPSThresh; //TPS must be below this figure for DFCO to engage (Unit: ...) byte ignBypassEnabled : 1; //Whether or not the ignition bypass is enabled byte ignBypassPin : 6; //Pin the ignition bypass is activated on byte ignBypassHiLo : 1; //Whether this should be active high or low. byte ADCFILTER_TPS; byte ADCFILTER_CLT; byte ADCFILTER_IAT; byte ADCFILTER_O2; byte ADCFILTER_BAT; byte ADCFILTER_MAP; //This is only used on Instantaneous MAP readings and is intentionally very weak to allow for faster response byte ADCFILTER_BARO; byte cltAdvBins[6]; /**< Coolant Temp timing advance curve bins */ byte cltAdvValues[6]; /**< Coolant timing advance curve values. These are translated by 15 to allow for negative values */ byte maeBins[4]; /**< MAP based AE MAPdot bins */ byte maeRates[4]; /**< MAP based AE values */ int8_t batVoltCorrect; /**< Battery voltage calibration offset (Given as 10x value, e.g. 2v => 20) */ byte baroFuelBins[8]; byte baroFuelValues[8]; byte idleAdvBins[6]; byte idleAdvValues[6]; byte engineProtectMaxRPM; int16_t vvt2CL0DutyAng; byte vvt2PWMdir : 1; byte inj4cylPairing : 2; byte dwellErrCorrect : 1; byte unusedBits4 : 4; byte ANGLEFILTER_VVT; byte FILTER_FLEX; byte vvtMinClt; byte vvtDelay; #if defined(CORE_AVR) }; #else } __attribute__((__packed__)); //The 32 bi systems require all structs to be fully packed #endif /** Page 6 of the config - mostly variables that are required for AFR targets and closed loop. See the ini file for further reference. */ struct config6 { byte egoAlgorithm : 2; ///< EGO Algorithm - Simple, PID, No correction byte egoType : 2; ///< EGO Sensor Type 0=Disabled/None, 1=Narrowband, 2=Wideband byte boostEnabled : 1; ///< Boost control enabled 0 =off, 1 = on byte vvtEnabled : 1; ///< byte engineProtectType : 2; byte egoKP; byte egoKI; byte egoKD; byte egoTemp; ///< The temperature above which closed loop is enabled byte egoCount; ///< The number of ignition cycles per (ego AFR ?) step byte vvtMode : 2; ///< Valid VVT modes are 'on/off', 'open loop' and 'closed loop' byte vvtLoadSource : 2; ///< Load source for VVT (TPS or MAP) byte vvtPWMdir : 1; ///< VVT direction (normal or reverse) byte vvtCLUseHold : 1; //Whether or not to use a hold duty cycle (Most cases are Yes) byte vvtCLAlterFuelTiming : 1; byte boostCutEnabled : 1; byte egoLimit; /// Maximum amount the closed loop EGO control will vary the fuelling byte ego_min; /// AFR must be above this for closed loop to function byte ego_max; /// AFR must be below this for closed loop to function byte ego_sdelay; /// Time in seconds after engine starts that closed loop becomes available byte egoRPM; /// RPM must be above this for closed loop to function byte egoTPSMax; /// TPS must be below this for closed loop to function byte vvt1Pin : 6; byte useExtBaro : 1; byte boostMode : 1; /// Boost control mode: 0=Simple (BOOST_MODE_SIMPLE) or 1=full (BOOST_MODE_FULL) byte boostPin : 6; byte tachoMode : 1; /// Whether to use fixed tacho pulse duration or match to dwell duration byte useEMAP : 1; ///< Enable EMAP byte voltageCorrectionBins[6]; //X axis bins for voltage correction tables byte injVoltageCorrectionValues[6]; //Correction table for injector PW vs battery voltage byte airDenBins[9]; byte airDenRates[9]; byte boostFreq; /// Frequency of the boost PWM valve byte vvtFreq; /// Frequency of the vvt PWM valve byte idleFreq; // Launch stuff, see beginning of speeduino.ino main loop byte launchPin : 6; ///< Launch (control ?) pin byte launchEnabled : 1; ///< Launch ...???... (control?) enabled byte launchHiLo : 1; // byte lnchSoftLim; int8_t lnchRetard; //Allow for negative advance value (ATDC) byte lnchHardLim; byte lnchFuelAdd; //PID values for idle needed to go here as out of room in the idle page byte idleKP; byte idleKI; byte idleKD; byte boostLimit; ///< Boost limit (Kpa). Stored value is actual (kPa) value divided by 2, allowing kPa values up to 511 byte boostKP; byte boostKI; byte boostKD; byte lnchPullRes : 1; byte iacPWMrun : 1; ///< Run the PWM idle valve before engine is cranked over (0 = off, 1 = on) byte fuelTrimEnabled : 1; byte flatSEnable : 1; ///< Flat shift enable byte baroPin : 4; byte flatSSoftWin; int8_t flatSRetard; byte flatSArm; byte iacCLValues[10]; //Closed loop target RPM value byte iacOLStepVal[10]; //Open loop step values for stepper motors byte iacOLPWMVal[10]; //Open loop duty values for PMWM valves byte iacBins[10]; //Temperature Bins for the above 3 curves byte iacCrankSteps[4]; //Steps to use when cranking (Stepper motor) byte iacCrankDuty[4]; //Duty cycle to use on PWM valves when cranking byte iacCrankBins[4]; //Temperature Bins for the above 2 curves byte iacAlgorithm : 3; //Valid values are: "None", "On/Off", "PWM", "PWM Closed Loop", "Stepper", "Stepper Closed Loop" byte iacStepTime : 3; //How long to pulse the stepper for to ensure the step completes (ms) byte iacChannels : 1; //How many outputs to use in PWM mode (0 = 1 channel, 1 = 2 channels) byte iacPWMdir : 1; //Direction of the PWM valve. 0 = Normal = Higher RPM with more duty. 1 = Reverse = Lower RPM with more duty byte iacFastTemp; //Fast idle temp when using a simple on/off valve byte iacStepHome; //When using a stepper motor, the number of steps to be taken on startup to home the motor byte iacStepHyster; //Hysteresis temperature (*10). Eg 2.2C = 22 byte fanInv : 1; // Fan output inversion bit byte fanUnused : 1; byte fanPin : 6; byte fanSP; // Cooling fan start temperature byte fanHyster; // Fan hysteresis byte fanFreq; // Fan PWM frequency byte fanPWMBins[4]; //Temperature Bins for the PWM fan control #if defined(CORE_AVR) }; #else } __attribute__((__packed__)); //The 32 bit systems require all structs to be fully packed #endif /** Page 9 of the config - mostly deals with CANBUS control. See ini file for further info (Config Page 10 in the ini). */ struct config9 { byte enable_secondarySerial:1; //enable secondary serial byte intcan_available:1; //enable internal can module byte enable_intcan:1; byte caninput_sel[16]; //bit status on/Can/analog_local/digtal_local if input is enabled uint16_t caninput_source_can_address[16]; //u16 [15] array holding can address of input uint8_t caninput_source_start_byte[16]; //u08 [15] array holds the start byte number(value of 0-7) uint16_t caninput_source_num_bytes; //u16 bit status of the number of bytes length 1 or 2 byte caninputEndianess:1; //byte unused:2 //... byte unused10_68; byte enable_candata_out : 1; byte canoutput_sel[8]; uint16_t canoutput_param_group[8]; uint8_t canoutput_param_start_byte[8]; byte canoutput_param_num_bytes[8]; byte unused10_110; byte unused10_111; byte unused10_112; byte unused10_113; byte speeduino_tsCanId:4; //speeduino TS canid (0-14) uint16_t true_address; //speeduino 11bit can address uint16_t realtime_base_address; //speeduino 11 bit realtime base address uint16_t obd_address; //speeduino OBD diagnostic address uint8_t Auxinpina[16]; //analog pin number when internal aux in use uint8_t Auxinpinb[16]; // digital pin number when internal aux in use byte iacStepperInv : 1; //stepper direction of travel to allow reversing. 0=normal, 1=inverted. byte iacCoolTime : 3; // how long to wait for the stepper to cool between steps byte boostByGearEnabled : 2; byte blankField : 1; byte iacStepperPower : 1; //Whether or not to power the stepper motor when not in use byte iacMaxSteps; // Step limit beyond which the stepper won't be driven. Should always be less than homing steps. Stored div 3 as per home steps. byte idleAdvStartDelay; //delay for idle advance engage byte boostByGear1; byte boostByGear2; byte boostByGear3; byte boostByGear4; byte boostByGear5; byte boostByGear6; byte PWMFanDuty[4]; byte hardRevMode : 2; byte coolantProtRPM[6]; byte coolantProtTemp[6]; byte unused10_179; byte unused10_180; byte unused10_181; byte unused10_182; byte unused10_183; byte unused10_184; byte afrProtectEnabled : 2; /* < AFR protection enabled status. 0 = disabled, 1 = fixed mode, 2 = table mode */ byte afrProtectMinMAP; /* < Minimum MAP. Stored value is divided by 2. Increments of 2 kPa, maximum 511 (?) kPa */ byte afrProtectMinRPM; /* < Minimum RPM. Stored value is divded by 100. Increments of 100 RPM, maximum 25500 RPM */ byte afrProtectMinTPS; /* < Minimum TPS. */ byte afrProtectDeviation; /* < Maximum deviation from AFR target table. Stored value is multiplied by 10 */ byte afrProtectCutTime; /* < Time in ms before cut. Stored value is divided by 100. Maximum of 2550 ms */ byte afrProtectReactivationTPS; /* Disable engine protection cut once below this TPS percentage */ #if defined(CORE_AVR) }; #else } __attribute__((__packed__)); //The 32 bit systems require all structs to be fully packed #endif /** Page 10 - No specific purpose. Created initially for the cranking enrich curve. 192 bytes long. See ini file for further info (Config Page 11 in the ini). */ struct config10 { byte crankingEnrichBins[4]; //Bytes 0-4 byte crankingEnrichValues[4]; //Bytes 4-7 //Byte 8 byte rotaryType : 2; byte stagingEnabled : 1; byte stagingMode : 1; byte EMAPPin : 4; byte rotarySplitValues[8]; //Bytes 9-16 byte rotarySplitBins[8]; //Bytes 17-24 uint16_t boostSens; //Bytes 25-26 byte boostIntv; //Byte 27 uint16_t stagedInjSizePri; //Bytes 28-29 uint16_t stagedInjSizeSec; //Bytes 30-31 byte lnchCtrlTPS; //Byte 32 uint8_t flexBoostBins[6]; //Bytes 33-38 int16_t flexBoostAdj[6]; //kPa to be added to the boost target @ current ethanol (negative values allowed). Bytes 39-50 uint8_t flexFuelBins[6]; //Bytes 51-56 uint8_t flexFuelAdj[6]; //Fuel % @ current ethanol (typically 100% @ 0%, 163% @ 100%). Bytes 57-62 uint8_t flexAdvBins[6]; //Bytes 63-68 uint8_t flexAdvAdj[6]; //Additional advance (in degrees) @ current ethanol (typically 0 @ 0%, 10-20 @ 100%). NOTE: THIS SHOULD BE A SIGNED VALUE BUT 2d TABLE LOOKUP NOT WORKING WITH IT CURRENTLY! //And another three corn rows die. //Bytes 69-74 //Byte 75 byte n2o_enable : 2; byte n2o_arming_pin : 6; byte n2o_minCLT; //Byte 76 byte n2o_maxMAP; //Byte 77 byte n2o_minTPS; //Byte 78 byte n2o_maxAFR; //Byte 79 //Byte 80 byte n2o_stage1_pin : 6; byte n2o_pin_polarity : 1; byte n2o_stage1_unused : 1; byte n2o_stage1_minRPM; //Byte 81 byte n2o_stage1_maxRPM; //Byte 82 byte n2o_stage1_adderMin; //Byte 83 byte n2o_stage1_adderMax; //Byte 84 byte n2o_stage1_retard; //Byte 85 //Byte 86 byte n2o_stage2_pin : 6; byte n2o_stage2_unused : 2; byte n2o_stage2_minRPM; //Byte 87 byte n2o_stage2_maxRPM; //Byte 88 byte n2o_stage2_adderMin; //Byte 89 byte n2o_stage2_adderMax; //Byte 90 byte n2o_stage2_retard; //Byte 91 //Byte 92 byte knock_mode : 2; byte knock_pin : 6; //Byte 93 byte knock_trigger : 1; byte knock_pullup : 1; byte knock_limiterDisable : 1; byte knock_unused : 2; byte knock_count : 3; byte knock_threshold; //Byte 94 byte knock_maxMAP; //Byte 95 byte knock_maxRPM; //Byte 96 byte knock_window_rpms[6]; //Bytes 97-102 byte knock_window_angle[6]; //Bytes 103-108 byte knock_window_dur[6]; //Bytes 109-114 byte knock_maxRetard; //Byte 115 byte knock_firstStep; //Byte 116 byte knock_stepSize; //Byte 117 byte knock_stepTime; //Byte 118 byte knock_duration; //Time after knock retard starts that it should start recovering. Byte 119 byte knock_recoveryStepTime; //Byte 120 byte knock_recoveryStep; //Byte 121 //Byte 122 byte fuel2Algorithm : 3; byte fuel2Mode : 3; byte fuel2SwitchVariable : 2; //Bytes 123-124 uint16_t fuel2SwitchValue; //Byte 125 byte fuel2InputPin : 6; byte fuel2InputPolarity : 1; byte fuel2InputPullup : 1; byte vvtCLholdDuty; //Byte 126 byte vvtCLKP; //Byte 127 byte vvtCLKI; //Byte 128 byte vvtCLKD; //Byte 129 int16_t vvtCL0DutyAng; //Bytes 130-131 uint8_t vvtCLMinAng; //Byte 132 uint8_t vvtCLMaxAng; //Byte 133 byte crankingEnrichTaper; //Byte 134 byte fuelPressureEnable : 1; ///< Enable fuel pressure sensing from an analog pin (@ref pinFuelPressure) byte oilPressureEnable : 1; ///< Enable oil pressure sensing from an analog pin (@ref pinOilPressure) byte oilPressureProtEnbl : 1; byte oilPressurePin : 5; byte fuelPressurePin : 5; byte unused11_165 : 3; int8_t fuelPressureMin; byte fuelPressureMax; int8_t oilPressureMin; byte oilPressureMax; byte oilPressureProtRPM[4]; byte oilPressureProtMins[4]; byte wmiEnabled : 1; // Byte 149 byte wmiMode : 6; byte wmiAdvEnabled : 1; byte wmiTPS; // Byte 150 byte wmiRPM; // Byte 151 byte wmiMAP; // Byte 152 byte wmiMAP2; // Byte 153 byte wmiIAT; // Byte 154 int8_t wmiOffset; // Byte 155 byte wmiIndicatorEnabled : 1; // 156 byte wmiIndicatorPin : 6; byte wmiIndicatorPolarity : 1; byte wmiEmptyEnabled : 1; // 157 byte wmiEmptyPin : 6; byte wmiEmptyPolarity : 1; byte wmiEnabledPin; // 158 byte wmiAdvBins[6]; //Bytes 159-164 byte wmiAdvAdj[6]; //Additional advance (in degrees) //Bytes 165-170 byte vvtCLminDuty; byte vvtCLmaxDuty; byte vvt2Pin : 6; byte vvt2Enabled : 1; byte TrigEdgeThrd : 1; byte fuelTempBins[6]; byte fuelTempValues[6]; //180 //Byte 186 byte spark2Algorithm : 3; byte spark2Mode : 3; byte spark2SwitchVariable : 2; //Bytes 187-188 uint16_t spark2SwitchValue; //Byte 189 byte spark2InputPin : 6; byte spark2InputPolarity : 1; byte spark2InputPullup : 1; byte oilPressureProtTime; byte unused11_191_191; //Bytes 187-191 #if defined(CORE_AVR) }; #else } __attribute__((__packed__)); //The 32 bit systems require all structs to be fully packed #endif /** Config for programmable I/O comparison operation (between 2 vars). * Operations are implemented in utilities.ino (@ref checkProgrammableIO()). */ struct cmpOperation{ uint8_t firstCompType : 3; ///< First cmp. op (COMPARATOR_* ops, see below) uint8_t secondCompType : 3; ///< Second cmp. op (0=COMPARATOR_EQUAL, 1=COMPARATOR_NOT_EQUAL,2=COMPARATOR_GREATER,3=COMPARATOR_GREATER_EQUAL,4=COMPARATOR_LESS,5=COMPARATOR_LESS_EQUAL,6=COMPARATOR_CHANGE) uint8_t bitwise : 2; ///< BITWISE_AND, BITWISE_OR, BITWISE_XOR }; /** Page 13 - Programmable outputs logic rules. 128 bytes long. Rules implemented in utilities.ino @ref checkProgrammableIO(). */ struct config13 { uint8_t outputInverted; ///< Invert (on/off) value before writing to output pin (for all programmable I/O:s). uint8_t kindOfLimiting; ///< Select which kind of output limiting are active (0 - minimum | 1 - maximum) uint8_t outputPin[8]; ///< Disable(0) or enable (set to valid pin number) Programmable Pin (output/target pin to set) uint8_t outputDelay[8]; ///< Output write delay for each programmable I/O (Unit: 0.1S) uint8_t firstDataIn[8]; ///< Set of first I/O vars to compare uint8_t secondDataIn[8];///< Set of second I/O vars to compare uint8_t outputTimeLimit[8]; ///< Output delay for each programmable I/O, kindOfLimiting bit dependent(Unit: 0.1S) uint8_t unused_13[8]; // Unused int16_t firstTarget[8]; ///< first target value to compare with numeric comp int16_t secondTarget[8];///< second target value to compare with bitwise op //89bytes struct cmpOperation operation[8]; ///< I/O variable comparison operations (See @ref cmpOperation) uint16_t candID[8]; ///< Actual CAN ID need 16bits, this is a placeholder byte unused12_106_116[10]; byte onboard_log_csv_separator :2; //";", ",", "tab", "space" byte onboard_log_file_style :2; // "Disabled", "CSV", "Binary", "INVALID" byte onboard_log_file_rate :2; // "1Hz", "4Hz", "10Hz", "30Hz" byte onboard_log_filenaming :2; // "Overwrite", "Date-time", "Sequential", "INVALID" byte onboard_log_storage :2; // "sd-card", "INVALID", "INVALID", "INVALID" ;In the future maybe an onboard spi flash can be used, or switch between SDIO vs SPI sd card interfaces. byte onboard_log_trigger_boot :1; // "Disabled", "On boot" byte onboard_log_trigger_RPM :1; // "Disabled", "Enabled" byte onboard_log_trigger_prot :1; // "Disabled", "Enabled" byte onboard_log_trigger_Vbat :1; // "Disabled", "Enabled" byte onboard_log_trigger_Epin :2; // "Disabled", "polling", "toggle" , "INVALID" uint16_t onboard_log_tr1_duration; // Duration of logging that starts on boot byte onboard_log_tr2_thr_on; // "RPM", 100.0, 0.0, 0, 10000, 0 byte onboard_log_tr2_thr_off; // "RPM", 100.0, 0.0, 0, 10000, 0 byte onboard_log_tr3_thr_RPM :1; // "Disabled", "Enabled" byte onboard_log_tr3_thr_MAP :1; // "Disabled", "Enabled" byte onboard_log_tr3_thr_Oil :1; // "Disabled", "Enabled" byte onboard_log_tr3_thr_AFR :1; // "Disabled", "Enabled" byte onboard_log_tr4_thr_on; // "V", 0.1, 0.0, 0.0, 15.90, 2 ; * ( 1 byte) byte onboard_log_tr4_thr_off; // "V", 0.1, 0.0, 0.0, 15.90, 2 ; * ( 1 byte) byte onboard_log_tr5_Epin_pin :6; // "pin", 0, 0, 0, 1, 255, 0 ; byte unused13_125_2 :2; byte unused12_126_127[2]; #if defined(CORE_AVR) }; #else } __attribute__((__packed__)); //The 32 bit systems require all structs to be fully packed #endif /** Page 15 - second page for VVT and boost control. 256 bytes long. */ struct config15 { byte boostControlEnable : 1; byte unused15_1 : 7; //7bits unused byte boostDCWhenDisabled; byte boostControlEnableThreshold; //if fixed value enable set threshold here. //Byte 83 - Air conditioning binary points byte airConEnable : 1; byte airConCompPol : 1; byte airConReqPol : 1; byte airConTurnsFanOn : 1; byte airConFanEnabled : 1; byte airConFanPol : 1; byte airConUnused1 : 2; //Bytes 84-97 - Air conditioning analog points byte airConCompPin : 6; byte airConUnused2 : 2; byte airConReqPin : 6; byte airConUnused3 : 2; byte airConTPSCut; byte airConMinRPMdiv10; byte airConMaxRPMdiv100; byte airConClTempCut; byte airConIdleSteps; byte airConTPSCutTime; byte airConCompOnDelay; byte airConAfterStartDelay; byte airConRPMCutTime; byte airConFanPin : 6; byte airConUnused4 : 2; byte airConIdleUpRPMAdder; byte airConPwmFanMinDuty; //Bytes 98-255 byte Unused15_98_255[158]; #if defined(CORE_AVR) }; #else } __attribute__((__packed__)); //The 32 bit systems require all structs to be fully packed #endif extern byte pinInjector1; //Output pin injector 1 extern byte pinInjector2; //Output pin injector 2 extern byte pinInjector3; //Output pin injector 3 extern byte pinInjector4; //Output pin injector 4 extern byte pinInjector5; //Output pin injector 5 extern byte pinInjector6; //Output pin injector 6 extern byte pinInjector7; //Output pin injector 7 extern byte pinInjector8; //Output pin injector 8 extern byte injectorOutputControl; //Specifies whether the injectors are controlled directly (Via an IO pin) or using something like the MC33810 extern byte pinCoil1; //Pin for coil 1 extern byte pinCoil2; //Pin for coil 2 extern byte pinCoil3; //Pin for coil 3 extern byte pinCoil4; //Pin for coil 4 extern byte pinCoil5; //Pin for coil 5 extern byte pinCoil6; //Pin for coil 6 extern byte pinCoil7; //Pin for coil 7 extern byte pinCoil8; //Pin for coil 8 extern byte ignitionOutputControl; //Specifies whether the coils are controlled directly (Via an IO pin) or using something like the MC33810 extern byte pinTrigger; //The CAS pin extern byte pinTrigger2; //The Cam Sensor pin extern byte pinTrigger3; //the 2nd cam sensor pin extern byte pinTPS;//TPS input pin extern byte pinMAP; //MAP sensor pin extern byte pinEMAP; //EMAP sensor pin extern byte pinMAP2; //2nd MAP sensor (Currently unused) extern byte pinIAT; //IAT sensor pin extern byte pinCLT; //CLS sensor pin extern byte pinO2; //O2 Sensor pin extern byte pinO2_2; //second O2 pin extern byte pinBat; //Battery voltage pin extern byte pinDisplayReset; // OLED reset pin extern byte pinTachOut; //Tacho output extern byte pinFuelPump; //Fuel pump on/off extern byte pinIdle1; //Single wire idle control extern byte pinIdle2; //2 wire idle control (Not currently used) extern byte pinIdleUp; //Input for triggering Idle Up extern byte pinIdleUpOutput; //Output that follows (normal or inverted) the idle up pin extern byte pinCTPS; //Input for triggering closed throttle state extern byte pinFuel2Input; //Input for switching to the 2nd fuel table extern byte pinSpark2Input; //Input for switching to the 2nd ignition table extern byte pinSpareTemp1; // Future use only extern byte pinSpareTemp2; // Future use only extern byte pinSpareOut1; //Generic output extern byte pinSpareOut2; //Generic output extern byte pinSpareOut3; //Generic output extern byte pinSpareOut4; //Generic output extern byte pinSpareOut5; //Generic output extern byte pinSpareOut6; //Generic output extern byte pinSpareHOut1; //spare high current output extern byte pinSpareHOut2; // spare high current output extern byte pinSpareLOut1; // spare low current output extern byte pinSpareLOut2; // spare low current output extern byte pinSpareLOut3; extern byte pinSpareLOut4; extern byte pinSpareLOut5; extern byte pinBoost; extern byte pinVVT_1; // vvt output 1 extern byte pinVVT_2; // vvt output 2 extern byte pinFan; // Cooling fan output extern byte pinStepperDir; //Direction pin for the stepper motor driver extern byte pinStepperStep; //Step pin for the stepper motor driver extern byte pinStepperEnable; //Turning the DRV8825 driver on/off extern byte pinLaunch; extern byte pinIgnBypass; //The pin used for an ignition bypass (Optional) extern byte pinFlex; //Pin with the flex sensor attached extern byte pinVSS; extern byte pinBaro; //Pin that an external barometric pressure sensor is attached to (If used) extern byte pinResetControl; // Output pin used control resetting the Arduino extern byte pinFuelPressure; extern byte pinOilPressure; extern byte pinWMIEmpty; // Water tank empty sensor extern byte pinWMIIndicator; // No water indicator bulb extern byte pinWMIEnabled; // ON-OFF output to relay/pump/solenoid extern byte pinMC33810_1_CS; extern byte pinMC33810_2_CS; extern byte pinSDEnable; //Input for manually enabling SD logging #ifdef USE_SPI_EEPROM extern byte pinSPIFlash_CS; #endif extern byte pinAirConComp; // Air conditioning compressor output extern byte pinAirConFan; // Stand-alone air conditioning fan output extern byte pinAirConRequest; // Air conditioning request input /* global variables */ // from speeduino.ino //#ifndef UNIT_TEST //#endif extern struct statuses currentStatus; //The global status object extern struct config2 configPage2; extern struct config4 configPage4; extern struct config6 configPage6; extern struct config9 configPage9; extern struct config10 configPage10; extern struct config13 configPage13; extern struct config15 configPage15; //extern byte cltCalibrationTable[CALIBRATION_TABLE_SIZE]; /**< An array containing the coolant sensor calibration values */ //extern byte iatCalibrationTable[CALIBRATION_TABLE_SIZE]; /**< An array containing the inlet air temperature sensor calibration values */ //extern byte o2CalibrationTable[CALIBRATION_TABLE_SIZE]; /**< An array containing the O2 sensor calibration values */ extern uint16_t cltCalibration_bins[32]; extern uint16_t cltCalibration_values[32]; extern uint16_t iatCalibration_bins[32]; extern uint16_t iatCalibration_values[32]; extern uint16_t o2Calibration_bins[32]; extern uint8_t o2Calibration_values[32]; // Note 8-bit values extern struct table2D cltCalibrationTable; /**< A 32 bin array containing the coolant temperature sensor calibration values */ extern struct table2D iatCalibrationTable; /**< A 32 bin array containing the inlet air temperature sensor calibration values */ extern struct table2D o2CalibrationTable; /**< A 32 bin array containing the O2 sensor calibration values */ bool pinIsOutput(byte pin); bool pinIsUsed(byte pin); #endif // GLOBALS_H
73,261
C++
.h
1,386
50.382395
410
0.733689
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,120
speeduino.h
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/speeduino.h
/** \file speeduino.h * @brief Speeduino main file containing initial setup and system loop functions * @author Josh Stewart * * This file contains the main system loop of the Speeduino core and thus much of the logic of the fuel and ignition algorithms is contained within this * It is where calls to all the auxiliary control systems, sensor reads, comms etc are made * * It also contains the setup() function that is called by the bootloader on system startup * */ #ifndef SPEEDUINO_H #define SPEEDUINO_H //#include "globals.h" #define CRANK_RUN_HYSTER 15 void setup(void); void loop(void); uint16_t PW(int REQ_FUEL, byte VE, long MAP, uint16_t corrections, int injOpen); byte getVE1(void); byte getAdvance1(void); extern uint16_t req_fuel_uS; /**< The required fuel variable (As calculated by TunerStudio) in uS */ extern uint16_t inj_opentime_uS; /**< The injector opening time. This is set within Tuner Studio, but stored here in uS rather than mS */ extern bool ignitionOn; /**< The current state of the ignition system (on or off) */ extern bool fuelOn; /**< The current state of the fuel system (on or off) */ extern byte curRollingCut; /**< Rolling rev limiter, current ignition channel being cut */ extern byte rollingCutCounter; /**< how many times (revolutions) the ignition has been cut in a row */ extern uint32_t rollingCutLastRev; /**< Tracks whether we're on the same or a different rev for the rolling cut */ /** @name Staging * These values are a percentage of the total (Combined) req_fuel value that would be required for each injector channel to deliver that much fuel. * * Eg: * - Pri injectors are 250cc * - Sec injectors are 500cc * - Total injector capacity = 750cc * * - staged_req_fuel_mult_pri = 300% (The primary injectors would have to run 3x the overall PW in order to be the equivalent of the full 750cc capacity * - staged_req_fuel_mult_sec = 150% (The secondary injectors would have to run 1.5x the overall PW in order to be the equivalent of the full 750cc capacity */ ///@{ extern uint16_t staged_req_fuel_mult_pri; extern uint16_t staged_req_fuel_mult_sec; ///@} #endif
2,154
C++
.h
42
49.404762
157
0.750238
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,121
board_teensy41.h
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/board_teensy41.h
#ifndef TEENSY41_H #define TEENSY41_H #if defined(CORE_TEENSY) && defined(__IMXRT1062__) /* *********************************************************************************************************** * General */ void initBoard(); uint16_t freeRam(); void doSystemReset(); void jumpToBootloader(); void setTriggerHysteresis(); time_t getTeensy3Time(); #define PORT_TYPE uint32_t //Size of the port variables #define PINMASK_TYPE uint32_t #define COMPARE_TYPE uint16_t #define COUNTER_TYPE uint16_t #define SERIAL_BUFFER_SIZE 517 //Size of the serial buffer used by new comms protocol. For SD transfers this must be at least 512 + 1 (flag) + 4 (sector) #define FPU_MAX_SIZE 32 //Size of the FPU buffer. 0 means no FPU. #define BOARD_MAX_DIGITAL_PINS 34 #define BOARD_MAX_IO_PINS 34 //digital pins + analog channels + 1 #define EEPROM_LIB_H <EEPROM.h> typedef int eeprom_address_t; #define RTC_ENABLED #define SD_LOGGING //SD logging enabled by default for Teensy 4.1 as it has the slot built in #define RTC_LIB_H "TimeLib.h" #define SD_CONFIG SdioConfig(FIFO_SDIO) //Set Teensy to use SDIO in FIFO mode. This is the fastest SD mode on Teensy as it offloads most of the writes #define micros_safe() micros() //timer5 method is not used on anything but AVR, the micros_safe() macro is simply an alias for the normal micros() //#define PWM_FAN_AVAILABLE #define pinIsReserved(pin) ( ((pin) == 0) || ((pin) == 42) || ((pin) == 43) || ((pin) == 44) || ((pin) == 45) || ((pin) == 46) || ((pin) == 47) ) //Forbidden pins like USB /* *********************************************************************************************************** * Schedules */ /* https://github.com/luni64/TeensyTimerTool/wiki/Supported-Timers#pit---periodic-timer https://github.com/luni64/TeensyTimerTool/wiki/Configuration#clock-setting-for-the-gpt-and-pit-timers The Quad timer (TMR) provides 4 timers each with 4 usable compare channels. The down compare and alternating compares are not usable FUEL 1-4: TMR1 IGN 1-4 : TMR2 FUEL 5-8: TMR3 IGN 5-8 : TMR4 */ #define FUEL1_COUNTER TMR1_CNTR0 #define FUEL2_COUNTER TMR1_CNTR1 #define FUEL3_COUNTER TMR1_CNTR2 #define FUEL4_COUNTER TMR1_CNTR3 #define FUEL5_COUNTER TMR3_CNTR0 #define FUEL6_COUNTER TMR3_CNTR1 #define FUEL7_COUNTER TMR3_CNTR2 #define FUEL8_COUNTER TMR3_CNTR3 #define IGN1_COUNTER TMR2_CNTR0 #define IGN2_COUNTER TMR2_CNTR1 #define IGN3_COUNTER TMR2_CNTR2 #define IGN4_COUNTER TMR2_CNTR3 #define IGN5_COUNTER TMR4_CNTR0 #define IGN6_COUNTER TMR4_CNTR1 #define IGN7_COUNTER TMR4_CNTR2 #define IGN8_COUNTER TMR4_CNTR3 #define FUEL1_COMPARE TMR1_COMP10 #define FUEL2_COMPARE TMR1_COMP11 #define FUEL3_COMPARE TMR1_COMP12 #define FUEL4_COMPARE TMR1_COMP13 #define FUEL5_COMPARE TMR3_COMP10 #define FUEL6_COMPARE TMR3_COMP11 #define FUEL7_COMPARE TMR3_COMP12 #define FUEL8_COMPARE TMR3_COMP13 #define IGN1_COMPARE TMR2_COMP10 #define IGN2_COMPARE TMR2_COMP11 #define IGN3_COMPARE TMR2_COMP12 #define IGN4_COMPARE TMR2_COMP13 #define IGN5_COMPARE TMR4_COMP10 #define IGN6_COMPARE TMR4_COMP11 #define IGN7_COMPARE TMR4_COMP12 #define IGN8_COMPARE TMR4_COMP13 #define FUEL1_TIMER_ENABLE() TMR1_CSCTRL0 |= TMR_CSCTRL_TCF1EN //Write 1 to the TCFIEN (Channel Interrupt Enable) bit of channel 0 Status/Control #define FUEL2_TIMER_ENABLE() TMR1_CSCTRL1 |= TMR_CSCTRL_TCF1EN #define FUEL3_TIMER_ENABLE() TMR1_CSCTRL2 |= TMR_CSCTRL_TCF1EN #define FUEL4_TIMER_ENABLE() TMR1_CSCTRL3 |= TMR_CSCTRL_TCF1EN #define FUEL5_TIMER_ENABLE() TMR3_CSCTRL0 |= TMR_CSCTRL_TCF1EN #define FUEL6_TIMER_ENABLE() TMR3_CSCTRL1 |= TMR_CSCTRL_TCF1EN #define FUEL7_TIMER_ENABLE() TMR3_CSCTRL2 |= TMR_CSCTRL_TCF1EN #define FUEL8_TIMER_ENABLE() TMR3_CSCTRL3 |= TMR_CSCTRL_TCF1EN #define FUEL1_TIMER_DISABLE() TMR1_CSCTRL0 &= ~TMR_CSCTRL_TCF1EN //Write 0 to the TCFIEN (Channel Interrupt Enable) bit of channel 0 Status/Control #define FUEL2_TIMER_DISABLE() TMR1_CSCTRL1 &= ~TMR_CSCTRL_TCF1EN #define FUEL3_TIMER_DISABLE() TMR1_CSCTRL2 &= ~TMR_CSCTRL_TCF1EN #define FUEL4_TIMER_DISABLE() TMR1_CSCTRL3 &= ~TMR_CSCTRL_TCF1EN #define FUEL5_TIMER_DISABLE() TMR3_CSCTRL0 &= ~TMR_CSCTRL_TCF1EN #define FUEL6_TIMER_DISABLE() TMR3_CSCTRL1 &= ~TMR_CSCTRL_TCF1EN #define FUEL7_TIMER_DISABLE() TMR3_CSCTRL2 &= ~TMR_CSCTRL_TCF1EN #define FUEL8_TIMER_DISABLE() TMR3_CSCTRL3 &= ~TMR_CSCTRL_TCF1EN #define IGN1_TIMER_ENABLE() TMR2_CSCTRL0 |= TMR_CSCTRL_TCF1EN #define IGN2_TIMER_ENABLE() TMR2_CSCTRL1 |= TMR_CSCTRL_TCF1EN #define IGN3_TIMER_ENABLE() TMR2_CSCTRL2 |= TMR_CSCTRL_TCF1EN #define IGN4_TIMER_ENABLE() TMR2_CSCTRL3 |= TMR_CSCTRL_TCF1EN #define IGN5_TIMER_ENABLE() TMR4_CSCTRL0 |= TMR_CSCTRL_TCF1EN #define IGN6_TIMER_ENABLE() TMR4_CSCTRL1 |= TMR_CSCTRL_TCF1EN #define IGN7_TIMER_ENABLE() TMR4_CSCTRL2 |= TMR_CSCTRL_TCF1EN #define IGN8_TIMER_ENABLE() TMR4_CSCTRL3 |= TMR_CSCTRL_TCF1EN #define IGN1_TIMER_DISABLE() TMR2_CSCTRL0 &= ~TMR_CSCTRL_TCF1EN #define IGN2_TIMER_DISABLE() TMR2_CSCTRL1 &= ~TMR_CSCTRL_TCF1EN #define IGN3_TIMER_DISABLE() TMR2_CSCTRL2 &= ~TMR_CSCTRL_TCF1EN #define IGN4_TIMER_DISABLE() TMR2_CSCTRL3 &= ~TMR_CSCTRL_TCF1EN #define IGN5_TIMER_DISABLE() TMR4_CSCTRL0 &= ~TMR_CSCTRL_TCF1EN #define IGN6_TIMER_DISABLE() TMR4_CSCTRL1 &= ~TMR_CSCTRL_TCF1EN #define IGN7_TIMER_DISABLE() TMR4_CSCTRL2 &= ~TMR_CSCTRL_TCF1EN #define IGN8_TIMER_DISABLE() TMR4_CSCTRL3 &= ~TMR_CSCTRL_TCF1EN //Bus Clock is 150Mhz @ 600 Mhz CPU. Need to handle this dynamically in the future for other frequencies //#define TMR_PRESCALE 128 //#define MAX_TIMER_PERIOD ((65535 * 1000000ULL) / (F_BUS_ACTUAL / TMR_PRESCALE)) //55923 @ 600Mhz. #define MAX_TIMER_PERIOD 55923UL #define uS_TO_TIMER_COMPARE(uS) ((uS * 75UL) >> 6) //Converts a given number of uS into the required number of timer ticks until that time has passed. /* To calculate the above uS_TO_TIMER_COMPARE Choose number of bit of precision. Eg: 6 Divide 2^6 by the time per tick (0.853333) = 75 Multiply and bitshift back by the precision: (uS * 75) >> 6 */ /* *********************************************************************************************************** * Auxiliaries */ #define ENABLE_BOOST_TIMER() PIT_TCTRL1 |= PIT_TCTRL_TEN #define DISABLE_BOOST_TIMER() PIT_TCTRL1 &= ~PIT_TCTRL_TEN #define ENABLE_VVT_TIMER() PIT_TCTRL2 |= PIT_TCTRL_TEN #define DISABLE_VVT_TIMER() PIT_TCTRL2 &= ~PIT_TCTRL_TEN //Ran out of timers, this most likely won't work. This should be possible to implement with the GPT timer. #define ENABLE_FAN_TIMER() TMR3_CSCTRL1 |= TMR_CSCTRL_TCF2EN #define DISABLE_FAN_TIMER() TMR3_CSCTRL1 &= ~TMR_CSCTRL_TCF2EN #define BOOST_TIMER_COMPARE PIT_LDVAL1 #define BOOST_TIMER_COUNTER 0 #define VVT_TIMER_COMPARE PIT_LDVAL2 #define VVT_TIMER_COUNTER 0 //these probaply need to be PIT_LDVAL something??? #define FAN_TIMER_COMPARE TMR3_COMP22 #define FAN_TIMER_COUNTER TMR3_CNTR1 /* *********************************************************************************************************** * Idle */ #define IDLE_COUNTER 0 #define IDLE_COMPARE PIT_LDVAL0 #define IDLE_TIMER_ENABLE() PIT_TCTRL0 |= PIT_TCTRL_TEN #define IDLE_TIMER_DISABLE() PIT_TCTRL0 &= ~PIT_TCTRL_TEN /* *********************************************************************************************************** * CAN / Second serial */ #define USE_SERIAL3 #include <FlexCAN_T4.h> extern FlexCAN_T4<CAN1, RX_SIZE_256, TX_SIZE_16> Can0; extern FlexCAN_T4<CAN2, RX_SIZE_256, TX_SIZE_16> Can1; extern FlexCAN_T4<CAN3, RX_SIZE_256, TX_SIZE_16> Can2; static CAN_message_t outMsg; static CAN_message_t inMsg; //#define NATIVE_CAN_AVAILABLE //Disable for now as it causes lockup #endif //CORE_TEENSY #endif //TEENSY41_H
7,893
C++
.h
158
47.107595
174
0.684818
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,122
int16_byte.h
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/int16_byte.h
/** * @addtogroup table_3d * @{ */ #pragma once #include <stdint.h> #ifdef USE_LIBDIVIDE #include "src/libdivide/libdivide.h" #endif /** @brief Byte type. This is not defined in any C or C++ standard header. */ typedef uint8_t byte; /** @brief Represents a 16-bit value as a byte. Useful for I/O. * * Often we need to deal internally with values that fit in 16-bits but do * not require much accuracy. E.g. table axes in RPM. For these values we can * save storage space (EEPROM) by scaling to/from 8-bits using a fixed divisor. */ class int16_byte { public: /** * @brief Construct * * @param factor The factor to multiply when converting \c byte to \c int16_t * @param divider The factor to divide by when converting \c int16_t to \c byte * * \c divider could be computed from \c factor, but including it as a parameter * allows callers to create \c factor instances at compile time. */ constexpr int16_byte(uint8_t factor #ifdef USE_LIBDIVIDE , const libdivide::libdivide_s16_t &divider #endif ) : _factor(factor) #ifdef USE_LIBDIVIDE , _divider(divider) #endif { } /** @brief Convert to a \c byte */ #ifdef USE_LIBDIVIDE inline byte to_byte(int16_t value) const { return _factor==1 ? value : _factor==2 ? value>>1 : (byte)libdivide::libdivide_s16_do(value, &_divider); } #else inline byte to_byte(int16_t value) const { return (byte)(value/_factor); } #endif /** @brief Convert from a \c byte */ inline int16_t from_byte( byte in ) const { return (int16_t)in * _factor; } private: uint8_t _factor; #ifdef USE_LIBDIVIDE libdivide::libdivide_s16_t _divider; #endif }; /** @} */
1,715
C++
.h
55
27.727273
153
0.677576
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,123
comms.h
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/comms.h
/** \file comms.h * @brief File for handling all serial requests * @author Josh Stewart * * This file contains all the functions associated with serial comms. * This includes sending of live data, sending/receiving current page data, sending CRC values of pages, receiving sensor calibration data etc * */ #ifndef NEW_COMMS_H #define NEW_COMMS_H #if defined(CORE_TEENSY) #define BLOCKING_FACTOR 251 #define TABLE_BLOCKING_FACTOR 256 #elif defined(CORE_STM32) #define BLOCKING_FACTOR 121 #define TABLE_BLOCKING_FACTOR 64 #elif defined(CORE_AVR) #define BLOCKING_FACTOR 121 #define TABLE_BLOCKING_FACTOR 64 #endif /** * @brief The serial receive pump. Should be called whenever the serial port * has data available to read. */ void serialReceive(void); /** @brief The serial transmit pump. Should be called when ::serialStatusFlag indicates a transmit * operation is in progress */ void serialTransmit(void); #endif // COMMS_H
974
C++
.h
29
31.517241
142
0.759574
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,124
board_template.h
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/board_template.h
#ifndef TEMPLATE_H #define TEMPLATE_H #if defined(CORE_TEMPLATE) /* *********************************************************************************************************** * General */ #define PORT_TYPE uint32_t //Size of the port variables (Eg inj1_pin_port). Most systems use a byte, but SAMD21 and possibly others are a 32-bit unsigned int #define PINMASK_TYPE uint32_t #define SERIAL_BUFFER_SIZE 517 //Size of the serial buffer used by new comms protocol. For SD transfers this must be at least 512 + 1 (flag) + 4 (sector) #define FPU_MAX_SIZE 0 //Size of the FPU buffer. 0 means no FPU. #define BOARD_MAX_IO_PINS 52 //digital pins + analog channels + 1 #define BOARD_MAX_DIGITAL_PINS 52 //Pretty sure this isn't right #define EEPROM_LIB_H <EEPROM.h> //The name of the file that provides the EEPROM class typedef int eeprom_address_t; #define micros_safe() micros() //timer5 method is not used on anything but AVR, the micros_safe() macro is simply an alias for the normal micros() void initBoard(); uint16_t freeRam(); void doSystemReset(); void jumpToBootloader(); #define pinIsReserved(pin) ( ((pin) == 0) ) //Forbidden pins like USB /* *********************************************************************************************************** * Schedules */ #define FUEL1_COUNTER <register here> #define FUEL2_COUNTER <register here> #define FUEL3_COUNTER <register here> #define FUEL4_COUNTER <register here> //The below are optional, but recommended if there are sufficient timers/compares #define FUEL5_COUNTER <register here> #define FUEL6_COUNTER <register here> #define FUEL7_COUNTER <register here> #define FUEL8_COUNTER <register here> #define IGN1_COUNTER <register here> #define IGN2_COUNTER <register here> #define IGN3_COUNTER <register here> #define IGN4_COUNTER <register here> //The below are optional, but recommended if there are sufficient timers/compares #define IGN5_COUNTER <register here> #define IGN6_COUNTER <register here> #define IGN7_COUNTER <register here> #define IGN8_COUNTER <register here> #define FUEL1_COMPARE <register here> #define FUEL2_COMPARE <register here> #define FUEL3_COMPARE <register here> #define FUEL4_COMPARE <register here> //The below are optional, but recommended if there are sufficient timers/compares #define FUEL5_COMPARE <register here> #define FUEL6_COMPARE <register here> #define FUEL7_COMPARE <register here> #define FUEL8_COMPARE <register here> #define IGN1_COMPARE <register here> #define IGN2_COMPARE <register here> #define IGN3_COMPARE <register here> #define IGN4_COMPARE <register here> //The below are optional, but recommended if there are sufficient timers/compares #define IGN5_COMPARE <register here> #define IGN6_COMPARE <register here> #define IGN7_COMPARE <register here> #define IGN8_COMPARE <register here> #define FUEL1_TIMER_ENABLE() <macro here> #define FUEL2_TIMER_ENABLE() <macro here> #define FUEL3_TIMER_ENABLE() <macro here> #define FUEL4_TIMER_ENABLE() <macro here> //The below are optional, but recommended if there are sufficient timers/compares #define FUEL5_TIMER_ENABLE() <macro here> #define FUEL6_TIMER_ENABLE() <macro here> #define FUEL7_TIMER_ENABLE() <macro here> #define FUEL8_TIMER_ENABLE() <macro here> #define FUEL1_TIMER_DISABLE() <macro here> #define FUEL2_TIMER_DISABLE() <macro here> #define FUEL3_TIMER_DISABLE() <macro here> #define FUEL4_TIMER_DISABLE() <macro here> //The below are optional, but recommended if there are sufficient timers/compares #define FUEL5_TIMER_DISABLE() <macro here> #define FUEL6_TIMER_DISABLE() <macro here> #define FUEL7_TIMER_DISABLE() <macro here> #define FUEL8_TIMER_DISABLE() <macro here> #define IGN1_TIMER_ENABLE() <macro here> #define IGN2_TIMER_ENABLE() <macro here> #define IGN3_TIMER_ENABLE() <macro here> #define IGN4_TIMER_ENABLE() <macro here> //The below are optional, but recommended if there are sufficient timers/compares #define IGN5_TIMER_ENABLE() <macro here> #define IGN6_TIMER_ENABLE() <macro here> #define IGN7_TIMER_ENABLE() <macro here> #define IGN8_TIMER_ENABLE() <macro here> #define IGN1_TIMER_DISABLE() <macro here> #define IGN2_TIMER_DISABLE() <macro here> #define IGN3_TIMER_DISABLE() <macro here> #define IGN4_TIMER_DISABLE() <macro here> //The below are optional, but recommended if there are sufficient timers/compares #define IGN5_TIMER_DISABLE() <macro here> #define IGN6_TIMER_DISABLE() <macro here> #define IGN7_TIMER_DISABLE() <macro here> #define IGN8_TIMER_DISABLE() <macro here> #define MAX_TIMER_PERIOD 139808 //This is the maximum time, in uS, that the compare channels can run before overflowing. It is typically 65535 * <how long each tick represents> #define uS_TO_TIMER_COMPARE(uS) ((uS * 15) >> 5) //Converts a given number of uS into the required number of timer ticks until that time has passed. /* *********************************************************************************************************** * Auxiliaries */ //macro functions for enabling and disabling timer interrupts for the boost and vvt functions #define ENABLE_BOOST_TIMER() <macro here> #define DISABLE_BOOST_TIMER() <macro here> #define ENABLE_VVT_TIMER() <macro here> #define DISABLE_VVT_TIMER() <macro here> #define BOOST_TIMER_COMPARE <register here> #define BOOST_TIMER_COUNTER <register here> #define VVT_TIMER_COMPARE <register here> #define VVT_TIMER_COUNTER <register here> /* *********************************************************************************************************** * Idle */ //Same as above, but for the timer controlling PWM idle #define IDLE_COUNTER <register here> #define IDLE_COMPARE <register here> #define IDLE_TIMER_ENABLE() <macro here> #define IDLE_TIMER_DISABLE() <macro here> /* *********************************************************************************************************** * CAN / Second serial */ #endif //CORE_TEMPLATE #endif //TEMPLATE_H
6,156
C++
.h
127
45.669291
178
0.67555
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,125
board_stm32_official.h
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/board_stm32_official.h
#ifndef STM32OFFICIAL_H #define STM32OFFICIAL_H #include <Arduino.h> #if defined(STM32_CORE_VERSION_MAJOR) #include <HardwareTimer.h> #include <HardwareSerial.h> #include "STM32RTC.h" #include <SPI.h> #if defined(STM32F1) #include "stm32f1xx_ll_tim.h" #elif defined(STM32F3) #include "stm32f3xx_ll_tim.h" #elif defined(STM32F4) #include "stm32f4xx_ll_tim.h" #else /*Default should be STM32F4*/ #include "stm32f4xx_ll_tim.h" #endif /* *********************************************************************************************************** * General */ #define PORT_TYPE uint32_t #define PINMASK_TYPE uint32_t #define COMPARE_TYPE uint16_t #define COUNTER_TYPE uint16_t #define SERIAL_BUFFER_SIZE 517 //Size of the serial buffer used by new comms protocol. For SD transfers this must be at least 512 + 1 (flag) + 4 (sector) #define FPU_MAX_SIZE 32 //Size of the FPU buffer. 0 means no FPU. #define micros_safe() micros() //timer5 method is not used on anything but AVR, the micros_safe() macro is simply an alias for the normal micros() #define TIMER_RESOLUTION 4 #if defined(USER_BTN) #define EEPROM_RESET_PIN USER_BTN //onboard key0 for black STM32F407 boards and blackpills, keep pressed during boot to reset eeprom #endif #if defined(STM32F407xx) //Comment out this to disable SD logging for STM32 if needed. Currently SD logging for STM32 is experimental feature for F407. #define SD_LOGGING #endif #if defined SD_LOGGING #define RTC_ENABLED //SD logging with STM32 uses SD card in SPI mode, because used SD library doesn't support SDIO implementation. By default SPI3 is used that uses same pins as SDIO also, but in different order. extern SPIClass SD_SPI; //SPI3_MOSI, SPI3_MISO, SPI3_SCK #define SD_CONFIG SdSpiConfig(SD_CS_PIN, DEDICATED_SPI, SD_SCK_MHZ(50), &SD_SPI) //Alternatively same SPI bus can be used as there is for SPI flash. But this is not recommended due to slower speed and other possible problems. //#define SD_CONFIG SdSpiConfig(SD_CS_PIN, SHARED_SPI, SD_SCK_MHZ(50), &SPI_for_flash) #endif #define USE_SERIAL3 //When building for Black board Serial1 is instantiated,building generic STM32F4x7 has serial2 and serial 1 must be done here #if SERIAL_UART_INSTANCE==2 HardwareSerial Serial1(PA10, PA9); #endif extern STM32RTC& rtc; void initBoard(); uint16_t freeRam(); void doSystemReset(); void jumpToBootloader(); extern "C" char* sbrk(int incr); #if defined(ARDUINO_BLUEPILL_F103C8) || defined(ARDUINO_BLUEPILL_F103CB) \ || defined(ARDUINO_BLACKPILL_F401CC) || defined(ARDUINO_BLACKPILL_F411CE) #define pinIsReserved(pin) ( ((pin) == PA11) || ((pin) == PA12) || ((pin) == PC14) || ((pin) == PC15) ) #ifndef PB11 //Hack for F4 BlackPills #define PB11 PB10 #endif //Hack to allow compilation on small STM boards #ifndef A10 #define A10 PA0 #define A11 PA1 #define A12 PA2 #define A13 PA3 #define A14 PA4 #define A15 PA5 #endif #else #ifdef USE_SPI_EEPROM #define pinIsReserved(pin) ( ((pin) == PA11) || ((pin) == PA12) || ((pin) == PB3) || ((pin) == PB4) || ((pin) == PB5) || ((pin) == USE_SPI_EEPROM) ) //Forbidden pins like USB #else #define pinIsReserved(pin) ( ((pin) == PA11) || ((pin) == PA12) || ((pin) == PB3) || ((pin) == PB4) || ((pin) == PB5) || ((pin) == PB0) ) //Forbidden pins like USB #endif #endif #define PWM_FAN_AVAILABLE #ifndef LED_BUILTIN #define LED_BUILTIN PA7 #endif /* *********************************************************************************************************** * EEPROM emulation */ #if defined(SRAM_AS_EEPROM) #define EEPROM_LIB_H "src/BackupSram/BackupSramAsEEPROM.h" typedef uint16_t eeprom_address_t; #include EEPROM_LIB_H extern BackupSramAsEEPROM EEPROM; #elif defined(USE_SPI_EEPROM) #define EEPROM_LIB_H "src/SPIAsEEPROM/SPIAsEEPROM.h" typedef uint16_t eeprom_address_t; #include EEPROM_LIB_H extern SPIClass SPI_for_flash; //SPI1_MOSI, SPI1_MISO, SPI1_SCK //windbond W25Q16 SPI flash EEPROM emulation extern EEPROM_Emulation_Config EmulatedEEPROMMconfig; extern Flash_SPI_Config SPIconfig; extern SPI_EEPROM_Class EEPROM; #elif defined(FRAM_AS_EEPROM) //https://github.com/VitorBoss/FRAM #define EEPROM_LIB_H "src/FRAM/Fram.h" typedef uint16_t eeprom_address_t; #include EEPROM_LIB_H #if defined(STM32F407xx) extern FramClass EEPROM; /*(mosi, miso, sclk, ssel, clockspeed) 31/01/2020*/ #else extern FramClass EEPROM; //Blue/Black Pills #endif #else //default case, internal flash as EEPROM #define EEPROM_LIB_H "src/SPIAsEEPROM/SPIAsEEPROM.h" typedef uint16_t eeprom_address_t; #include EEPROM_LIB_H extern InternalSTM32F4_EEPROM_Class EEPROM; #if defined(STM32F401xC) #define SMALL_FLASH_MODE #endif #endif #define RTC_LIB_H "STM32RTC.h" /* *********************************************************************************************************** * Schedules * Timers Table for STM32F1 * TIMER1 TIMER2 TIMER3 TIMER4 * 1 - FAN 1 - INJ1 1 - IGN1 1 - oneMSInterval * 2 - BOOST 2 - INJ2 2 - IGN2 2 - * 3 - VVT 3 - INJ3 3 - IGN3 3 - * 4 - IDLE 4 - INJ4 4 - IGN4 4 - * * Timers Table for STM32F4 * TIMER1 | TIMER2 | TIMER3 | TIMER4 | TIMER5 | TIMER11 * 1 - FAN |1 - INJ1 |1 - IGN1 |1 - IGN5 |1 - INJ5 |1 - oneMSInterval * 2 - BOOST |2 - INJ2 |2 - IGN2 |2 - IGN6 |2 - INJ6 | * 3 - VVT |3 - INJ3 |3 - IGN3 |3 - IGN7 |3 - INJ7 | * 4 - IDLE |4 - INJ4 |4 - IGN4 |4 - IGN8 |4 - INJ8 | */ #define MAX_TIMER_PERIOD 65535*4 //The longest period of time (in uS) that the timer can permit (IN this case it is 65535 * 4, as each timer tick is 4uS) #define uS_TO_TIMER_COMPARE(uS) (uS>>2) //Converts a given number of uS into the required number of timer ticks until that time has passed. #define FUEL1_COUNTER (TIM3)->CNT #define FUEL2_COUNTER (TIM3)->CNT #define FUEL3_COUNTER (TIM3)->CNT #define FUEL4_COUNTER (TIM3)->CNT #define FUEL1_COMPARE (TIM3)->CCR1 #define FUEL2_COMPARE (TIM3)->CCR2 #define FUEL3_COMPARE (TIM3)->CCR3 #define FUEL4_COMPARE (TIM3)->CCR4 #define IGN1_COUNTER (TIM2)->CNT #define IGN2_COUNTER (TIM2)->CNT #define IGN3_COUNTER (TIM2)->CNT #define IGN4_COUNTER (TIM2)->CNT #define IGN1_COMPARE (TIM2)->CCR1 #define IGN2_COMPARE (TIM2)->CCR2 #define IGN3_COMPARE (TIM2)->CCR3 #define IGN4_COMPARE (TIM2)->CCR4 #define FUEL5_COUNTER (TIM5)->CNT #define FUEL6_COUNTER (TIM5)->CNT #define FUEL7_COUNTER (TIM5)->CNT #define FUEL8_COUNTER (TIM5)->CNT #define FUEL5_COMPARE (TIM5)->CCR1 #define FUEL6_COMPARE (TIM5)->CCR2 #define FUEL7_COMPARE (TIM5)->CCR3 #define FUEL8_COMPARE (TIM5)->CCR4 #define IGN5_COUNTER (TIM4)->CNT #define IGN6_COUNTER (TIM4)->CNT #define IGN7_COUNTER (TIM4)->CNT #define IGN8_COUNTER (TIM4)->CNT #define IGN5_COMPARE (TIM4)->CCR1 #define IGN6_COMPARE (TIM4)->CCR2 #define IGN7_COMPARE (TIM4)->CCR3 #define IGN8_COMPARE (TIM4)->CCR4 #define FUEL1_TIMER_ENABLE() (TIM3)->CR1 |= TIM_CR1_CEN; (TIM3)->SR = ~TIM_FLAG_CC1; (TIM3)->DIER |= TIM_DIER_CC1IE #define FUEL2_TIMER_ENABLE() (TIM3)->CR1 |= TIM_CR1_CEN; (TIM3)->SR = ~TIM_FLAG_CC2; (TIM3)->DIER |= TIM_DIER_CC2IE #define FUEL3_TIMER_ENABLE() (TIM3)->CR1 |= TIM_CR1_CEN; (TIM3)->SR = ~TIM_FLAG_CC3; (TIM3)->DIER |= TIM_DIER_CC3IE #define FUEL4_TIMER_ENABLE() (TIM3)->CR1 |= TIM_CR1_CEN; (TIM3)->SR = ~TIM_FLAG_CC4; (TIM3)->DIER |= TIM_DIER_CC4IE #define FUEL1_TIMER_DISABLE() (TIM3)->DIER &= ~TIM_DIER_CC1IE #define FUEL2_TIMER_DISABLE() (TIM3)->DIER &= ~TIM_DIER_CC2IE #define FUEL3_TIMER_DISABLE() (TIM3)->DIER &= ~TIM_DIER_CC3IE #define FUEL4_TIMER_DISABLE() (TIM3)->DIER &= ~TIM_DIER_CC4IE #define IGN1_TIMER_ENABLE() (TIM2)->CR1 |= TIM_CR1_CEN; (TIM2)->SR = ~TIM_FLAG_CC1; (TIM2)->DIER |= TIM_DIER_CC1IE #define IGN2_TIMER_ENABLE() (TIM2)->CR1 |= TIM_CR1_CEN; (TIM2)->SR = ~TIM_FLAG_CC2; (TIM2)->DIER |= TIM_DIER_CC2IE #define IGN3_TIMER_ENABLE() (TIM2)->CR1 |= TIM_CR1_CEN; (TIM2)->SR = ~TIM_FLAG_CC3; (TIM2)->DIER |= TIM_DIER_CC3IE #define IGN4_TIMER_ENABLE() (TIM2)->CR1 |= TIM_CR1_CEN; (TIM2)->SR = ~TIM_FLAG_CC4; (TIM2)->DIER |= TIM_DIER_CC4IE #define IGN1_TIMER_DISABLE() (TIM2)->DIER &= ~TIM_DIER_CC1IE #define IGN2_TIMER_DISABLE() (TIM2)->DIER &= ~TIM_DIER_CC2IE #define IGN3_TIMER_DISABLE() (TIM2)->DIER &= ~TIM_DIER_CC3IE #define IGN4_TIMER_DISABLE() (TIM2)->DIER &= ~TIM_DIER_CC4IE #define FUEL5_TIMER_ENABLE() (TIM5)->CR1 |= TIM_CR1_CEN; (TIM5)->CR1 |= TIM_CR1_CEN; (TIM5)->SR = ~TIM_FLAG_CC1; (TIM5)->DIER |= TIM_DIER_CC1IE #define FUEL6_TIMER_ENABLE() (TIM5)->CR1 |= TIM_CR1_CEN; (TIM5)->CR1 |= TIM_CR1_CEN; (TIM5)->SR = ~TIM_FLAG_CC2; (TIM5)->DIER |= TIM_DIER_CC2IE #define FUEL7_TIMER_ENABLE() (TIM5)->CR1 |= TIM_CR1_CEN; (TIM5)->CR1 |= TIM_CR1_CEN; (TIM5)->SR = ~TIM_FLAG_CC3; (TIM5)->DIER |= TIM_DIER_CC3IE #define FUEL8_TIMER_ENABLE() (TIM5)->CR1 |= TIM_CR1_CEN; (TIM5)->CR1 |= TIM_CR1_CEN; (TIM5)->SR = ~TIM_FLAG_CC4; (TIM5)->DIER |= TIM_DIER_CC4IE #define FUEL5_TIMER_DISABLE() (TIM5)->DIER &= ~TIM_DIER_CC1IE #define FUEL6_TIMER_DISABLE() (TIM5)->DIER &= ~TIM_DIER_CC2IE #define FUEL7_TIMER_DISABLE() (TIM5)->DIER &= ~TIM_DIER_CC3IE #define FUEL8_TIMER_DISABLE() (TIM5)->DIER &= ~TIM_DIER_CC4IE #define IGN5_TIMER_ENABLE() (TIM4)->CR1 |= TIM_CR1_CEN; (TIM4)->SR = ~TIM_FLAG_CC1; (TIM4)->DIER |= TIM_DIER_CC1IE #define IGN6_TIMER_ENABLE() (TIM4)->CR1 |= TIM_CR1_CEN; (TIM4)->SR = ~TIM_FLAG_CC2; (TIM4)->DIER |= TIM_DIER_CC2IE #define IGN7_TIMER_ENABLE() (TIM4)->CR1 |= TIM_CR1_CEN; (TIM4)->SR = ~TIM_FLAG_CC3; (TIM4)->DIER |= TIM_DIER_CC3IE #define IGN8_TIMER_ENABLE() (TIM4)->CR1 |= TIM_CR1_CEN; (TIM4)->SR = ~TIM_FLAG_CC4; (TIM4)->DIER |= TIM_DIER_CC4IE #define IGN5_TIMER_DISABLE() (TIM4)->DIER &= ~TIM_DIER_CC1IE #define IGN6_TIMER_DISABLE() (TIM4)->DIER &= ~TIM_DIER_CC2IE #define IGN7_TIMER_DISABLE() (TIM4)->DIER &= ~TIM_DIER_CC3IE #define IGN8_TIMER_DISABLE() (TIM4)->DIER &= ~TIM_DIER_CC4IE /* *********************************************************************************************************** * Auxiliaries */ #define ENABLE_BOOST_TIMER() (TIM1)->SR = ~TIM_FLAG_CC2; (TIM1)->DIER |= TIM_DIER_CC2IE; (TIM1)->CR1 |= TIM_CR1_CEN; #define DISABLE_BOOST_TIMER() (TIM1)->DIER &= ~TIM_DIER_CC2IE #define ENABLE_VVT_TIMER() (TIM1)->SR = ~TIM_FLAG_CC3; (TIM1)->DIER |= TIM_DIER_CC3IE; (TIM1)->CR1 |= TIM_CR1_CEN; #define DISABLE_VVT_TIMER() (TIM1)->DIER &= ~TIM_DIER_CC3IE #define ENABLE_FAN_TIMER() (TIM1)->SR = ~TIM_FLAG_CC1; (TIM1)->DIER |= TIM_DIER_CC1IE; (TIM1)->CR1 |= TIM_CR1_CEN; #define DISABLE_FAN_TIMER() (TIM1)->DIER &= ~TIM_DIER_CC1IE #define BOOST_TIMER_COMPARE (TIM1)->CCR2 #define BOOST_TIMER_COUNTER (TIM1)->CNT #define VVT_TIMER_COMPARE (TIM1)->CCR3 #define VVT_TIMER_COUNTER (TIM1)->CNT #define FAN_TIMER_COMPARE (TIM1)->CCR1 #define FAN_TIMER_COUNTER (TIM1)->CNT /* *********************************************************************************************************** * Idle */ #define IDLE_COUNTER (TIM1)->CNT #define IDLE_COMPARE (TIM1)->CCR4 #define IDLE_TIMER_ENABLE() (TIM1)->SR = ~TIM_FLAG_CC4; (TIM1)->DIER |= TIM_DIER_CC4IE; (TIM1)->CR1 |= TIM_CR1_CEN; #define IDLE_TIMER_DISABLE() (TIM1)->DIER &= ~TIM_DIER_CC4IE /* *********************************************************************************************************** * Timers */ extern HardwareTimer Timer1; extern HardwareTimer Timer2; extern HardwareTimer Timer3; extern HardwareTimer Timer4; #if !defined(ARDUINO_BLUEPILL_F103C8) && !defined(ARDUINO_BLUEPILL_F103CB) //F103 just have 4 timers extern HardwareTimer Timer5; #if defined(TIM11) extern HardwareTimer Timer11; #elif defined(TIM7) extern HardwareTimer Timer11; #endif #endif #if ((STM32_CORE_VERSION_MINOR<=8) & (STM32_CORE_VERSION_MAJOR==1)) void oneMSInterval(HardwareTimer*); void boostInterrupt(HardwareTimer*); void fuelSchedule1Interrupt(HardwareTimer*); void fuelSchedule2Interrupt(HardwareTimer*); void fuelSchedule3Interrupt(HardwareTimer*); void fuelSchedule4Interrupt(HardwareTimer*); #if (INJ_CHANNELS >= 5) void fuelSchedule5Interrupt(HardwareTimer*); #endif #if (INJ_CHANNELS >= 6) void fuelSchedule6Interrupt(HardwareTimer*); #endif #if (INJ_CHANNELS >= 7) void fuelSchedule7Interrupt(HardwareTimer*); #endif #if (INJ_CHANNELS >= 8) void fuelSchedule8Interrupt(HardwareTimer*); #endif void idleInterrupt(HardwareTimer*); void vvtInterrupt(HardwareTimer*); void fanInterrupt(HardwareTimer*); void ignitionSchedule1Interrupt(HardwareTimer*); void ignitionSchedule2Interrupt(HardwareTimer*); void ignitionSchedule3Interrupt(HardwareTimer*); void ignitionSchedule4Interrupt(HardwareTimer*); #if (IGN_CHANNELS >= 5) void ignitionSchedule5Interrupt(HardwareTimer*); #endif #if (IGN_CHANNELS >= 6) void ignitionSchedule6Interrupt(HardwareTimer*); #endif #if (IGN_CHANNELS >= 7) void ignitionSchedule7Interrupt(HardwareTimer*); #endif #if (IGN_CHANNELS >= 8) void ignitionSchedule8Interrupt(HardwareTimer*); #endif #endif //End core<=1.8 /* *********************************************************************************************************** * CAN / Second serial */ #if HAL_CAN_MODULE_ENABLED #define NATIVE_CAN_AVAILABLE //HardwareSerial CANSerial(PD6, PD5); #include <src/STM32_CAN/STM32_CAN.h> //This activates CAN1 interface on STM32, but it's named as Can0, because that's how Teensy implementation is done extern STM32_CAN Can0; static CAN_message_t outMsg; static CAN_message_t inMsg; #endif #endif //CORE_STM32 #endif //STM32_H
13,445
C++
.h
295
43.752542
194
0.673948
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,126
cancomms.h
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/cancomms.h
#ifndef CANCOMMS_H #define CANCOMMS_H #define NEW_CAN_PACKET_SIZE 123 #define CAN_PACKET_SIZE 75 #if ( defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) ) #define CANSerial_AVAILABLE extern HardwareSerial &CANSerial; #elif defined(CORE_STM32) #define CANSerial_AVAILABLE #ifndef HAVE_HWSERIAL2 //Hack to get the code to compile on BlackPills #define Serial2 Serial1 #endif #if defined(STM32GENERIC) // STM32GENERIC core extern SerialUART &CANSerial; #else //libmaple core aka STM32DUINO extern HardwareSerial &CANSerial; #endif #elif defined(CORE_TEENSY) #define CANSerial_AVAILABLE extern HardwareSerial &CANSerial; #endif void secondserial_Command(void);//This is the heart of the Command Line Interpreter. All that needed to be done was to make it human readable. void sendcanValues(uint16_t offset, uint16_t packetLength, byte cmd, byte portNum); void can_Command(void); void sendCancommand(uint8_t cmdtype , uint16_t canadddress, uint8_t candata1, uint8_t candata2, uint16_t sourcecanAddress); void obd_response(uint8_t therequestedPID , uint8_t therequestedPIDlow, uint8_t therequestedPIDhigh); void readAuxCanBus(); #endif // CANCOMMS_H
1,194
C++
.h
28
40.357143
143
0.786575
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,127
decoders.h
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/decoders.h
#ifndef DECODERS_H #define DECODERS_H #include "globals.h" #if defined(CORE_AVR) #define READ_PRI_TRIGGER() ((*triggerPri_pin_port & triggerPri_pin_mask) ? true : false) #define READ_SEC_TRIGGER() ((*triggerSec_pin_port & triggerSec_pin_mask) ? true : false) #define READ_THIRD_TRIGGER() ((*triggerThird_pin_port & triggerThird_pin_mask) ? true : false) #else #define READ_PRI_TRIGGER() digitalRead(pinTrigger) #define READ_SEC_TRIGGER() digitalRead(pinTrigger2) #define READ_THIRD_TRIGGER() digitalRead(pinTrigger3) #endif #define DECODER_MISSING_TOOTH 0 #define DECODER_BASIC_DISTRIBUTOR 1 #define DECODER_DUAL_WHEEL 2 #define DECODER_GM7X 3 #define DECODER_4G63 4 #define DECODER_24X 5 #define DECODER_JEEP2000 6 #define DECODER_AUDI135 7 #define DECODER_HONDA_D17 8 #define DECODER_MIATA_9905 9 #define DECODER_MAZDA_AU 10 #define DECODER_NON360 11 #define DECODER_NISSAN_360 12 #define DECODER_SUBARU_67 13 #define DECODER_DAIHATSU_PLUS1 14 #define DECODER_HARLEY 15 #define DECODER_36_2_2_2 16 #define DECODER_36_2_1 17 #define DECODER_420A 18 #define DECODER_WEBER 19 #define DECODER_ST170 20 #define DECODER_DRZ400 21 #define DECODER_NGC 22 #define DECODER_VMAX 23 #define DECODER_RENIX 24 #define DECODER_ROVERMEMS 25 #define BIT_DECODER_2ND_DERIV 0 //The use of the 2nd derivative calculation is limited to certain decoders. This is set to either true or false in each decoders setup routine #define BIT_DECODER_IS_SEQUENTIAL 1 //Whether or not the decoder supports sequential operation #define BIT_DECODER_UNUSED1 2 #define BIT_DECODER_HAS_SECONDARY 3 //Whether or not the decoder supports fixed cranking timing #define BIT_DECODER_HAS_FIXED_CRANKING 4 #define BIT_DECODER_VALID_TRIGGER 5 //Is set true when the last trigger (Primary or secondary) was valid (ie passed filters) #define BIT_DECODER_TOOTH_ANG_CORRECT 6 //Whether or not the triggerToothAngle variable is currently accurate. Some patterns have times when the triggerToothAngle variable cannot be accurately set. //220 bytes free extern volatile uint8_t decoderState; /* extern volatile bool validTrigger; //Is set true when the last trigger (Primary or secondary) was valid (ie passed filters) extern volatile bool triggerToothAngleIsCorrect; //Whether or not the triggerToothAngle variable is currently accurate. Some patterns have times when the triggerToothAngle variable cannot be accurately set. extern bool secondDerivEnabled; //The use of the 2nd derivative calculation is limited to certain decoders. This is set to either true or false in each decoders setup routine extern bool decoderIsSequential; //Whether or not the decoder supports sequential operation extern bool decoderHasSecondary; //Whether or not the pattern uses a secondary input extern bool decoderHasFixedCrankingTiming; */ //This isn't to to filter out wrong pulses on triggers, but just to smooth out the cam angle reading for better closed loop VVT control. #define ANGLE_FILTER(input, alpha, prior) (((long)input * (256 - alpha) + ((long)prior * alpha))) >> 8 void loggerPrimaryISR(void); void loggerSecondaryISR(void); void loggerTertiaryISR(void); //All of the below are the 6 required functions for each decoder / pattern void triggerSetup_missingTooth(void); void triggerPri_missingTooth(void); void triggerSec_missingTooth(void); void triggerThird_missingTooth(void); uint16_t getRPM_missingTooth(void); int getCrankAngle_missingTooth(void); extern void triggerSetEndTeeth_missingTooth(void); void triggerSetup_DualWheel(void); void triggerPri_DualWheel(void); void triggerSec_DualWheel(void); uint16_t getRPM_DualWheel(void); int getCrankAngle_DualWheel(void); void triggerSetEndTeeth_DualWheel(void); void triggerSetup_BasicDistributor(void); void triggerPri_BasicDistributor(void); void triggerSec_BasicDistributor(void); uint16_t getRPM_BasicDistributor(void); int getCrankAngle_BasicDistributor(void); void triggerSetEndTeeth_BasicDistributor(void); void triggerSetup_GM7X(void); void triggerPri_GM7X(void); void triggerSec_GM7X(void); uint16_t getRPM_GM7X(void); int getCrankAngle_GM7X(void); void triggerSetEndTeeth_GM7X(void); void triggerSetup_4G63(void); void triggerPri_4G63(void); void triggerSec_4G63(void); uint16_t getRPM_4G63(void); int getCrankAngle_4G63(void); void triggerSetEndTeeth_4G63(void); void triggerSetup_24X(void); void triggerPri_24X(void); void triggerSec_24X(void); uint16_t getRPM_24X(void); int getCrankAngle_24X(void); void triggerSetEndTeeth_24X(void); void triggerSetup_Jeep2000(void); void triggerPri_Jeep2000(void); void triggerSec_Jeep2000(void); uint16_t getRPM_Jeep2000(void); int getCrankAngle_Jeep2000(void); void triggerSetEndTeeth_Jeep2000(void); void triggerSetup_Audi135(void); void triggerPri_Audi135(void); void triggerSec_Audi135(void); uint16_t getRPM_Audi135(void); int getCrankAngle_Audi135(void); void triggerSetEndTeeth_Audi135(void); void triggerSetup_HondaD17(void); void triggerPri_HondaD17(void); void triggerSec_HondaD17(void); uint16_t getRPM_HondaD17(void); int getCrankAngle_HondaD17(void); void triggerSetEndTeeth_HondaD17(void); void triggerSetup_Miata9905(void); void triggerPri_Miata9905(void); void triggerSec_Miata9905(void); uint16_t getRPM_Miata9905(void); int getCrankAngle_Miata9905(void); void triggerSetEndTeeth_Miata9905(void); int getCamAngle_Miata9905(void); void triggerSetup_MazdaAU(void); void triggerPri_MazdaAU(void); void triggerSec_MazdaAU(void); uint16_t getRPM_MazdaAU(void); int getCrankAngle_MazdaAU(void); void triggerSetEndTeeth_MazdaAU(void); void triggerSetup_non360(void); void triggerPri_non360(void); void triggerSec_non360(void); uint16_t getRPM_non360(void); int getCrankAngle_non360(void); void triggerSetEndTeeth_non360(void); void triggerSetup_Nissan360(void); void triggerPri_Nissan360(void); void triggerSec_Nissan360(void); uint16_t getRPM_Nissan360(void); int getCrankAngle_Nissan360(void); void triggerSetEndTeeth_Nissan360(void); void triggerSetup_Subaru67(void); void triggerPri_Subaru67(void); void triggerSec_Subaru67(void); uint16_t getRPM_Subaru67(void); int getCrankAngle_Subaru67(void); void triggerSetEndTeeth_Subaru67(void); void triggerSetup_Daihatsu(void); void triggerPri_Daihatsu(void); void triggerSec_Daihatsu(void); uint16_t getRPM_Daihatsu(void); int getCrankAngle_Daihatsu(void); void triggerSetEndTeeth_Daihatsu(void); void triggerSetup_Harley(void); void triggerPri_Harley(void); void triggerSec_Harley(void); uint16_t getRPM_Harley(void); int getCrankAngle_Harley(void); void triggerSetEndTeeth_Harley(void); void triggerSetup_ThirtySixMinus222(void); void triggerPri_ThirtySixMinus222(void); void triggerSec_ThirtySixMinus222(void); uint16_t getRPM_ThirtySixMinus222(void); int getCrankAngle_ThirtySixMinus222(void); void triggerSetEndTeeth_ThirtySixMinus222(void); void triggerSetup_ThirtySixMinus21(void); void triggerPri_ThirtySixMinus21(void); void triggerSec_ThirtySixMinus21(void); uint16_t getRPM_ThirtySixMinus21(void); int getCrankAngle_ThirtySixMinus21(void); void triggerSetEndTeeth_ThirtySixMinus21(void); void triggerSetup_420a(void); void triggerPri_420a(void); void triggerSec_420a(void); uint16_t getRPM_420a(void); int getCrankAngle_420a(void); void triggerSetEndTeeth_420a(void); void triggerPri_Webber(void); void triggerSec_Webber(void); void triggerSetup_FordST170(void); void triggerSec_FordST170(void); uint16_t getRPM_FordST170(void); int getCrankAngle_FordST170(void); void triggerSetEndTeeth_FordST170(void); void triggerSetup_DRZ400(void); void triggerSec_DRZ400(void); void triggerSetup_NGC(void); void triggerPri_NGC(void); void triggerSec_NGC4(void); void triggerSec_NGC68(void); uint16_t getRPM_NGC(void); void triggerSetEndTeeth_NGC(void); void triggerSetup_Renix(void); void triggerPri_Renix(void); void triggerSetEndTeeth_Renix(void); void triggerSetup_RoverMEMS(void); void triggerPri_RoverMEMS(void); void triggerSec_RoverMEMS(void); uint16_t getRPM_RoverMEMS(void); int getCrankAngle_RoverMEMS(void); void triggerSetEndTeeth_RoverMEMS(void); void triggerSetup_Vmax(void); void triggerPri_Vmax(void); void triggerSec_Vmax(void); uint16_t getRPM_Vmax(void); int getCrankAngle_Vmax(void); void triggerSetEndTeeth_Vmax(void); extern void (*triggerHandler)(void); //Pointer for the trigger function (Gets pointed to the relevant decoder) extern void (*triggerSecondaryHandler)(void); //Pointer for the secondary trigger function (Gets pointed to the relevant decoder) extern void (*triggerTertiaryHandler)(void); //Pointer for the tertiary trigger function (Gets pointed to the relevant decoder) extern uint16_t (*getRPM)(void); //Pointer to the getRPM function (Gets pointed to the relevant decoder) extern int (*getCrankAngle)(void); //Pointer to the getCrank Angle function (Gets pointed to the relevant decoder) extern void (*triggerSetEndTeeth)(void); //Pointer to the triggerSetEndTeeth function of each decoder extern volatile unsigned long curTime; extern volatile unsigned long curGap; extern volatile unsigned long curTime2; extern volatile unsigned long curGap2; extern volatile unsigned long lastGap; extern volatile unsigned long targetGap; extern unsigned long MAX_STALL_TIME; //The maximum time (in uS) that the system will continue to function before the engine is considered stalled/stopped. This is unique to each decoder, depending on the number of teeth etc. 500000 (half a second) is used as the default value, most decoders will be much less. extern volatile uint16_t toothCurrentCount; //The current number of teeth (Once sync has been achieved, this can never actually be 0 extern volatile byte toothSystemCount; //Used for decoders such as Audi 135 where not every tooth is used for calculating crank angle. This variable stores the actual number of teeth, not the number being used to calculate crank angle extern volatile unsigned long toothSystemLastToothTime; //As below, but used for decoders where not every tooth count is used for calculation extern volatile unsigned long toothLastToothTime; //The time (micros()) that the last tooth was registered extern volatile unsigned long toothLastSecToothTime; //The time (micros()) that the last tooth was registered on the secondary input extern volatile unsigned long toothLastThirdToothTime; //The time (micros()) that the last tooth was registered on the second cam input extern volatile unsigned long toothLastMinusOneToothTime; //The time (micros()) that the tooth before the last tooth was registered extern volatile unsigned long toothLastMinusOneSecToothTime; //The time (micros()) that the tooth before the last tooth was registered on secondary input extern volatile unsigned long targetGap2; extern volatile unsigned long toothOneTime; //The time (micros()) that tooth 1 last triggered extern volatile unsigned long toothOneMinusOneTime; //The 2nd to last time (micros()) that tooth 1 last triggered extern volatile bool revolutionOne; // For sequential operation, this tracks whether the current revolution is 1 or 2 (not 1) extern volatile unsigned int secondaryToothCount; //Used for identifying the current secondary (Usually cam) tooth for patterns with multiple secondary teeth extern volatile unsigned long secondaryLastToothTime; //The time (micros()) that the last tooth was registered (Cam input) extern volatile unsigned long secondaryLastToothTime1; //The time (micros()) that the last tooth was registered (Cam input) extern uint16_t triggerActualTeeth; extern volatile unsigned long triggerFilterTime; // The shortest time (in uS) that pulses will be accepted (Used for debounce filtering) extern volatile unsigned long triggerSecFilterTime; // The shortest time (in uS) that pulses will be accepted (Used for debounce filtering) for the secondary input extern unsigned int triggerSecFilterTime_duration; // The shortest valid time (in uS) pulse DURATION extern volatile uint16_t triggerToothAngle; //The number of crank degrees that elapse per tooth extern byte checkSyncToothCount; //How many teeth must've been seen on this revolution before we try to confirm sync (Useful for missing tooth type decoders) extern unsigned long elapsedTime; extern unsigned long lastCrankAngleCalc; extern int16_t lastToothCalcAdvance; //Invalid value here forces calculation of this on first main loop extern unsigned long lastVVTtime; //The time between the vvt reference pulse and the last crank pulse extern uint16_t ignition1EndTooth; extern uint16_t ignition2EndTooth; extern uint16_t ignition3EndTooth; extern uint16_t ignition4EndTooth; extern uint16_t ignition5EndTooth; extern uint16_t ignition6EndTooth; extern uint16_t ignition7EndTooth; extern uint16_t ignition8EndTooth; extern int16_t toothAngles[24]; //An array for storing fixed tooth angles. Currently sized at 24 for the GM 24X decoder, but may grow later if there are other decoders that use this style //Used for identifying long and short pulses on the 4G63 (And possibly other) trigger patterns #define LONG 0; #define SHORT 1; #define CRANK_SPEED 0 #define CAM_SPEED 1 #define TOOTH_CRANK 0 #define TOOTH_CAM_SECONDARY 1 #define TOOTH_CAM_TERTIARY 2 // used by the ROVER MEMS pattern #define ID_TOOTH_PATTERN 0 // have we identified teeth to skip for calculating RPM? #define SKIP_TOOTH1 1 #define SKIP_TOOTH2 2 #define SKIP_TOOTH3 3 #define SKIP_TOOTH4 4 #endif
13,602
C++
.h
269
49.327138
310
0.806248
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,128
SD_logger.h
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/SD_logger.h
#ifndef SD_LOGGER_H #define SD_LOGGER_H #ifdef SD_LOGGING #ifdef __SD_H__ #include <SD.h> #else #include "SdFat.h" #endif #include "logger.h" //#include <SdSpiCard.h> #include "RingBuf.h" #define SD_STATUS_OFF 0 /**< SD system is inactive. FS and file remain closed */ #define SD_STATUS_READY 1 /**< Card is present and ready, but a log session has not commenced */ #define SD_STATUS_ACTIVE 2 /**< Log session commenced */ #define SD_STATUS_ERROR_NO_CARD 3 /**< No SD card found when attempting to open file */ #define SD_STATUS_ERROR_NO_FS 4 /**< No filesystem found when attempting to open file */ #define SD_STATUS_ERROR_NO_WRITE 5 /**< Card and filesystem found, however file creation failed due to no write access */ #define SD_STATUS_ERROR_NO_SPACE 6 /**< File could not be preallocated as there is not enough space on card */ #define SD_STATUS_ERROR_WRITE_FAIL 7 /**< Log file created and opened, but a sector write failed during logging */ #define SD_STATUS_ERROR_FORMAT_FAIL 8 /**< Attempted formatting of SD card failed */ #define SD_STATUS_CARD_PRESENT 0 //0=no card, 1=card present #define SD_STATUS_CARD_TYPE 1 //0=SD, 1=SDHC #define SD_STATUS_CARD_READY 2 //0=not ready, 1=ready #define SD_STATUS_CARD_LOGGING 3 //0=not logging, 1=logging #define SD_STATUS_CARD_ERROR 4 //0=no error, 1=error #define SD_STATUS_CARD_VERSION 5 //0=1.x, 1=2.x #define SD_STATUS_CARD_FS 6 //0=no FAT16, 1=FAT32 #define SD_STATUS_CARD_UNUSED 7 //0=normal, 1=unused #define SD_SECTOR_SIZE 512 // Standard SD sector size #if defined CORE_TEENSY #define SD_CS_PIN BUILTIN_SDCARD #elif defined CORE_STM32 #define SD_CS_PIN PD2 //CS pin can be pretty much anything, but PD2 is one of the ones left unused from SDIO pins. #else #define SD_CS_PIN 10 //This is a made up value for now #endif //Test values only #define SD_LOG_FILE_SIZE 10000000 //Default 10mb file size #define MAX_LOG_FILES 10000 #define LOG_FILE_PREFIX "SPD_" #define LOG_FILE_EXTENSION "csv" #define RING_BUF_CAPACITY (SD_LOG_ENTRY_SIZE * 10) //Allow for 10 entries in the ringbuffer. Will need tuning /* Standard FAT16/32 SdFs sd; FsFile logFile; RingBuf<ExFile, RING_BUF_CAPACITY> rb; */ //ExFat extern SdExFat sd; extern ExFile logFile; extern RingBuf<ExFile, RING_BUF_CAPACITY> rb; extern uint8_t SD_status; extern uint16_t currentLogFileNumber; extern bool manualLogActive; void initSD(); void writeSDLogEntry(); void writetSDLogHeader(); void beginSDLogging(); void endSDLogging(); void syncSDLog(); void setTS_SD_status(); void formatExFat(); void deleteLogFile(char, char, char, char); bool createLogFile(); void dateTime(uint16_t*, uint16_t*, uint8_t*); //Used for timestamping with RTC uint16_t getNextSDLogFileNumber(); bool getSDLogFileDetails(uint8_t* , uint16_t); void readSDSectors(uint8_t*, uint32_t, uint16_t); uint32_t sectorCount(); #endif //SD_LOGGING #endif //SD_LOGGER_H
3,005
C++
.h
72
40.291667
124
0.721727
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,129
table3d_axis_io.h
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/table3d_axis_io.h
/** * @addtogroup table_3d * @{ */ /** \file * @brief 3D table axis I/O support */ #pragma once #include "int16_byte.h" #include "table3d_axes.h" #ifdef USE_LIBDIVIDE #include "src/libdivide/constant_fast_div.h" #endif /** @brief table axis I/O support * * @attention Using \c constexpr class static variables seems to be the best * combination of size and speed - \c constexpr implies \c inline, so we * can't use it on traditional \c extern global variables. */ class table3d_axis_io { public: /** * @brief Obtain a converter instance for a given axis domain. * * Often we need to deal internally with values that fit in 16-bits but do * not require much accuracy. E.g. RPM. For these values we can * save storage space (EEPROM) by scaling to/from 8-bits using a fixed divisor. * * The divisor is dependent on the domain. I.e all axes with the same domain use * the same divisor * * Conversion during I/O is orthogonal to other axis concerns, so is separated and * encapsulated here. */ static constexpr const int16_byte* get_converter(axis_domain domain) { return domain==axis_domain_Rpm ? &converter_100 : domain==axis_domain_Load ? &converter_2 : &converter_1; } /** * @brief Convert to a \c byte * * Useful for converting a single value. * If converting multiple, probably faster to cache the converter rather than * repeatedly calling this function. */ static inline byte to_byte(axis_domain domain, int16_t value) { return get_converter(domain)->to_byte(value); } /** * @brief Convert from a \c byte * * Useful for converting a single value. * If converting multiple, probably faster to cache the converter rather than * repeatedly calling this function. */ static inline int16_t from_byte(axis_domain domain, byte in ) { return get_converter(domain)->from_byte(in); } private: #ifdef USE_LIBDIVIDE static constexpr int16_byte converter_100 = { 100, { S16_MAGIC(100), S16_MORE(100) } }; static constexpr int16_byte converter_2 = { 2, { S16_MAGIC(2), S16_MORE(2) } }; static constexpr int16_byte converter_1 = { 1, { S16_MAGIC(1), S16_MORE(1) } }; #else static constexpr int16_byte converter_100 = { 100 }; static constexpr int16_byte converter_2 = { 2 }; static constexpr int16_byte converter_1 = { 1 }; #endif }; /** @} */
2,466
C++
.h
66
32.848485
118
0.674749
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,130
board_teensy35.h
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/board_teensy35.h
#ifndef TEENSY35_H #define TEENSY35_H #if defined(CORE_TEENSY) && defined(CORE_TEENSY35) /* *********************************************************************************************************** * General */ void initBoard(); uint16_t freeRam(); void doSystemReset(); void jumpToBootloader(); time_t getTeensy3Time(); #define PORT_TYPE uint8_t //Size of the port variables #define PINMASK_TYPE uint8_t #define COMPARE_TYPE uint16_t #define COUNTER_TYPE uint16_t #define SERIAL_BUFFER_SIZE 517 //Size of the serial buffer used by new comms protocol. For SD transfers this must be at least 512 + 1 (flag) + 4 (sector) #define FPU_MAX_SIZE 32 //Size of the FPU buffer. 0 means no FPU. #define SD_LOGGING //SD logging enabled by default for Teensy 3.5 as it has the slot built in #define BOARD_MAX_DIGITAL_PINS 34 #define BOARD_MAX_IO_PINS 34 //digital pins + analog channels + 1 #ifdef USE_SPI_EEPROM #define EEPROM_LIB_H "src/SPIAsEEPROM/SPIAsEEPROM.h" typedef uint16_t eeprom_address_t; #else #define EEPROM_LIB_H <EEPROM.h> typedef int eeprom_address_t; #endif #define RTC_ENABLED #define RTC_LIB_H "TimeLib.h" #define SD_CONFIG SdioConfig(FIFO_SDIO) //Set Teensy to use SDIO in FIFO mode. This is the fastest SD mode on Teensy as it offloads most of the writes #define micros_safe() micros() //timer5 method is not used on anything but AVR, the micros_safe() macro is simply an alias for the normal micros() #define PWM_FAN_AVAILABLE #define pinIsReserved(pin) ( ((pin) == 0) || ((pin) == 1) || ((pin) == 3) || ((pin) == 4) ) //Forbidden pins like USB /* *********************************************************************************************************** * Schedules */ //shawnhymel.com/661/learning-the-teensy-lc-interrupt-service-routines/ #define FUEL1_COUNTER FTM0_CNT #define FUEL2_COUNTER FTM0_CNT #define FUEL3_COUNTER FTM0_CNT #define FUEL4_COUNTER FTM0_CNT #define FUEL5_COUNTER FTM3_CNT #define FUEL6_COUNTER FTM3_CNT #define FUEL7_COUNTER FTM3_CNT #define FUEL8_COUNTER FTM3_CNT #define IGN1_COUNTER FTM0_CNT #define IGN2_COUNTER FTM0_CNT #define IGN3_COUNTER FTM0_CNT #define IGN4_COUNTER FTM0_CNT #define IGN5_COUNTER FTM3_CNT #define IGN6_COUNTER FTM3_CNT #define IGN7_COUNTER FTM3_CNT #define IGN8_COUNTER FTM3_CNT #define FUEL1_COMPARE FTM0_C0V #define FUEL2_COMPARE FTM0_C1V #define FUEL3_COMPARE FTM0_C2V #define FUEL4_COMPARE FTM0_C3V #define FUEL5_COMPARE FTM3_C0V #define FUEL6_COMPARE FTM3_C1V #define FUEL7_COMPARE FTM3_C2V #define FUEL8_COMPARE FTM3_C3V #define IGN1_COMPARE FTM0_C4V #define IGN2_COMPARE FTM0_C5V #define IGN3_COMPARE FTM0_C6V #define IGN4_COMPARE FTM0_C7V #define IGN5_COMPARE FTM3_C4V #define IGN6_COMPARE FTM3_C5V #define IGN7_COMPARE FTM3_C6V #define IGN8_COMPARE FTM3_C7V #define FUEL1_TIMER_ENABLE() FTM0_C0SC |= FTM_CSC_CHIE //Write 1 to the CHIE (Channel Interrupt Enable) bit of channel 0 Status/Control #define FUEL2_TIMER_ENABLE() FTM0_C1SC |= FTM_CSC_CHIE #define FUEL3_TIMER_ENABLE() FTM0_C2SC |= FTM_CSC_CHIE #define FUEL4_TIMER_ENABLE() FTM0_C3SC |= FTM_CSC_CHIE #define FUEL5_TIMER_ENABLE() FTM3_C0SC |= FTM_CSC_CHIE #define FUEL6_TIMER_ENABLE() FTM3_C1SC |= FTM_CSC_CHIE #define FUEL7_TIMER_ENABLE() FTM3_C2SC |= FTM_CSC_CHIE #define FUEL8_TIMER_ENABLE() FTM3_C3SC |= FTM_CSC_CHIE #define FUEL1_TIMER_DISABLE() FTM0_C0SC &= ~FTM_CSC_CHIE //Write 0 to the CHIE (Channel Interrupt Enable) bit of channel 0 Status/Control #define FUEL2_TIMER_DISABLE() FTM0_C1SC &= ~FTM_CSC_CHIE #define FUEL3_TIMER_DISABLE() FTM0_C2SC &= ~FTM_CSC_CHIE #define FUEL4_TIMER_DISABLE() FTM0_C3SC &= ~FTM_CSC_CHIE #define FUEL5_TIMER_DISABLE() FTM3_C0SC &= ~FTM_CSC_CHIE //Write 0 to the CHIE (Channel Interrupt Enable) bit of channel 0 Status/Control #define FUEL6_TIMER_DISABLE() FTM3_C1SC &= ~FTM_CSC_CHIE #define FUEL7_TIMER_DISABLE() FTM3_C2SC &= ~FTM_CSC_CHIE #define FUEL8_TIMER_DISABLE() FTM3_C3SC &= ~FTM_CSC_CHIE #define IGN1_TIMER_ENABLE() FTM0_C4SC |= FTM_CSC_CHIE #define IGN2_TIMER_ENABLE() FTM0_C5SC |= FTM_CSC_CHIE #define IGN3_TIMER_ENABLE() FTM0_C6SC |= FTM_CSC_CHIE #define IGN4_TIMER_ENABLE() FTM0_C7SC |= FTM_CSC_CHIE #define IGN5_TIMER_ENABLE() FTM3_C4SC |= FTM_CSC_CHIE #define IGN6_TIMER_ENABLE() FTM3_C5SC |= FTM_CSC_CHIE #define IGN7_TIMER_ENABLE() FTM3_C6SC |= FTM_CSC_CHIE #define IGN8_TIMER_ENABLE() FTM3_C7SC |= FTM_CSC_CHIE #define IGN1_TIMER_DISABLE() FTM0_C4SC &= ~FTM_CSC_CHIE #define IGN2_TIMER_DISABLE() FTM0_C5SC &= ~FTM_CSC_CHIE #define IGN3_TIMER_DISABLE() FTM0_C6SC &= ~FTM_CSC_CHIE #define IGN4_TIMER_DISABLE() FTM0_C7SC &= ~FTM_CSC_CHIE #define IGN5_TIMER_DISABLE() FTM3_C4SC &= ~FTM_CSC_CHIE #define IGN6_TIMER_DISABLE() FTM3_C5SC &= ~FTM_CSC_CHIE #define IGN7_TIMER_DISABLE() FTM3_C6SC &= ~FTM_CSC_CHIE #define IGN8_TIMER_DISABLE() FTM3_C7SC &= ~FTM_CSC_CHIE #define MAX_TIMER_PERIOD 139808 // 2.13333333uS * 65535 #define uS_TO_TIMER_COMPARE(uS) ((uS * 15) >> 5) //Converts a given number of uS into the required number of timer ticks until that time has passed. /* *********************************************************************************************************** * Auxiliaries */ #define ENABLE_BOOST_TIMER() FTM1_C0SC |= FTM_CSC_CHIE #define DISABLE_BOOST_TIMER() FTM1_C0SC &= ~FTM_CSC_CHIE #define ENABLE_VVT_TIMER() FTM1_C1SC |= FTM_CSC_CHIE #define DISABLE_VVT_TIMER() FTM1_C1SC &= ~FTM_CSC_CHIE #define ENABLE_FAN_TIMER() FTM2_C1SC |= FTM_CSC_CHIE #define DISABLE_FAN_TIMER() FTM2_C1SC &= ~FTM_CSC_CHIE #define BOOST_TIMER_COMPARE FTM1_C0V #define BOOST_TIMER_COUNTER FTM1_CNT #define VVT_TIMER_COMPARE FTM1_C1V #define VVT_TIMER_COUNTER FTM1_CNT #define FAN_TIMER_COMPARE FTM2_C1V #define FAN_TIMER_COUNTER FTM2_CNT void boostInterrupt(); void vvtInterrupt(); void fanInterrupt(); /* *********************************************************************************************************** * Idle */ #define IDLE_COUNTER FTM2_CNT #define IDLE_COMPARE FTM2_C0V #define IDLE_TIMER_ENABLE() FTM2_C0SC |= FTM_CSC_CHIE #define IDLE_TIMER_DISABLE() FTM2_C0SC &= ~FTM_CSC_CHIE void idleInterrupt(); /* *********************************************************************************************************** * CAN / Second serial */ #define USE_SERIAL3 // Secondary serial port to use #include <FlexCAN_T4.h> #if defined(__MK64FX512__) // use for Teensy 3.5 only extern FlexCAN_T4<CAN0, RX_SIZE_256, TX_SIZE_16> Can0; #elif defined(__MK66FX1M0__) // use for Teensy 3.6 only extern FlexCAN_T4<CAN0, RX_SIZE_256, TX_SIZE_16> Can0; extern FlexCAN_T4<CAN1, RX_SIZE_256, TX_SIZE_16> Can1; #endif static CAN_message_t outMsg; static CAN_message_t inMsg; #define NATIVE_CAN_AVAILABLE #endif //CORE_TEENSY #endif //TEENSY35_H
6,981
C++
.h
150
43.693333
155
0.663974
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,131
table3d.h
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/table3d.h
/** * @defgroup table_3d 3D Tables * @brief Structures and functions related to 3D tables, such as VE, Spark Advance, AFR etc. * * Logical: * - each 3D table is a continuous height map spread over a cartesian (x, y) plane * - Continuous: we expect to interpolate between any 4 points * - The axes are * - Bounded. I.e. non-infinite * - Non-linear. I.e. x[n]-x[n-1] != x[n+1]-x[n] * - Increasing. I.e. x[n] >= x[n-1] * - Do not have to start at [0,0] * * E.g. for a 3x3 table, this is what the TS table editor would show: * <pre> * Y-Max V6 V7 V8 * Y-Int V3 V4 V5 * Y-Min V0 V1 V2 * X-Min X-Int X-Max * </pre> * * In memory, we store rows in reverse: * - Both axes are inverted: * - <c>x[0]</c> stores \c X-Max * - <c>x[2]</c> stores \c X-Min * - <c>y[0]</c> stores \c Y-Max * - <c>y[2]</c> stores \c Y-Min * - The value locations match the axes. * - <c>value[0][0]</c> stores \c V6. * - <c>value[2][0]</c> stores \c V0. * * I.e. * <pre> * Y-Min V0 V1 V2 * Y-Int V3 V4 V5 * Y-Max V6 V7 V8 * X-Min X-Int X-Max * </pre> * @{ */ /** \file * @brief 3D table data types and functions */ #pragma once #include "table3d_interpolate.h" #include "table3d_axes.h" #include "table3d_values.h" #define TO_TYPE_KEY(size, xDom, yDom) table3d ## size ## xDom ## yDom ## _key /** * @brief Table \b type identifiers. Limited compile time RTTI * * With no virtual functions (they have quite a bit of overhead in both space & * time), we have to pass void* around in certain cases. In order to cast that * back to a concrete table type, we need to somehow identify the type. * * Once approach is to register each type - but that requires a central registry * which will use RAM. * * Since we have a compile time fixed set of table types, we can map a unique * identifier to the type via a cast - this enum is that unique identifier. * * Typically used in conjunction with the '#CONCRETE_TABLE_ACTION' macro */ enum table_type_t { table_type_None, #define TABLE3D_GEN_TYPEKEY(size, xDom, yDom) TO_TYPE_KEY(size, xDom, yDom), TABLE3D_GENERATOR(TABLE3D_GEN_TYPEKEY) }; // Generate the 3D table types #define TABLE3D_GEN_TYPE(size, xDom, yDom) \ /** @brief A 3D table with size x size dimensions, xDom x-axis and yDom y-axis */ \ struct TABLE3D_TYPENAME_BASE(size, xDom, yDom) \ { \ typedef TABLE3D_TYPENAME_AXIS(size, xDom) xaxis_t; \ typedef TABLE3D_TYPENAME_AXIS(size, yDom) yaxis_t; \ typedef TABLE3D_TYPENAME_VALUE(size, xDom, yDom) value_t; \ /* This will take up zero space unless we take the address somewhere */ \ static constexpr table_type_t type_key = TO_TYPE_KEY(size, xDom, yDom); \ \ table3DGetValueCache get_value_cache; \ value_t values; \ xaxis_t axisX; \ yaxis_t axisY; \ }; TABLE3D_GENERATOR(TABLE3D_GEN_TYPE) // Generate get3DTableValue() functions #define TABLE3D_GEN_GET_TABLE_VALUE(size, xDom, yDom) \ static inline table3d_value_t get3DTableValue(TABLE3D_TYPENAME_BASE(size, xDom, yDom) *pTable, table3d_axis_t y, table3d_axis_t x) \ { \ return get3DTableValue( &pTable->get_value_cache, \ TABLE3D_TYPENAME_BASE(size, xDom, yDom)::value_t::row_size, \ pTable->values.values, \ pTable->axisX.axis, \ pTable->axisY.axis, \ y, x); \ } TABLE3D_GENERATOR(TABLE3D_GEN_GET_TABLE_VALUE) // =============================== Table function calls ========================= // With no templates or inheritance we need some way to call functions // for the various distinct table types. CONCRETE_TABLE_ACTION dispatches // to a caller defined function overloaded by the type of the table. #define CONCRETE_TABLE_ACTION_INNER(size, xDomain, yDomain, action, ...) \ case TO_TYPE_KEY(size, xDomain, yDomain): action(size, xDomain, yDomain, ##__VA_ARGS__); #define CONCRETE_TABLE_ACTION(testKey, action, ...) \ switch ((table_type_t)testKey) { \ TABLE3D_GENERATOR(CONCRETE_TABLE_ACTION_INNER, action, ##__VA_ARGS__ ) \ default: abort(); } // =============================== Table function calls ========================= table_value_iterator rows_begin(const void *pTable, table_type_t key); table_axis_iterator x_begin(const void *pTable, table_type_t key); table_axis_iterator x_rbegin(const void *pTable, table_type_t key); table_axis_iterator y_begin(const void *pTable, table_type_t key); table_axis_iterator y_rbegin(const void *pTable, table_type_t key); /** @} */
4,877
C++
.h
114
38.552632
136
0.60973
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,132
board_avr2560.h
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/board_avr2560.h
#ifndef AVR2560_H #define AVR2560_H #if defined(CORE_AVR) #include <avr/interrupt.h> #include <avr/io.h> /* *********************************************************************************************************** * General */ #define PORT_TYPE uint8_t //Size of the port variables (Eg inj1_pin_port). #define PINMASK_TYPE uint8_t #define COMPARE_TYPE uint16_t #define COUNTER_TYPE uint16_t #define SERIAL_BUFFER_SIZE (256+7+1) //Size of the serial buffer used by new comms protocol. The largest single packet is the O2 calibration which is 256 bytes + 7 bytes of overhead #define FPU_MAX_SIZE 0 //Size of the FPU buffer. 0 means no FPU. #ifdef USE_SPI_EEPROM #define EEPROM_LIB_H "src/SPIAsEEPROM/SPIAsEEPROM.h" typedef uint16_t eeprom_address_t; #else #define EEPROM_LIB_H <EEPROM.h> typedef int eeprom_address_t; #endif #ifdef PLATFORMIO #define RTC_LIB_H <TimeLib.h> #else #define RTC_LIB_H <Time.h> #endif void initBoard(void); uint16_t freeRam(void); void doSystemReset(void); void jumpToBootloader(void); #if defined(TIMER5_MICROS) /*#define micros() (((timer5_overflow_count << 16) + TCNT5) * 4) */ //Fast version of micros() that uses the 4uS tick of timer5. See timers.ino for the overflow ISR of timer5 #define millis() (ms_counter) //Replaces the standard millis() function with this macro. It is both faster and more accurate. See timers.ino for its counter increment. static inline unsigned long micros_safe(); //A version of micros() that is interrupt safe #else #define micros_safe() micros() //If the timer5 method is not used, the micros_safe() macro is simply an alias for the normal micros() #endif #define pinIsReserved(pin) ( ((pin) == 0) ) //Forbidden pins like USB on other boards //Mega 2561 MCU does not have a serial3 available. #if not defined(__AVR_ATmega2561__) #define USE_SERIAL3 #endif /* *********************************************************************************************************** * Schedules */ //Refer to svn.savannah.nongnu.org/viewvc/trunk/avr-libc/include/avr/iomxx0_1.h?root=avr-libc&view=markup #define FUEL1_COUNTER TCNT3 #define FUEL2_COUNTER TCNT3 #define FUEL3_COUNTER TCNT3 #define FUEL4_COUNTER TCNT4 #define FUEL5_COUNTER TCNT4 #define FUEL6_COUNTER TCNT4 //Replaces ignition 4 #define FUEL7_COUNTER TCNT5 //Replaces ignition 3 #define FUEL8_COUNTER TCNT5 //Replaces ignition 2 #define IGN1_COUNTER TCNT5 #define IGN2_COUNTER TCNT5 #define IGN3_COUNTER TCNT5 #define IGN4_COUNTER TCNT4 #define IGN5_COUNTER TCNT4 #define IGN6_COUNTER TCNT4 //Replaces injector 4 #define IGN7_COUNTER TCNT3 //Replaces injector 3 #define IGN8_COUNTER TCNT3 //Replaces injector 2 #define FUEL1_COMPARE OCR3A #define FUEL2_COMPARE OCR3B #define FUEL3_COMPARE OCR3C #define FUEL4_COMPARE OCR4B //Replaces ignition 6 #define FUEL5_COMPARE OCR4C //Replaces ignition 5 #define FUEL6_COMPARE OCR4A //Replaces ignition 4 #define FUEL7_COMPARE OCR5C //Replaces ignition 3 #define FUEL8_COMPARE OCR5B //Replaces ignition 2 #define IGN1_COMPARE OCR5A #define IGN2_COMPARE OCR5B #define IGN3_COMPARE OCR5C #define IGN4_COMPARE OCR4A //Replaces injector 6 #define IGN5_COMPARE OCR4C //Replaces injector 5 #define IGN6_COMPARE OCR4B //Replaces injector 4 #define IGN7_COMPARE OCR3C //Replaces injector 3 #define IGN8_COMPARE OCR3B //Replaces injector 2 //Note that the interrupt flag is reset BEFORE the interrupt is enabled #define FUEL1_TIMER_ENABLE() TIFR3 |= (1<<OCF3A); TIMSK3 |= (1 << OCIE3A) //Turn on the A compare unit (ie turn on the interrupt) #define FUEL2_TIMER_ENABLE() TIFR3 |= (1<<OCF3B); TIMSK3 |= (1 << OCIE3B) //Turn on the B compare unit (ie turn on the interrupt) #define FUEL3_TIMER_ENABLE() TIFR3 |= (1<<OCF3C); TIMSK3 |= (1 << OCIE3C) //Turn on the C compare unit (ie turn on the interrupt) #define FUEL4_TIMER_ENABLE() TIFR4 |= (1<<OCF4B); TIMSK4 |= (1 << OCIE4B) //Turn on the B compare unit (ie turn on the interrupt) #define FUEL5_TIMER_ENABLE() TIFR4 |= (1<<OCF4C); TIMSK4 |= (1 << OCIE4C) //Turn on the C compare unit (ie turn on the interrupt) #define FUEL6_TIMER_ENABLE() TIFR4 |= (1<<OCF4A); TIMSK4 |= (1 << OCIE4A) //Turn on the A compare unit (ie turn on the interrupt) #define FUEL7_TIMER_ENABLE() TIFR5 |= (1<<OCF5C); TIMSK5 |= (1 << OCIE5C) // #define FUEL8_TIMER_ENABLE() TIFR5 |= (1<<OCF5B); TIMSK5 |= (1 << OCIE5B) // #define FUEL1_TIMER_DISABLE() TIMSK3 &= ~(1 << OCIE3A); //Turn off this output compare unit #define FUEL2_TIMER_DISABLE() TIMSK3 &= ~(1 << OCIE3B); //Turn off this output compare unit #define FUEL3_TIMER_DISABLE() TIMSK3 &= ~(1 << OCIE3C); //Turn off this output compare unit #define FUEL4_TIMER_DISABLE() TIMSK4 &= ~(1 << OCIE4B); //Turn off this output compare unit #define FUEL5_TIMER_DISABLE() TIMSK4 &= ~(1 << OCIE4C); // #define FUEL6_TIMER_DISABLE() TIMSK4 &= ~(1 << OCIE4A); // #define FUEL7_TIMER_DISABLE() TIMSK5 &= ~(1 << OCIE5C); // #define FUEL8_TIMER_DISABLE() TIMSK5 &= ~(1 << OCIE5B); // //These have the TIFR5 bits set to 1 to clear the interrupt flag. This prevents a false interrupt being called the first time the channel is enabled. #define IGN1_TIMER_ENABLE() TIFR5 |= (1<<OCF5A); TIMSK5 |= (1 << OCIE5A) //Turn on the A compare unit (ie turn on the interrupt) #define IGN2_TIMER_ENABLE() TIFR5 |= (1<<OCF5B); TIMSK5 |= (1 << OCIE5B) //Turn on the B compare unit (ie turn on the interrupt) #define IGN3_TIMER_ENABLE() TIFR5 |= (1<<OCF5C); TIMSK5 |= (1 << OCIE5C) //Turn on the C compare unit (ie turn on the interrupt) #define IGN4_TIMER_ENABLE() TIFR4 |= (1<<OCF4A); TIMSK4 |= (1 << OCIE4A) //Turn on the A compare unit (ie turn on the interrupt) #define IGN5_TIMER_ENABLE() TIFR4 |= (1<<OCF4C); TIMSK4 |= (1 << OCIE4C) //Turn on the A compare unit (ie turn on the interrupt) #define IGN6_TIMER_ENABLE() TIFR4 |= (1<<OCF4B); TIMSK4 |= (1 << OCIE4B) //Replaces injector 4 #define IGN7_TIMER_ENABLE() TIMSK3 |= (1 << OCIE3C) //Replaces injector 3 #define IGN8_TIMER_ENABLE() TIMSK3 |= (1 << OCIE3B) //Replaces injector 2 #define IGN1_TIMER_DISABLE() TIMSK5 &= ~(1 << OCIE5A) //Turn off this output compare unit #define IGN2_TIMER_DISABLE() TIMSK5 &= ~(1 << OCIE5B) //Turn off this output compare unit #define IGN3_TIMER_DISABLE() TIMSK5 &= ~(1 << OCIE5C) //Turn off this output compare unit #define IGN4_TIMER_DISABLE() TIMSK4 &= ~(1 << OCIE4A) //Turn off this output compare unit #define IGN5_TIMER_DISABLE() TIMSK4 &= ~(1 << OCIE4C) //Turn off this output compare unit #define IGN6_TIMER_DISABLE() TIMSK4 &= ~(1 << OCIE4B) //Replaces injector 4 #define IGN7_TIMER_DISABLE() TIMSK3 &= ~(1 << OCIE3C) //Replaces injector 3 #define IGN8_TIMER_DISABLE() TIMSK3 &= ~(1 << OCIE3B) //Replaces injector 2 #define MAX_TIMER_PERIOD 262140UL //The longest period of time (in uS) that the timer can permit (IN this case it is 65535 * 4, as each timer tick is 4uS) #define uS_TO_TIMER_COMPARE(uS1) ((uS1) >> 2) //Converts a given number of uS into the required number of timer ticks until that time has passed /* *********************************************************************************************************** * Auxiliaries */ #define ENABLE_BOOST_TIMER() TIMSK1 |= (1 << OCIE1A) #define DISABLE_BOOST_TIMER() TIMSK1 &= ~(1 << OCIE1A) #define ENABLE_VVT_TIMER() TIMSK1 |= (1 << OCIE1B) #define DISABLE_VVT_TIMER() TIMSK1 &= ~(1 << OCIE1B) #define BOOST_TIMER_COMPARE OCR1A #define BOOST_TIMER_COUNTER TCNT1 #define VVT_TIMER_COMPARE OCR1B #define VVT_TIMER_COUNTER TCNT1 /* *********************************************************************************************************** * Idle */ #define IDLE_COUNTER TCNT1 #define IDLE_COMPARE OCR1C #define IDLE_TIMER_ENABLE() TIMSK1 |= (1 << OCIE1C) #define IDLE_TIMER_DISABLE() TIMSK1 &= ~(1 << OCIE1C) /* *********************************************************************************************************** * CAN / Second serial */ #endif //CORE_AVR #endif //AVR2560_H
8,145
C++
.h
142
54.43662
183
0.658149
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,133
canBroadcast.h
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/canBroadcast.h
#ifndef CANBROADCAST_H #define CANBROADCAST_H #if defined(NATIVE_CAN_AVAILABLE) //For BMW e46/e39/e38, rover and mini other CAN instrument clusters #define CAN_BMW_ASC1 0x153 //Rx message from ACS unit that includes speed #define CAN_BMW_DME1 0x316 //Tx message that includes RPM #define CAN_BMW_DME2 0x329 //Tx message that includes CLT and TPS #define CAN_BMW_DME4 0x545 //Tx message that includes CLT and TPS #define CAN_BMW_ICL2 0x613 #define CAN_BMW_ICL3 0x615 //For VAG CAN instrument clusters #define CAN_VAG_RPM 0x280 #define CAN_VAG_VSS 0x5A0 void sendBMWCluster(); void sendVAGCluster(); void DashMessages(uint16_t DashMessageID); #endif #endif // CANBROADCAST_H
676
C++
.h
18
36.388889
73
0.80458
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,134
logger.h
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/logger.h
/** \file logger.h * @brief File for generating log files and meta data * @author Josh Stewart * * This file contains functions for creating a log file for use with by TunerStudio directly or to be written to an SD card * */ #ifndef LOGGER_H #define LOGGER_H #include <assert.h> #include "globals.h" // Needed for FPU_MAX_SIZE #ifndef UNIT_TEST // Scope guard for unit testing #define LOG_ENTRY_SIZE 125 /**< The size of the live data packet. This MUST match ochBlockSize setting in the ini file */ #define SD_LOG_ENTRY_SIZE 125 /**< The size of the live data packet used by the SD card.*/ #else #define LOG_ENTRY_SIZE 1 /**< The size of the live data packet. This MUST match ochBlockSize setting in the ini file */ #define SD_LOG_ENTRY_SIZE 1 /**< The size of the live data packet used by the SD card.*/ #endif #define SD_LOG_NUM_FIELDS 90 /**< The number of fields that are in the log. This is always smaller than the entry size due to some fields being 2 bytes */ byte getTSLogEntry(uint16_t byteNum); int16_t getReadableLogEntry(uint16_t logIndex); #if FPU_MAX_SIZE >= 32 float getReadableFloatLogEntry(uint16_t logIndex); #endif bool is2ByteEntry(uint8_t key); void startToothLogger(void); void stopToothLogger(void); void startCompositeLogger(void); void stopCompositeLogger(void); void startCompositeLoggerTertiary(void); void stopCompositeLoggerTertiary(void); void startCompositeLoggerCams(void); void stopCompositeLoggerCams(void); // This array indicates which index values from the log are 2 byte values // This array MUST remain in ascending order // !!!! WARNING: If any value above 255 is required in this array, changes MUST be made to is2ByteEntry() function !!!! const byte PROGMEM fsIntIndex[] = {4, 14, 17, 22, 26, 28, 33, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 76, 78, 80, 82, 86, 88, 90, 93, 95, 99, 104, 111, 121 }; //List of logger field names. This must be in the same order and length as logger_updateLogdataCSV() const char header_0[] PROGMEM = "secl"; const char header_1[] PROGMEM = "status1"; const char header_2[] PROGMEM = "engine"; const char header_3[] PROGMEM = "Sync Loss #"; const char header_4[] PROGMEM = "MAP"; const char header_5[] PROGMEM = "IAT(C)"; const char header_6[] PROGMEM = "CLT(C)"; const char header_7[] PROGMEM = "Battery Correction"; const char header_8[] PROGMEM = "Battery V"; const char header_9[] PROGMEM = "AFR"; const char header_10[] PROGMEM = "EGO Correction"; const char header_11[] PROGMEM = "IAT Correction"; const char header_12[] PROGMEM = "WUE Correction"; const char header_13[] PROGMEM = "RPM"; const char header_14[] PROGMEM = "Accel. Correction"; const char header_15[] PROGMEM = "Gamma Correction"; const char header_16[] PROGMEM = "VE1"; const char header_17[] PROGMEM = "VE2"; const char header_18[] PROGMEM = "AFR Target"; const char header_19[] PROGMEM = "TPSdot"; const char header_20[] PROGMEM = "Advance Current"; const char header_21[] PROGMEM = "TPS"; const char header_22[] PROGMEM = "Loops/S"; const char header_23[] PROGMEM = "Free RAM"; const char header_24[] PROGMEM = "Boost Target"; const char header_25[] PROGMEM = "Boost Duty"; const char header_26[] PROGMEM = "status2"; const char header_27[] PROGMEM = "rpmDOT"; const char header_28[] PROGMEM = "Eth%"; const char header_29[] PROGMEM = "Flex Fuel Correction"; const char header_30[] PROGMEM = "Flex Adv Correction"; const char header_31[] PROGMEM = "IAC Steps/Duty"; const char header_32[] PROGMEM = "testoutputs"; const char header_33[] PROGMEM = "AFR2"; const char header_34[] PROGMEM = "Baro"; const char header_35[] PROGMEM = "AUX_IN 0"; const char header_36[] PROGMEM = "AUX_IN 1"; const char header_37[] PROGMEM = "AUX_IN 2"; const char header_38[] PROGMEM = "AUX_IN 3"; const char header_39[] PROGMEM = "AUX_IN 4"; const char header_40[] PROGMEM = "AUX_IN 5"; const char header_41[] PROGMEM = "AUX_IN 6"; const char header_42[] PROGMEM = "AUX_IN 7"; const char header_43[] PROGMEM = "AUX_IN 8"; const char header_44[] PROGMEM = "AUX_IN 9"; const char header_45[] PROGMEM = "AUX_IN 10"; const char header_46[] PROGMEM = "AUX_IN 11"; const char header_47[] PROGMEM = "AUX_IN 12"; const char header_48[] PROGMEM = "AUX_IN 13"; const char header_49[] PROGMEM = "AUX_IN 14"; const char header_50[] PROGMEM = "AUX_IN 15"; const char header_51[] PROGMEM = "TPS ADC"; const char header_52[] PROGMEM = "Errors"; const char header_53[] PROGMEM = "PW"; const char header_54[] PROGMEM = "PW2"; const char header_55[] PROGMEM = "PW3"; const char header_56[] PROGMEM = "PW4"; const char header_57[] PROGMEM = "status3"; const char header_58[] PROGMEM = "Engine Protect"; const char header_59[] PROGMEM = ""; const char header_60[] PROGMEM = "Fuel Load"; const char header_61[] PROGMEM = "Ign Load"; const char header_62[] PROGMEM = "Dwell"; const char header_63[] PROGMEM = "Idle Target (RPM)"; const char header_64[] PROGMEM = "MAP DOT"; const char header_65[] PROGMEM = "VVT1 Angle"; const char header_66[] PROGMEM = "VVT1 Target"; const char header_67[] PROGMEM = "VVT1 Duty"; const char header_68[] PROGMEM = "Flex Boost Adj"; const char header_69[] PROGMEM = "Baro Correction"; const char header_70[] PROGMEM = "VE Current"; const char header_71[] PROGMEM = "ASE Correction"; const char header_72[] PROGMEM = "Vehicle Speed"; const char header_73[] PROGMEM = "Gear"; const char header_74[] PROGMEM = "Fuel Pressure"; const char header_75[] PROGMEM = "Oil Pressure"; const char header_76[] PROGMEM = "WMI PW"; const char header_77[] PROGMEM = "status4"; const char header_78[] PROGMEM = "VVT2 Angle"; const char header_79[] PROGMEM = "VVT2 Target"; const char header_80[] PROGMEM = "VVT2 Duty"; const char header_81[] PROGMEM = "outputs"; const char header_82[] PROGMEM = "Fuel Temp"; const char header_83[] PROGMEM = "Fuel Temp Correction"; const char header_84[] PROGMEM = "Advance 1"; const char header_85[] PROGMEM = "Advance 2"; const char header_86[] PROGMEM = "SD Status"; const char header_87[] PROGMEM = "EMAP"; const char header_88[] PROGMEM = "Fan Duty"; const char header_89[] PROGMEM = "AirConStatus"; /* const char header_90[] PROGMEM = ""; const char header_91[] PROGMEM = ""; const char header_92[] PROGMEM = ""; const char header_93[] PROGMEM = ""; const char header_94[] PROGMEM = ""; const char header_95[] PROGMEM = ""; const char header_96[] PROGMEM = ""; const char header_97[] PROGMEM = ""; const char header_98[] PROGMEM = ""; const char header_99[] PROGMEM = ""; const char header_100[] PROGMEM = ""; const char header_101[] PROGMEM = ""; const char header_102[] PROGMEM = ""; const char header_103[] PROGMEM = ""; const char header_104[] PROGMEM = ""; const char header_105[] PROGMEM = ""; const char header_106[] PROGMEM = ""; const char header_107[] PROGMEM = ""; const char header_108[] PROGMEM = ""; const char header_109[] PROGMEM = ""; const char header_110[] PROGMEM = ""; const char header_111[] PROGMEM = ""; const char header_112[] PROGMEM = ""; const char header_113[] PROGMEM = ""; const char header_114[] PROGMEM = ""; const char header_115[] PROGMEM = ""; const char header_116[] PROGMEM = ""; const char header_117[] PROGMEM = ""; const char header_118[] PROGMEM = ""; const char header_119[] PROGMEM = ""; const char header_120[] PROGMEM = ""; const char header_121[] PROGMEM = ""; */ const char* const header_table[] PROGMEM = { header_0,\ header_1,\ header_2,\ header_3,\ header_4,\ header_5,\ header_6,\ header_7,\ header_8,\ header_9,\ header_10,\ header_11,\ header_12,\ header_13,\ header_14,\ header_15,\ header_16,\ header_17,\ header_18,\ header_19,\ header_20,\ header_21,\ header_22,\ header_23,\ header_24,\ header_25,\ header_26,\ header_27,\ header_28,\ header_29,\ header_30,\ header_31,\ header_32,\ header_33,\ header_34,\ header_35,\ header_36,\ header_37,\ header_38,\ header_39,\ header_40,\ header_41,\ header_42,\ header_43,\ header_44,\ header_45,\ header_46,\ header_47,\ header_48,\ header_49,\ header_50,\ header_51,\ header_52,\ header_53,\ header_54,\ header_55,\ header_56,\ header_57,\ header_58,\ header_59,\ header_60,\ header_61,\ header_62,\ header_63,\ header_64,\ header_65,\ header_66,\ header_67,\ header_68,\ header_69,\ header_70,\ header_71,\ header_72,\ header_73,\ header_74,\ header_75,\ header_76,\ header_77,\ header_78,\ header_79,\ header_80,\ header_81,\ header_82,\ header_83,\ header_84,\ header_85,\ header_86,\ header_87,\ header_88,\ header_89,\ /* header_90,\ header_91,\ header_92,\ header_93,\ header_94,\ header_95,\ header_96,\ header_97,\ header_98,\ header_99,\ header_100,\ header_101,\ header_102,\ header_103,\ header_104,\ header_105,\ header_106,\ header_107,\ header_108,\ header_109,\ header_110,\ header_111,\ header_112,\ header_113,\ header_114,\ header_115,\ header_116,\ header_117,\ header_118,\ header_119,\ header_120,\ header_121,\ */ }; static_assert(sizeof(header_table) == (sizeof(char*) * SD_LOG_NUM_FIELDS), "Number of header table titles must match number of log fields"); #endif
14,723
C++
.h
289
30.103806
182
0.432455
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,135
idle.h
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/idle.h
#ifndef IDLE_H #define IDLE_H #include "globals.h" #include "table2d.h" #include BOARD_H //Note that this is not a real file, it is defined in globals.h. #define IAC_ALGORITHM_NONE 0 #define IAC_ALGORITHM_ONOFF 1 #define IAC_ALGORITHM_PWM_OL 2 #define IAC_ALGORITHM_PWM_CL 3 #define IAC_ALGORITHM_STEP_OL 4 #define IAC_ALGORITHM_STEP_CL 5 #define IAC_ALGORITHM_PWM_OLCL 6 //Openloop plus closedloop IAC control #define IAC_ALGORITHM_STEP_OLCL 7 //Openloop plus closedloop IAC control #define IDLE_PIN_LOW() *idle_pin_port &= ~(idle_pin_mask) #define IDLE_PIN_HIGH() *idle_pin_port |= (idle_pin_mask) #define IDLE2_PIN_LOW() *idle2_pin_port &= ~(idle2_pin_mask) #define IDLE2_PIN_HIGH() *idle2_pin_port |= (idle2_pin_mask) #define STEPPER_FORWARD 0 #define STEPPER_BACKWARD 1 #define STEPPER_POWER_WHEN_ACTIVE 0 #define IDLE_TABLE_SIZE 10 enum StepperStatus {SOFF, STEPPING, COOLING}; //The 2 statuses that a stepper can have. STEPPING means that a high pulse is currently being sent and will need to be turned off at some point. struct StepperIdle { int curIdleStep; //Tracks the current location of the stepper int targetIdleStep; //What the targeted step is volatile StepperStatus stepperStatus; volatile unsigned long stepStartTime; byte lessAirDirection; byte moreAirDirection; }; struct table2D iacPWMTable; struct table2D iacStepTable; //Open loop tables specifically for cranking struct table2D iacCrankStepsTable; struct table2D iacCrankDutyTable; struct StepperIdle idleStepper; bool idleOn; //Simply tracks whether idle was on last time around byte idleInitComplete = 99; //Tracks which idle method was initialised. 99 is a method that will never exist unsigned int iacStepTime_uS; unsigned int iacCoolTime_uS; unsigned int completedHomeSteps; volatile PORT_TYPE *idle_pin_port; volatile PINMASK_TYPE idle_pin_mask; volatile PORT_TYPE *idle2_pin_port; volatile PINMASK_TYPE idle2_pin_mask; volatile PORT_TYPE *idleUpOutput_pin_port; volatile PINMASK_TYPE idleUpOutput_pin_mask; volatile bool idle_pwm_state; bool lastDFCOValue; unsigned int idle_pwm_max_count; //Used for variable PWM frequency volatile unsigned int idle_pwm_cur_value; long idle_pid_target_value; long FeedForwardTerm; unsigned long idle_pwm_target_value; long idle_cl_target_rpm; byte idleCounter; //Used for tracking the number of calls to the idle control function uint8_t idleTaper; byte idleUpOutputHIGH = HIGH; // Used to invert the idle Up Output byte idleUpOutputLOW = LOW; // Used to invert the idle Up Output void initialiseIdle(bool forcehoming); void idleControl(void); void initialiseIdleUpOutput(void); void disableIdle(void); void idleInterrupt(void); #endif
2,693
C++
.h
66
39.378788
190
0.802219
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,136
table2d.h
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/table2d.h
/* This file is used for everything related to maps/tables including their definition, functions etc */ #ifndef TABLE_H #define TABLE_H #define SIZE_BYTE 8 #define SIZE_INT 16 /* The 2D table can contain either 8-bit (byte) or 16-bit (int) values The valueSize variable should be set to either 8 or 16 to indicate this BEFORE the table is used */ struct table2D { //Used 5414 RAM with original version byte valueSize; byte axisSize; byte xSize; void *values; void *axisX; //int16_t *values16; //int16_t *axisX16; //Store the last X and Y coordinates in the table. This is used to make the next check faster int16_t lastXMax; int16_t lastXMin; //Store the last input and output for caching int16_t lastInput; int16_t lastOutput; byte cacheTime; //Tracks when the last cache value was set so it can expire after x seconds. A timeout is required to pickup when a tuning value is changed, otherwise the old cached value will continue to be returned as the X value isn't changing. }; int16_t table2D_getAxisValue(struct table2D *fromTable, byte X_in); int16_t table2D_getRawValue(struct table2D *fromTable, byte X_index); int table2D_getValue(struct table2D *fromTable, int X_in); #endif // TABLE_H
1,255
C++
.h
32
36.96875
250
0.755354
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,137
schedule_calcs.h
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/schedule_calcs.h
#pragma once #include <stdint.h> #include "scheduler.h" extern int ignition1StartAngle; extern int ignition2StartAngle; extern int ignition3StartAngle; extern int ignition4StartAngle; extern int ignition5StartAngle; extern int ignition6StartAngle; extern int ignition7StartAngle; extern int ignition8StartAngle; extern int channel1IgnDegrees; /**< The number of crank degrees until cylinder 1 is at TDC (This is obviously 0 for virtually ALL engines, but there's some weird ones) */ extern int channel2IgnDegrees; /**< The number of crank degrees until cylinder 2 (and 5/6/7/8) is at TDC */ extern int channel3IgnDegrees; /**< The number of crank degrees until cylinder 3 (and 5/6/7/8) is at TDC */ extern int channel4IgnDegrees; /**< The number of crank degrees until cylinder 4 (and 5/6/7/8) is at TDC */ extern int channel5IgnDegrees; /**< The number of crank degrees until cylinder 5 is at TDC */ extern int channel6IgnDegrees; /**< The number of crank degrees until cylinder 6 is at TDC */ extern int channel7IgnDegrees; /**< The number of crank degrees until cylinder 7 is at TDC */ extern int channel8IgnDegrees; /**< The number of crank degrees until cylinder 8 is at TDC */ extern int channel1InjDegrees; /**< The number of crank degrees until cylinder 1 is at TDC (This is obviously 0 for virtually ALL engines, but there's some weird ones) */ extern int channel2InjDegrees; /**< The number of crank degrees until cylinder 2 (and 5/6/7/8) is at TDC */ extern int channel3InjDegrees; /**< The number of crank degrees until cylinder 3 (and 5/6/7/8) is at TDC */ extern int channel4InjDegrees; /**< The number of crank degrees until cylinder 4 (and 5/6/7/8) is at TDC */ extern int channel5InjDegrees; /**< The number of crank degrees until cylinder 5 is at TDC */ extern int channel6InjDegrees; /**< The number of crank degrees until cylinder 6 is at TDC */ extern int channel7InjDegrees; /**< The number of crank degrees until cylinder 7 is at TDC */ extern int channel8InjDegrees; /**< The number of crank degrees until cylinder 8 is at TDC */ inline uint16_t __attribute__((always_inline)) calculateInjectorStartAngle(uint16_t PWdivTimerPerDegree, int16_t injChannelDegrees); inline uint32_t __attribute__((always_inline)) calculateInjector1Timeout(int injector1StartAngle, int crankAngle); inline uint32_t __attribute__((always_inline)) calculateInjectorNTimeout(const FuelSchedule &schedule, int channelInjDegrees, int injectorStartAngle, int crankAngle); inline void __attribute__((always_inline)) calculateIgnitionAngle1(int dwellAngle); inline void __attribute__((always_inline)) calculateIgnitionAngle2(int dwellAngle); inline void __attribute__((always_inline)) calculateIgnitionAngle3(int dwellAngle); // ignition 3 for rotary inline void __attribute__((always_inline)) calculateIgnitionAngle3(int dwellAngle, int rotarySplitDegrees); inline void __attribute__((always_inline)) calculateIgnitionAngle4(int dwellAngle); // ignition 4 for rotary inline void __attribute__((always_inline)) calculateIgnitionAngle4(int dwellAngle, int rotarySplitDegrees); inline void __attribute__((always_inline)) calculateIgnitionAngle5(int dwellAngle); inline void __attribute__((always_inline)) calculateIgnitionAngle6(int dwellAngle); inline void __attribute__((always_inline)) calculateIgnitionAngle7(int dwellAngle); inline void __attribute__((always_inline)) calculateIgnitionAngle8(int dwellAngle); inline uint32_t __attribute__((always_inline)) calculateIgnition1Timeout(int crankAngle); inline uint32_t __attribute__((always_inline)) calculateIgnitionNTimeout(const Schedule &schedule, int startAngle, int channelIgnDegrees, int crankAngle); #include "schedule_calcs.hpp"
3,689
C++
.h
45
80.822222
170
0.790212
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,138
comms_sd.h
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/comms_sd.h
#pragma once //Hardcoded TunerStudio addresses/commands for various SD/RTC commands #define SD_READWRITE_PAGE 0x11 #define SD_READFILE_PAGE 0x14 #define SD_RTC_PAGE 0x07 #define SD_READ_STAT_ARG1 0x0000 #define SD_READ_STAT_ARG2 0x0010 #define SD_READ_DIR_ARG1 0x0000 #define SD_READ_DIR_ARG2 0x0202 #define SD_READ_SEC_ARG1 0x0002 #define SD_READ_SEC_ARG2 0x0004 #define SD_READ_STRM_ARG1 0x0004 #define SD_READ_STRM_ARG2 0x0001 #define SD_READ_COMP_ARG1 0x0000 //Not used for anything #define SD_READ_COMP_ARG2 0x0800 #define SD_RTC_READ_ARG1 0x024D #define SD_RTC_READ_ARG2 0x0008 #define SD_WRITE_DO_ARG1 0x0000 #define SD_WRITE_DO_ARG2 0x0001 #define SD_WRITE_DIR_ARG1 0x0001 #define SD_WRITE_DIR_ARG2 0x0002 #define SD_WRITE_SEC_ARG1 0x0003 #define SD_WRITE_SEC_ARG2 0x0204 #define SD_WRITE_COMP_ARG1 0x0005 #define SD_WRITE_COMP_ARG2 0x0008 #define SD_ERASEFILE_ARG1 0x0006 #define SD_ERASEFILE_ARG2 0x0006 #define SD_SPD_TEST_ARG1 0x0007 #define SD_SPD_TEST_ARG2 0x0004 #define SD_RTC_WRITE_ARG1 0x027E #define SD_RTC_WRITE_ARG2 0x0009
1,120
C++
.h
31
35.032258
70
0.760589
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,139
TS_CommandButtonHandler.h
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/TS_CommandButtonHandler.h
/** \file * Header file for the TunerStudio command handler * The command handler manages all the inputs FROM TS which are issued when a command button is clicked by the user */ #define TS_CMD_TEST_DSBL 256 #define TS_CMD_TEST_ENBL 257 #define TS_CMD_INJ1_ON 513 #define TS_CMD_INJ1_OFF 514 #define TS_CMD_INJ1_50PC 515 #define TS_CMD_INJ2_ON 516 #define TS_CMD_INJ2_OFF 517 #define TS_CMD_INJ2_50PC 518 #define TS_CMD_INJ3_ON 519 #define TS_CMD_INJ3_OFF 520 #define TS_CMD_INJ3_50PC 521 #define TS_CMD_INJ4_ON 522 #define TS_CMD_INJ4_OFF 523 #define TS_CMD_INJ4_50PC 524 #define TS_CMD_INJ5_ON 525 #define TS_CMD_INJ5_OFF 526 #define TS_CMD_INJ5_50PC 527 #define TS_CMD_INJ6_ON 528 #define TS_CMD_INJ6_OFF 529 #define TS_CMD_INJ6_50PC 530 #define TS_CMD_INJ7_ON 531 #define TS_CMD_INJ7_OFF 532 #define TS_CMD_INJ7_50PC 533 #define TS_CMD_INJ8_ON 534 #define TS_CMD_INJ8_OFF 535 #define TS_CMD_INJ8_50PC 536 #define TS_CMD_IGN1_ON 769 #define TS_CMD_IGN1_OFF 770 #define TS_CMD_IGN1_50PC 771 #define TS_CMD_IGN2_ON 772 #define TS_CMD_IGN2_OFF 773 #define TS_CMD_IGN2_50PC 774 #define TS_CMD_IGN3_ON 775 #define TS_CMD_IGN3_OFF 776 #define TS_CMD_IGN3_50PC 777 #define TS_CMD_IGN4_ON 778 #define TS_CMD_IGN4_OFF 779 #define TS_CMD_IGN4_50PC 780 #define TS_CMD_IGN5_ON 781 #define TS_CMD_IGN5_OFF 782 #define TS_CMD_IGN5_50PC 783 #define TS_CMD_IGN6_ON 784 #define TS_CMD_IGN6_OFF 785 #define TS_CMD_IGN6_50PC 786 #define TS_CMD_IGN7_ON 787 #define TS_CMD_IGN7_OFF 788 #define TS_CMD_IGN7_50PC 789 #define TS_CMD_IGN8_ON 790 #define TS_CMD_IGN8_OFF 791 #define TS_CMD_IGN8_50PC 792 #define TS_CMD_STM32_REBOOT 12800 #define TS_CMD_STM32_BOOTLOADER 12801 #define TS_CMD_SD_FORMAT 13057 #define TS_CMD_VSS_60KMH 39168 //0x99x00 #define TS_CMD_VSS_RATIO1 39169 #define TS_CMD_VSS_RATIO2 39170 #define TS_CMD_VSS_RATIO3 39171 #define TS_CMD_VSS_RATIO4 39172 #define TS_CMD_VSS_RATIO5 39173 #define TS_CMD_VSS_RATIO6 39174 /* the maximum id number is 65,535 */ bool TS_CommandButtonsHandler(uint16_t buttonCommand);
2,124
C++
.h
66
31.015152
115
0.743415
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,140
errors.h
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/errors.h
#ifndef ERRORS_H #define ERRORS_H /* * Up to 64 different error codes may be defined (6 bits) */ #define ERR_NONE 0 //No error #define ERR_UNKNOWN 1 //Unknown error #define ERR_IAT_SHORT 2 //Inlet sensor shorted #define ERR_IAT_GND 3 //Inlet sensor grounded #define ERR_CLT_SHORT 4 //Coolant sensor shorted #define ERR_CLT_GND 5 //Coolant Sensor grounded #define ERR_O2_SHORT 6 //O2 sensor shorted #define ERR_O2_GND 7 //O2 sensor grounded #define ERR_TPS_SHORT 8 //TPS shorted (Is potentially valid) #define ERR_TPS_GND 9 //TPS grounded (Is potentially valid) #define ERR_BAT_HIGH 10 //Battery voltage is too high #define ERR_BAT_LOW 11 //Battery voltage is too low #define ERR_MAP_HIGH 12 //MAP output is too high #define ERR_MAP_LOW 13 //MAP output is too low #define ERR_DEFAULT_IAT_SHORT 80 //Note that the default is 40C. 80 is used due to the -40 offset #define ERR_DEFAULT_IAT_GND 80 //Note that the default is 40C. 80 is used due to the -40 offset #define ERR_DEFAULT_CKT_SHORT 80 //Note that the default is 40C. 80 is used due to the -40 offset #define ERR_DEFAULT_CLT_GND 80 //Note that the default is 40C. 80 is used due to the -40 offset #define ERR_DEFAULT_O2_SHORT 147 //14.7 #define ERR_DEFAULT_O2_GND 147 //14.7 #define ERR_DEFAULT_TPS_SHORT 50 //50% #define ERR_DEFAULT_TPS_GND 50 //50% #define ERR_DEFAULT_BAT_HIGH 130 //13v #define ERR_DEFAULT_BAT_LOW 130 //13v #define ERR_DEFAULT_MAP_HIGH 240 #define ERR_DEFAULT_MAP_LOW 80 #define MAX_ERRORS 4 //The number of errors the system can hold simultaneously. Should be a power of 2 /* * This struct is a single byte in length and is sent to TS * The first 2 bits are used to define the current error (0-3) * The remaining 6 bits are used to give the error number */ struct packedError { byte errorNum : 2; byte errorID : 6; }; byte getNextError(void); byte setError(byte errorID); void clearError(byte errorID); extern byte errorCount; #endif
2,021
C++
.h
47
41.617021
103
0.722787
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,141
auxiliaries.h
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/auxiliaries.h
#ifndef AUX_H #define AUX_H #include BOARD_H //Note that this is not a real file, it is defined in globals.h. #if defined(CORE_AVR) #include <util/atomic.h> #endif void initialiseAuxPWM(void); void boostControl(void); void boostDisable(void); void boostByGear(void); void vvtControl(void); void initialiseFan(void); void initialiseAirCon(void); void nitrousControl(void); void fanControl(void); void airConControl(void); bool READ_AIRCON_REQUEST(void); void wmiControl(void); static inline void checkAirConCoolantLockout(void); static inline void checkAirConTPSLockout(void); static inline void checkAirConRPMLockout(void); #define SIMPLE_BOOST_P 1 #define SIMPLE_BOOST_I 1 #define SIMPLE_BOOST_D 1 #if(defined(CORE_TEENSY) || defined(CORE_STM32)) #define BOOST_PIN_LOW() (digitalWrite(pinBoost, LOW)) #define BOOST_PIN_HIGH() (digitalWrite(pinBoost, HIGH)) #define VVT1_PIN_LOW() (digitalWrite(pinVVT_1, LOW)) #define VVT1_PIN_HIGH() (digitalWrite(pinVVT_1, HIGH)) #define VVT2_PIN_LOW() (digitalWrite(pinVVT_2, LOW)) #define VVT2_PIN_HIGH() (digitalWrite(pinVVT_2, HIGH)) #define FAN_PIN_LOW() (digitalWrite(pinFan, LOW)) #define FAN_PIN_HIGH() (digitalWrite(pinFan, HIGH)) #define N2O_STAGE1_PIN_LOW() (digitalWrite(configPage10.n2o_stage1_pin, LOW)) #define N2O_STAGE1_PIN_HIGH() (digitalWrite(configPage10.n2o_stage1_pin, HIGH)) #define N2O_STAGE2_PIN_LOW() (digitalWrite(configPage10.n2o_stage2_pin, LOW)) #define N2O_STAGE2_PIN_HIGH() (digitalWrite(configPage10.n2o_stage2_pin, HIGH)) #define AIRCON_PIN_LOW() (digitalWrite(pinAirConComp, LOW)) #define AIRCON_PIN_HIGH() (digitalWrite(pinAirConComp, HIGH)) #define AIRCON_FAN_PIN_LOW() (digitalWrite(pinAirConFan, LOW)) #define AIRCON_FAN_PIN_HIGH() (digitalWrite(pinAirConFan, HIGH)) #define FUEL_PUMP_ON() (digitalWrite(pinFuelPump, HIGH)) #define FUEL_PUMP_OFF() (digitalWrite(pinFuelPump, LOW)) #define AIRCON_ON() { ((((configPage15.airConCompPol&1)==1)) ? AIRCON_PIN_LOW() : AIRCON_PIN_HIGH()); BIT_SET(currentStatus.airConStatus, BIT_AIRCON_COMPRESSOR); } #define AIRCON_OFF() { ((((configPage15.airConCompPol&1)==1)) ? AIRCON_PIN_HIGH() : AIRCON_PIN_LOW()); BIT_CLEAR(currentStatus.airConStatus, BIT_AIRCON_COMPRESSOR); } #define AIRCON_FAN_ON() { ((((configPage15.airConFanPol&1)==1)) ? AIRCON_FAN_PIN_LOW() : AIRCON_FAN_PIN_HIGH()); BIT_SET(currentStatus.airConStatus, BIT_AIRCON_FAN); } #define AIRCON_FAN_OFF() { ((((configPage15.airConFanPol&1)==1)) ? AIRCON_FAN_PIN_HIGH() : AIRCON_FAN_PIN_LOW()); BIT_CLEAR(currentStatus.airConStatus, BIT_AIRCON_FAN); } #define FAN_ON() { ((configPage6.fanInv) ? FAN_PIN_LOW() : FAN_PIN_HIGH()); } #define FAN_OFF() { ((configPage6.fanInv) ? FAN_PIN_HIGH() : FAN_PIN_LOW()); } #else #define BOOST_PIN_LOW() ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { *boost_pin_port &= ~(boost_pin_mask); } #define BOOST_PIN_HIGH() ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { *boost_pin_port |= (boost_pin_mask); } #define VVT1_PIN_LOW() ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { *vvt1_pin_port &= ~(vvt1_pin_mask); } #define VVT1_PIN_HIGH() ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { *vvt1_pin_port |= (vvt1_pin_mask); } #define VVT2_PIN_LOW() ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { *vvt2_pin_port &= ~(vvt2_pin_mask); } #define VVT2_PIN_HIGH() ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { *vvt2_pin_port |= (vvt2_pin_mask); } #define N2O_STAGE1_PIN_LOW() ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { *n2o_stage1_pin_port &= ~(n2o_stage1_pin_mask); } #define N2O_STAGE1_PIN_HIGH() ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { *n2o_stage1_pin_port |= (n2o_stage1_pin_mask); } #define N2O_STAGE2_PIN_LOW() ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { *n2o_stage2_pin_port &= ~(n2o_stage2_pin_mask); } #define N2O_STAGE2_PIN_HIGH() ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { *n2o_stage2_pin_port |= (n2o_stage2_pin_mask); } #define FUEL_PUMP_ON() ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { *pump_pin_port |= (pump_pin_mask); } #define FUEL_PUMP_OFF() ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { *pump_pin_port &= ~(pump_pin_mask); } //Note the below macros cannot use ATOMIC_BLOCK(ATOMIC_RESTORESTATE) as they are called from within ternary operators. The ATOMIC_BLOCK wrapped is instead placed around the ternary call below #define FAN_PIN_LOW() *fan_pin_port &= ~(fan_pin_mask) #define FAN_PIN_HIGH() *fan_pin_port |= (fan_pin_mask) #define AIRCON_PIN_LOW() *aircon_comp_pin_port &= ~(aircon_comp_pin_mask) #define AIRCON_PIN_HIGH() *aircon_comp_pin_port |= (aircon_comp_pin_mask) #define AIRCON_FAN_PIN_LOW() *aircon_fan_pin_port &= ~(aircon_fan_pin_mask) #define AIRCON_FAN_PIN_HIGH() *aircon_fan_pin_port |= (aircon_fan_pin_mask) #define AIRCON_ON() ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { ((((configPage15.airConCompPol&1)==1)) ? AIRCON_PIN_LOW() : AIRCON_PIN_HIGH()); BIT_SET(currentStatus.airConStatus, BIT_AIRCON_COMPRESSOR); } #define AIRCON_OFF() ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { ((((configPage15.airConCompPol&1)==1)) ? AIRCON_PIN_HIGH() : AIRCON_PIN_LOW()); BIT_CLEAR(currentStatus.airConStatus, BIT_AIRCON_COMPRESSOR); } #define AIRCON_FAN_ON() ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { ((((configPage15.airConFanPol&1)==1)) ? AIRCON_FAN_PIN_LOW() : AIRCON_FAN_PIN_HIGH()); BIT_SET(currentStatus.airConStatus, BIT_AIRCON_FAN); } #define AIRCON_FAN_OFF() ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { ((((configPage15.airConFanPol&1)==1)) ? AIRCON_FAN_PIN_HIGH() : AIRCON_FAN_PIN_LOW()); BIT_CLEAR(currentStatus.airConStatus, BIT_AIRCON_FAN); } #define FAN_ON() ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { ((configPage6.fanInv) ? FAN_PIN_LOW() : FAN_PIN_HIGH()); } #define FAN_OFF() ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { ((configPage6.fanInv) ? FAN_PIN_HIGH() : FAN_PIN_LOW()); } #endif #define READ_N2O_ARM_PIN() ((*n2o_arming_pin_port & n2o_arming_pin_mask) ? true : false) #define VVT1_PIN_ON() VVT1_PIN_HIGH(); #define VVT1_PIN_OFF() VVT1_PIN_LOW(); #define VVT2_PIN_ON() VVT2_PIN_HIGH(); #define VVT2_PIN_OFF() VVT2_PIN_LOW(); #define VVT_TIME_DELAY_MULTIPLIER 50 #define WMI_TANK_IS_EMPTY() ((configPage10.wmiEmptyEnabled) ? ((configPage10.wmiEmptyPolarity) ? digitalRead(pinWMIEmpty) : !digitalRead(pinWMIEmpty)) : 1) volatile PORT_TYPE *boost_pin_port; volatile PINMASK_TYPE boost_pin_mask; volatile PORT_TYPE *vvt1_pin_port; volatile PINMASK_TYPE vvt1_pin_mask; volatile PORT_TYPE *vvt2_pin_port; volatile PINMASK_TYPE vvt2_pin_mask; volatile PORT_TYPE *fan_pin_port; volatile PINMASK_TYPE fan_pin_mask; volatile PORT_TYPE *n2o_stage1_pin_port; volatile PINMASK_TYPE n2o_stage1_pin_mask; volatile PORT_TYPE *n2o_stage2_pin_port; volatile PINMASK_TYPE n2o_stage2_pin_mask; volatile PORT_TYPE *n2o_arming_pin_port; volatile PINMASK_TYPE n2o_arming_pin_mask; volatile PORT_TYPE *aircon_comp_pin_port; volatile PINMASK_TYPE aircon_comp_pin_mask; volatile PORT_TYPE *aircon_fan_pin_port; volatile PINMASK_TYPE aircon_fan_pin_mask; volatile PORT_TYPE *aircon_req_pin_port; volatile PINMASK_TYPE aircon_req_pin_mask; volatile bool boost_pwm_state; unsigned int boost_pwm_max_count; //Used for variable PWM frequency volatile unsigned int boost_pwm_cur_value; long boost_pwm_target_value; long boost_cl_target_boost; byte boostCounter; byte vvtCounter; #if defined(PWM_FAN_AVAILABLE)//PWM fan not available on Arduino MEGA volatile bool fan_pwm_state; unsigned int fan_pwm_max_count; //Used for variable PWM frequency volatile unsigned int fan_pwm_cur_value; long fan_pwm_value; void fanInterrupt(void); #endif uint32_t vvtWarmTime; bool vvtIsHot; bool vvtTimeHold; volatile bool vvt1_pwm_state; volatile bool vvt2_pwm_state; volatile bool vvt1_max_pwm; volatile bool vvt2_max_pwm; volatile char nextVVT; unsigned int vvt_pwm_max_count; //Used for variable PWM frequency volatile unsigned int vvt1_pwm_cur_value; volatile unsigned int vvt2_pwm_cur_value; long vvt1_pwm_value; long vvt2_pwm_value; long vvt_pid_target_angle; long vvt2_pid_target_angle; long vvt_pid_current_angle; long vvt2_pid_current_angle; void boostInterrupt(void); void vvtInterrupt(void); bool acIsEnabled; bool acStandAloneFanIsEnabled; uint8_t acStartDelay; uint8_t acTPSLockoutDelay; uint8_t acRPMLockoutDelay; uint8_t acAfterEngineStartDelay; bool waitedAfterCranking; // This starts false and prevents the A/C from running until a few seconds after cranking #endif
8,553
C++
.h
144
58.25
211
0.723209
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,142
updates.h
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/updates.h
#ifndef UPDATES_H #define UPDATES_H #include "table3d.h" void doUpdates(void); void multiplyTableLoad(const void *pTable, table_type_t key, uint8_t multiplier); //Added 202201 - to update the table Y axis as TPS now works at 0.5% increments. Multiplies the load axis values by 4 (most tables) or by 2 (VVT table) void divideTableLoad(const void *pTable, table_type_t key, uint8_t divisor); //Added 202201 - to update the table Y axis as TPS now works at 0.5% increments. This should only be needed by the VVT tables when using MAP as load. #endif
550
C++
.h
7
77.142857
233
0.767098
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,143
init.h
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/init.h
#ifndef INIT_H #define INIT_H void initialiseAll(void); void initialiseTriggers(void); void setPinMapping(byte boardID); void changeHalfToFullSync(void); void changeFullToHalfSync(void); #define VSS_USES_RPM2() ((configPage2.vssMode > 1) && (pinVSS == pinTrigger2) && !BIT_CHECK(decoderState, BIT_DECODER_HAS_SECONDARY)) // VSS is on the same pin as RPM2 and RPM2 is not used as part of the decoder #define FLEX_USES_RPM2() ((configPage2.flexEnabled > 0) && (pinFlex == pinTrigger2) && !BIT_CHECK(decoderState, BIT_DECODER_HAS_SECONDARY)) // Same as above, but for Flex sensor #endif
586
C++
.h
10
57.4
211
0.763066
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,144
crankMaths.h
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/crankMaths.h
#ifndef CRANKMATHS_H #define CRANKMATHS_H #define CRANKMATH_METHOD_INTERVAL_DEFAULT 0 #define CRANKMATH_METHOD_INTERVAL_REV 1 #define CRANKMATH_METHOD_INTERVAL_TOOTH 2 #define CRANKMATH_METHOD_ALPHA_BETA 3 #define CRANKMATH_METHOD_2ND_DERIVATIVE 4 #define SECOND_DERIV_ENABLED 0 //#define fastDegreesToUS(targetDegrees) ((targetDegrees) * (unsigned long)timePerDegree) #define fastDegreesToUS(targetDegrees) (((targetDegrees) * (unsigned long)timePerDegreex16) >> 4) /*#define fastTimeToAngle(time) (((unsigned long)time * degreesPeruSx2048) / 2048) */ //Divide by 2048 will be converted at compile time to bitshift #define fastTimeToAngle(time) (((unsigned long)(time) * degreesPeruSx32768) / 32768) //Divide by 32768 will be converted at compile time to bitshift #define ignitionLimits(angle) ( (((int16_t)(angle)) >= CRANK_ANGLE_MAX_IGN) ? ((angle) - CRANK_ANGLE_MAX_IGN) : ( ((int16_t)(angle) < 0) ? ((angle) + CRANK_ANGLE_MAX_IGN) : (angle)) ) unsigned long angleToTime(int16_t angle, byte method); uint16_t timeToAngle(unsigned long time, byte method); void doCrankSpeedCalcs(void); extern volatile uint16_t timePerDegree; extern volatile uint16_t timePerDegreex16; extern volatile unsigned long degreesPeruSx32768; #endif
1,280
C++
.h
20
62.15
183
0.757382
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,145
timers.h
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/timers.h
/* NOTE - This file and it's associated functions need a CLEARER NAME //Purpose We're implementing a lower frequency interrupt loop to perform calculations that are needed less often, some of which depend on time having passed (delta/time) to be meaningful. //Technical Timer2 is only 8bit so we are setting the prescaler to 128 to get the most out of it. This means that the counter increments every 0.008ms and the overflow at 256 will be after 2.048ms Max Period = (Prescale)*(1/Frequency)*(2^8) (See arduinomega.blogspot.com.au/2011/05/timer2-and-overflow-interrupt-lets-get.html) We're after a 1ms interval so we'll need 131 intervals to reach this ( 1ms / 0.008ms per tick = 125). Hence we will preload the timer with 131 cycles to leave 125 until overflow (1ms). */ #ifndef TIMERS_H #define TIMERS_H #define SET_COMPARE(compare, value) compare = (COMPARE_TYPE)(value) // It is important that we cast this to the actual overflow limit of the timer. The compare variables type can be bigger than the timer overflow. volatile bool tachoAlt = false; #define TACHO_PULSE_HIGH() *tach_pin_port |= (tach_pin_mask) #define TACHO_PULSE_LOW() *tach_pin_port &= ~(tach_pin_mask) enum TachoOutputStatus {TACHO_INACTIVE, READY, ACTIVE}; //The 3 statuses that the tacho output pulse can have. NOTE: Cannot just use 'INACTIVE' as this is already defined within the Teensy Libs volatile uint8_t tachoEndTime; //The time (in ms) that the tacho pulse needs to end at volatile TachoOutputStatus tachoOutputFlag; volatile bool tachoSweepEnabled; volatile uint16_t tachoSweepIncr; volatile uint16_t tachoSweepAccum; #define TACHO_SWEEP_TIME_MS 1500 #define TACHO_SWEEP_RAMP_MS (TACHO_SWEEP_TIME_MS * 2 / 3) #define MS_PER_SEC 1000 volatile byte loop33ms; volatile byte loop66ms; volatile byte loop100ms; volatile byte loop250ms; volatile int loopSec; volatile unsigned int dwellLimit_uS; volatile uint16_t lastRPM_100ms; //Need to record this for rpmDOT calculation volatile uint16_t last250msLoopCount = 1000; //Set to effectively random number on startup. Just need this to be different to what mainLoopCount equals initially (Probably 0) #if defined (CORE_TEENSY) IntervalTimer lowResTimer; void oneMSInterval(void); #elif defined (ARDUINO_ARCH_STM32) void oneMSInterval(void); #endif void initialiseTimers(void); #endif // TIMERS_H
2,343
C++
.h
42
54.309524
213
0.794491
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,146
corrections.h
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/corrections.h
/* All functions in the gamma file return */ #ifndef CORRECTIONS_H #define CORRECTIONS_H #define IGN_IDLE_THRESHOLD 200 //RPM threshold (below CL idle target) for when ign based idle control will engage void initialiseCorrections(void); uint16_t correctionsFuel(void); byte correctionWUE(void); //Warmup enrichment uint16_t correctionCranking(void); //Cranking enrichment byte correctionASE(void); //After Start Enrichment uint16_t correctionAccel(void); //Acceleration Enrichment byte correctionFloodClear(void); //Check for flood clear on cranking byte correctionAFRClosedLoop(void); //Closed loop AFR adjustment byte correctionFlex(void); //Flex fuel adjustment byte correctionFuelTemp(void); //Fuel temp correction byte correctionBatVoltage(void); //Battery voltage correction byte correctionIATDensity(void); //Inlet temp density correction byte correctionBaro(void); //Barometric pressure correction byte correctionLaunch(void); //Launch control correction bool correctionDFCO(void); //Decelleration fuel cutoff int8_t correctionsIgn(int8_t advance); int8_t correctionFixedTiming(int8_t advance); int8_t correctionCrankingFixedTiming(int8_t advance); int8_t correctionFlexTiming(int8_t advance); int8_t correctionWMITiming(int8_t advance); int8_t correctionIATretard(int8_t advance); int8_t correctionCLTadvance(int8_t advance); int8_t correctionIdleAdvance(int8_t advance); int8_t correctionSoftRevLimit(int8_t advance); int8_t correctionNitrous(int8_t advance); int8_t correctionSoftLaunch(int8_t advance); int8_t correctionSoftFlatShift(int8_t advance); int8_t correctionKnock(int8_t advance); uint16_t correctionsDwell(uint16_t dwell); extern byte activateMAPDOT; //The mapDOT value seen when the MAE was activated. extern byte activateTPSDOT; //The tpsDOT value seen when the MAE was activated. extern uint16_t AFRnextCycle; extern unsigned long knockStartTime; extern byte lastKnockCount; extern int16_t knockWindowMin; //The current minimum crank angle for a knock pulse to be valid extern int16_t knockWindowMax;//The current maximum crank angle for a knock pulse to be valid extern uint8_t aseTaper; extern uint8_t dfcoTaper; extern uint8_t idleAdvTaper; extern uint8_t crankingEnrichTaper; #endif // CORRECTIONS_H
2,241
C++
.h
47
46.446809
113
0.832037
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,147
scheduler.h
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/scheduler.h
/** @file Injector and Ignition (on/off) scheduling (structs). This scheduler is designed to maintain 2 schedules for use by the fuel and ignition systems. It functions by waiting for the overflow vectors from each of the timers in use to overflow, which triggers an interrupt. ## Technical Currently I am prescaling the 16-bit timers to 256 for injection and 64 for ignition. This means that the counter increments every 16us (injection) / 4uS (ignition) and will overflow every 1048576uS. Max Period = (Prescale)*(1/Frequency)*(2^17) For more details see https://playground.arduino.cc/Code/Timer1/ (OLD: http://playground.arduino.cc/code/timer1 ). This means that the precision of the scheduler is: - 16uS (+/- 8uS of target) for fuel - 4uS (+/- 2uS) for ignition ## Features This differs from most other schedulers in that its calls are non-recurring (ie when you schedule an event at a certain time and once it has occurred, it will not reoccur unless you explicitly ask/re-register for it). Each timer can have only 1 callback associated with it at any given time. If you call the setCallback function a 2nd time, the original schedule will be overwritten and not occur. ## Timer identification Arduino timers usage for injection and ignition schedules: - timer3 is used for schedule 1(?) (fuel 1,2,3,4 ign 7,8) - timer4 is used for schedule 2(?) (fuel 5,6 ign 4,5,6) - timer5 is used ... (fuel 7,8, ign 1,2,3) Timers 3,4 and 5 are 16-bit timers (ie count to 65536). See page 136 of the processors datasheet: http://www.atmel.com/Images/doc2549.pdf . 256 prescale gives tick every 16uS. 256 prescale gives overflow every 1048576uS (This means maximum wait time is 1.0485 seconds). */ #ifndef SCHEDULER_H #define SCHEDULER_H #include "globals.h" #define USE_IGN_REFRESH #define IGNITION_REFRESH_THRESHOLD 30 //Time in uS that the refresh functions will check to ensure there is enough time before changing the end compare #define DWELL_AVERAGE_ALPHA 30 #define DWELL_AVERAGE(input) (((long)input * (256 - DWELL_AVERAGE_ALPHA) + ((long)currentStatus.actualDwell * DWELL_AVERAGE_ALPHA))) >> 8 //#define DWELL_AVERAGE(input) (currentStatus.dwell) //Can be use to disable the above for testing extern void (*inj1StartFunction)(void); extern void (*inj1EndFunction)(void); extern void (*inj2StartFunction)(void); extern void (*inj2EndFunction)(void); extern void (*inj3StartFunction)(void); extern void (*inj3EndFunction)(void); extern void (*inj4StartFunction)(void); extern void (*inj4EndFunction)(void); extern void (*inj5StartFunction)(void); extern void (*inj5EndFunction)(void); extern void (*inj6StartFunction)(void); extern void (*inj6EndFunction)(void); extern void (*inj7StartFunction)(void); extern void (*inj7EndFunction)(void); extern void (*inj8StartFunction)(void); extern void (*inj8EndFunction)(void); /** @name IgnitionCallbacks * These are the (global) function pointers that get called to begin and end the ignition coil charging. * They are required for the various spark output modes. * @{ */ extern void (*ign1StartFunction)(void); extern void (*ign1EndFunction)(void); extern void (*ign2StartFunction)(void); extern void (*ign2EndFunction)(void); extern void (*ign3StartFunction)(void); extern void (*ign3EndFunction)(void); extern void (*ign4StartFunction)(void); extern void (*ign4EndFunction)(void); extern void (*ign5StartFunction)(void); extern void (*ign5EndFunction)(void); extern void (*ign6StartFunction)(void); extern void (*ign6EndFunction)(void); extern void (*ign7StartFunction)(void); extern void (*ign7EndFunction)(void); extern void (*ign8StartFunction)(void); extern void (*ign8EndFunction)(void); /** @} */ void initialiseSchedulers(void); void beginInjectorPriming(void); void setFuelSchedule1(unsigned long timeout, unsigned long duration); void setFuelSchedule2(unsigned long timeout, unsigned long duration); void setFuelSchedule3(unsigned long timeout, unsigned long duration); void setFuelSchedule4(unsigned long timeout, unsigned long duration); //void setFuelSchedule5(void (*startCallback)(), unsigned long timeout, unsigned long duration, void(*endCallback)()); //Schedule 5 remains a special case for now due to the way it's implemented void setFuelSchedule5(unsigned long timeout, unsigned long duration); void setFuelSchedule6(unsigned long timeout, unsigned long duration); void setFuelSchedule7(unsigned long timeout, unsigned long duration); void setFuelSchedule8(unsigned long timeout, unsigned long duration); void setIgnitionSchedule1(void (*startCallback)(), unsigned long timeout, unsigned long duration, void(*endCallback)()); void setIgnitionSchedule2(void (*startCallback)(), unsigned long timeout, unsigned long duration, void(*endCallback)()); void setIgnitionSchedule3(void (*startCallback)(), unsigned long timeout, unsigned long duration, void(*endCallback)()); void setIgnitionSchedule4(void (*startCallback)(), unsigned long timeout, unsigned long duration, void(*endCallback)()); void setIgnitionSchedule5(void (*startCallback)(), unsigned long timeout, unsigned long duration, void(*endCallback)()); void setIgnitionSchedule6(void (*startCallback)(), unsigned long timeout, unsigned long duration, void(*endCallback)()); void setIgnitionSchedule7(void (*startCallback)(), unsigned long timeout, unsigned long duration, void(*endCallback)()); void setIgnitionSchedule8(void (*startCallback)(), unsigned long timeout, unsigned long duration, void(*endCallback)()); inline void refreshIgnitionSchedule1(unsigned long timeToEnd) __attribute__((always_inline)); //The ARM cores use separate functions for their ISRs #if defined(ARDUINO_ARCH_STM32) || defined(CORE_TEENSY) inline void fuelSchedule1Interrupt(void); inline void fuelSchedule2Interrupt(void); inline void fuelSchedule3Interrupt(void); inline void fuelSchedule4Interrupt(void); #if (INJ_CHANNELS >= 5) inline void fuelSchedule5Interrupt(void); #endif #if (INJ_CHANNELS >= 6) inline void fuelSchedule6Interrupt(void); #endif #if (INJ_CHANNELS >= 7) inline void fuelSchedule7Interrupt(void); #endif #if (INJ_CHANNELS >= 8) inline void fuelSchedule8Interrupt(void); #endif #if (IGN_CHANNELS >= 1) inline void ignitionSchedule1Interrupt(void); #endif #if (IGN_CHANNELS >= 2) inline void ignitionSchedule2Interrupt(void); #endif #if (IGN_CHANNELS >= 3) inline void ignitionSchedule3Interrupt(void); #endif #if (IGN_CHANNELS >= 4) inline void ignitionSchedule4Interrupt(void); #endif #if (IGN_CHANNELS >= 5) inline void ignitionSchedule5Interrupt(void); #endif #if (IGN_CHANNELS >= 6) inline void ignitionSchedule6Interrupt(void); #endif #if (IGN_CHANNELS >= 7) inline void ignitionSchedule7Interrupt(void); #endif #if (IGN_CHANNELS >= 8) inline void ignitionSchedule8Interrupt(void); #endif #endif /** Schedule statuses. * - OFF - Schedule turned off and there is no scheduled plan * - PENDING - There's a scheduled plan, but is has not started to run yet * - STAGED - (???, Not used) * - RUNNING - Schedule is currently running */ enum ScheduleStatus {OFF, PENDING, STAGED, RUNNING}; //The statuses that a schedule can have /** Ignition schedule. */ struct Schedule { volatile unsigned long duration;///< Scheduled duration (uS ?) volatile ScheduleStatus Status; ///< Schedule status: OFF, PENDING, STAGED, RUNNING volatile byte schedulesSet; ///< A counter of how many times the schedule has been set void (*StartCallback)(); ///< Start Callback function for schedule void (*EndCallback)(); ///< End Callback function for schedule volatile unsigned long startTime; /**< The system time (in uS) that the schedule started, used by the overdwell protection in timers.ino */ volatile COMPARE_TYPE startCompare; ///< The counter value of the timer when this will start volatile COMPARE_TYPE endCompare; ///< The counter value of the timer when this will end COMPARE_TYPE nextStartCompare; ///< Planned start of next schedule (when current schedule is RUNNING) COMPARE_TYPE nextEndCompare; ///< Planned end of next schedule (when current schedule is RUNNING) volatile bool hasNextSchedule = false; ///< Enable flag for planned next schedule (when current schedule is RUNNING) volatile bool endScheduleSetByDecoder = false; }; /** Fuel injection schedule. * Fuel schedules don't use the callback pointers, or the startTime/endScheduleSetByDecoder variables. * They are removed in this struct to save RAM. */ struct FuelSchedule { volatile unsigned long duration;///< Scheduled duration (uS ?) volatile ScheduleStatus Status; ///< Schedule status: OFF, PENDING, STAGED, RUNNING volatile byte schedulesSet; ///< A counter of how many times the schedule has been set volatile COMPARE_TYPE startCompare; ///< The counter value of the timer when this will start volatile COMPARE_TYPE endCompare; ///< The counter value of the timer when this will end COMPARE_TYPE nextStartCompare; COMPARE_TYPE nextEndCompare; volatile bool hasNextSchedule = false; }; //volatile Schedule *timer3Aqueue[4]; //Schedule *timer3Bqueue[4]; //Schedule *timer3Cqueue[4]; extern FuelSchedule fuelSchedule1; extern FuelSchedule fuelSchedule2; extern FuelSchedule fuelSchedule3; extern FuelSchedule fuelSchedule4; extern FuelSchedule fuelSchedule5; extern FuelSchedule fuelSchedule6; extern FuelSchedule fuelSchedule7; extern FuelSchedule fuelSchedule8; extern Schedule ignitionSchedule1; extern Schedule ignitionSchedule2; extern Schedule ignitionSchedule3; extern Schedule ignitionSchedule4; extern Schedule ignitionSchedule5; extern Schedule ignitionSchedule6; extern Schedule ignitionSchedule7; extern Schedule ignitionSchedule8; //IgnitionSchedule nullSchedule; //This is placed at the end of the queue. It's status will always be set to OFF and hence will never perform any action within an ISR static inline COMPARE_TYPE setQueue(volatile Schedule *queue[], Schedule *schedule1, Schedule *schedule2, unsigned int CNT) { //Create an array of all the upcoming targets, relative to the current count on the timer unsigned int tmpQueue[4]; //Set the initial queue state. This order matches the tmpQueue order if(schedule1->Status == OFF) { queue[0] = schedule2; queue[1] = schedule2; tmpQueue[0] = schedule2->startCompare - CNT; tmpQueue[1] = schedule2->endCompare - CNT; } else { queue[0] = schedule1; queue[1] = schedule1; tmpQueue[0] = schedule1->startCompare - CNT; tmpQueue[1] = schedule1->endCompare - CNT; } if(schedule2->Status == OFF) { queue[2] = schedule1; queue[3] = schedule1; tmpQueue[2] = schedule1->startCompare - CNT; tmpQueue[3] = schedule1->endCompare - CNT; } else { queue[2] = schedule2; queue[3] = schedule2; tmpQueue[2] = schedule2->startCompare - CNT; tmpQueue[3] = schedule2->endCompare - CNT; } //Sort the queues. Both queues are kept in sync. //This implements a sorting networking based on the Bose-Nelson sorting network //See: pages.ripco.net/~jgamble/nw.html #define SWAP(x,y) if(tmpQueue[y] < tmpQueue[x]) { unsigned int tmp = tmpQueue[x]; tmpQueue[x] = tmpQueue[y]; tmpQueue[y] = tmp; volatile Schedule *tmpS = queue[x]; queue[x] = queue[y]; queue[y] = tmpS; } /*SWAP(0, 1); */ //Likely not needed /*SWAP(2, 3); */ //Likely not needed SWAP(0, 2); SWAP(1, 3); SWAP(1, 2); //Return the next compare time in the queue return tmpQueue[0] + CNT; //Return the } /* * Moves all the Schedules in a queue forward one position. * The current item (0) is discarded * The final queue slot is set to nullSchedule to indicate that no action should be taken */ static inline unsigned int popQueue(volatile Schedule *queue[]) { queue[0] = queue[1]; queue[1] = queue[2]; queue[2] = queue[3]; //queue[3] = &nullSchedule; unsigned int returnCompare; if( queue[0]->Status == PENDING ) { returnCompare = queue[0]->startCompare; } else { returnCompare = queue[0]->endCompare; } return returnCompare; } #endif // SCHEDULER_H
12,027
C++
.h
255
45.141176
205
0.767749
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,148
schedule_calcs.hpp
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/schedule_calcs.hpp
#include "globals.h" #include "scheduler.h" #include "crankMaths.h" inline uint16_t calculateInjectorStartAngle(uint16_t PWdivTimerPerDegree, int16_t injChannelDegrees) { uint16_t tempInjectorStartAngle = (currentStatus.injAngle + injChannelDegrees); if(tempInjectorStartAngle < PWdivTimerPerDegree) { tempInjectorStartAngle += CRANK_ANGLE_MAX_INJ; } tempInjectorStartAngle -= PWdivTimerPerDegree; while(tempInjectorStartAngle > (uint16_t)CRANK_ANGLE_MAX_INJ) { tempInjectorStartAngle -= CRANK_ANGLE_MAX_INJ; } return tempInjectorStartAngle; } inline uint32_t calculateInjector1Timeout(int injector1StartAngle, int crankAngle) { if ( (injector1StartAngle <= crankAngle) && (fuelSchedule1.Status == RUNNING) ) { injector1StartAngle += CRANK_ANGLE_MAX_INJ; } if (injector1StartAngle > crankAngle) { return ((injector1StartAngle - crankAngle) * (unsigned long)timePerDegree); } return 0U; } inline uint32_t calculateInjectorNTimeout(const FuelSchedule &schedule, int channelInjDegrees, int injectorStartAngle, int crankAngle) { int tempCrankAngle = crankAngle - channelInjDegrees; if( tempCrankAngle < 0) { tempCrankAngle += CRANK_ANGLE_MAX_INJ; } int tempStartAngle = injectorStartAngle - channelInjDegrees; if ( tempStartAngle < 0) { tempStartAngle += CRANK_ANGLE_MAX_INJ; } if ( (tempStartAngle <= tempCrankAngle) && (schedule.Status == RUNNING) ) { tempStartAngle += CRANK_ANGLE_MAX_INJ; } if ( tempStartAngle > tempCrankAngle ) { return (((uint32_t)tempStartAngle - (uint32_t)tempCrankAngle) * (uint32_t)timePerDegree); } return 0U; } inline void calculateIgnitionAngle1(int dwellAngle) { ignition1EndAngle = CRANK_ANGLE_MAX_IGN - currentStatus.advance; if(ignition1EndAngle > CRANK_ANGLE_MAX_IGN) {ignition1EndAngle -= CRANK_ANGLE_MAX_IGN;} ignition1StartAngle = ignition1EndAngle - dwellAngle; // 360 - desired advance angle - number of degrees the dwell will take if(ignition1StartAngle < 0) {ignition1StartAngle += CRANK_ANGLE_MAX_IGN;} } inline void calculateIgnitionAngle2(int dwellAngle) { ignition2EndAngle = channel2IgnDegrees - currentStatus.advance; if(ignition2EndAngle > CRANK_ANGLE_MAX_IGN) {ignition2EndAngle -= CRANK_ANGLE_MAX_IGN;} ignition2StartAngle = ignition2EndAngle - dwellAngle; if(ignition2StartAngle < 0) {ignition2StartAngle += CRANK_ANGLE_MAX_IGN;} } inline void calculateIgnitionAngle3(int dwellAngle) { ignition3EndAngle = channel3IgnDegrees - currentStatus.advance; if(ignition3EndAngle > CRANK_ANGLE_MAX_IGN) {ignition3EndAngle -= CRANK_ANGLE_MAX_IGN;} ignition3StartAngle = ignition3EndAngle - dwellAngle; if(ignition3StartAngle < 0) {ignition3StartAngle += CRANK_ANGLE_MAX_IGN;} } // ignition 3 for rotary inline void calculateIgnitionAngle3(int dwellAngle, int rotarySplitDegrees) { ignition3EndAngle = ignition1EndAngle + rotarySplitDegrees; ignition3StartAngle = ignition3EndAngle - dwellAngle; if(ignition3StartAngle > CRANK_ANGLE_MAX_IGN) {ignition3StartAngle -= CRANK_ANGLE_MAX_IGN;} if(ignition3StartAngle < 0) {ignition3StartAngle += CRANK_ANGLE_MAX_IGN;} } inline void calculateIgnitionAngle4(int dwellAngle) { ignition4EndAngle = channel4IgnDegrees - currentStatus.advance; if(ignition4EndAngle > CRANK_ANGLE_MAX_IGN) {ignition4EndAngle -= CRANK_ANGLE_MAX_IGN;} ignition4StartAngle = ignition4EndAngle - dwellAngle; if(ignition4StartAngle < 0) {ignition4StartAngle += CRANK_ANGLE_MAX_IGN;} } // ignition 4 for rotary inline void calculateIgnitionAngle4(int dwellAngle, int rotarySplitDegrees) { ignition4EndAngle = ignition2EndAngle + rotarySplitDegrees; ignition4StartAngle = ignition4EndAngle - dwellAngle; if(ignition4StartAngle > CRANK_ANGLE_MAX_IGN) {ignition4StartAngle -= CRANK_ANGLE_MAX_IGN;} if(ignition4StartAngle < 0) {ignition4StartAngle += CRANK_ANGLE_MAX_IGN;} } inline void calculateIgnitionAngle5(int dwellAngle) { ignition5EndAngle = channel5IgnDegrees - currentStatus.advance; if(ignition5EndAngle > CRANK_ANGLE_MAX_IGN) {ignition5EndAngle -= CRANK_ANGLE_MAX_IGN;} ignition5StartAngle = ignition5EndAngle - dwellAngle; if(ignition5StartAngle < 0) {ignition5StartAngle += CRANK_ANGLE_MAX_IGN;} } inline void calculateIgnitionAngle6(int dwellAngle) { ignition6EndAngle = channel6IgnDegrees - currentStatus.advance; if(ignition6EndAngle > CRANK_ANGLE_MAX_IGN) {ignition6EndAngle -= CRANK_ANGLE_MAX_IGN;} ignition6StartAngle = ignition6EndAngle - dwellAngle; if(ignition6StartAngle < 0) {ignition6StartAngle += CRANK_ANGLE_MAX_IGN;} } inline void calculateIgnitionAngle7(int dwellAngle) { ignition7EndAngle = channel7IgnDegrees - currentStatus.advance; if(ignition7EndAngle > CRANK_ANGLE_MAX_IGN) {ignition7EndAngle -= CRANK_ANGLE_MAX_IGN;} ignition7StartAngle = ignition7EndAngle - dwellAngle; if(ignition7StartAngle < 0) {ignition7StartAngle += CRANK_ANGLE_MAX_IGN;} } inline void calculateIgnitionAngle8(int dwellAngle) { ignition8EndAngle = channel8IgnDegrees - currentStatus.advance; if(ignition8EndAngle > CRANK_ANGLE_MAX_IGN) {ignition8EndAngle -= CRANK_ANGLE_MAX_IGN;} ignition8StartAngle = ignition8EndAngle - dwellAngle; if(ignition8StartAngle < 0) {ignition8StartAngle += CRANK_ANGLE_MAX_IGN;} } inline uint32_t calculateIgnition1Timeout(int crankAngle) { if ( (ignition1StartAngle <= crankAngle) && (ignitionSchedule1.Status == RUNNING) ) { ignition1StartAngle += CRANK_ANGLE_MAX_IGN; } if ( ignition1StartAngle > crankAngle) { return angleToTime((ignition1StartAngle - crankAngle), CRANKMATH_METHOD_INTERVAL_REV); } return 0; } inline uint32_t calculateIgnitionNTimeout(const Schedule &schedule, int startAngle, int channelIgnDegrees, int crankAngle) { int tempCrankAngle = crankAngle - channelIgnDegrees; if( tempCrankAngle < 0) { tempCrankAngle += CRANK_ANGLE_MAX_IGN; } int tempStartAngle = startAngle - channelIgnDegrees; if ( tempStartAngle < 0) { tempStartAngle += CRANK_ANGLE_MAX_IGN; } if ( (tempStartAngle <= tempCrankAngle) && (schedule.Status == RUNNING) ) { tempStartAngle += CRANK_ANGLE_MAX_IGN; } if(tempStartAngle > tempCrankAngle) { return angleToTime((tempStartAngle - tempCrankAngle), CRANKMATH_METHOD_INTERVAL_REV); } return 0U; }
6,283
C++
.h
127
46.425197
135
0.780659
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,149
acc_mc33810.h
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/acc_mc33810.h
#ifndef MC33810_H #define MC33810_H #include <SPI.h> volatile PORT_TYPE *mc33810_1_pin_port; volatile PINMASK_TYPE mc33810_1_pin_mask; volatile PORT_TYPE *mc33810_2_pin_port; volatile PINMASK_TYPE mc33810_2_pin_mask; //#define MC33810_ONOFF_CMD 3 static uint8_t MC33810_ONOFF_CMD = 0x30; //48 in decimal volatile uint8_t mc33810_1_requestedState; //Current binary state of the 1st ICs IGN and INJ values volatile uint8_t mc33810_2_requestedState; //Current binary state of the 2nd ICs IGN and INJ values volatile uint8_t mc33810_1_returnState; //Current binary state of the 1st ICs IGN and INJ values volatile uint8_t mc33810_2_returnState; //Current binary state of the 2nd ICs IGN and INJ values void initMC33810(void); #define MC33810_1_ACTIVE() (*mc33810_1_pin_port &= ~(mc33810_1_pin_mask)) #define MC33810_1_INACTIVE() (*mc33810_1_pin_port |= (mc33810_1_pin_mask)) #define MC33810_2_ACTIVE() (*mc33810_2_pin_port &= ~(mc33810_2_pin_mask)) #define MC33810_2_INACTIVE() (*mc33810_2_pin_port |= (mc33810_2_pin_mask)) //These are default values for which injector is attached to which output on the IC. //They may (Probably will) be changed during init by the board specific config in init.ino uint8_t MC33810_BIT_INJ1 = 1; uint8_t MC33810_BIT_INJ2 = 2; uint8_t MC33810_BIT_INJ3 = 3; uint8_t MC33810_BIT_INJ4 = 4; uint8_t MC33810_BIT_INJ5 = 5; uint8_t MC33810_BIT_INJ6 = 6; uint8_t MC33810_BIT_INJ7 = 7; uint8_t MC33810_BIT_INJ8 = 8; uint8_t MC33810_BIT_IGN1 = 1; uint8_t MC33810_BIT_IGN2 = 2; uint8_t MC33810_BIT_IGN3 = 3; uint8_t MC33810_BIT_IGN4 = 4; uint8_t MC33810_BIT_IGN5 = 5; uint8_t MC33810_BIT_IGN6 = 6; uint8_t MC33810_BIT_IGN7 = 7; uint8_t MC33810_BIT_IGN8 = 8; #define openInjector1_MC33810() MC33810_1_ACTIVE(); BIT_SET(mc33810_1_requestedState, MC33810_BIT_INJ1); mc33810_1_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_1_requestedState)); MC33810_1_INACTIVE() #define openInjector2_MC33810() MC33810_1_ACTIVE(); BIT_SET(mc33810_1_requestedState, MC33810_BIT_INJ2); mc33810_1_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_1_requestedState)); MC33810_1_INACTIVE() #define openInjector3_MC33810() MC33810_1_ACTIVE(); BIT_SET(mc33810_1_requestedState, MC33810_BIT_INJ3); mc33810_1_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_1_requestedState)); MC33810_1_INACTIVE() #define openInjector4_MC33810() MC33810_1_ACTIVE(); BIT_SET(mc33810_1_requestedState, MC33810_BIT_INJ4); mc33810_1_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_1_requestedState)); MC33810_1_INACTIVE() #define openInjector5_MC33810() MC33810_2_ACTIVE(); BIT_SET(mc33810_2_requestedState, MC33810_BIT_INJ5); mc33810_2_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_2_requestedState)); MC33810_2_INACTIVE() #define openInjector6_MC33810() MC33810_2_ACTIVE(); BIT_SET(mc33810_2_requestedState, MC33810_BIT_INJ6); mc33810_2_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_2_requestedState)); MC33810_2_INACTIVE() #define openInjector7_MC33810() MC33810_2_ACTIVE(); BIT_SET(mc33810_2_requestedState, MC33810_BIT_INJ7); mc33810_2_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_2_requestedState)); MC33810_2_INACTIVE() #define openInjector8_MC33810() MC33810_2_ACTIVE(); BIT_SET(mc33810_2_requestedState, MC33810_BIT_INJ8); mc33810_2_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_2_requestedState)); MC33810_2_INACTIVE() #define closeInjector1_MC33810() MC33810_1_ACTIVE(); BIT_CLEAR(mc33810_1_requestedState, MC33810_BIT_INJ1); mc33810_1_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_1_requestedState)); MC33810_1_INACTIVE() #define closeInjector2_MC33810() MC33810_1_ACTIVE(); BIT_CLEAR(mc33810_1_requestedState, MC33810_BIT_INJ2); mc33810_1_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_1_requestedState)); MC33810_1_INACTIVE() #define closeInjector3_MC33810() MC33810_1_ACTIVE(); BIT_CLEAR(mc33810_1_requestedState, MC33810_BIT_INJ3); mc33810_1_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_1_requestedState)); MC33810_1_INACTIVE() #define closeInjector4_MC33810() MC33810_1_ACTIVE(); BIT_CLEAR(mc33810_1_requestedState, MC33810_BIT_INJ4); mc33810_1_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_1_requestedState)); MC33810_1_INACTIVE() #define closeInjector5_MC33810() MC33810_2_ACTIVE(); BIT_CLEAR(mc33810_2_requestedState, MC33810_BIT_INJ5); mc33810_2_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_2_requestedState)); MC33810_2_INACTIVE() #define closeInjector6_MC33810() MC33810_2_ACTIVE(); BIT_CLEAR(mc33810_2_requestedState, MC33810_BIT_INJ6); mc33810_2_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_2_requestedState)); MC33810_2_INACTIVE() #define closeInjector7_MC33810() MC33810_2_ACTIVE(); BIT_CLEAR(mc33810_2_requestedState, MC33810_BIT_INJ7); mc33810_2_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_2_requestedState)); MC33810_2_INACTIVE() #define closeInjector8_MC33810() MC33810_2_ACTIVE(); BIT_CLEAR(mc33810_2_requestedState, MC33810_BIT_INJ8); mc33810_2_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_2_requestedState)); MC33810_2_INACTIVE() #define injector1Toggle_MC33810() MC33810_1_ACTIVE(); BIT_TOGGLE(mc33810_1_requestedState, MC33810_BIT_INJ1); mc33810_1_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_1_requestedState)); MC33810_1_INACTIVE() #define injector2Toggle_MC33810() MC33810_1_ACTIVE(); BIT_TOGGLE(mc33810_1_requestedState, MC33810_BIT_INJ2); mc33810_1_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_1_requestedState)); MC33810_1_INACTIVE() #define injector3Toggle_MC33810() MC33810_1_ACTIVE(); BIT_TOGGLE(mc33810_1_requestedState, MC33810_BIT_INJ3); mc33810_1_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_1_requestedState)); MC33810_1_INACTIVE() #define injector4Toggle_MC33810() MC33810_1_ACTIVE(); BIT_TOGGLE(mc33810_1_requestedState, MC33810_BIT_INJ4); mc33810_1_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_1_requestedState)); MC33810_1_INACTIVE() #define injector5Toggle_MC33810() MC33810_2_ACTIVE(); BIT_TOGGLE(mc33810_2_requestedState, MC33810_BIT_INJ5); mc33810_2_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_2_requestedState)); MC33810_2_INACTIVE() #define injector6Toggle_MC33810() MC33810_2_ACTIVE(); BIT_TOGGLE(mc33810_2_requestedState, MC33810_BIT_INJ6); mc33810_2_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_2_requestedState)); MC33810_2_INACTIVE() #define injector7Toggle_MC33810() MC33810_2_ACTIVE(); BIT_TOGGLE(mc33810_2_requestedState, MC33810_BIT_INJ7); mc33810_2_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_2_requestedState)); MC33810_2_INACTIVE() #define injector8Toggle_MC33810() MC33810_2_ACTIVE(); BIT_TOGGLE(mc33810_2_requestedState, MC33810_BIT_INJ8); mc33810_2_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_2_requestedState)); MC33810_2_INACTIVE() #define coil1High_MC33810() MC33810_1_ACTIVE(); BIT_SET(mc33810_1_requestedState, MC33810_BIT_IGN1); mc33810_1_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_1_requestedState)); MC33810_1_INACTIVE() #define coil2High_MC33810() MC33810_1_ACTIVE(); BIT_SET(mc33810_1_requestedState, MC33810_BIT_IGN2); mc33810_1_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_1_requestedState)); MC33810_1_INACTIVE() //#define coil1High_MC33810() MC33810_1_ACTIVE(); BIT_SET(mc33810_1_requestedState, MC33810_BIT_IGN1); MC33810_1_INACTIVE() //#define coil2High_MC33810() MC33810_1_ACTIVE(); BIT_SET(mc33810_1_requestedState, MC33810_BIT_IGN2); MC33810_1_INACTIVE() #define coil3High_MC33810() MC33810_1_ACTIVE(); BIT_SET(mc33810_1_requestedState, MC33810_BIT_IGN3); mc33810_1_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_1_requestedState)); MC33810_1_INACTIVE() #define coil4High_MC33810() MC33810_1_ACTIVE(); BIT_SET(mc33810_1_requestedState, MC33810_BIT_IGN4); mc33810_1_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_1_requestedState)); MC33810_1_INACTIVE() #define coil5High_MC33810() MC33810_2_ACTIVE(); BIT_SET(mc33810_2_requestedState, MC33810_BIT_IGN5); mc33810_2_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_2_requestedState)); MC33810_2_INACTIVE() #define coil6High_MC33810() MC33810_2_ACTIVE(); BIT_SET(mc33810_2_requestedState, MC33810_BIT_IGN6); mc33810_2_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_2_requestedState)); MC33810_2_INACTIVE() #define coil7High_MC33810() MC33810_2_ACTIVE(); BIT_SET(mc33810_2_requestedState, MC33810_BIT_IGN7); mc33810_2_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_2_requestedState)); MC33810_2_INACTIVE() #define coil8High_MC33810() MC33810_2_ACTIVE(); BIT_SET(mc33810_2_requestedState, MC33810_BIT_IGN8); mc33810_2_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_2_requestedState)); MC33810_2_INACTIVE() #define coil1Low_MC33810() MC33810_1_ACTIVE(); BIT_CLEAR(mc33810_1_requestedState, MC33810_BIT_IGN1); mc33810_1_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_1_requestedState)); MC33810_1_INACTIVE() #define coil2Low_MC33810() MC33810_1_ACTIVE(); BIT_CLEAR(mc33810_1_requestedState, MC33810_BIT_IGN2); mc33810_1_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_1_requestedState)); MC33810_1_INACTIVE() #define coil3Low_MC33810() MC33810_1_ACTIVE(); BIT_CLEAR(mc33810_1_requestedState, MC33810_BIT_IGN3); mc33810_1_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_1_requestedState)); MC33810_1_INACTIVE() #define coil4Low_MC33810() MC33810_1_ACTIVE(); BIT_CLEAR(mc33810_1_requestedState, MC33810_BIT_IGN4); mc33810_1_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_1_requestedState)); MC33810_1_INACTIVE() #define coil5Low_MC33810() MC33810_2_ACTIVE(); BIT_CLEAR(mc33810_2_requestedState, MC33810_BIT_IGN5); mc33810_2_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_2_requestedState)); MC33810_2_INACTIVE() #define coil6Low_MC33810() MC33810_2_ACTIVE(); BIT_CLEAR(mc33810_2_requestedState, MC33810_BIT_IGN6); mc33810_2_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_2_requestedState)); MC33810_2_INACTIVE() #define coil7Low_MC33810() MC33810_2_ACTIVE(); BIT_CLEAR(mc33810_2_requestedState, MC33810_BIT_IGN7); mc33810_2_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_2_requestedState)); MC33810_2_INACTIVE() #define coil8Low_MC33810() MC33810_2_ACTIVE(); BIT_CLEAR(mc33810_2_requestedState, MC33810_BIT_IGN8); mc33810_2_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_2_requestedState)); MC33810_2_INACTIVE() #define coil1Toggle_MC33810() MC33810_1_ACTIVE(); BIT_TOGGLE(mc33810_1_requestedState, MC33810_BIT_IGN1); mc33810_1_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_1_requestedState)); MC33810_1_INACTIVE() #define coil2Toggle_MC33810() MC33810_1_ACTIVE(); BIT_TOGGLE(mc33810_1_requestedState, MC33810_BIT_IGN2); mc33810_1_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_1_requestedState)); MC33810_1_INACTIVE() #define coil3Toggle_MC33810() MC33810_1_ACTIVE(); BIT_TOGGLE(mc33810_1_requestedState, MC33810_BIT_IGN3); mc33810_1_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_1_requestedState)); MC33810_1_INACTIVE() #define coil4Toggle_MC33810() MC33810_1_ACTIVE(); BIT_TOGGLE(mc33810_1_requestedState, MC33810_BIT_IGN4); mc33810_1_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_1_requestedState)); MC33810_1_INACTIVE() #define coil5Toggle_MC33810() MC33810_2_ACTIVE(); BIT_TOGGLE(mc33810_2_requestedState, MC33810_BIT_IGN5); mc33810_2_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_2_requestedState)); MC33810_2_INACTIVE() #define coil6Toggle_MC33810() MC33810_2_ACTIVE(); BIT_TOGGLE(mc33810_2_requestedState, MC33810_BIT_IGN6); mc33810_2_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_2_requestedState)); MC33810_2_INACTIVE() #define coil7Toggle_MC33810() MC33810_2_ACTIVE(); BIT_TOGGLE(mc33810_2_requestedState, MC33810_BIT_IGN7); mc33810_2_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_2_requestedState)); MC33810_2_INACTIVE() #define coil8Toggle_MC33810() MC33810_2_ACTIVE(); BIT_TOGGLE(mc33810_2_requestedState, MC33810_BIT_IGN8); mc33810_2_returnState = SPI.transfer16(word(MC33810_ONOFF_CMD, mc33810_2_requestedState)); MC33810_2_INACTIVE() #endif
12,379
C++
.h
87
141.126437
221
0.78679
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,150
table3d_axes.h
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/table3d_axes.h
/** * @addtogroup table_3d * @{ */ /** \file * @brief 3D table axis types and iterators */ #pragma once #include "table3d_typedefs.h" /**\enum axis_domain * @brief Encodes the real world measurement that a table axis captures * */ enum axis_domain { /** RPM (engine speed) */ axis_domain_Rpm, /** Load */ axis_domain_Load, /** Throttle position */ axis_domain_Tps }; /** @brief Iterate over table axis elements */ class table_axis_iterator { public: /** @brief Construct */ table_axis_iterator(table3d_axis_t *pStart, const table3d_axis_t *pEnd, axis_domain domain) : _pAxis(pStart), _pAxisEnd(pEnd), _stride(pEnd>pStart ? stride_inc : stride_dec), _domain(domain) //cppcheck-suppress misra-c2012-10.4 { } axis_domain get_domain(void) const { return _domain; } /** @brief Advance the iterator * @param steps The number of elements to move the iterator */ table_axis_iterator& advance(int8_t steps) { _pAxis = _pAxis + ((int16_t)_stride * steps); return *this; } /** @brief Increment the iterator by one element*/ table_axis_iterator& operator++(void) { return advance(1); } /** @brief Test for end of iteration */ bool at_end(void) const { return _pAxis == _pAxisEnd; } /** @brief Dereference the iterator */ table3d_axis_t& operator*(void) { return *_pAxis; } /** @copydoc table_axis_iterator::operator*() */ const table3d_axis_t& operator*(void) const { return *_pAxis; } private: static constexpr int8_t stride_inc = 1; static constexpr int8_t stride_dec = -1; table3d_axis_t *_pAxis; const table3d_axis_t *_pAxisEnd; int8_t _stride; const axis_domain _domain; }; #define TABLE3D_TYPENAME_AXIS(size, domain) table3d ## size ## domain ## _axis #define TABLE3D_GEN_AXIS(size, dom) \ /** @brief The dxis for a 3D table with size x size dimensions and domain 'domain' */ \ struct TABLE3D_TYPENAME_AXIS(size, dom) { \ /** @brief The length of the axis in elements */ \ static constexpr table3d_dim_t length = (size); \ /** @brief The domain the axis represents */ \ static constexpr axis_domain domain = axis_domain_ ## dom; \ /** @brief The axis elements\ */ \ table3d_axis_t axis[(size)]; \ \ /** @brief Iterate over the axis elements */ \ table_axis_iterator begin(void) \ { \ return table_axis_iterator(axis+(size)-1, axis-1, domain); \ } \ /** @brief Iterate over the axis elements, from largest to smallest */ \ table_axis_iterator rbegin(void) \ { \ return table_axis_iterator(axis, axis+(size), domain); \ } \ }; // This generates the axis types for the following sizes & domains: TABLE3D_GEN_AXIS(6, Rpm) TABLE3D_GEN_AXIS(6, Load) TABLE3D_GEN_AXIS(4, Rpm) TABLE3D_GEN_AXIS(4, Load) TABLE3D_GEN_AXIS(8, Rpm) TABLE3D_GEN_AXIS(8, Load) TABLE3D_GEN_AXIS(8, Tps) TABLE3D_GEN_AXIS(16, Rpm) TABLE3D_GEN_AXIS(16, Load) /** @} */
3,151
C++
.h
101
26.049505
140
0.625083
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,151
PID_v1.h
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/src/PID_v1/PID_v1.h
#ifndef PID_v1_h #define PID_v1_h #define LIBRARY_VERSION 1.0.0 class PID { public: //Constants used in some of the functions below #define AUTOMATIC 1 #define MANUAL 0 #define DIRECT 0 #define REVERSE 1 //commonly used functions ************************************************************************** PID(long*, long*, long*, // * constructor. links the PID to the Input, Output, and byte, byte, byte, byte); // Setpoint. Initial tuning parameters are also set here void SetMode(int Mode); // * sets PID to either Manual (0) or Auto (non-0) bool Compute(); // * performs the PID calculation. it should be // called every time loop() cycles. ON/OFF and // calculation frequency can be set using SetMode // SetSampleTime respectively void SetOutputLimits(long, long); //clamps the output to a specific range. 0-255 by default, but //it's likely the user will want to change this depending on //the application //available but not commonly used functions ******************************************************** void SetTunings(byte, byte, // * While most users will set the tunings once in the byte); // constructor, this function gives the user the option // of changing tunings during runtime for Adaptive control void SetControllerDirection(byte); // * Sets the Direction, or "Action" of the controller. DIRECT // means the output will increase when error is positive. REVERSE // means the opposite. it's very unlikely that this will be needed // once it is set in the constructor. void SetSampleTime(int); // * sets the frequency, in Milliseconds, with which // the PID calculation is performed. default is 100 //Display functions **************************************************************** int16_t GetKp(); // These functions query the pid for interal values. int16_t GetKi(); // they were created mainly for the pid front-end, int16_t GetKd(); // where it's important to know what is actually int GetMode(); // inside the PID. int GetDirection(); // private: void Initialize(); long dispKp; // * we'll hold on to the tuning parameters in user-entered long dispKi; // format for display purposes long dispKd; // long kp; // * (P)roportional Tuning Parameter long ki; // * (I)ntegral Tuning Parameter long kd; // * (D)erivative Tuning Parameter int controllerDirection; long *myInput; // * Pointers to the Input, Output, and Setpoint variables long *myOutput; // This creates a hard link between the variables and the long *mySetpoint; // PID, freeing the user from having to constantly tell us // what these values are. with pointers we'll just know. unsigned long lastTime; long ITerm, lastInput; unsigned long SampleTime; long outMin, outMax; bool inAuto; }; class integerPID { public: //Constants used in some of the functions below #define AUTOMATIC 1 #define MANUAL 0 #define DIRECT 0 #define REVERSE 1 #define PID_SHIFTS 10 //Increased resolution //commonly used functions ************************************************************************** integerPID(long*, long*, long*, // * constructor. links the PID to the Input, Output, and int16_t, int16_t, int16_t, byte); // Setpoint. Initial tuning parameters are also set here void SetMode(int Mode); // * sets PID to either Manual (0) or Auto (non-0) bool Compute(bool, long FeedForwardTerm = 0); // * performs the PID calculation. it should be // called every time loop() cycles. ON/OFF and // calculation frequency can be set using SetMode // SetSampleTime respectively bool Compute2(int, int, bool); bool ComputeVVT(uint32_t); void SetOutputLimits(long, long); //clamps the output to a specific range. 0-255 by default, but //it's likely the user will want to change this depending on //the application //available but not commonly used functions ******************************************************** void SetTunings(int16_t, int16_t, // * While most users will set the tunings once in the int16_t, byte=0); // constructor, this function gives the user the option // of changing tunings during runtime for Adaptive control void SetControllerDirection(byte); // * Sets the Direction, or "Action" of the controller. DIRECT // means the output will increase when error is positive. REVERSE // means the opposite. it's very unlikely that this will be needed // once it is set in the constructor. void SetSampleTime(uint16_t); // * sets the frequency, in Milliseconds, with which // the PID calculation is performed. default is 100 //Display functions **************************************************************** int GetMode(); // inside the PID. int GetDirection(); // void Initialize(); void ResetIntegeral(); private: int16_t dispKp; int16_t dispKi; int16_t dispKd; int16_t kp; // * (P)roportional Tuning Parameter int16_t ki; // * (I)ntegral Tuning Parameter int16_t kd; // * (D)erivative Tuning Parameter int controllerDirection; long *myInput; // * Pointers to the Input, Output, and Setpoint variables long *myOutput; // This creates a hard link between the variables and the long *mySetpoint; // PID, freeing the user from having to constantly tell us // what these values are. with pointers we'll just know. unsigned long lastTime; long outputSum, lastInput, lastMinusOneInput; int16_t lastError; uint16_t SampleTime; long outMin, outMax; bool inAuto; }; class integerPID_ideal { public: //Constants used in some of the functions below #define AUTOMATIC 1 #define MANUAL 0 #define DIRECT 0 #define REVERSE 1 //commonly used functions ************************************************************************** integerPID_ideal(long*, uint16_t*, uint16_t*, uint16_t*, byte*, // * constructor. links the PID to the Input, Output, and byte, byte, byte, byte); // Setpoint. Initial tuning parameters are also set here bool Compute(); // * performs the PID calculation. it should be // called every time loop() cycles. ON/OFF and // calculation frequency can be set using SetMode // SetSampleTime respectively bool Compute(uint16_t); // * performs the PID calculation. it should be // called every time loop() cycles. ON/OFF and // calculation frequency can be set using SetMode // SetSampleTime respectively void SetOutputLimits(long, long); //clamps the output to a specific range. 0-255 by default, but //it's likely the user will want to change this depending on //the application //available but not commonly used functions ******************************************************** void SetTunings(byte, byte, // * While most users will set the tunings once in the byte); // constructor, this function gives the user the option // of changing tunings during runtime for Adaptive control void SetControllerDirection(byte); // * Sets the Direction, or "Action" of the controller. DIRECT // means the output will increase when error is positive. REVERSE // means the opposite. it's very unlikely that this will be needed // once it is set in the constructor. //Display functions **************************************************************** int GetMode(); // inside the PID. int GetDirection(); // void Initialize(); private: byte dispKp; // * we'll hold on to the tuning parameters in user-entered byte dispKi; // format for display purposes byte dispKd; // uint16_t kp; // * (P)roportional Tuning Parameter uint16_t ki; // * (I)ntegral Tuning Parameter uint16_t kd; // * (D)erivative Tuning Parameter int controllerDirection; long *myInput; // uint16_t *myOutput; // This is a percentage figure multipled by 100 (To give 2 points of precision) uint16_t *mySetpoint; // uint16_t *mySensitivity; byte *mySampleTime; unsigned long lastTime; long lastError; long ITerm, lastInput; long outMin, outMax; }; #endif
9,619
C++
.h
166
48.753012
133
0.561488
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,153
STM32_CAN.h
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/src/STM32_CAN/STM32_CAN.h
/* This is universal CAN library for STM32 that was made to be used with Speeduino EFI. It should support all STM32 MCUs that are also supported in stm32duino Arduino_Core_STM32 and supports up to 3x CAN busses. The library is created because at least currently (year 2021) there is no official CAN library in the STM32 core. This library is based on several STM32 CAN example libraries linked below and it has been combined with few things from Teensy FlexCAN library to make it compatible with the CAN features that exist in speeduino for Teensy. Links to repositories that have helped with this: https://github.com/nopnop2002/Arduino-STM32-CAN https://github.com/J-f-Jensen/libraries/tree/master/STM32_CAN https://github.com/jiauka/STM32F1_CAN STM32 core: https://github.com/stm32duino/Arduino_Core_STM32 */ #if HAL_CAN_MODULE_ENABLED #ifndef STM32_CAN_H #define STM32_CAN_H #include <Arduino.h> // This struct is directly copied from Teensy FlexCAN library to retain compatibility with it. Not all are in use with STM32. // Source: https://github.com/tonton81/FlexCAN_T4/ typedef struct CAN_message_t { uint32_t id = 0; // can identifier uint16_t timestamp = 0; // time when message arrived uint8_t idhit = 0; // filter that id came from struct { bool extended = 0; // identifier is extended (29-bit) bool remote = 0; // remote transmission request packet type bool overrun = 0; // message overrun bool reserved = 0; } flags; uint8_t len = 8; // length of data uint8_t buf[8] = { 0 }; // data int8_t mb = 0; // used to identify mailbox reception uint8_t bus = 1; // used to identify where the message came (CAN1, CAN2 or CAN3) bool seq = 0; // sequential frames } CAN_message_t; typedef enum CAN_PINS {DEF, ALT, ALT_2,} CAN_PINS; typedef enum RXQUEUE_TABLE { RX_SIZE_2 = (uint16_t)2, RX_SIZE_4 = (uint16_t)4, RX_SIZE_8 = (uint16_t)8, RX_SIZE_16 = (uint16_t)16, RX_SIZE_32 = (uint16_t)32, RX_SIZE_64 = (uint16_t)64, RX_SIZE_128 = (uint16_t)128, RX_SIZE_256 = (uint16_t)256, RX_SIZE_512 = (uint16_t)512, RX_SIZE_1024 = (uint16_t)1024 } RXQUEUE_TABLE; typedef enum TXQUEUE_TABLE { TX_SIZE_2 = (uint16_t)2, TX_SIZE_4 = (uint16_t)4, TX_SIZE_8 = (uint16_t)8, TX_SIZE_16 = (uint16_t)16, TX_SIZE_32 = (uint16_t)32, TX_SIZE_64 = (uint16_t)64, TX_SIZE_128 = (uint16_t)128, TX_SIZE_256 = (uint16_t)256, TX_SIZE_512 = (uint16_t)512, TX_SIZE_1024 = (uint16_t)1024 } TXQUEUE_TABLE; /* Teensy FlexCAN uses Mailboxes for different RX filters, but in STM32 there is Filter Banks. These work practically same way, so the Filter Banks are named as mailboxes in "setMBFilter" -functions, to retain compatibility with Teensy FlexCAN library. */ typedef enum CAN_BANK { MB0 = 0, MB1 = 1, MB2 = 2, MB3 = 3, MB4 = 4, MB5 = 5, MB6 = 6, MB7 = 7, MB8 = 8, MB9 = 9, MB10 = 10, MB11 = 11, MB12 = 12, MB13 = 13, MB14 = 14, MB15 = 15, MB16 = 16, MB17 = 17, MB18 = 18, MB19 = 19, MB20 = 20, MB21 = 21, MB22 = 22, MB23 = 23, MB24 = 24, MB25 = 25, MB26 = 26, MB27 = 27 } CAN_BANK; typedef enum CAN_FLTEN { ACCEPT_ALL = 0, REJECT_ALL = 1 } CAN_FLTEN; class STM32_CAN { public: // Default buffer sizes are set to 16. But this can be changed by using constructor in main code. STM32_CAN(CAN_TypeDef* canPort, CAN_PINS pins, RXQUEUE_TABLE rxSize = RX_SIZE_16, TXQUEUE_TABLE txSize = TX_SIZE_16); // Begin. By default the automatic retransmission is disabled in Speeduino, because it has been observed to cause sync issues. void begin(bool retransmission = false); void setBaudRate(uint32_t baud); bool write(CAN_message_t &CAN_tx_msg, bool sendMB = false); bool read(CAN_message_t &CAN_rx_msg); // Manually set STM32 filter bank parameters bool setFilter(uint8_t bank_num, uint32_t filter_id, uint32_t mask, uint32_t filter_mode = CAN_FILTERMODE_IDMASK, uint32_t filter_scale = CAN_FILTERSCALE_32BIT, uint32_t fifo = CAN_FILTER_FIFO0); // Teensy FlexCAN style "set filter" -functions bool setMBFilterProcessing(CAN_BANK bank_num, uint32_t filter_id, uint32_t mask); void setMBFilter(CAN_FLTEN input); /* enable/disable traffic for all MBs (for individual masking) */ void setMBFilter(CAN_BANK bank_num, CAN_FLTEN input); /* set specific MB to accept/deny traffic */ bool setMBFilter(CAN_BANK bank_num, uint32_t id1); /* input 1 ID to be filtered */ bool setMBFilter(CAN_BANK bank_num, uint32_t id1, uint32_t id2); /* input 2 ID's to be filtered */ void enableLoopBack(bool yes = 1); void enableSilentMode(bool yes = 1); void enableSilentLoopBack(bool yes = 1); void enableFIFO(bool status = 1); void enableMBInterrupts(); void disableMBInterrupts(); // These are public because these are also used from interupts. typedef struct RingbufferTypeDef { volatile uint16_t head; volatile uint16_t tail; uint16_t size; volatile CAN_message_t *buffer; } RingbufferTypeDef; RingbufferTypeDef rxRing; RingbufferTypeDef txRing; bool addToRingBuffer(RingbufferTypeDef &ring, const CAN_message_t &msg); bool removeFromRingBuffer(RingbufferTypeDef &ring, CAN_message_t &msg); protected: uint16_t sizeRxBuffer; uint16_t sizeTxBuffer; private: void initializeFilters(); bool isInitialized() { return rx_buffer != 0; } void initRingBuffer(RingbufferTypeDef &ring, volatile CAN_message_t *buffer, uint32_t size); void initializeBuffers(void); bool isRingBufferEmpty(RingbufferTypeDef &ring); uint32_t ringBufferCount(RingbufferTypeDef &ring); void calculateBaudrate(CAN_HandleTypeDef *CanHandle, int Baudrate); uint32_t getAPB1Clock(void); volatile CAN_message_t *rx_buffer; volatile CAN_message_t *tx_buffer; bool _canIsActive = false; CAN_PINS _pins; CAN_HandleTypeDef *n_pCanHandle; CAN_TypeDef* _canPort; }; static STM32_CAN* _CAN1 = nullptr; static CAN_HandleTypeDef hcan1; #ifdef CAN2 static STM32_CAN* _CAN2 = nullptr; static CAN_HandleTypeDef hcan2; #endif #ifdef CAN3 static STM32_CAN* _CAN3 = nullptr; static CAN_HandleTypeDef hcan3; #endif #endif #endif
6,308
C++
.h
161
35.857143
199
0.705805
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,154
LambdaCtrl.h
oelprinz-org_BlitzboxBL49sp/software/Onboard_WB_Lambda_V0.1.2_and_newer/LambdaCtrl.h
/* LambdaCtrl.h * * This is the main header for the project. * Here are all defines, objects and function prototypes * * Mario Schöbinger * 2018/11 * **/ #pragma once #include <Arduino.h> #include <SPI.h> #include <stdint.h> #include <FastPID.h> #include <Wire.h> #include <avr/eeprom.h> /* Define IO */ #define CJ125_NSS_PIN 10 /* Pin used for chip select in SPI communication. */ #define LED_STATUS_POWER 7 /* Pin used for power the status LED, indicating we have power. */ #define LED_STATUS_HEATER 5 /* Pin used for the heater status LED, indicating heater activity. */ #define HEATER_OUTPUT_PIN 6 /* Pin used for the PWM output to the heater circuit. */ #define USUP_ANALOG_INPUT_PIN A0 /* Analog input for power supply.*/ #define UVREF_ANALOG_INPUT_PIN A1 /* Analog input for reference voltage supply.*/ #define UR_ANALOG_INPUT_PIN A6 /* Analog input for temperature.*/ #define UA_ANALOG_INPUT_PIN A7 /* Analog input for lambda.*/ #define LAMBDA_PWM_OUTPUT_PIN 3 /* spare analog output (narrow band simulation or AFR Gauge 0-1V/0-5V) */ #define EN_INPUT_PIN 16 /* Enable pin, low when engine running */ //#define SP1_INPUT_PIN 2 /* Spare input 1 */ //#define SP2_INPUT_PIN 4 /* Spare input 2 */ /* Define parameters */ #define START_CONF_CNT 10 // Startup confident count, Min < UBatterie < Max, CJ Status ok #define CJ_OK_CONF_CNT 10 // Cj read with status ready confident count #define CJ_CALIBRATION_SAMPLES 10 // Read values this time and build average (10) #define CJ_CALIBRATION_PERIOD 150 // Read a value every xx milliseconds (150) #define CJ_PUMP_FACTOR 1000 // 1000 according to datasheet #define CJ_PUMP_RES_SHUNT 61.9 // 61,9 Ohm according to datasheet #define CJ_ERR_CNT 2 // xx Reads with error triggers a error for cj #define LAMBDA_PERIOD 17 // Every xx milliseconds calculate lambda #define UA_MIN_VALUE 150 // Min allowed calibration value #define UA_MAX_VALUE 400 // Max allowed calibration value #define UR_MIN_VALUE 150 // Min allowed calibration value #define UR_MAX_VALUE 300 // Max allowed calibration value #define USUP_MIN_ERR 10500 // Min allowed supply voltage value #define USUP_MAX_ERR 17000 // Max allowed supply voltage value #define USUP_MIN_OK 11000 // Min allowed supply voltage value #define USUP_MAX_OK 16500 // Max allowed supply voltage value #define USUP_ERR_CNT 2 // Allowed error count, switch to preset if supply out of range for this count #define PROBE_CONDENSATE_PERIOD 6000 // xx milliseconds #define PROBE_CONDENSATE_VOLT 1500 // xx millivolt during condensate heat #define PROBE_CONDENSATE_LIMIT 34 // 34 is the value which is used for 11V supply voltage #define PROBE_PREHEAT_PERIOD 1000 // xx milliseconds between each step (1000ms) #define PROBE_PREHEAT_STEP 400 // xx millivolt per step (400mV) #define PROBE_PREHEAT_MAX 13000 // xx millivolt for end preheat, after this we go to pid #define PROBE_PREHEAT_TIMOUT 15000 // xx milliseconds preheat timeout (15000ms) #define PROBE_PID_PERIOD 10 // xx milliseconds #define DEBUG 1 // Define debug mode 0 = off, 1 = Minimum, 2= all /* Define CJ125 registers */ #define CJ125_IDENT_REG_REQUEST 0x4800 /* Identify request, gives revision of the chip. */ #define CJ125_DIAG_REG_REQUEST 0x7800 /* Dignostic request, gives the current status. */ #define CJ125_INIT_REG1_REQUEST 0x6C00 /* Requests the first init register. */ #define CJ125_INIT_REG2_REQUEST 0x7E00 /* Requests the second init register. */ #define CJ125_INIT_REG1_MODE_CALIBRATE 0x569D /* Sets the first init register in calibration mode. */ #define CJ125_INIT_REG1_MODE_NORMAL_V8 0x5688 /* Sets the first init register in operation mode. V=8 amplification. */ #define CJ125_INIT_REG1_MODE_NORMAL_V17 0x5689 /* Sets the first init register in operation mode. V=17 amplification. */ #define CJ125_DIAG_REG_STATUS_OK 0x28FF /* The response of the diagnostic register when everything is ok. */ #define CJ125_DIAG_REG_STATUS_NOPOWER 0x2855 /* The response of the diagnostic register when power is low. */ #define CJ125_DIAG_REG_STATUS_NOSENSOR 0x287F /* The response of the diagnostic register when no sensor is connected. */ #define CJ125_INIT_REG1_STATUS_0 0x2888 /* The response of the init register when V=8 amplification is in use. */ #define CJ125_INIT_REG1_STATUS_1 0x2889 /* The response of the init register when V=17 amplification is in use. */ /* Define DAC MCP4725 address MCP4725A2T-E/CH */ #define DAC1_ADDR 0x60 /* Address for DAC 1 chip A0 tied to GND */ /* Define DAC MCP4725 registers */ #define MCP4725_CMD_WRITEDAC 0x40 /* Writes data to the DAC */ #define MCP4725_CMD_WRITEDACEEPROM 0x60 /* Writes data to the DAC and the EEPROM (persisting the assigned value after reset) */ /* Lambda Outputs are defined as follow: * * 0.5V = 0,68 Lambda = 10 AFR (Gasoline) * 4,5V = 1,36 Lambda = 20 AFR (Gasoline) * * Internal Lambda is used in a range from 68..136 * **/ #define LambdaToVoltage(a) ((a * 5882UL / 100UL) - 3500UL) #define VoltageTo8BitDac(a) (a * 255UL / 5000UL) #define VoltageTo12BitDac(a) (a * 4095UL / 5000UL) /* Calculate millivolt from adc */ #define AdcToVoltage(a) (a * 5000UL / 1023UL) typedef enum{ INVALID = 0, PRESET, START, CALIBRATION, IDLE, CONDENSATE, PREHEAT, PID, RUNNING, ERROR } state; typedef enum { cjINVALID, cjCALIBRATION, cjNORMALV8, cjNORMALV17, cjERROR, } cjmode; typedef struct { uint8_t StartConfCnt; uint8_t CjConfCnt; uint8_t CjCalSamples; uint8_t CjCalPeriod; uint8_t CjErrCnt; uint8_t LambdaPeriod; uint8_t SupplErrCnt; uint16_t tCondensate; uint16_t tPreheat; }tCfg; typedef struct { uint8_t Mode; uint16_t Flags; uint32_t Tick; uint32_t LastHeatTick; uint32_t LastCjTick; uint32_t StartHeatTick; uint32_t LastSerialTick; uint32_t LastErrorTick; int16_t VoltageOffset; int16_t SupplyVoltage; uint8_t SupplyErrCnt; int16_t RefVoltage; uint16_t CjState; uint8_t CjMode; uint8_t CjErrCnt; uint16_t UAOpt; uint16_t UROpt; uint8_t HeatState; int16_t Lambda; } tAbl; typedef struct { int16_t UA; int16_t UR; int16_t USup; int16_t URef; uint8_t EN; uint8_t S1; uint8_t S2; } tInputs; typedef struct { uint8_t Heater; uint8_t Wbl; uint16_t Dac1; uint16_t Dac2; uint8_t Led1; uint8_t Led2; } tOutputs; typedef struct { int16_t IP; int16_t UR; int16_t UB; } tCj125; const static char ModeName[][15] = { { "INVALID" }, { "PRESET" }, { "START" }, { "CALIBRATION" }, { "IDLE" }, { "CONDENSATION" }, { "PREHEAT" }, { "PID" }, { "RUNNING" }, { "ERROR" }, }; extern FastPID HeaterPid; extern void Preset(void); extern void Start(void); extern void Calibrate(void); extern void Idle(void); extern void Condensate(void); extern void Preheat(void); extern void Running(void); extern void Error(void); extern uint8_t CheckUBatt(void); extern void Inputs(tInputs* In); extern void Outputs(tOutputs* Out); extern uint16_t ComCj(uint16_t data); extern void ComDac(uint8_t addr, uint16_t data); extern int16_t CalcLambda(void); extern int16_t Interpolate(int16_t Ip); extern void ParseSerial(uint8_t ch);
8,048
C++
.h
196
38.117347
134
0.659766
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,155
test_PW.h
oelprinz-org_BlitzboxBL49sp/software/202310/speeduino-202310/test/test_fuel/test_PW.h
void testPW(); void test_PW_No_Multiply(); void test_PW_MAP_Multiply(void); void test_PW_AFR_Multiply(void); void test_PW_MAP_Multiply_Compatibility(void); void test_PW_ALL_Multiply(void); void test_PW_Large_Correction(); void test_PW_Very_Large_Correction(); void test_PW_4Cyl_PW0(void);
288
C++
.h
9
31.111111
46
0.778571
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,156
board_stm32_generic.h
oelprinz-org_BlitzboxBL49sp/software/202310/speeduino-202310/speeduino/board_stm32_generic.h
#ifndef STM32_H #define STM32_H #if defined(CORE_STM32_GENERIC) /* *********************************************************************************************************** * General */ #define PORT_TYPE uint32_t #define PINMASK_TYPE uint32_t #define COMPARE_TYPE uint16_t #define COUNTER_TYPE uint16_t #define SERIAL_BUFFER_SIZE 517 //Size of the serial buffer used by new comms protocol. For SD transfers this must be at least 512 + 1 (flag) + 4 (sector) #define FPU_MAX_SIZE 32 //Size of the FPU buffer. 0 means no FPU. #define TIMER_RESOLUTION 2 #define micros_safe() micros() //timer5 method is not used on anything but AVR, the micros_safe() macro is simply an alias for the normal micros() #if defined(SRAM_AS_EEPROM) #define EEPROM_LIB_H "src/BackupSram/BackupSramAsEEPROM.h" #elif defined(FRAM_AS_EEPROM) //https://github.com/VitorBoss/FRAM #define EEPROM_LIB_H <Fram.h> typedef uint16_t eeprom_address_t; #else #define EEPROM_LIB_H "src/SPIAsEEPROM/SPIAsEEPROM.h" typedef uint16_t eeprom_address_t; #endif #ifndef USE_SERIAL3 #define USE_SERIAL3 #endif void initBoard(); uint16_t freeRam(); void doSystemReset(); void jumpToBootloader(); #define pinIsReserved(pin) ( ((pin) == PA11) || ((pin) == PA12) ) //Forbidden pins like USB #ifndef Serial #define Serial Serial1 #endif #if defined(FRAM_AS_EEPROM) #include <Fram.h> #if defined(STM32F407xx) extern FramClass EEPROM; /*(mosi, miso, sclk, ssel, clockspeed) 31/01/2020*/ #else extern FramClass EEPROM; //Blue/Black Pills #endif #endif #if !defined (A0) #define A0 PA0 #define A1 PA1 #define A2 PA2 #define A3 PA3 #define A4 PA4 #define A5 PA5 #define A6 PA6 #define A7 PA7 #define A8 PB0 #define A9 PB1 #endif //STM32F1 have only 10 12bit adc #if !defined (A10) #define A10 PA0 #define A11 PA1 #define A12 PA2 #define A13 PA3 #define A14 PA4 #define A15 PA5 #endif #ifndef PB11 //Hack for F4 BlackPills #define PB11 PB10 #endif #define PWM_FAN_AVAILABLE /* *********************************************************************************************************** * Schedules * Timers Table for STM32F1 * TIMER1 TIMER2 TIMER3 TIMER4 * 1 - FAN 1 - INJ1 1 - IGN1 1 - oneMSInterval * 2 - BOOST 2 - INJ2 2 - IGN2 2 - * 3 - VVT 3 - INJ3 3 - IGN3 3 - * 4 - IDLE 4 - INJ4 4 - IGN4 4 - * * Timers Table for STM32F4 * TIMER1 TIMER2 TIMER3 TIMER4 TIMER5 TIMER11 * 1 - FAN 1 - INJ1 1 - IGN1 1 - IGN5 1 - INJ5 1 - oneMSInterval * 2 - BOOST 2 - INJ2 2 - IGN2 2 - IGN6 2 - INJ6 2 - * 3 - VVT 3 - INJ3 3 - IGN3 3 - IGN7 3 - INJ7 3 - * 4 - IDLE 4 - INJ4 4 - IGN4 4 - IGN8 4 - INJ8 4 - * */ #define MAX_TIMER_PERIOD 65535*2 //The longest period of time (in uS) that the timer can permit (IN this case it is 65535 * 2, as each timer tick is 2uS) #define uS_TO_TIMER_COMPARE(uS) (uS >> 1) //Converts a given number of uS into the required number of timer ticks until that time has passed. #define FUEL1_COUNTER (TIM2)->CNT #define FUEL2_COUNTER (TIM2)->CNT #define FUEL3_COUNTER (TIM2)->CNT #define FUEL4_COUNTER (TIM2)->CNT #define FUEL1_COMPARE (TIM2)->CCR1 #define FUEL2_COMPARE (TIM2)->CCR2 #define FUEL3_COMPARE (TIM2)->CCR3 #define FUEL4_COMPARE (TIM2)->CCR4 #define IGN1_COUNTER (TIM3)->CNT #define IGN2_COUNTER (TIM3)->CNT #define IGN3_COUNTER (TIM3)->CNT #define IGN4_COUNTER (TIM3)->CNT #define IGN1_COMPARE (TIM3)->CCR1 #define IGN2_COMPARE (TIM3)->CCR2 #define IGN3_COMPARE (TIM3)->CCR3 #define IGN4_COMPARE (TIM3)->CCR4 #ifndef SMALL_FLASH_MODE #define FUEL5_COUNTER (TIM5)->CNT #define FUEL6_COUNTER (TIM5)->CNT #define FUEL7_COUNTER (TIM5)->CNT #define FUEL8_COUNTER (TIM5)->CNT #define FUEL5_COMPARE (TIM5)->CCR1 #define FUEL6_COMPARE (TIM5)->CCR2 #define FUEL7_COMPARE (TIM5)->CCR3 #define FUEL8_COMPARE (TIM5)->CCR4 #define IGN5_COUNTER (TIM4)->CNT #define IGN6_COUNTER (TIM4)->CNT #define IGN7_COUNTER (TIM4)->CNT #define IGN8_COUNTER (TIM4)->CNT #define IGN5_COMPARE (TIM4)->CCR1 #define IGN6_COMPARE (TIM4)->CCR2 #define IGN7_COMPARE (TIM4)->CCR3 #define IGN8_COMPARE (TIM4)->CCR4 #endif //github.com/rogerclarkmelbourne/Arduino_STM32/blob/754bc2969921f1ef262bd69e7faca80b19db7524/STM32F1/system/libmaple/include/libmaple/timer.h#L444 #define FUEL1_TIMER_ENABLE() (TIM3)->SR = ~TIM_FLAG_CC1; (TIM3)->DIER |= TIM_DIER_CC1IE #define FUEL2_TIMER_ENABLE() (TIM3)->SR = ~TIM_FLAG_CC2; (TIM3)->DIER |= TIM_DIER_CC2IE #define FUEL3_TIMER_ENABLE() (TIM3)->SR = ~TIM_FLAG_CC3; (TIM3)->DIER |= TIM_DIER_CC3IE #define FUEL4_TIMER_ENABLE() (TIM3)->SR = ~TIM_FLAG_CC4; (TIM3)->DIER |= TIM_DIER_CC4IE #define FUEL1_TIMER_DISABLE() (TIM3)->DIER &= ~TIM_DIER_CC1IE #define FUEL2_TIMER_DISABLE() (TIM3)->DIER &= ~TIM_DIER_CC2IE #define FUEL3_TIMER_DISABLE() (TIM3)->DIER &= ~TIM_DIER_CC3IE #define FUEL4_TIMER_DISABLE() (TIM3)->DIER &= ~TIM_DIER_CC4IE #define IGN1_TIMER_ENABLE() (TIM2)->SR = ~TIM_FLAG_CC1; (TIM2)->DIER |= TIM_DIER_CC1IE #define IGN2_TIMER_ENABLE() (TIM2)->SR = ~TIM_FLAG_CC2; (TIM2)->DIER |= TIM_DIER_CC2IE #define IGN3_TIMER_ENABLE() (TIM2)->SR = ~TIM_FLAG_CC3; (TIM2)->DIER |= TIM_DIER_CC3IE #define IGN4_TIMER_ENABLE() (TIM2)->SR = ~TIM_FLAG_CC4; (TIM2)->DIER |= TIM_DIER_CC4IE #define IGN1_TIMER_DISABLE() (TIM2)->DIER &= ~TIM_DIER_CC1IE #define IGN2_TIMER_DISABLE() (TIM2)->DIER &= ~TIM_DIER_CC2IE #define IGN3_TIMER_DISABLE() (TIM2)->DIER &= ~TIM_DIER_CC3IE #define IGN4_TIMER_DISABLE() (TIM2)->DIER &= ~TIM_DIER_CC4IE #ifndef SMALL_FLASH_MODE #define FUEL5_TIMER_ENABLE() (TIM5)->SR = ~TIM_FLAG_CC1; (TIM5)->DIER |= TIM_DIER_CC1IE #define FUEL6_TIMER_ENABLE() (TIM5)->SR = ~TIM_FLAG_CC2; (TIM5)->DIER |= TIM_DIER_CC2IE #define FUEL7_TIMER_ENABLE() (TIM5)->SR = ~TIM_FLAG_CC3; (TIM5)->DIER |= TIM_DIER_CC3IE #define FUEL8_TIMER_ENABLE() (TIM5)->SR = ~TIM_FLAG_CC4; (TIM5)->DIER |= TIM_DIER_CC4IE #define FUEL5_TIMER_DISABLE() (TIM5)->DIER &= ~TIM_DIER_CC1IE #define FUEL6_TIMER_DISABLE() (TIM5)->DIER &= ~TIM_DIER_CC2IE #define FUEL7_TIMER_DISABLE() (TIM5)->DIER &= ~TIM_DIER_CC3IE #define FUEL8_TIMER_DISABLE() (TIM5)->DIER &= ~TIM_DIER_CC4IE #define IGN5_TIMER_ENABLE() (TIM4)->SR = ~TIM_FLAG_CC1; (TIM4)->DIER |= TIM_DIER_CC1IE #define IGN6_TIMER_ENABLE() (TIM4)->SR = ~TIM_FLAG_CC2; (TIM4)->DIER |= TIM_DIER_CC2IE #define IGN7_TIMER_ENABLE() (TIM4)->SR = ~TIM_FLAG_CC3; (TIM4)->DIER |= TIM_DIER_CC3IE #define IGN8_TIMER_ENABLE() (TIM4)->SR = ~TIM_FLAG_CC4; (TIM4)->DIER |= TIM_DIER_CC4IE #define IGN5_TIMER_DISABLE() (TIM4)->DIER &= ~TIM_DIER_CC1IE #define IGN6_TIMER_DISABLE() (TIM4)->DIER &= ~TIM_DIER_CC2IE #define IGN7_TIMER_DISABLE() (TIM4)->DIER &= ~TIM_DIER_CC3IE #define IGN8_TIMER_DISABLE() (TIM4)->DIER &= ~TIM_DIER_CC4IE #endif /* *********************************************************************************************************** * Auxiliaries */ #define ENABLE_BOOST_TIMER() (TIM1)->SR = ~TIM_FLAG_CC2; (TIM1)->DIER |= TIM_DIER_CC2IE #define DISABLE_BOOST_TIMER() (TIM1)->DIER &= ~TIM_DIER_CC2IE #define ENABLE_VVT_TIMER() (TIM1)->SR = ~TIM_FLAG_CC3; (TIM1)->DIER |= TIM_DIER_CC3IE #define DISABLE_VVT_TIMER() (TIM1)->DIER &= ~TIM_DIER_CC3IE #define ENABLE_FAN_TIMER() (TIM1)->SR = ~TIM_FLAG_CC1; (TIM1)->DIER |= TIM_DIER_CC1IE #define DISABLE_FAN_TIMER() (TIM1)->DIER &= ~TIM_DIER_CC1IE #define BOOST_TIMER_COMPARE (TIM1)->CCR2 #define BOOST_TIMER_COUNTER (TIM1)->CNT #define VVT_TIMER_COMPARE (TIM1)->CCR3 #define VVT_TIMER_COUNTER (TIM1)->CNT #define FAN_TIMER_COMPARE (TIM1)->CCR1 #define FAN_TIMER_COUNTER (TIM1)->CNT /* *********************************************************************************************************** * Idle */ #define IDLE_COUNTER (TIM1)->CNT #define IDLE_COMPARE (TIM1)->CCR4 #define IDLE_TIMER_ENABLE() (TIM1)->SR = ~TIM_FLAG_CC4; (TIM1)->DIER |= TIM_DIER_CC4IE #define IDLE_TIMER_DISABLE() (TIM1)->DIER &= ~TIM_DIER_CC4IE /* *********************************************************************************************************** * Timers */ /* *********************************************************************************************************** * CAN / Second serial */ #if defined(STM32GENERIC) // STM32GENERIC core SerialUART &secondarySerial = Serial2; #else //libmaple core aka STM32DUINO HardwareSerial &secondarySerial = Serial2; #endif #endif //CORE_STM32 #endif //STM32_H
8,736
C++
.h
196
41.076531
155
0.619299
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,157
board_same51.h
oelprinz-org_BlitzboxBL49sp/software/202310/speeduino-202310/speeduino/board_same51.h
#ifndef SAME51_H #define SAME51_H #if defined(CORE_SAME51) #include "sam.h" /* *********************************************************************************************************** * General */ #define PORT_TYPE uint32_t //Size of the port variables (Eg inj1_pin_port). Most systems use a byte, but SAMD21 is a 32-bit unsigned int #define BOARD_MAX_DIGITAL_PINS 54 //digital pins +1 #define BOARD_MAX_IO_PINS 58 //digital pins + analog channels + 1 //#define PORT_TYPE uint8_t //Size of the port variables (Eg inj1_pin_port). #define PINMASK_TYPE uint8_t #define COMPARE_TYPE uint16_t #define COUNTER_TYPE uint16_t #define SERIAL_BUFFER_SIZE 257 //Size of the serial buffer used by new comms protocol. Additional 1 byte is for flag #define FPU_MAX_SIZE 32 //Size of the FPU buffer. 0 means no FPU. #ifdef USE_SPI_EEPROM #define EEPROM_LIB_H "src/SPIAsEEPROM/SPIAsEEPROM.h" typedef uint16_t eeprom_address_t; #include EEPROM_LIB_H //SPIClass SPI_for_flash(1, 2, 3); //SPI1_MOSI, SPI1_MISO, SPI1_SCK SPIClass SPI_for_flash = SPI; //SPI1_MOSI, SPI1_MISO, SPI1_SCK //windbond W25Q16 SPI flash EEPROM emulation EEPROM_Emulation_Config EmulatedEEPROMMconfig{255UL, 4096UL, 31, 0x00100000UL}; //Flash_SPI_Config SPIconfig{USE_SPI_EEPROM, SPI_for_flash}; SPI_EEPROM_Class EEPROM(EmulatedEEPROMMconfig, SPIconfig); #else //#define EEPROM_LIB_H <EEPROM.h> #define EEPROM_LIB_H "src/FlashStorage/FlashAsEEPROM.h" typedef uint16_t eeprom_address_t; #endif #define RTC_LIB_H "TimeLib.h" void initBoard(); uint16_t freeRam(); void doSystemReset(); void jumpToBootloader(); #if defined(TIMER5_MICROS) /*#define micros() (((timer5_overflow_count << 16) + TCNT5) * 4) */ //Fast version of micros() that uses the 4uS tick of timer5. See timers.ino for the overflow ISR of timer5 #define millis() (ms_counter) //Replaces the standard millis() function with this macro. It is both faster and more accurate. See timers.ino for its counter increment. static inline unsigned long micros_safe(); //A version of micros() that is interrupt safe #else #define micros_safe() micros() //If the timer5 method is not used, the micros_safe() macro is simply an alias for the normal micros() #endif #define pinIsReserved(pin) ( ((pin) == 0) ) //Forbidden pins like USB on other boards //Additional analog pins (These won't work without other changes) #define PIN_A6 (8ul) #define PIN_A7 (9ul) #define PIN_A8 (10ul) #define PIN_A9 (11ul) #define PIN_A13 (9ul) #define PIN_A14 (9ul) #define PIN_A15 (9ul) static const uint8_t A7 = PIN_A7; static const uint8_t A8 = PIN_A8; static const uint8_t A9 = PIN_A9; static const uint8_t A13 = PIN_A13; static const uint8_t A14 = PIN_A14; static const uint8_t A15 = PIN_A15; /* *********************************************************************************************************** * Schedules */ //See : https://electronics.stackexchange.com/questions/325159/the-value-of-the-tcc-counter-on-an-atsam-controller-always-reads-as-zero // SAME512 Timer channel list: https://user-images.githubusercontent.com/11770912/62131781-2e150b80-b31f-11e9-9970-9a6c2356a17c.png #define FUEL1_COUNTER TCC0->COUNT.reg #define FUEL2_COUNTER TCC0->COUNT.reg #define FUEL3_COUNTER TCC0->COUNT.reg #define FUEL4_COUNTER TCC0->COUNT.reg //The below are NOT YET RIGHT! #define FUEL5_COUNTER TCC1->COUNT.reg #define FUEL6_COUNTER TCC1->COUNT.reg #define FUEL7_COUNTER TCC1->COUNT.reg #define FUEL8_COUNTER TCC1->COUNT.reg #define IGN1_COUNTER TCC1->COUNT.reg #define IGN2_COUNTER TCC1->COUNT.reg #define IGN3_COUNTER TCC2->COUNT.reg #define IGN4_COUNTER TCC2->COUNT.reg //The below are NOT YET RIGHT! #define IGN5_COUNTER TCC1->COUNT.reg #define IGN6_COUNTER TCC1->COUNT.reg #define IGN7_COUNTER TCC2->COUNT.reg #define IGN8_COUNTER TCC2->COUNT.reg #define FUEL1_COMPARE TCC0->CC[0].bit.CC #define FUEL2_COMPARE TCC0->CC[1].bit.CC #define FUEL3_COMPARE TCC0->CC[2].bit.CC #define FUEL4_COMPARE TCC0->CC[3].bit.CC //The below are NOT YET RIGHT! #define FUEL5_COMPARE TCC1->CC[0].bit.CC #define FUEL6_COMPARE TCC1->CC[1].bit.CC #define FUEL7_COMPARE TCC1->CC[2].bit.CC #define FUEL8_COMPARE TCC1->CC[3].bit.CC #define IGN1_COMPARE TCC1->CC[0].bit.CC #define IGN2_COMPARE TCC1->CC[1].bit.CC #define IGN3_COMPARE TCC2->CC[0].bit.CC #define IGN4_COMPARE TCC2->CC[1].bit.CC //The below are NOT YET RIGHT! #define IGN5_COMPARE TCC1->CC[0].bit.CC #define IGN6_COMPARE TCC1->CC[1].bit.CC #define IGN7_COMPARE TCC2->CC[0].bit.CC #define IGN8_COMPARE TCC2->CC[1].bit.CC #define FUEL1_TIMER_ENABLE() TCC0->INTENSET.bit.MC0 = 0x1 #define FUEL2_TIMER_ENABLE() TCC0->INTENSET.bit.MC1 = 0x1 #define FUEL3_TIMER_ENABLE() TCC0->INTENSET.bit.MC2 = 0x1 #define FUEL4_TIMER_ENABLE() TCC0->INTENSET.bit.MC3 = 0x1 //The below are NOT YET RIGHT! #define FUEL5_TIMER_ENABLE() TCC0->INTENSET.bit.MC0 = 0x1 #define FUEL6_TIMER_ENABLE() TCC0->INTENSET.bit.MC1 = 0x1 #define FUEL7_TIMER_ENABLE() TCC0->INTENSET.bit.MC2 = 0x1 #define FUEL8_TIMER_ENABLE() TCC0->INTENSET.bit.MC3 = 0x1 #define FUEL1_TIMER_DISABLE() TCC0->INTENSET.bit.MC0 = 0x0 #define FUEL2_TIMER_DISABLE() TCC0->INTENSET.bit.MC0 = 0x0 #define FUEL3_TIMER_DISABLE() TCC0->INTENSET.bit.MC0 = 0x0 #define FUEL4_TIMER_DISABLE() TCC0->INTENSET.bit.MC0 = 0x0 //The below are NOT YET RIGHT! #define FUEL5_TIMER_DISABLE() TCC0->INTENSET.bit.MC0 = 0x0 #define FUEL6_TIMER_DISABLE() TCC0->INTENSET.bit.MC0 = 0x0 #define FUEL7_TIMER_DISABLE() TCC0->INTENSET.bit.MC0 = 0x0 #define FUEL8_TIMER_DISABLE() TCC0->INTENSET.bit.MC0 = 0x0 #define IGN1_TIMER_ENABLE() TCC1->INTENSET.bit.MC0 = 0x1 #define IGN2_TIMER_ENABLE() TCC1->INTENSET.bit.MC1 = 0x1 #define IGN3_TIMER_ENABLE() TCC2->INTENSET.bit.MC0 = 0x1 #define IGN4_TIMER_ENABLE() TCC2->INTENSET.bit.MC1 = 0x1 //The below are NOT YET RIGHT! #define IGN5_TIMER_ENABLE() TCC1->INTENSET.bit.MC0 = 0x1 #define IGN6_TIMER_ENABLE() TCC1->INTENSET.bit.MC1 = 0x1 #define IGN7_TIMER_ENABLE() TCC2->INTENSET.bit.MC0 = 0x1 #define IGN8_TIMER_ENABLE() TCC2->INTENSET.bit.MC1 = 0x1 #define IGN1_TIMER_DISABLE() TCC1->INTENSET.bit.MC0 = 0x0 #define IGN2_TIMER_DISABLE() TCC1->INTENSET.bit.MC1 = 0x0 #define IGN3_TIMER_DISABLE() TCC2->INTENSET.bit.MC0 = 0x0 #define IGN4_TIMER_DISABLE() TCC2->INTENSET.bit.MC1 = 0x0 //The below are NOT YET RIGHT! #define IGN5_TIMER_DISABLE() TCC1->INTENSET.bit.MC0 = 0x0 #define IGN6_TIMER_DISABLE() TCC1->INTENSET.bit.MC1 = 0x0 #define IGN7_TIMER_DISABLE() TCC2->INTENSET.bit.MC0 = 0x0 #define IGN8_TIMER_DISABLE() TCC2->INTENSET.bit.MC1 = 0x0 #define MAX_TIMER_PERIOD 139808 // 2.13333333uS * 65535 #define MAX_TIMER_PERIOD_SLOW 139808 #define uS_TO_TIMER_COMPARE(uS) ((uS * 15) >> 5) //Converts a given number of uS into the required number of timer ticks until that time has passed. //Hack compatibility with AVR timers that run at different speeds #define uS_TO_TIMER_COMPARE_SLOW(uS) ((uS * 15) >> 5) /* *********************************************************************************************************** * Auxiliaries */ //Uses the 2nd TC //The 2nd TC is referred to as TC4 #define ENABLE_BOOST_TIMER() TC4->COUNT16.INTENSET.bit.MC0 = 0x1 // Enable match interrupts on compare channel 0 #define DISABLE_BOOST_TIMER() TC4->COUNT16.INTENSET.bit.MC0 = 0x0 #define ENABLE_VVT_TIMER() TC4->COUNT16.INTENSET.bit.MC1 = 0x1 #define DISABLE_VVT_TIMER() TC4->COUNT16.INTENSET.bit.MC1 = 0x0 #define BOOST_TIMER_COMPARE TC4->COUNT16.CC[0].reg #define BOOST_TIMER_COUNTER TC4->COUNT16.COUNT.bit.COUNT #define VVT_TIMER_COMPARE TC4->COUNT16.CC[1].reg #define VVT_TIMER_COUNTER TC4->COUNT16.COUNT.bit.COUNT /* *********************************************************************************************************** * Idle */ //3rd TC is aliased as TC5 #define IDLE_COUNTER TC5->COUNT16.COUNT.bit.COUNT #define IDLE_COMPARE TC5->COUNT16.CC[0].reg #define IDLE_TIMER_ENABLE() TC5->COUNT16.INTENSET.bit.MC0 = 0x1 #define IDLE_TIMER_DISABLE() TC5->COUNT16.INTENSET.bit.MC0 = 0x0 /* *********************************************************************************************************** * CAN / Second serial */ Uart secondarySerial (&sercom3, 0, 1, SERCOM_RX_PAD_1, UART_TX_PAD_0); #endif //CORE_SAMD21 #endif //SAMD21_H
8,603
C++
.h
172
46.982558
178
0.670394
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,158
comms_legacy.h
oelprinz-org_BlitzboxBL49sp/software/202310/speeduino-202310/speeduino/comms_legacy.h
/** \file comms.h * @brief File for handling all serial requests * @author Josh Stewart * * This file contains all the functions associated with serial comms. * This includes sending of live data, sending/receiving current page data, sending CRC values of pages, receiving sensor calibration data etc * */ #ifndef COMMS_H #define COMMS_H /** \enum SerialStatus * @brief The current state of serial communication * */ enum SerialStatus { /** No serial comms is in progress */ SERIAL_INACTIVE, /** A partial write is in progress. */ SERIAL_TRANSMIT_INPROGRESS, /** A partial write is in progress (legacy send). */ SERIAL_TRANSMIT_INPROGRESS_LEGACY, /** We are part way through transmitting the tooth log */ SERIAL_TRANSMIT_TOOTH_INPROGRESS, /** We are part way through transmitting the tooth log (legacy send) */ SERIAL_TRANSMIT_TOOTH_INPROGRESS_LEGACY, /** We are part way through transmitting the composite log */ SERIAL_TRANSMIT_COMPOSITE_INPROGRESS, /** We are part way through transmitting the composite log (legacy send) */ SERIAL_TRANSMIT_COMPOSITE_INPROGRESS_LEGACY, /** Whether or not a serial request has only been partially received. * This occurs when a the length has been received in the serial buffer, * but not all of the payload or CRC has yet been received. * * Expectation is that ::serialReceive is called until the status reverts * to SERIAL_INACTIVE */ SERIAL_RECEIVE_INPROGRESS, /** We are part way through processing a legacy serial commang: call ::serialReceive */ SERIAL_COMMAND_INPROGRESS_LEGACY, }; /** @brief Current status of serial comms. */ extern SerialStatus serialStatusFlag; extern SerialStatus serialSecondaryStatusFlag; /** * @brief Is a serial write in progress? * * Expectation is that ::serialTransmit is called until this * returns false */ inline bool serialTransmitInProgress(void) { return serialStatusFlag==SERIAL_TRANSMIT_INPROGRESS || serialStatusFlag==SERIAL_TRANSMIT_INPROGRESS_LEGACY || serialStatusFlag==SERIAL_TRANSMIT_TOOTH_INPROGRESS || serialStatusFlag==SERIAL_TRANSMIT_TOOTH_INPROGRESS_LEGACY || serialStatusFlag==SERIAL_TRANSMIT_COMPOSITE_INPROGRESS || serialStatusFlag==SERIAL_TRANSMIT_COMPOSITE_INPROGRESS_LEGACY; } /** * @brief Is a non-blocking serial receive operation in progress? * * Expectation is the ::serialReceive is called until this * returns false. */ inline bool serialRecieveInProgress(void) { return serialStatusFlag==SERIAL_RECEIVE_INPROGRESS || serialStatusFlag==SERIAL_COMMAND_INPROGRESS_LEGACY; } extern bool firstCommsRequest; /**< The number of times the A command has been issued. This is used to track whether a reset has recently been performed on the controller */ extern byte logItemsTransmitted; extern byte inProgressLength; void legacySerialCommand(void);//This is the heart of the Command Line Interpreter. All that needed to be done was to make it human readable. void legacySerialHandler(byte cmd, Stream &targetPort, SerialStatus &targetStatusFlag); void sendValues(uint16_t offset, uint16_t packetLength, byte cmd, Stream &targetPort, SerialStatus &targetStatusFlag); void sendValuesLegacy(void); void sendPage(void); void sendPageASCII(void); void receiveCalibration(byte tableID); void testComm(void); void sendToothLog_legacy(byte startOffset); void sendCompositeLog_legacy(byte startOffset); #endif // COMMS_H
3,429
C++
.h
80
40.3625
173
0.778576
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,159
maths.h
oelprinz-org_BlitzboxBL49sp/software/202310/speeduino-202310/speeduino/maths.h
#ifndef MATH_H #define MATH_H unsigned long percentage(uint8_t x, unsigned long y); unsigned long halfPercentage(uint8_t x, unsigned long y); inline long powint(int factor, unsigned int exponent); uint8_t random1to100(); #ifdef USE_LIBDIVIDE #include "src/libdivide/libdivide.h" extern const struct libdivide::libdivide_u16_t libdiv_u16_100; extern const struct libdivide::libdivide_s16_t libdiv_s16_100; extern const struct libdivide::libdivide_u32_t libdiv_u32_100; extern const struct libdivide::libdivide_s32_t libdiv_s32_100; extern const struct libdivide::libdivide_u32_t libdiv_u32_360; #endif inline uint8_t div100(uint8_t n) { return n / (uint8_t)100U; } inline int8_t div100(int8_t n) { return n / (int8_t)100U; } inline uint16_t div100(uint16_t n) { #ifdef USE_LIBDIVIDE return libdivide::libdivide_u16_do(n, &libdiv_u16_100); #else return n / (uint16_t)100U; #endif } inline int16_t div100(int16_t n) { #ifdef USE_LIBDIVIDE return libdivide::libdivide_s16_do(n, &libdiv_s16_100); #else return n / (int16_t)100; #endif } inline uint32_t div100(uint32_t n) { #ifdef USE_LIBDIVIDE return libdivide::libdivide_u32_do(n, &libdiv_u32_100); #else return n / (uint32_t)100U; #endif } #if defined(__arm__) inline int div100(int n) { #ifdef USE_LIBDIVIDE return libdivide::libdivide_s32_do(n, &libdiv_s32_100); #else return n / (int)100; #endif } #else inline int32_t div100(int32_t n) { #ifdef USE_LIBDIVIDE return libdivide::libdivide_s32_do(n, &libdiv_s32_100); #else return n / (int32_t)100; #endif } #endif inline uint32_t div360(uint32_t n) { #ifdef USE_LIBDIVIDE return libdivide::libdivide_u32_do(n, &libdiv_u32_360); #else return n / 360U; #endif } #define DIV_ROUND_CLOSEST(n, d) ((((n) < 0) ^ ((d) < 0)) ? (((n) - (d)/2)/(d)) : (((n) + (d)/2)/(d))) #define IS_INTEGER(d) (d == (int32_t)d) //This is a dedicated function that specifically handles the case of mapping 0-1023 values into a 0 to X range //This is a common case because it means converting from a standard 10-bit analog input to a byte or 10-bit analog into 0-511 (Eg the temperature readings) #define fastMap1023toX(x, out_max) ( ((unsigned long)x * out_max) >> 10) //This is a new version that allows for out_min #define fastMap10Bit(x, out_min, out_max) ( ( ((unsigned long)x * (out_max-out_min)) >> 10 ) + out_min) #endif
2,383
C++
.h
73
30.520548
155
0.717014
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,160
globals.h
oelprinz-org_BlitzboxBL49sp/software/202310/speeduino-202310/speeduino/globals.h
/** @file * Global defines, macros, struct definitions (@ref statuses, @ref config2, @ref config4, config*), extern-definitions (for globally accessible vars). * * ### Note on configuration struct layouts * * Once the struct members have been assigned to certain "role" (in certain SW version), they should not be "moved around" * as the structs are stored onto EEPROM as-is and the offset and size of member needs to remain constant. Also removing existing struct members * would disturb layouts. Because of this a certain amount unused old members will be left into the structs. For the storage related reasons also the * bit fields are defined in byte-size (or multiple of ...) chunks. * * ### Config Structs and 2D, 3D Tables * * The config* structures contain information coming from tuning SW (e.g. TS) for 2D and 3D tables, where looked up value is not a result of direct * array lookup, but from interpolation algorithm. Because of standard, reusable interpolation routines associated with structs table2D and table3D, * the values from config are copied from config* structs to table2D (table3D destined configurations are not stored in config* structures). * * ### Board choice * There's a C-preprocessor based "#if defined" logic present in this header file based on the Arduino IDE compiler set CPU * (+board?) type, e.g. `__AVR_ATmega2560__`. This respectively drives (withi it's "#if defined ..." block): * - The setting of various BOARD_* C-preprocessor variables (e.g. BOARD_MAX_ADC_PINS) * - Setting of BOARD_H (Board header) file (e.g. "board_avr2560.h"), which is later used to include the header file * - Seems Arduino ide implicitly compiles and links respective .ino file (by it's internal build/compilation rules) (?) * - Setting of CPU (?) CORE_* variables (e.g. CORE_AVR), that is used across codebase to distinguish CPU. */ #ifndef GLOBALS_H #define GLOBALS_H #include <Arduino.h> #include "table2d.h" #include "table3d.h" #include <assert.h> #include "src/FastCRC/FastCRC.h" #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega2561__) #define BOARD_MAX_DIGITAL_PINS 54 //digital pins +1 #define BOARD_MAX_IO_PINS 70 //digital pins + analog channels + 1 #define BOARD_MAX_ADC_PINS 15 //Number of analog pins #ifndef LED_BUILTIN #define LED_BUILTIN 13 #endif #define CORE_AVR #define BOARD_H "board_avr2560.h" #define INJ_CHANNELS 4 #define IGN_CHANNELS 5 #if defined(__AVR_ATmega2561__) //This is a workaround to avoid having to change all the references to higher ADC channels. We simply define the channels (Which don't exist on the 2561) as being the same as A0-A7 //These Analog inputs should never be used on any 2561 board definition (Because they don't exist on the MCU), so it will not cause any issues #define A8 A0 #define A9 A1 #define A10 A2 #define A11 A3 #define A12 A4 #define A13 A5 #define A14 A6 #define A15 A7 #endif //#define TIMER5_MICROS #elif defined(CORE_TEENSY) #if defined(__MK64FX512__) || defined(__MK66FX1M0__) #define CORE_TEENSY35 #define BOARD_H "board_teensy35.h" #define BOARD_MAX_ADC_PINS 22 //Number of analog pins #elif defined(__IMXRT1062__) #define CORE_TEENSY41 #define BOARD_H "board_teensy41.h" #define BOARD_MAX_ADC_PINS 17 //Number of analog pins #endif #define INJ_CHANNELS 8 #define IGN_CHANNELS 8 #elif defined(STM32_MCU_SERIES) || defined(ARDUINO_ARCH_STM32) || defined(STM32) #define CORE_STM32 #define BOARD_MAX_ADC_PINS NUM_ANALOG_INPUTS-1 //Number of analog pins from core. #if defined(STM32F407xx) //F407 can do 8x8 STM32F401/STM32F411 not #define INJ_CHANNELS 8 #define IGN_CHANNELS 8 #else #define INJ_CHANNELS 4 #define IGN_CHANNELS 5 #endif //Select one for EEPROM,the default is EEPROM emulation on internal flash. //#define SRAM_AS_EEPROM /*Use 4K battery backed SRAM, requires a 3V continuous source (like battery) connected to Vbat pin */ //#define USE_SPI_EEPROM PB0 /*Use M25Qxx SPI flash */ //#define FRAM_AS_EEPROM /*Use FRAM like FM25xxx, MB85RSxxx or any SPI compatible */ #ifndef word #define word(h, l) ((h << 8) | l) //word() function not defined for this platform in the main library #endif #if defined(ARDUINO_BLUEPILL_F103C8) || defined(ARDUINO_BLUEPILL_F103CB) \ || defined(ARDUINO_BLACKPILL_F401CC) || defined(ARDUINO_BLACKPILL_F411CE) //STM32 Pill boards #ifndef NUM_DIGITAL_PINS #define NUM_DIGITAL_PINS 35 #endif #ifndef LED_BUILTIN #define LED_BUILTIN PB1 //Maple Mini #endif #elif defined(STM32F407xx) #ifndef NUM_DIGITAL_PINS #define NUM_DIGITAL_PINS 75 #endif #endif #if defined(STM32_CORE_VERSION) #define BOARD_H "board_stm32_official.h" #else #define CORE_STM32_GENERIC #define BOARD_H "board_stm32_generic.h" #endif //Specific mode for Bluepill due to its small flash size. This disables a number of strings from being compiled into the flash #if defined(MCU_STM32F103C8) || defined(MCU_STM32F103CB) #define SMALL_FLASH_MODE #endif #define BOARD_MAX_DIGITAL_PINS NUM_DIGITAL_PINS #define BOARD_MAX_IO_PINS NUM_DIGITAL_PINS #if __GNUC__ < 7 //Already included on GCC 7 extern "C" char* sbrk(int incr); //Used to freeRam #endif #ifndef digitalPinToInterrupt inline uint32_t digitalPinToInterrupt(uint32_t Interrupt_pin) { return Interrupt_pin; } //This isn't included in the stm32duino libs (yet) #endif #elif defined(__SAMD21G18A__) #define BOARD_H "board_samd21.h" #define CORE_SAMD21 #define CORE_SAM #define INJ_CHANNELS 4 #define IGN_CHANNELS 4 #elif defined(__SAMC21J18A__) #define BOARD_H "board_samc21.h" #define CORE_SAMC21 #define CORE_SAM #elif defined(__SAME51J19A__) #define BOARD_H "board_same51.h" #define CORE_SAME51 #define CORE_SAM #define INJ_CHANNELS 8 #define IGN_CHANNELS 8 #else #error Incorrect board selected. Please select the correct board (Usually Mega 2560) and upload again #endif //This can only be included after the above section #include BOARD_H //Note that this is not a real file, it is defined in globals.h. //Handy bitsetting macros #define BIT_SET(a,b) ((a) |= (1U<<(b))) #define BIT_CLEAR(a,b) ((a) &= ~(1U<<(b))) #define BIT_CHECK(var,pos) !!((var) & (1U<<(pos))) #define BIT_TOGGLE(var,pos) ((var)^= 1UL << (pos)) #define BIT_WRITE(var, pos, bitvalue) ((bitvalue) ? BIT_SET((var), (pos)) : bitClear((var), (pos))) #define CRANK_ANGLE_MAX (max(CRANK_ANGLE_MAX_IGN, CRANK_ANGLE_MAX_INJ)) #define interruptSafe(c) (noInterrupts(); {c} interrupts();) //Wraps any code between nointerrupt and interrupt calls #define MS_IN_MINUTE 60000 #define US_IN_MINUTE 60000000 #define SERIAL_PORT_PRIMARY 0 #define SERIAL_PORT_SECONDARY 3 //Define the load algorithm #define LOAD_SOURCE_MAP 0 #define LOAD_SOURCE_TPS 1 #define LOAD_SOURCE_IMAPEMAP 2 //Define bit positions within engine variable #define BIT_ENGINE_RUN 0 // Engine running #define BIT_ENGINE_CRANK 1 // Engine cranking #define BIT_ENGINE_ASE 2 // after start enrichment (ASE) #define BIT_ENGINE_WARMUP 3 // Engine in warmup #define BIT_ENGINE_ACC 4 // in acceleration mode (TPS accel) #define BIT_ENGINE_DCC 5 // in deceleration mode #define BIT_ENGINE_MAPACC 6 // MAP acceleration mode #define BIT_ENGINE_MAPDCC 7 // MAP deceleration mode //Define masks for Status1 #define BIT_STATUS1_INJ1 0 //inj1 #define BIT_STATUS1_INJ2 1 //inj2 #define BIT_STATUS1_INJ3 2 //inj3 #define BIT_STATUS1_INJ4 3 //inj4 #define BIT_STATUS1_DFCO 4 //Deceleration fuel cutoff #define BIT_STATUS1_BOOSTCUT 5 //Fuel component of MAP based boost cut out #define BIT_STATUS1_TOOTHLOG1READY 6 //Used to flag if tooth log 1 is ready #define BIT_STATUS1_TOOTHLOG2READY 7 //Used to flag if tooth log 2 is ready (Log is not currently used) //Define masks for spark variable #define BIT_SPARK_HLAUNCH 0 //Hard Launch indicator #define BIT_SPARK_SLAUNCH 1 //Soft Launch indicator #define BIT_SPARK_HRDLIM 2 //Hard limiter indicator #define BIT_SPARK_SFTLIM 3 //Soft limiter indicator #define BIT_SPARK_BOOSTCUT 4 //Spark component of MAP based boost cut out #define BIT_SPARK_ERROR 5 // Error is detected #define BIT_SPARK_IDLE 6 // idle on #define BIT_SPARK_SYNC 7 // Whether engine has sync or not #define BIT_SPARK2_FLATSH 0 //Flat shift hard cut #define BIT_SPARK2_FLATSS 1 //Flat shift soft cut #define BIT_SPARK2_SPARK2_ACTIVE 2 #define BIT_SPARK2_UNUSED4 3 #define BIT_SPARK2_UNUSED5 4 #define BIT_SPARK2_UNUSED6 5 #define BIT_SPARK2_UNUSED7 6 #define BIT_SPARK2_UNUSED8 7 #define BIT_TIMER_1HZ 0 #define BIT_TIMER_4HZ 1 #define BIT_TIMER_10HZ 2 #define BIT_TIMER_15HZ 3 #define BIT_TIMER_30HZ 4 #define BIT_TIMER_1KHZ 7 #define BIT_STATUS3_RESET_PREVENT 0 //Indicates whether reset prevention is enabled #define BIT_STATUS3_NITROUS 1 #define BIT_STATUS3_FUEL2_ACTIVE 2 #define BIT_STATUS3_VSS_REFRESH 3 #define BIT_STATUS3_HALFSYNC 4 //shows if there is only sync from primary trigger, but not from secondary. #define BIT_STATUS3_NSQUIRTS1 5 #define BIT_STATUS3_NSQUIRTS2 6 #define BIT_STATUS3_NSQUIRTS3 7 #define BIT_STATUS4_WMI_EMPTY 0 //Indicates whether the WMI tank is empty #define BIT_STATUS4_VVT1_ERROR 1 //VVT1 cam angle within limits or not #define BIT_STATUS4_VVT2_ERROR 2 //VVT2 cam angle within limits or not #define BIT_STATUS4_FAN 3 //Fan Status #define BIT_STATUS4_BURNPENDING 4 #define BIT_STATUS4_STAGING_ACTIVE 5 #define BIT_STATUS4_COMMS_COMPAT 6 #define BIT_STATUS4_ALLOW_LEGACY_COMMS 7 #define BIT_AIRCON_REQUEST 0 //Indicates whether the A/C button is pressed #define BIT_AIRCON_COMPRESSOR 1 //Indicates whether the A/C compressor is running #define BIT_AIRCON_RPM_LOCKOUT 2 //Indicates the A/C is locked out due to the RPM being too high/low, or the post-high/post-low-RPM "stand-down" lockout period #define BIT_AIRCON_TPS_LOCKOUT 3 //Indicates the A/C is locked out due to high TPS, or the post-high-TPS "stand-down" lockout period #define BIT_AIRCON_TURNING_ON 4 //Indicates the A/C request is on (i.e. A/C button pressed), the lockouts are off, however the start delay has not yet elapsed. This gives the idle up time to kick in before the compressor. #define BIT_AIRCON_CLT_LOCKOUT 5 //Indicates the A/C is locked out either due to high coolant temp. #define BIT_AIRCON_FAN 6 //Indicates whether the A/C fan is running #define BIT_AIRCON_UNUSED8 7 #define VALID_MAP_MAX 1022 //The largest ADC value that is valid for the MAP sensor #define VALID_MAP_MIN 2 //The smallest ADC value that is valid for the MAP sensor #ifndef UNIT_TEST #define TOOTH_LOG_SIZE 127 #else #define TOOTH_LOG_SIZE 1 #endif #define O2_CALIBRATION_PAGE 2U #define IAT_CALIBRATION_PAGE 1U #define CLT_CALIBRATION_PAGE 0U // note the sequence of these defines which refernce the bits used in a byte has moved when the third trigger & engine cycle was incorporated #define COMPOSITE_LOG_PRI 0 #define COMPOSITE_LOG_SEC 1 #define COMPOSITE_LOG_THIRD 2 #define COMPOSITE_LOG_TRIG 3 #define COMPOSITE_LOG_SYNC 4 #define COMPOSITE_ENGINE_CYCLE 5 #define EGO_TYPE_OFF 0 #define EGO_TYPE_NARROW 1 #define EGO_TYPE_WIDE 2 #define INJ_TYPE_PORT 0 #define INJ_TYPE_TBODY 1 #define INJ_PAIRED 0 #define INJ_SEMISEQUENTIAL 1 #define INJ_BANKED 2 #define INJ_SEQUENTIAL 3 #define INJ_PAIR_13_24 0 #define INJ_PAIR_14_23 1 #define OUTPUT_CONTROL_DIRECT 0 #define OUTPUT_CONTROL_MC33810 10 #define IGN_MODE_WASTED 0 #define IGN_MODE_SINGLE 1 #define IGN_MODE_WASTEDCOP 2 #define IGN_MODE_SEQUENTIAL 3 #define IGN_MODE_ROTARY 4 #define SEC_TRIGGER_SINGLE 0 #define SEC_TRIGGER_4_1 1 #define SEC_TRIGGER_POLL 2 #define SEC_TRIGGER_5_3_2 3 #define ROTARY_IGN_FC 0 #define ROTARY_IGN_FD 1 #define ROTARY_IGN_RX8 2 #define BOOST_MODE_SIMPLE 0 #define BOOST_MODE_FULL 1 #define EN_BOOST_CONTROL_BARO 0 #define EN_BOOST_CONTROL_FIXED 1 #define WMI_MODE_SIMPLE 0 #define WMI_MODE_PROPORTIONAL 1 #define WMI_MODE_OPENLOOP 2 #define WMI_MODE_CLOSEDLOOP 3 #define HARD_CUT_FULL 0 #define HARD_CUT_ROLLING 1 #define EVEN_FIRE 0 #define ODD_FIRE 1 #define EGO_ALGORITHM_SIMPLE 0 #define EGO_ALGORITHM_PID 2 #define STAGING_MODE_TABLE 0 #define STAGING_MODE_AUTO 1 #define NITROUS_OFF 0 #define NITROUS_STAGE1 1 #define NITROUS_STAGE2 2 #define NITROUS_BOTH 3 #define PROTECT_CUT_OFF 0 #define PROTECT_CUT_IGN 1 #define PROTECT_CUT_FUEL 2 #define PROTECT_CUT_BOTH 3 #define PROTECT_IO_ERROR 7 #define AE_MODE_TPS 0 #define AE_MODE_MAP 1 #define AE_MODE_MULTIPLIER 0 #define AE_MODE_ADDER 1 #define KNOCK_MODE_OFF 0 #define KNOCK_MODE_DIGITAL 1 #define KNOCK_MODE_ANALOG 2 #define FUEL2_MODE_OFF 0 #define FUEL2_MODE_MULTIPLY 1 #define FUEL2_MODE_ADD 2 #define FUEL2_MODE_CONDITIONAL_SWITCH 3 #define FUEL2_MODE_INPUT_SWITCH 4 #define SPARK2_MODE_OFF 0 #define SPARK2_MODE_MULTIPLY 1 #define SPARK2_MODE_ADD 2 #define SPARK2_MODE_CONDITIONAL_SWITCH 3 #define SPARK2_MODE_INPUT_SWITCH 4 #define FUEL2_CONDITION_RPM 0 #define FUEL2_CONDITION_MAP 1 #define FUEL2_CONDITION_TPS 2 #define FUEL2_CONDITION_ETH 3 #define SPARK2_CONDITION_RPM 0 #define SPARK2_CONDITION_MAP 1 #define SPARK2_CONDITION_TPS 2 #define SPARK2_CONDITION_ETH 3 #define RESET_CONTROL_DISABLED 0 #define RESET_CONTROL_PREVENT_WHEN_RUNNING 1 #define RESET_CONTROL_PREVENT_ALWAYS 2 #define RESET_CONTROL_SERIAL_COMMAND 3 #define OPEN_LOOP_BOOST 0 #define CLOSED_LOOP_BOOST 1 #define SOFT_LIMIT_FIXED 0 #define SOFT_LIMIT_RELATIVE 1 #define VVT_MODE_ONOFF 0 #define VVT_MODE_OPEN_LOOP 1 #define VVT_MODE_CLOSED_LOOP 2 #define VVT_LOAD_MAP 0 #define VVT_LOAD_TPS 1 #define MULTIPLY_MAP_MODE_OFF 0 #define MULTIPLY_MAP_MODE_BARO 1 #define MULTIPLY_MAP_MODE_100 2 #define FOUR_STROKE 0 #define TWO_STROKE 1 #define GOING_LOW 0 #define GOING_HIGH 1 #define MAX_RPM 18000 /**< The maximum rpm that the ECU will attempt to run at. It is NOT related to the rev limiter, but is instead dictates how fast certain operations will be allowed to run. Lower number gives better performance */ #define BATTV_COR_MODE_WHOLE 0 #define BATTV_COR_MODE_OPENTIME 1 #define INJ1_CMD_BIT 0 #define INJ2_CMD_BIT 1 #define INJ3_CMD_BIT 2 #define INJ4_CMD_BIT 3 #define INJ5_CMD_BIT 4 #define INJ6_CMD_BIT 5 #define INJ7_CMD_BIT 6 #define INJ8_CMD_BIT 7 #define IGN1_CMD_BIT 0 #define IGN2_CMD_BIT 1 #define IGN3_CMD_BIT 2 #define IGN4_CMD_BIT 3 #define IGN5_CMD_BIT 4 #define IGN6_CMD_BIT 5 #define IGN7_CMD_BIT 6 #define IGN8_CMD_BIT 7 #define ENGINE_PROTECT_BIT_RPM 0 #define ENGINE_PROTECT_BIT_MAP 1 #define ENGINE_PROTECT_BIT_OIL 2 #define ENGINE_PROTECT_BIT_AFR 3 #define ENGINE_PROTECT_BIT_COOLANT 4 #define CALIBRATION_TABLE_SIZE 512 ///< Calibration table size for CLT, IAT, O2 #define CALIBRATION_TEMPERATURE_OFFSET 40 /**< All temperature measurements are stored offset by 40 degrees. This is so we can use an unsigned byte (0-255) to represent temperature ranges from -40 to 215 */ #define OFFSET_FUELTRIM 127 ///< The fuel trim tables are offset by 128 to allow for -128 to +128 values #define OFFSET_IGNITION 40 ///< Ignition values from the main spark table are offset 40 degrees downwards to allow for negative spark timing #define SERIAL_BUFFER_THRESHOLD 32 ///< When the serial buffer is filled to greater than this threshold value, the serial processing operations will be performed more urgently in order to avoid it overflowing. Serial buffer is 64 bytes long, so the threshold is set at half this as a reasonable figure #define LOGGER_CSV_SEPARATOR_SEMICOLON 0 #define LOGGER_CSV_SEPARATOR_COMMA 1 #define LOGGER_CSV_SEPARATOR_TAB 2 #define LOGGER_CSV_SEPARATOR_SPACE 3 #define LOGGER_DISABLED 0 #define LOGGER_CSV 1 #define LOGGER_BINARY 2 #define LOGGER_RATE_1HZ 0 #define LOGGER_RATE_4HZ 1 #define LOGGER_RATE_10HZ 2 #define LOGGER_RATE_30HZ 3 #define LOGGER_FILENAMING_OVERWRITE 0 #define LOGGER_FILENAMING_DATETIME 1 #define LOGGER_FILENAMING_SEQENTIAL 2 extern const char TSfirmwareVersion[] PROGMEM; extern const byte data_structure_version; //This identifies the data structure when reading / writing. Now in use: CURRENT_DATA_VERSION (migration on-the fly) ? extern struct table3d16RpmLoad fuelTable; //16x16 fuel map extern struct table3d16RpmLoad fuelTable2; //16x16 fuel map extern struct table3d16RpmLoad ignitionTable; //16x16 ignition map extern struct table3d16RpmLoad ignitionTable2; //16x16 ignition map extern struct table3d16RpmLoad afrTable; //16x16 afr target map extern struct table3d8RpmLoad stagingTable; //8x8 fuel staging table extern struct table3d8RpmLoad boostTable; //8x8 boost map extern struct table3d8RpmLoad boostTableLookupDuty; //8x8 boost map extern struct table3d8RpmLoad vvtTable; //8x8 vvt map extern struct table3d8RpmLoad vvt2Table; //8x8 vvt map extern struct table3d8RpmLoad wmiTable; //8x8 wmi map typedef table3d6RpmLoad trimTable3d; extern trimTable3d trim1Table; //6x6 Fuel trim 1 map extern trimTable3d trim2Table; //6x6 Fuel trim 2 map extern trimTable3d trim3Table; //6x6 Fuel trim 3 map extern trimTable3d trim4Table; //6x6 Fuel trim 4 map extern trimTable3d trim5Table; //6x6 Fuel trim 5 map extern trimTable3d trim6Table; //6x6 Fuel trim 6 map extern trimTable3d trim7Table; //6x6 Fuel trim 7 map extern trimTable3d trim8Table; //6x6 Fuel trim 8 map extern struct table3d4RpmLoad dwellTable; //4x4 Dwell map extern struct table2D taeTable; //4 bin TPS Acceleration Enrichment map (2D) extern struct table2D maeTable; extern struct table2D WUETable; //10 bin Warm Up Enrichment map (2D) extern struct table2D ASETable; //4 bin After Start Enrichment map (2D) extern struct table2D ASECountTable; //4 bin After Start duration map (2D) extern struct table2D PrimingPulseTable; //4 bin Priming pulsewidth map (2D) extern struct table2D crankingEnrichTable; //4 bin cranking Enrichment map (2D) extern struct table2D dwellVCorrectionTable; //6 bin dwell voltage correction (2D) extern struct table2D injectorVCorrectionTable; //6 bin injector voltage correction (2D) extern struct table2D injectorAngleTable; //4 bin injector timing curve (2D) extern struct table2D IATDensityCorrectionTable; //9 bin inlet air temperature density correction (2D) extern struct table2D baroFuelTable; //8 bin baro correction curve (2D) extern struct table2D IATRetardTable; //6 bin ignition adjustment based on inlet air temperature (2D) extern struct table2D idleTargetTable; //10 bin idle target table for idle timing (2D) extern struct table2D idleAdvanceTable; //6 bin idle advance adjustment table based on RPM difference (2D) extern struct table2D CLTAdvanceTable; //6 bin ignition adjustment based on coolant temperature (2D) extern struct table2D rotarySplitTable; //8 bin ignition split curve for rotary leading/trailing (2D) extern struct table2D flexFuelTable; //6 bin flex fuel correction table for fuel adjustments (2D) extern struct table2D flexAdvTable; //6 bin flex fuel correction table for timing advance (2D) extern struct table2D flexBoostTable; //6 bin flex fuel correction table for boost adjustments (2D) extern struct table2D fuelTempTable; //6 bin fuel temperature correction table for fuel adjustments (2D) extern struct table2D knockWindowStartTable; extern struct table2D knockWindowDurationTable; extern struct table2D oilPressureProtectTable; extern struct table2D wmiAdvTable; //6 bin wmi correction table for timing advance (2D) extern struct table2D coolantProtectTable; //6 bin coolant temperature protection table for engine protection (2D) extern struct table2D fanPWMTable; extern struct table2D rollingCutTable; //These are for the direct port manipulation of the injectors, coils and aux outputs extern volatile PORT_TYPE *inj1_pin_port; extern volatile PINMASK_TYPE inj1_pin_mask; extern volatile PORT_TYPE *inj2_pin_port; extern volatile PINMASK_TYPE inj2_pin_mask; extern volatile PORT_TYPE *inj3_pin_port; extern volatile PINMASK_TYPE inj3_pin_mask; extern volatile PORT_TYPE *inj4_pin_port; extern volatile PINMASK_TYPE inj4_pin_mask; extern volatile PORT_TYPE *inj5_pin_port; extern volatile PINMASK_TYPE inj5_pin_mask; extern volatile PORT_TYPE *inj6_pin_port; extern volatile PINMASK_TYPE inj6_pin_mask; extern volatile PORT_TYPE *inj7_pin_port; extern volatile PINMASK_TYPE inj7_pin_mask; extern volatile PORT_TYPE *inj8_pin_port; extern volatile PINMASK_TYPE inj8_pin_mask; extern volatile PORT_TYPE *ign1_pin_port; extern volatile PINMASK_TYPE ign1_pin_mask; extern volatile PORT_TYPE *ign2_pin_port; extern volatile PINMASK_TYPE ign2_pin_mask; extern volatile PORT_TYPE *ign3_pin_port; extern volatile PINMASK_TYPE ign3_pin_mask; extern volatile PORT_TYPE *ign4_pin_port; extern volatile PINMASK_TYPE ign4_pin_mask; extern volatile PORT_TYPE *ign5_pin_port; extern volatile PINMASK_TYPE ign5_pin_mask; extern volatile PORT_TYPE *ign6_pin_port; extern volatile PINMASK_TYPE ign6_pin_mask; extern volatile PORT_TYPE *ign7_pin_port; extern volatile PINMASK_TYPE ign7_pin_mask; extern volatile PORT_TYPE *ign8_pin_port; extern volatile PINMASK_TYPE ign8_pin_mask; extern volatile PORT_TYPE *tach_pin_port; extern volatile PINMASK_TYPE tach_pin_mask; extern volatile PORT_TYPE *pump_pin_port; extern volatile PINMASK_TYPE pump_pin_mask; extern volatile PORT_TYPE *flex_pin_port; extern volatile PINMASK_TYPE flex_pin_mask; extern volatile PORT_TYPE *triggerPri_pin_port; extern volatile PINMASK_TYPE triggerPri_pin_mask; extern volatile PORT_TYPE *triggerSec_pin_port; extern volatile PINMASK_TYPE triggerSec_pin_mask; extern volatile PORT_TYPE *triggerThird_pin_port; extern volatile PINMASK_TYPE triggerThird_pin_mask; extern byte triggerInterrupt; extern byte triggerInterrupt2; extern byte triggerInterrupt3; extern bool initialisationComplete; //Tracks whether the setup() function has run completely extern byte fpPrimeTime; //The time (in seconds, based on currentStatus.secl) that the fuel pump started priming extern uint8_t softLimitTime; //The time (in 0.1 seconds, based on seclx10) that the soft limiter started extern volatile uint16_t mainLoopCount; extern unsigned long revolutionTime; //The time in uS that one revolution would take at current speed (The time tooth 1 was last seen, minus the time it was seen prior to that) extern volatile unsigned long timer5_overflow_count; //Increments every time counter 5 overflows. Used for the fast version of micros() extern volatile unsigned long ms_counter; //A counter that increments once per ms extern uint16_t fixedCrankingOverride; extern bool clutchTrigger; extern bool previousClutchTrigger; extern volatile uint32_t toothHistory[TOOTH_LOG_SIZE]; extern volatile uint8_t compositeLogHistory[TOOTH_LOG_SIZE]; extern volatile bool fpPrimed; //Tracks whether or not the fuel pump priming has been completed yet extern volatile bool injPrimed; //Tracks whether or not the injector priming has been completed yet extern volatile unsigned int toothHistoryIndex; extern unsigned long currentLoopTime; /**< The time (in uS) that the current mainloop started */ extern volatile uint16_t ignitionCount; /**< The count of ignition events that have taken place since the engine started */ //The below shouldn't be needed and probably should be cleaned up, but the Atmel SAM (ARM) boards use a specific type for the trigger edge values rather than a simple byte/int #if defined(CORE_SAMD21) extern PinStatus primaryTriggerEdge; extern PinStatus secondaryTriggerEdge; extern PinStatus tertiaryTriggerEdge; #else extern byte primaryTriggerEdge; extern byte secondaryTriggerEdge; extern byte tertiaryTriggerEdge; #endif extern int CRANK_ANGLE_MAX_IGN; extern int CRANK_ANGLE_MAX_INJ; ///< The number of crank degrees that the system track over. 360 for wasted / timed batch and 720 for sequential extern volatile uint32_t runSecsX10; /**< Counter of seconds since cranking commenced (similar to runSecs) but in increments of 0.1 seconds */ extern volatile uint32_t seclx10; /**< Counter of seconds since powered commenced (similar to secl) but in increments of 0.1 seconds */ extern volatile byte HWTest_INJ; /**< Each bit in this variable represents one of the injector channels and it's HW test status */ extern volatile byte HWTest_INJ_50pc; /**< Each bit in this variable represents one of the injector channels and it's 50% HW test status */ extern volatile byte HWTest_IGN; /**< Each bit in this variable represents one of the ignition channels and it's HW test status */ extern volatile byte HWTest_IGN_50pc; /**< Each bit in this variable represents one of the ignition channels and it's 50% HW test status */ extern byte maxIgnOutputs; /**< Number of ignition outputs being used by the current tune configuration */ extern byte maxInjOutputs; /**< Number of injection outputs being used by the current tune configuration */ extern byte resetControl; ///< resetControl needs to be here (as global) because using the config page (4) directly can prevent burning the setting extern volatile byte TIMER_mask; extern volatile byte LOOP_TIMER; //These functions all do checks on a pin to determine if it is already in use by another (higher importance) function #define pinIsInjector(pin) ( ((pin) == pinInjector1) || ((pin) == pinInjector2) || ((pin) == pinInjector3) || ((pin) == pinInjector4) || ((pin) == pinInjector5) || ((pin) == pinInjector6) || ((pin) == pinInjector7) || ((pin) == pinInjector8) ) #define pinIsIgnition(pin) ( ((pin) == pinCoil1) || ((pin) == pinCoil2) || ((pin) == pinCoil3) || ((pin) == pinCoil4) || ((pin) == pinCoil5) || ((pin) == pinCoil6) || ((pin) == pinCoil7) || ((pin) == pinCoil8) ) //#define pinIsOutput(pin) ( pinIsInjector((pin)) || pinIsIgnition((pin)) || ((pin) == pinFuelPump) || ((pin) == pinFan) || ((pin) == pinAirConComp) || ((pin) == pinAirConFan)|| ((pin) == pinVVT_1) || ((pin) == pinVVT_2) || ( ((pin) == pinBoost) && configPage6.boostEnabled) || ((pin) == pinIdle1) || ((pin) == pinIdle2) || ((pin) == pinTachOut) || ((pin) == pinStepperEnable) || ((pin) == pinStepperStep) ) #define pinIsSensor(pin) ( ((pin) == pinCLT) || ((pin) == pinIAT) || ((pin) == pinMAP) || ((pin) == pinTPS) || ((pin) == pinO2) || ((pin) == pinBat) || (((pin) == pinFlex) && (configPage2.flexEnabled != 0)) ) //#define pinIsUsed(pin) ( pinIsSensor((pin)) || pinIsOutput((pin)) || pinIsReserved((pin)) ) /** The status struct with current values for all 'live' variables. * In current version this is 64 bytes. Instantiated as global currentStatus. * int *ADC (Analog-to-digital value / count) values contain the "raw" value from AD conversion, which get converted to * unit based values in similar variable(s) without ADC part in name (see sensors.ino for reading of sensors). */ struct statuses { volatile bool hasSync; /**< Flag for crank/cam position being known by decoders (See decoders.ino). This is used for sanity checking e.g. before logging tooth history or reading some sensors and computing readings. */ uint16_t RPM; ///< RPM - Current Revs per minute byte RPMdiv100; ///< RPM value scaled (divided by 100) to fit a byte (0-255, e.g. 12000 => 120) long longRPM; ///< RPM as long int (gets assigned to / maintained in statuses.RPM as well) int mapADC; int baroADC; long MAP; ///< Manifold absolute pressure. Has to be a long for PID calcs (Boost control) int16_t EMAP; ///< EMAP ... (See @ref config6.useEMAP for EMAP enablement) int16_t EMAPADC; byte baro; ///< Barometric pressure is simply the initial MAP reading, taken before the engine is running. Alternatively, can be taken from an external sensor byte TPS; /**< The current TPS reading (0% - 100%). Is the tpsADC value after the calibration is applied */ byte tpsADC; /**< byte (valued: 0-255) representation of the TPS. Downsampled from the original 10-bit (0-1023) reading, but before any calibration is applied */ int16_t tpsDOT; /**< TPS delta over time. Measures the % per second that the TPS is changing. Note that is signed value, because TPSdot can be also negative */ byte TPSlast; /**< The previous TPS reading */ int16_t mapDOT; /**< MAP delta over time. Measures the kpa per second that the MAP is changing. Note that is signed value, because MAPdot can be also negative */ volatile int rpmDOT; /**< RPM delta over time (RPM increase / s ?) */ byte VE; /**< The current VE value being used in the fuel calculation. Can be the same as VE1 or VE2, or a calculated value of both. */ byte VE1; /**< The VE value from fuel table 1 */ byte VE2; /**< The VE value from fuel table 2, if in use (and required conditions are met) */ byte O2; /**< Primary O2 sensor reading */ byte O2_2; /**< Secondary O2 sensor reading */ int coolant; /**< Coolant temperature reading */ int cltADC; int IAT; /**< Inlet air temperature reading */ int iatADC; int batADC; int O2ADC; int O2_2ADC; int dwell; ///< dwell (coil primary winding/circuit on) time (in ms * 10 ? See @ref correctionsDwell) volatile int16_t actualDwell; ///< actual dwell time if new ignition mode is used (in uS) byte dwellCorrection; /**< The amount of correction being applied to the dwell time (in unit ...). */ byte battery10; /**< The current BRV in volts (multiplied by 10. Eg 12.5V = 125) */ int8_t advance; /**< The current advance value being used in the spark calculation. Can be the same as advance1 or advance2, or a calculated value of both */ int8_t advance1; /**< The advance value from ignition table 1 */ int8_t advance2; /**< The advance value from ignition table 2 */ uint16_t corrections; /**< The total current corrections % amount */ uint16_t AEamount; /**< The amount of acceleration enrichment currently being applied. 100=No change. Varies above 255 */ byte egoCorrection; /**< The amount of closed loop AFR enrichment currently being applied */ byte wueCorrection; /**< The amount of warmup enrichment currently being applied */ byte batCorrection; /**< The amount of battery voltage enrichment currently being applied */ byte iatCorrection; /**< The amount of inlet air temperature adjustment currently being applied */ byte baroCorrection; /**< The amount of correction being applied for the current baro reading */ byte launchCorrection; /**< The amount of correction being applied if launch control is active */ byte flexCorrection; /**< Amount of correction being applied to compensate for ethanol content */ byte fuelTempCorrection; /**< Amount of correction being applied to compensate for fuel temperature */ int8_t flexIgnCorrection;/**< Amount of additional advance being applied based on flex. Note the type as this allows for negative values */ byte afrTarget; /**< Current AFR Target looked up from AFR target table (x10 ? See @ref afrTable)*/ byte CLIdleTarget; /**< The target idle RPM (when closed loop idle control is active) */ bool idleUpActive; /**< Whether the externally controlled idle up is currently active */ bool CTPSActive; /**< Whether the externally controlled closed throttle position sensor is currently active */ volatile byte ethanolPct; /**< Ethanol reading (if enabled). 0 = No ethanol, 100 = pure ethanol. Eg E85 = 85. */ volatile int8_t fuelTemp; unsigned long AEEndTime; /**< The target end time used whenever AE (acceleration enrichment) is turned on */ volatile byte status1; ///< Status bits (See BIT_STATUS1_* defines on top of this file) volatile byte spark; ///< Spark status/control indicator bits (launch control, boost cut, spark errors, See BIT_SPARK_* defines) volatile byte spark2; ///< Spark 2 ... (See also @ref config10 spark2* members and BIT_SPARK2_* defines) uint8_t engine; ///< Engine status bits (See BIT_ENGINE_* defines on top of this file) unsigned int PW1; ///< In uS unsigned int PW2; ///< In uS unsigned int PW3; ///< In uS unsigned int PW4; ///< In uS unsigned int PW5; ///< In uS unsigned int PW6; ///< In uS unsigned int PW7; ///< In uS unsigned int PW8; ///< In uS volatile byte runSecs; /**< Counter of seconds since cranking commenced (Maxes out at 255 to prevent overflow) */ volatile byte secl; /**< Counter incrementing once per second. Will overflow after 255 and begin again. This is used by TunerStudio to maintain comms sync */ volatile uint32_t loopsPerSecond; /**< A performance indicator showing the number of main loops that are being executed each second */ bool launchingSoft; /**< Indicator showing whether soft launch control adjustments are active */ bool launchingHard; /**< Indicator showing whether hard launch control adjustments are active */ uint16_t freeRAM; unsigned int clutchEngagedRPM; /**< The RPM at which the clutch was last depressed. Used for distinguishing between launch control and flat shift */ bool flatShiftingHard; volatile uint32_t startRevolutions; /**< A counter for how many revolutions have been completed since sync was achieved. */ uint16_t boostTarget; byte testOutputs; ///< Test Output bits (only first bit used/tested ?) bool testActive; // Not in use ? Replaced by testOutputs ? uint16_t boostDuty; ///< Boost Duty percentage value * 100 to give 2 points of precision byte idleLoad; ///< Either the current steps or current duty cycle for the idle control uint16_t canin[16]; ///< 16bit raw value of selected canin data for channels 0-15 uint8_t current_caninchannel = 0; /**< Current CAN channel, defaults to 0 */ uint16_t crankRPM = 400; /**< The actual cranking RPM limit. This is derived from the value in the config page, but saves us multiplying it every time it's used (Config page value is stored divided by 10) */ volatile byte status3; ///< Status bits (See BIT_STATUS3_* defines on top of this file) int16_t flexBoostCorrection; /**< Amount of boost added based on flex */ byte nitrous_status; byte nSquirts; ///< Number of injector squirts per cycle (per injector) byte nChannels; /**< Number of fuel and ignition channels. */ int16_t fuelLoad; int16_t fuelLoad2; int16_t ignLoad; int16_t ignLoad2; bool fuelPumpOn; /**< Indicator showing the current status of the fuel pump */ volatile byte syncLossCounter; byte knockRetard; bool knockActive; bool toothLogEnabled; byte compositeTriggerUsed; // 0 means composite logger disabled, 2 means use secondary input (1st cam), 3 means use tertiary input (2nd cam), 4 means log both cams together int16_t vvt1Angle; //Has to be a long for PID calcs (CL VVT control) byte vvt1TargetAngle; long vvt1Duty; //Has to be a long for PID calcs (CL VVT control) uint16_t injAngle; byte ASEValue; uint16_t vss; /**< Current speed reading. Natively stored in kph and converted to mph in TS if required */ bool idleUpOutputActive; /**< Whether the idle up output is currently active */ byte gear; /**< Current gear (Calculated from vss) */ byte fuelPressure; /**< Fuel pressure in PSI */ byte oilPressure; /**< Oil pressure in PSI */ byte engineProtectStatus; byte fanDuty; byte wmiPW; volatile byte status4; ///< Status bits (See BIT_STATUS4_* defines on top of this file) int16_t vvt2Angle; //Has to be a long for PID calcs (CL VVT control) byte vvt2TargetAngle; long vvt2Duty; //Has to be a long for PID calcs (CL VVT control) byte outputsStatus; byte TS_SD_Status; //TunerStudios SD card status byte airConStatus; }; /** Page 2 of the config - mostly variables that are required for fuel. * These are "non-live" EFI setting, engine and "system" variables that remain fixed once sent * (and stored to e.g. EEPROM) from configuration/tuning SW (from outside by USBserial/bluetooth). * Contains a lots of *Min, *Max (named) variables to constrain values to sane ranges. * See the ini file for further reference. * */ struct config2 { byte aseTaperTime; byte aeColdPct; //AE cold clt modifier % byte aeColdTaperMin; //AE cold modifier, taper start temp (full modifier, was ASE in early versions) byte aeMode : 2; /**< Acceleration Enrichment mode. 0 = TPS, 1 = MAP. Values 2 and 3 reserved for potential future use (ie blended TPS / MAP) */ byte battVCorMode : 1; byte SoftLimitMode : 1; byte useTachoSweep : 1; byte aeApplyMode : 1; ///< Acceleration enrichment calc mode: 0 = Multiply | 1 = Add (AE_MODE_ADDER) byte multiplyMAP : 2; ///< MAP value processing: 0 = off, 1 = div by currentStatus.baro, 2 = div by 100 (to gain usable value) byte wueValues[10]; ///< Warm up enrichment array (10 bytes, transferred to @ref WUETable) byte crankingPct; ///< Cranking enrichment (See @ref config10, updates.ino) byte pinMapping; ///< The board / ping mapping number / id to be used (See: @ref setPinMapping in init.ino) byte tachoPin : 6; ///< Custom pin setting for tacho output (if != 0, override copied to pinTachOut, which defaults to board assigned tach pin) byte tachoDiv : 2; ///< Whether to change the tacho speed ("half speed tacho" ?) byte tachoDuration; //The duration of the tacho pulse in mS byte maeThresh; /**< The MAPdot threshold that must be exceeded before AE is engaged */ byte taeThresh; /**< The TPSdot threshold that must be exceeded before AE is engaged */ byte aeTime; byte taeMinChange; /**< The minimum change in TPS that must be made before AE is engaged */ byte maeMinChange; /**< The minimum change in MAP that must be made before AE is engaged */ //Display config bits byte displayB1 : 4; //23 byte displayB2 : 4; byte reqFuel; //24 byte divider; byte injTiming : 1; ///< Injector timing (aka. injector staging) 0=simultaneous, 1=alternating byte crkngAddCLTAdv : 1; byte includeAFR : 1; //< Enable AFR compensation ? (See also @ref config2.incorporateAFR) byte hardCutType : 1; byte ignAlgorithm : 3; byte indInjAng : 1; byte injOpen; ///< Injector opening time (ms * 10) uint16_t injAng[4]; //config1 in ini byte mapSample : 2; ///< MAP sampling method (0=Instantaneous, 1=Cycle Average, 2=Cycle Minimum, 4=Ign. event average, See sensors.ino) byte strokes : 1; ///< Engine cycle type: four-stroke (0) / two-stroke (1) byte injType : 1; ///< Injector type 0=Port (INJ_TYPE_PORT), 1=Throttle Body / TBI (INJ_TYPE_TBODY) byte nCylinders : 4; ///< Number of cylinders //config2 in ini byte fuelAlgorithm : 3;///< Fuel algorithm - 0=Manifold pressure/MAP (LOAD_SOURCE_MAP, default, proven), 1=Throttle/TPS (LOAD_SOURCE_TPS), 2=IMAP/EMAP (LOAD_SOURCE_IMAPEMAP) byte fixAngEnable : 1; ///< Whether fixed/locked timing is enabled (0=disable, 1=enable, See @ref configPage4.FixAng) byte nInjectors : 4; ///< Number of injectors //config3 in ini byte engineType : 1; ///< Engine crank/ign phasing type: 0=even fire, 1=odd fire byte flexEnabled : 1; ///< Enable Flex fuel sensing (pin / interrupt) byte legacyMAP : 1; ///< Legacy MAP reading behaviour byte baroCorr : 1; // Unused ? byte injLayout : 2; /**< Injector Layout - 0=INJ_PAIRED (number outputs == number cyls/2, timed over 1 crank rev), 1=INJ_SEMISEQUENTIAL (like paired, but number outputs == number cyls, only for 4 cyl), 2=INJ_BANKED (2 outputs are used), 3=INJ_SEQUENTIAL (number outputs == number cyls, timed over full cycle, 2 crank revs) */ byte perToothIgn : 1; ///< Experimental / New ignition mode ... (?) (See decoders.ino) byte dfcoEnabled : 1; ///< Whether or not DFCO (deceleration fuel cut-off) is turned on byte aeColdTaperMax; ///< AE cold modifier, taper end temp (no modifier applied, was primePulse in early versions) byte dutyLim; byte flexFreqLow; //Lowest valid frequency reading from the flex sensor byte flexFreqHigh; //Highest valid frequency reading from the flex sensor byte boostMaxDuty; byte tpsMin; byte tpsMax; int8_t mapMin; //Must be signed uint16_t mapMax; byte fpPrime; ///< Time (In seconds) that the fuel pump should be primed for on power up byte stoich; ///< Stoichiometric ratio (x10, so e.g. 14.7 => 147) uint16_t oddfire2; ///< The ATDC angle of channel 2 for oddfire uint16_t oddfire3; ///< The ATDC angle of channel 3 for oddfire uint16_t oddfire4; ///< The ATDC angle of channel 4 for oddfire byte idleUpPin : 6; byte idleUpPolarity : 1; byte idleUpEnabled : 1; byte idleUpAdder; byte aeTaperMin; byte aeTaperMax; byte iacCLminValue; byte iacCLmaxValue; byte boostMinDuty; int8_t baroMin; //Must be signed uint16_t baroMax; int8_t EMAPMin; //Must be signed uint16_t EMAPMax; byte fanWhenOff : 1; ///< Allow running fan with engine off: 0 = Only run fan when engine is running, 1 = Allow even with engine off byte fanWhenCranking : 1; ///< Set whether the fan output will stay on when the engine is cranking (0=force off, 1=allow on) byte useDwellMap : 1; ///< Setting to change between fixed dwell value and dwell map (0=Fixed value from @ref configPage4.dwellRun, 1=Use @ref dwellTable) byte fanEnable : 2; ///< Fan mode. 0=Off, 1=On/Off, 2=PWM byte rtc_mode : 2; // Unused ? byte incorporateAFR : 1; ///< Enable AFR target (stoich/afrtgt) compensation in PW calculation byte asePct[4]; ///< Afterstart enrichment values (%) byte aseCount[4]; ///< Afterstart enrichment cycles. This is the number of ignition cycles that the afterstart enrichment % lasts for byte aseBins[4]; ///< Afterstart enrichment temperatures (x-axis) for (target) enrichment values byte primePulse[4];//Priming pulsewidth values (mS, copied to @ref PrimingPulseTable) byte primeBins[4]; //Priming temperatures (source,x-axis) byte CTPSPin : 6; byte CTPSPolarity : 1; byte CTPSEnabled : 1; byte idleAdvEnabled : 2; byte idleAdvAlgorithm : 1; byte idleAdvDelay : 5; byte idleAdvRPM; byte idleAdvTPS; byte injAngRPM[4]; byte idleTaperTime; byte dfcoDelay; byte dfcoMinCLT; //VSS Stuff byte vssMode : 2; ///< VSS (Vehicle speed sensor) mode (0=none, 1=CANbus, 2,3=Interrupt driven) byte vssPin : 6; ///< VSS (Vehicle speed sensor) pin number uint16_t vssPulsesPerKm; ///< VSS (Vehicle speed sensor) pulses per Km byte vssSmoothing; uint16_t vssRatio1; uint16_t vssRatio2; uint16_t vssRatio3; uint16_t vssRatio4; uint16_t vssRatio5; uint16_t vssRatio6; byte idleUpOutputEnabled : 1; byte idleUpOutputInv : 1; byte idleUpOutputPin : 6; byte tachoSweepMaxRPM; byte primingDelay; byte iacTPSlimit; byte iacRPMlimitHysteresis; int8_t rtc_trim; byte idleAdvVss; byte mapSwitchPoint; byte canBMWCluster : 1; byte canVAGCluster : 1; byte enableCluster1 : 1; byte enableCluster2 : 1; byte vssAuxCh : 4; byte decelAmount; #if defined(CORE_AVR) }; #else } __attribute__((__packed__)); //The 32 bit systems require all structs to be fully packed #endif /** Page 4 of the config - variables required for ignition and rpm/crank phase /cam phase decoding. * See the ini file for further reference. */ struct config4 { int16_t triggerAngle; ///< Angle (ATDC) when tooth No:1 on the primary wheel sends signal (-360 to +360 deg.) int8_t FixAng; ///< Fixed Ignition angle value (enabled by @ref configPage2.fixAngEnable, copied to ignFixValue, Negative values allowed, See corrections.ino) int8_t CrankAng; ///< Fixed start-up/cranking ignition angle (See: corrections.ino) byte TrigAngMul; ///< Multiplier for non evenly divisible tooth counts. byte TrigEdge : 1; ///< Primary (RPM1) Trigger Edge - 0 - RISING, 1 = FALLING (Copied from this config to primaryTriggerEdge) byte TrigSpeed : 1; ///< Primary (RPM1) Trigger speed - 0 = crank speed (CRANK_SPEED), 1 = cam speed (CAM_SPEED), See decoders.ino byte IgInv : 1; ///< Ignition signal invert (?) (GOING_LOW=0 (default by init.ino) / GOING_HIGH=1 ) byte TrigPattern : 5; ///< Decoder configured (DECODER_MISSING_TOOTH, DECODER_BASIC_DISTRIBUTOR, DECODER_GM7X, ... See init.ino) byte TrigEdgeSec : 1; ///< Secondary (RPM2) Trigger Edge (See RPM1) byte fuelPumpPin : 6; ///< Fuel pump pin (copied as override to pinFuelPump, defaults to board default, See: init.ino) byte useResync : 1; byte sparkDur; ///< Spark duration in ms * 10 byte trigPatternSec : 7; ///< Mode for Missing tooth secondary trigger - 0=single tooth cam wheel (SEC_TRIGGER_SINGLE), 1=4-1 (SEC_TRIGGER_4_1) or 2=poll level mode (SEC_TRIGGER_POLL) byte PollLevelPolarity : 1; //for poll level cam trigger. Sets if the cam trigger is supposed to be high or low for revolution one. uint8_t bootloaderCaps; //Capabilities of the bootloader over stock. e.g., 0=Stock, 1=Reset protection, etc. byte resetControlConfig : 2; /** Which method of reset control to use - 0=Disabled (RESET_CONTROL_DISABLED), 1=Prevent When Running (RESET_CONTROL_PREVENT_WHEN_RUNNING), 2=Prevent Always (RESET_CONTROL_PREVENT_ALWAYS), 3=Serial Command (RESET_CONTROL_SERIAL_COMMAND) - Copied to resetControl (See init.ino, utilities.ino) */ byte resetControlPin : 6; byte StgCycles; //The number of initial cycles before the ignition should fire when first cranking byte boostType : 1; ///< Boost Control type: 0=Open loop (OPEN_LOOP_BOOST), 1=closed loop (CLOSED_LOOP_BOOST) byte useDwellLim : 1; //Whether the dwell limiter is off or on byte sparkMode : 3; /** Ignition/Spark output mode - 0=Wasted spark (IGN_MODE_WASTED), 1=single channel (IGN_MODE_SINGLE), 2=Wasted COP (IGN_MODE_WASTEDCOP), 3=Sequential (IGN_MODE_SEQUENTIAL), 4=Rotary (IGN_MODE_ROTARY) */ byte triggerFilter : 2; //The mode of trigger filter being used (0=Off, 1=Light (Not currently used), 2=Normal, 3=Aggressive) byte ignCranklock : 1; //Whether or not the ignition timing during cranking is locked to a CAS (crank) pulse. Only currently valid for Basic distributor and 4G63. byte dwellCrank; ///< Dwell time whilst cranking byte dwellRun; ///< Dwell time whilst running byte triggerTeeth; ///< The full count of teeth on the trigger wheel if there were no gaps byte triggerMissingTeeth; ///< The size of the tooth gap (ie number of missing teeth) byte crankRPM; ///< RPM below which the engine is considered to be cranking byte floodClear; ///< TPS (raw adc count? % ?) value that triggers flood clear mode (No fuel whilst cranking, See @ref correctionFloodClear()) byte SoftRevLim; ///< Soft rev limit (RPM/100) byte SoftLimRetard; ///< Amount soft limit (ignition) retard (degrees) byte SoftLimMax; ///< Time the soft limit can run (units 0.1S) byte HardRevLim; ///< Hard rev limit (RPM/100) byte taeBins[4]; ///< TPS based acceleration enrichment bins (Unit: %/s) byte taeValues[4]; ///< TPS based acceleration enrichment rates (Unit: % to add), values matched to thresholds of taeBins byte wueBins[10]; ///< Warmup Enrichment bins (Values are in @ref configPage2.wueValues OLD:configTable1) byte dwellLimit; byte dwellCorrectionValues[6]; ///< Correction table for dwell vs battery voltage byte iatRetBins[6]; ///< Inlet Air Temp timing retard curve bins (Unit: ...) byte iatRetValues[6]; ///< Inlet Air Temp timing retard curve values (Unit: ...) byte dfcoRPM; ///< RPM at which DFCO turns off/on at byte dfcoHyster; //Hysteris RPM for DFCO byte dfcoTPSThresh; //TPS must be below this figure for DFCO to engage (Unit: ...) byte ignBypassEnabled : 1; //Whether or not the ignition bypass is enabled byte ignBypassPin : 6; //Pin the ignition bypass is activated on byte ignBypassHiLo : 1; //Whether this should be active high or low. byte ADCFILTER_TPS; byte ADCFILTER_CLT; byte ADCFILTER_IAT; byte ADCFILTER_O2; byte ADCFILTER_BAT; byte ADCFILTER_MAP; //This is only used on Instantaneous MAP readings and is intentionally very weak to allow for faster response byte ADCFILTER_BARO; byte cltAdvBins[6]; /**< Coolant Temp timing advance curve bins */ byte cltAdvValues[6]; /**< Coolant timing advance curve values. These are translated by 15 to allow for negative values */ byte maeBins[4]; /**< MAP based AE MAPdot bins */ byte maeRates[4]; /**< MAP based AE values */ int8_t batVoltCorrect; /**< Battery voltage calibration offset (Given as 10x value, e.g. 2v => 20) */ byte baroFuelBins[8]; byte baroFuelValues[8]; byte idleAdvBins[6]; byte idleAdvValues[6]; byte engineProtectMaxRPM; int16_t vvt2CL0DutyAng; byte vvt2PWMdir : 1; byte inj4cylPairing : 2; byte dwellErrCorrect : 1; byte unusedBits4 : 4; byte ANGLEFILTER_VVT; byte FILTER_FLEX; byte vvtMinClt; byte vvtDelay; #if defined(CORE_AVR) }; #else } __attribute__((__packed__)); //The 32 bi systems require all structs to be fully packed #endif /** Page 6 of the config - mostly variables that are required for AFR targets and closed loop. See the ini file for further reference. */ struct config6 { byte egoAlgorithm : 2; ///< EGO Algorithm - Simple, PID, No correction byte egoType : 2; ///< EGO Sensor Type 0=Disabled/None, 1=Narrowband, 2=Wideband byte boostEnabled : 1; ///< Boost control enabled 0 =off, 1 = on byte vvtEnabled : 1; ///< byte engineProtectType : 2; byte egoKP; byte egoKI; byte egoKD; byte egoTemp; ///< The temperature above which closed loop is enabled byte egoCount; ///< The number of ignition cycles per (ego AFR ?) step byte vvtMode : 2; ///< Valid VVT modes are 'on/off', 'open loop' and 'closed loop' byte vvtLoadSource : 2; ///< Load source for VVT (TPS or MAP) byte vvtPWMdir : 1; ///< VVT direction (normal or reverse) byte vvtCLUseHold : 1; //Whether or not to use a hold duty cycle (Most cases are Yes) byte vvtCLAlterFuelTiming : 1; byte boostCutEnabled : 1; byte egoLimit; /// Maximum amount the closed loop EGO control will vary the fuelling byte ego_min; /// AFR must be above this for closed loop to function byte ego_max; /// AFR must be below this for closed loop to function byte ego_sdelay; /// Time in seconds after engine starts that closed loop becomes available byte egoRPM; /// RPM must be above this for closed loop to function byte egoTPSMax; /// TPS must be below this for closed loop to function byte vvt1Pin : 6; byte useExtBaro : 1; byte boostMode : 1; /// Boost control mode: 0=Simple (BOOST_MODE_SIMPLE) or 1=full (BOOST_MODE_FULL) byte boostPin : 6; byte tachoMode : 1; /// Whether to use fixed tacho pulse duration or match to dwell duration byte useEMAP : 1; ///< Enable EMAP byte voltageCorrectionBins[6]; //X axis bins for voltage correction tables byte injVoltageCorrectionValues[6]; //Correction table for injector PW vs battery voltage byte airDenBins[9]; byte airDenRates[9]; byte boostFreq; /// Frequency of the boost PWM valve byte vvtFreq; /// Frequency of the vvt PWM valve byte idleFreq; // Launch stuff, see beginning of speeduino.ino main loop byte launchPin : 6; ///< Launch (control ?) pin byte launchEnabled : 1; ///< Launch ...???... (control?) enabled byte launchHiLo : 1; // byte lnchSoftLim; int8_t lnchRetard; //Allow for negative advance value (ATDC) byte lnchHardLim; byte lnchFuelAdd; //PID values for idle needed to go here as out of room in the idle page byte idleKP; byte idleKI; byte idleKD; byte boostLimit; ///< Boost limit (Kpa). Stored value is actual (kPa) value divided by 2, allowing kPa values up to 511 byte boostKP; byte boostKI; byte boostKD; byte lnchPullRes : 1; byte iacPWMrun : 1; ///< Run the PWM idle valve before engine is cranked over (0 = off, 1 = on) byte fuelTrimEnabled : 1; byte flatSEnable : 1; ///< Flat shift enable byte baroPin : 4; byte flatSSoftWin; int8_t flatSRetard; byte flatSArm; byte iacCLValues[10]; //Closed loop target RPM value byte iacOLStepVal[10]; //Open loop step values for stepper motors byte iacOLPWMVal[10]; //Open loop duty values for PMWM valves byte iacBins[10]; //Temperature Bins for the above 3 curves byte iacCrankSteps[4]; //Steps to use when cranking (Stepper motor) byte iacCrankDuty[4]; //Duty cycle to use on PWM valves when cranking byte iacCrankBins[4]; //Temperature Bins for the above 2 curves byte iacAlgorithm : 3; //Valid values are: "None", "On/Off", "PWM", "PWM Closed Loop", "Stepper", "Stepper Closed Loop" byte iacStepTime : 3; //How long to pulse the stepper for to ensure the step completes (ms) byte iacChannels : 1; //How many outputs to use in PWM mode (0 = 1 channel, 1 = 2 channels) byte iacPWMdir : 1; //Direction of the PWM valve. 0 = Normal = Higher RPM with more duty. 1 = Reverse = Lower RPM with more duty byte iacFastTemp; //Fast idle temp when using a simple on/off valve byte iacStepHome; //When using a stepper motor, the number of steps to be taken on startup to home the motor byte iacStepHyster; //Hysteresis temperature (*10). Eg 2.2C = 22 byte fanInv : 1; // Fan output inversion bit byte fanUnused : 1; byte fanPin : 6; byte fanSP; // Cooling fan start temperature byte fanHyster; // Fan hysteresis byte fanFreq; // Fan PWM frequency byte fanPWMBins[4]; //Temperature Bins for the PWM fan control #if defined(CORE_AVR) }; #else } __attribute__((__packed__)); //The 32 bit systems require all structs to be fully packed #endif /** Page 9 of the config - mostly deals with CANBUS control. See ini file for further info (Config Page 10 in the ini). */ struct config9 { byte enable_secondarySerial:1; //enable secondary serial byte intcan_available:1; //enable internal can module byte enable_intcan:1; byte secondarySerialProtocol:3; //protocol for secondary serial. 0=Generic, 1=CAN, 2=msDroid, 3=Real Dash byte unused9_0:2; byte caninput_sel[16]; //bit status on/Can/analog_local/digtal_local if input is enabled uint16_t caninput_source_can_address[16]; //u16 [15] array holding can address of input uint8_t caninput_source_start_byte[16]; //u08 [15] array holds the start byte number(value of 0-7) uint16_t caninput_source_num_bytes; //u16 bit status of the number of bytes length 1 or 2 byte caninputEndianess:1; //byte unused:2 //... byte unused10_68; byte enable_candata_out : 1; byte canoutput_sel[8]; uint16_t canoutput_param_group[8]; uint8_t canoutput_param_start_byte[8]; byte canoutput_param_num_bytes[8]; byte unused10_110; byte unused10_111; byte unused10_112; byte unused10_113; byte speeduino_tsCanId:4; //speeduino TS canid (0-14) uint16_t true_address; //speeduino 11bit can address uint16_t realtime_base_address; //speeduino 11 bit realtime base address uint16_t obd_address; //speeduino OBD diagnostic address uint8_t Auxinpina[16]; //analog pin number when internal aux in use uint8_t Auxinpinb[16]; // digital pin number when internal aux in use byte iacStepperInv : 1; //stepper direction of travel to allow reversing. 0=normal, 1=inverted. byte iacCoolTime : 3; // how long to wait for the stepper to cool between steps byte boostByGearEnabled : 2; byte blankField : 1; byte iacStepperPower : 1; //Whether or not to power the stepper motor when not in use byte iacMaxSteps; // Step limit beyond which the stepper won't be driven. Should always be less than homing steps. Stored div 3 as per home steps. byte idleAdvStartDelay; //delay for idle advance engage byte boostByGear1; byte boostByGear2; byte boostByGear3; byte boostByGear4; byte boostByGear5; byte boostByGear6; byte PWMFanDuty[4]; byte hardRevMode : 2; byte coolantProtRPM[6]; byte coolantProtTemp[6]; byte unused10_179; byte unused10_180; byte unused10_181; byte unused10_182; byte unused10_183; byte unused10_184; byte afrProtectEnabled : 2; /* < AFR protection enabled status. 0 = disabled, 1 = fixed mode, 2 = table mode */ byte afrProtectMinMAP; /* < Minimum MAP. Stored value is divided by 2. Increments of 2 kPa, maximum 511 (?) kPa */ byte afrProtectMinRPM; /* < Minimum RPM. Stored value is divded by 100. Increments of 100 RPM, maximum 25500 RPM */ byte afrProtectMinTPS; /* < Minimum TPS. */ byte afrProtectDeviation; /* < Maximum deviation from AFR target table. Stored value is multiplied by 10 */ byte afrProtectCutTime; /* < Time in ms before cut. Stored value is divided by 100. Maximum of 2550 ms */ byte afrProtectReactivationTPS; /* Disable engine protection cut once below this TPS percentage */ #if defined(CORE_AVR) }; #else } __attribute__((__packed__)); //The 32 bit systems require all structs to be fully packed #endif /** Page 10 - No specific purpose. Created initially for the cranking enrich curve. 192 bytes long. See ini file for further info (Config Page 11 in the ini). */ struct config10 { byte crankingEnrichBins[4]; //Bytes 0-4 byte crankingEnrichValues[4]; //Bytes 4-7 //Byte 8 byte rotaryType : 2; byte stagingEnabled : 1; byte stagingMode : 1; byte EMAPPin : 4; byte rotarySplitValues[8]; //Bytes 9-16 byte rotarySplitBins[8]; //Bytes 17-24 uint16_t boostSens; //Bytes 25-26 byte boostIntv; //Byte 27 uint16_t stagedInjSizePri; //Bytes 28-29 uint16_t stagedInjSizeSec; //Bytes 30-31 byte lnchCtrlTPS; //Byte 32 uint8_t flexBoostBins[6]; //Bytes 33-38 int16_t flexBoostAdj[6]; //kPa to be added to the boost target @ current ethanol (negative values allowed). Bytes 39-50 uint8_t flexFuelBins[6]; //Bytes 51-56 uint8_t flexFuelAdj[6]; //Fuel % @ current ethanol (typically 100% @ 0%, 163% @ 100%). Bytes 57-62 uint8_t flexAdvBins[6]; //Bytes 63-68 uint8_t flexAdvAdj[6]; //Additional advance (in degrees) @ current ethanol (typically 0 @ 0%, 10-20 @ 100%). NOTE: THIS SHOULD BE A SIGNED VALUE BUT 2d TABLE LOOKUP NOT WORKING WITH IT CURRENTLY! //And another three corn rows die. //Bytes 69-74 //Byte 75 byte n2o_enable : 2; byte n2o_arming_pin : 6; byte n2o_minCLT; //Byte 76 byte n2o_maxMAP; //Byte 77 byte n2o_minTPS; //Byte 78 byte n2o_maxAFR; //Byte 79 //Byte 80 byte n2o_stage1_pin : 6; byte n2o_pin_polarity : 1; byte n2o_stage1_unused : 1; byte n2o_stage1_minRPM; //Byte 81 byte n2o_stage1_maxRPM; //Byte 82 byte n2o_stage1_adderMin; //Byte 83 byte n2o_stage1_adderMax; //Byte 84 byte n2o_stage1_retard; //Byte 85 //Byte 86 byte n2o_stage2_pin : 6; byte n2o_stage2_unused : 2; byte n2o_stage2_minRPM; //Byte 87 byte n2o_stage2_maxRPM; //Byte 88 byte n2o_stage2_adderMin; //Byte 89 byte n2o_stage2_adderMax; //Byte 90 byte n2o_stage2_retard; //Byte 91 //Byte 92 byte knock_mode : 2; byte knock_pin : 6; //Byte 93 byte knock_trigger : 1; byte knock_pullup : 1; byte knock_limiterDisable : 1; byte knock_unused : 2; byte knock_count : 3; byte knock_threshold; //Byte 94 byte knock_maxMAP; //Byte 95 byte knock_maxRPM; //Byte 96 byte knock_window_rpms[6]; //Bytes 97-102 byte knock_window_angle[6]; //Bytes 103-108 byte knock_window_dur[6]; //Bytes 109-114 byte knock_maxRetard; //Byte 115 byte knock_firstStep; //Byte 116 byte knock_stepSize; //Byte 117 byte knock_stepTime; //Byte 118 byte knock_duration; //Time after knock retard starts that it should start recovering. Byte 119 byte knock_recoveryStepTime; //Byte 120 byte knock_recoveryStep; //Byte 121 //Byte 122 byte fuel2Algorithm : 3; byte fuel2Mode : 3; byte fuel2SwitchVariable : 2; //Bytes 123-124 uint16_t fuel2SwitchValue; //Byte 125 byte fuel2InputPin : 6; byte fuel2InputPolarity : 1; byte fuel2InputPullup : 1; byte vvtCLholdDuty; //Byte 126 byte vvtCLKP; //Byte 127 byte vvtCLKI; //Byte 128 byte vvtCLKD; //Byte 129 int16_t vvtCL0DutyAng; //Bytes 130-131 uint8_t vvtCLMinAng; //Byte 132 uint8_t vvtCLMaxAng; //Byte 133 byte crankingEnrichTaper; //Byte 134 byte fuelPressureEnable : 1; ///< Enable fuel pressure sensing from an analog pin (@ref pinFuelPressure) byte oilPressureEnable : 1; ///< Enable oil pressure sensing from an analog pin (@ref pinOilPressure) byte oilPressureProtEnbl : 1; byte oilPressurePin : 5; byte fuelPressurePin : 5; byte unused11_165 : 3; int8_t fuelPressureMin; byte fuelPressureMax; int8_t oilPressureMin; byte oilPressureMax; byte oilPressureProtRPM[4]; byte oilPressureProtMins[4]; byte wmiEnabled : 1; // Byte 149 byte wmiMode : 6; byte wmiAdvEnabled : 1; byte wmiTPS; // Byte 150 byte wmiRPM; // Byte 151 byte wmiMAP; // Byte 152 byte wmiMAP2; // Byte 153 byte wmiIAT; // Byte 154 int8_t wmiOffset; // Byte 155 byte wmiIndicatorEnabled : 1; // 156 byte wmiIndicatorPin : 6; byte wmiIndicatorPolarity : 1; byte wmiEmptyEnabled : 1; // 157 byte wmiEmptyPin : 6; byte wmiEmptyPolarity : 1; byte wmiEnabledPin; // 158 byte wmiAdvBins[6]; //Bytes 159-164 byte wmiAdvAdj[6]; //Additional advance (in degrees) //Bytes 165-170 byte vvtCLminDuty; byte vvtCLmaxDuty; byte vvt2Pin : 6; byte vvt2Enabled : 1; byte TrigEdgeThrd : 1; byte fuelTempBins[6]; byte fuelTempValues[6]; //180 //Byte 186 byte spark2Algorithm : 3; byte spark2Mode : 3; byte spark2SwitchVariable : 2; //Bytes 187-188 uint16_t spark2SwitchValue; //Byte 189 byte spark2InputPin : 6; byte spark2InputPolarity : 1; byte spark2InputPullup : 1; byte oilPressureProtTime; byte unused11_191_191; #if defined(CORE_AVR) }; #else } __attribute__((__packed__)); //The 32 bit systems require all structs to be fully packed #endif /** Config for programmable I/O comparison operation (between 2 vars). * Operations are implemented in utilities.ino (@ref checkProgrammableIO()). */ struct cmpOperation{ uint8_t firstCompType : 3; ///< First cmp. op (COMPARATOR_* ops, see below) uint8_t secondCompType : 3; ///< Second cmp. op (0=COMPARATOR_EQUAL, 1=COMPARATOR_NOT_EQUAL,2=COMPARATOR_GREATER,3=COMPARATOR_GREATER_EQUAL,4=COMPARATOR_LESS,5=COMPARATOR_LESS_EQUAL,6=COMPARATOR_CHANGE) uint8_t bitwise : 2; ///< BITWISE_AND, BITWISE_OR, BITWISE_XOR }; /** Page 13 - Programmable outputs logic rules. 128 bytes long. Rules implemented in utilities.ino @ref checkProgrammableIO(). */ struct config13 { uint8_t outputInverted; ///< Invert (on/off) value before writing to output pin (for all programmable I/O:s). uint8_t kindOfLimiting; ///< Select which kind of output limiting are active (0 - minimum | 1 - maximum) uint8_t outputPin[8]; ///< Disable(0) or enable (set to valid pin number) Programmable Pin (output/target pin to set) uint8_t outputDelay[8]; ///< Output write delay for each programmable I/O (Unit: 0.1S) uint8_t firstDataIn[8]; ///< Set of first I/O vars to compare uint8_t secondDataIn[8];///< Set of second I/O vars to compare uint8_t outputTimeLimit[8]; ///< Output delay for each programmable I/O, kindOfLimiting bit dependent(Unit: 0.1S) uint8_t unused_13[8]; // Unused int16_t firstTarget[8]; ///< first target value to compare with numeric comp int16_t secondTarget[8];///< second target value to compare with bitwise op //89bytes struct cmpOperation operation[8]; ///< I/O variable comparison operations (See @ref cmpOperation) uint16_t candID[8]; ///< Actual CAN ID need 16bits, this is a placeholder byte unused12_106_116[10]; byte onboard_log_csv_separator :2; //";", ",", "tab", "space" byte onboard_log_file_style :2; // "Disabled", "CSV", "Binary", "INVALID" byte onboard_log_file_rate :2; // "1Hz", "4Hz", "10Hz", "30Hz" byte onboard_log_filenaming :2; // "Overwrite", "Date-time", "Sequential", "INVALID" byte onboard_log_storage :2; // "sd-card", "INVALID", "INVALID", "INVALID" ;In the future maybe an onboard spi flash can be used, or switch between SDIO vs SPI sd card interfaces. byte onboard_log_trigger_boot :1; // "Disabled", "On boot" byte onboard_log_trigger_RPM :1; // "Disabled", "Enabled" byte onboard_log_trigger_prot :1; // "Disabled", "Enabled" byte onboard_log_trigger_Vbat :1; // "Disabled", "Enabled" byte onboard_log_trigger_Epin :2; // "Disabled", "polling", "toggle" , "INVALID" uint16_t onboard_log_tr1_duration; // Duration of logging that starts on boot byte onboard_log_tr2_thr_on; // "RPM", 100.0, 0.0, 0, 10000, 0 byte onboard_log_tr2_thr_off; // "RPM", 100.0, 0.0, 0, 10000, 0 byte onboard_log_tr3_thr_RPM :1; // "Disabled", "Enabled" byte onboard_log_tr3_thr_MAP :1; // "Disabled", "Enabled" byte onboard_log_tr3_thr_Oil :1; // "Disabled", "Enabled" byte onboard_log_tr3_thr_AFR :1; // "Disabled", "Enabled" byte onboard_log_tr4_thr_on; // "V", 0.1, 0.0, 0.0, 15.90, 2 ; * ( 1 byte) byte onboard_log_tr4_thr_off; // "V", 0.1, 0.0, 0.0, 15.90, 2 ; * ( 1 byte) byte onboard_log_tr5_Epin_pin :6; // "pin", 0, 0, 0, 1, 255, 0 ; byte unused13_125_2 :2; byte unused12_126_127[2]; #if defined(CORE_AVR) }; #else } __attribute__((__packed__)); //The 32 bit systems require all structs to be fully packed #endif /** Page 15 - second page for VVT and boost control. 256 bytes long. */ struct config15 { byte boostControlEnable : 1; byte unused15_1 : 7; //7bits unused byte boostDCWhenDisabled; byte boostControlEnableThreshold; //if fixed value enable set threshold here. //Byte 83 - Air conditioning binary points byte airConEnable : 1; byte airConCompPol : 1; byte airConReqPol : 1; byte airConTurnsFanOn : 1; byte airConFanEnabled : 1; byte airConFanPol : 1; byte airConUnused1 : 2; //Bytes 84-97 - Air conditioning analog points byte airConCompPin : 6; byte airConUnused2 : 2; byte airConReqPin : 6; byte airConUnused3 : 2; byte airConTPSCut; byte airConMinRPMdiv10; byte airConMaxRPMdiv100; byte airConClTempCut; byte airConIdleSteps; byte airConTPSCutTime; byte airConCompOnDelay; byte airConAfterStartDelay; byte airConRPMCutTime; byte airConFanPin : 6; byte airConUnused4 : 2; byte airConIdleUpRPMAdder; byte airConPwmFanMinDuty; int8_t rollingProtRPMDelta[4]; // Signed RPM value representing how much below the RPM limit. Divided by 10 byte rollingProtCutPercent[4]; //Bytes 98-255 byte Unused15_98_255[150]; #if defined(CORE_AVR) }; #else } __attribute__((__packed__)); //The 32 bit systems require all structs to be fully packed #endif extern byte pinInjector1; //Output pin injector 1 extern byte pinInjector2; //Output pin injector 2 extern byte pinInjector3; //Output pin injector 3 extern byte pinInjector4; //Output pin injector 4 extern byte pinInjector5; //Output pin injector 5 extern byte pinInjector6; //Output pin injector 6 extern byte pinInjector7; //Output pin injector 7 extern byte pinInjector8; //Output pin injector 8 extern byte injectorOutputControl; //Specifies whether the injectors are controlled directly (Via an IO pin) or using something like the MC33810 extern byte pinCoil1; //Pin for coil 1 extern byte pinCoil2; //Pin for coil 2 extern byte pinCoil3; //Pin for coil 3 extern byte pinCoil4; //Pin for coil 4 extern byte pinCoil5; //Pin for coil 5 extern byte pinCoil6; //Pin for coil 6 extern byte pinCoil7; //Pin for coil 7 extern byte pinCoil8; //Pin for coil 8 extern byte ignitionOutputControl; //Specifies whether the coils are controlled directly (Via an IO pin) or using something like the MC33810 extern byte pinTrigger; //The CAS pin extern byte pinTrigger2; //The Cam Sensor pin extern byte pinTrigger3; //the 2nd cam sensor pin extern byte pinTPS;//TPS input pin extern byte pinMAP; //MAP sensor pin extern byte pinEMAP; //EMAP sensor pin extern byte pinMAP2; //2nd MAP sensor (Currently unused) extern byte pinIAT; //IAT sensor pin extern byte pinCLT; //CLS sensor pin extern byte pinO2; //O2 Sensor pin extern byte pinO2_2; //second O2 pin extern byte pinBat; //Battery voltage pin extern byte pinDisplayReset; // OLED reset pin extern byte pinTachOut; //Tacho output extern byte pinFuelPump; //Fuel pump on/off extern byte pinIdle1; //Single wire idle control extern byte pinIdle2; //2 wire idle control (Not currently used) extern byte pinIdleUp; //Input for triggering Idle Up extern byte pinIdleUpOutput; //Output that follows (normal or inverted) the idle up pin extern byte pinCTPS; //Input for triggering closed throttle state extern byte pinFuel2Input; //Input for switching to the 2nd fuel table extern byte pinSpark2Input; //Input for switching to the 2nd ignition table extern byte pinSpareTemp1; // Future use only extern byte pinSpareTemp2; // Future use only extern byte pinSpareOut1; //Generic output extern byte pinSpareOut2; //Generic output extern byte pinSpareOut3; //Generic output extern byte pinSpareOut4; //Generic output extern byte pinSpareOut5; //Generic output extern byte pinSpareOut6; //Generic output extern byte pinSpareHOut1; //spare high current output extern byte pinSpareHOut2; // spare high current output extern byte pinSpareLOut1; // spare low current output extern byte pinSpareLOut2; // spare low current output extern byte pinSpareLOut3; extern byte pinSpareLOut4; extern byte pinSpareLOut5; extern byte pinBoost; extern byte pinVVT_1; // vvt output 1 extern byte pinVVT_2; // vvt output 2 extern byte pinFan; // Cooling fan output extern byte pinStepperDir; //Direction pin for the stepper motor driver extern byte pinStepperStep; //Step pin for the stepper motor driver extern byte pinStepperEnable; //Turning the DRV8825 driver on/off extern byte pinLaunch; extern byte pinIgnBypass; //The pin used for an ignition bypass (Optional) extern byte pinFlex; //Pin with the flex sensor attached extern byte pinVSS; extern byte pinBaro; //Pin that an external barometric pressure sensor is attached to (If used) extern byte pinResetControl; // Output pin used control resetting the Arduino extern byte pinFuelPressure; extern byte pinOilPressure; extern byte pinWMIEmpty; // Water tank empty sensor extern byte pinWMIIndicator; // No water indicator bulb extern byte pinWMIEnabled; // ON-OFF output to relay/pump/solenoid extern byte pinMC33810_1_CS; extern byte pinMC33810_2_CS; extern byte pinSDEnable; //Input for manually enabling SD logging #ifdef USE_SPI_EEPROM extern byte pinSPIFlash_CS; #endif extern byte pinAirConComp; // Air conditioning compressor output extern byte pinAirConFan; // Stand-alone air conditioning fan output extern byte pinAirConRequest; // Air conditioning request input /* global variables */ // from speeduino.ino //#ifndef UNIT_TEST //#endif extern struct statuses currentStatus; //The global status object extern struct config2 configPage2; extern struct config4 configPage4; extern struct config6 configPage6; extern struct config9 configPage9; extern struct config10 configPage10; extern struct config13 configPage13; extern struct config15 configPage15; //extern byte cltCalibrationTable[CALIBRATION_TABLE_SIZE]; /**< An array containing the coolant sensor calibration values */ //extern byte iatCalibrationTable[CALIBRATION_TABLE_SIZE]; /**< An array containing the inlet air temperature sensor calibration values */ //extern byte o2CalibrationTable[CALIBRATION_TABLE_SIZE]; /**< An array containing the O2 sensor calibration values */ extern uint16_t cltCalibration_bins[32]; extern uint16_t cltCalibration_values[32]; extern uint16_t iatCalibration_bins[32]; extern uint16_t iatCalibration_values[32]; extern uint16_t o2Calibration_bins[32]; extern uint8_t o2Calibration_values[32]; // Note 8-bit values extern struct table2D cltCalibrationTable; /**< A 32 bin array containing the coolant temperature sensor calibration values */ extern struct table2D iatCalibrationTable; /**< A 32 bin array containing the inlet air temperature sensor calibration values */ extern struct table2D o2CalibrationTable; /**< A 32 bin array containing the O2 sensor calibration values */ bool pinIsOutput(byte pin); bool pinIsUsed(byte pin); #endif // GLOBALS_H
73,168
C++
.h
1,376
50.681686
410
0.732468
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,161
speeduino.h
oelprinz-org_BlitzboxBL49sp/software/202310/speeduino-202310/speeduino/speeduino.h
/** \file speeduino.h * @brief Speeduino main file containing initial setup and system loop functions * @author Josh Stewart * * This file contains the main system loop of the Speeduino core and thus much of the logic of the fuel and ignition algorithms is contained within this * It is where calls to all the auxiliary control systems, sensor reads, comms etc are made * * It also contains the setup() function that is called by the bootloader on system startup * */ #ifndef SPEEDUINO_H #define SPEEDUINO_H //#include "globals.h" #define CRANK_RUN_HYSTER 15 void setup(void); void loop(void); uint16_t PW(int REQ_FUEL, byte VE, long MAP, uint16_t corrections, int injOpen); byte getVE1(void); byte getAdvance1(void); void calculateStaging(uint32_t); void checkLaunchAndFlatShift(); extern uint16_t req_fuel_uS; /**< The required fuel variable (As calculated by TunerStudio) in uS */ extern uint16_t inj_opentime_uS; /**< The injector opening time. This is set within Tuner Studio, but stored here in uS rather than mS */ /** @name Staging * These values are a percentage of the total (Combined) req_fuel value that would be required for each injector channel to deliver that much fuel. * * Eg: * - Pri injectors are 250cc * - Sec injectors are 500cc * - Total injector capacity = 750cc * * - staged_req_fuel_mult_pri = 300% (The primary injectors would have to run 3x the overall PW in order to be the equivalent of the full 750cc capacity * - staged_req_fuel_mult_sec = 150% (The secondary injectors would have to run 1.5x the overall PW in order to be the equivalent of the full 750cc capacity */ ///@{ extern uint16_t staged_req_fuel_mult_pri; extern uint16_t staged_req_fuel_mult_sec; ///@} #endif
1,746
C++
.h
39
42.871795
157
0.75515
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,162
board_stm32_official.h
oelprinz-org_BlitzboxBL49sp/software/202310/speeduino-202310/speeduino/board_stm32_official.h
#ifndef STM32OFFICIAL_H #define STM32OFFICIAL_H #include <Arduino.h> #if defined(STM32_CORE_VERSION_MAJOR) #include <HardwareTimer.h> #include <HardwareSerial.h> #include "STM32RTC.h" #include <SPI.h> #if defined(STM32F1) #include "stm32f1xx_ll_tim.h" #elif defined(STM32F3) #include "stm32f3xx_ll_tim.h" #elif defined(STM32F4) #include "stm32f4xx_ll_tim.h" #else /*Default should be STM32F4*/ #include "stm32f4xx_ll_tim.h" #endif /* *********************************************************************************************************** * General */ #define PORT_TYPE uint32_t #define PINMASK_TYPE uint32_t #define COMPARE_TYPE uint16_t #define COUNTER_TYPE uint16_t #define SERIAL_BUFFER_SIZE 517 //Size of the serial buffer used by new comms protocol. For SD transfers this must be at least 512 + 1 (flag) + 4 (sector) #define FPU_MAX_SIZE 32 //Size of the FPU buffer. 0 means no FPU. #define micros_safe() micros() //timer5 method is not used on anything but AVR, the micros_safe() macro is simply an alias for the normal micros() #define TIMER_RESOLUTION 4 #if defined(USER_BTN) #define EEPROM_RESET_PIN USER_BTN //onboard key0 for black STM32F407 boards and blackpills, keep pressed during boot to reset eeprom #endif #if defined(STM32F407xx) //Comment out this to disable SD logging for STM32 if needed. Currently SD logging for STM32 is experimental feature for F407. #define SD_LOGGING #endif #if defined SD_LOGGING #define RTC_ENABLED //SD logging with STM32 uses SD card in SPI mode, because used SD library doesn't support SDIO implementation. By default SPI3 is used that uses same pins as SDIO also, but in different order. extern SPIClass SD_SPI; //SPI3_MOSI, SPI3_MISO, SPI3_SCK #define SD_CONFIG SdSpiConfig(SD_CS_PIN, DEDICATED_SPI, SD_SCK_MHZ(50), &SD_SPI) //Alternatively same SPI bus can be used as there is for SPI flash. But this is not recommended due to slower speed and other possible problems. //#define SD_CONFIG SdSpiConfig(SD_CS_PIN, SHARED_SPI, SD_SCK_MHZ(50), &SPI_for_flash) #endif #define USE_SERIAL3 //When building for Black board Serial1 is instantiated,building generic STM32F4x7 has serial2 and serial 1 must be done here #if SERIAL_UART_INSTANCE==2 HardwareSerial Serial1(PA10, PA9); #endif extern STM32RTC& rtc; void initBoard(); uint16_t freeRam(); void doSystemReset(); void jumpToBootloader(); extern "C" char* sbrk(int incr); #if defined(ARDUINO_BLUEPILL_F103C8) || defined(ARDUINO_BLUEPILL_F103CB) \ || defined(ARDUINO_BLACKPILL_F401CC) || defined(ARDUINO_BLACKPILL_F411CE) #define pinIsReserved(pin) ( ((pin) == PA11) || ((pin) == PA12) || ((pin) == PC14) || ((pin) == PC15) ) #ifndef PB11 //Hack for F4 BlackPills #define PB11 PB10 #endif //Hack to allow compilation on small STM boards #ifndef A10 #define A10 PA0 #define A11 PA1 #define A12 PA2 #define A13 PA3 #define A14 PA4 #define A15 PA5 #endif #else #ifdef USE_SPI_EEPROM #define pinIsReserved(pin) ( ((pin) == PA11) || ((pin) == PA12) || ((pin) == PB3) || ((pin) == PB4) || ((pin) == PB5) || ((pin) == USE_SPI_EEPROM) ) //Forbidden pins like USB #else #define pinIsReserved(pin) ( ((pin) == PA11) || ((pin) == PA12) || ((pin) == PB3) || ((pin) == PB4) || ((pin) == PB5) || ((pin) == PB0) ) //Forbidden pins like USB #endif #endif #define PWM_FAN_AVAILABLE #ifndef LED_BUILTIN #define LED_BUILTIN PA7 #endif /* *********************************************************************************************************** * EEPROM emulation */ #if defined(SRAM_AS_EEPROM) #define EEPROM_LIB_H "src/BackupSram/BackupSramAsEEPROM.h" typedef uint16_t eeprom_address_t; #include EEPROM_LIB_H extern BackupSramAsEEPROM EEPROM; #elif defined(USE_SPI_EEPROM) #define EEPROM_LIB_H "src/SPIAsEEPROM/SPIAsEEPROM.h" typedef uint16_t eeprom_address_t; #include EEPROM_LIB_H extern SPIClass SPI_for_flash; //SPI1_MOSI, SPI1_MISO, SPI1_SCK //windbond W25Q16 SPI flash EEPROM emulation extern EEPROM_Emulation_Config EmulatedEEPROMMconfig; extern Flash_SPI_Config SPIconfig; extern SPI_EEPROM_Class EEPROM; #elif defined(FRAM_AS_EEPROM) //https://github.com/VitorBoss/FRAM #define EEPROM_LIB_H "src/FRAM/Fram.h" typedef uint16_t eeprom_address_t; #include EEPROM_LIB_H #if defined(STM32F407xx) extern FramClass EEPROM; /*(mosi, miso, sclk, ssel, clockspeed) 31/01/2020*/ #else extern FramClass EEPROM; //Blue/Black Pills #endif #else //default case, internal flash as EEPROM #define EEPROM_LIB_H "src/SPIAsEEPROM/SPIAsEEPROM.h" typedef uint16_t eeprom_address_t; #include EEPROM_LIB_H extern InternalSTM32F4_EEPROM_Class EEPROM; #if defined(STM32F401xC) #define SMALL_FLASH_MODE #endif #endif #define RTC_LIB_H "STM32RTC.h" /* *********************************************************************************************************** * Schedules * Timers Table for STM32F1 * TIMER1 TIMER2 TIMER3 TIMER4 * 1 - FAN 1 - INJ1 1 - IGN1 1 - oneMSInterval * 2 - BOOST 2 - INJ2 2 - IGN2 2 - * 3 - VVT 3 - INJ3 3 - IGN3 3 - * 4 - IDLE 4 - INJ4 4 - IGN4 4 - * * Timers Table for STM32F4 * TIMER1 | TIMER2 | TIMER3 | TIMER4 | TIMER5 | TIMER11 * 1 - FAN |1 - INJ1 |1 - IGN1 |1 - IGN5 |1 - INJ5 |1 - oneMSInterval * 2 - BOOST |2 - INJ2 |2 - IGN2 |2 - IGN6 |2 - INJ6 | * 3 - VVT |3 - INJ3 |3 - IGN3 |3 - IGN7 |3 - INJ7 | * 4 - IDLE |4 - INJ4 |4 - IGN4 |4 - IGN8 |4 - INJ8 | */ #define MAX_TIMER_PERIOD 65535*4 //The longest period of time (in uS) that the timer can permit (IN this case it is 65535 * 4, as each timer tick is 4uS) #define uS_TO_TIMER_COMPARE(uS) (uS>>2) //Converts a given number of uS into the required number of timer ticks until that time has passed. #define FUEL1_COUNTER (TIM3)->CNT #define FUEL2_COUNTER (TIM3)->CNT #define FUEL3_COUNTER (TIM3)->CNT #define FUEL4_COUNTER (TIM3)->CNT #define FUEL1_COMPARE (TIM3)->CCR1 #define FUEL2_COMPARE (TIM3)->CCR2 #define FUEL3_COMPARE (TIM3)->CCR3 #define FUEL4_COMPARE (TIM3)->CCR4 #define IGN1_COUNTER (TIM2)->CNT #define IGN2_COUNTER (TIM2)->CNT #define IGN3_COUNTER (TIM2)->CNT #define IGN4_COUNTER (TIM2)->CNT #define IGN1_COMPARE (TIM2)->CCR1 #define IGN2_COMPARE (TIM2)->CCR2 #define IGN3_COMPARE (TIM2)->CCR3 #define IGN4_COMPARE (TIM2)->CCR4 #define FUEL5_COUNTER (TIM5)->CNT #define FUEL6_COUNTER (TIM5)->CNT #define FUEL7_COUNTER (TIM5)->CNT #define FUEL8_COUNTER (TIM5)->CNT #define FUEL5_COMPARE (TIM5)->CCR1 #define FUEL6_COMPARE (TIM5)->CCR2 #define FUEL7_COMPARE (TIM5)->CCR3 #define FUEL8_COMPARE (TIM5)->CCR4 #define IGN5_COUNTER (TIM4)->CNT #define IGN6_COUNTER (TIM4)->CNT #define IGN7_COUNTER (TIM4)->CNT #define IGN8_COUNTER (TIM4)->CNT #define IGN5_COMPARE (TIM4)->CCR1 #define IGN6_COMPARE (TIM4)->CCR2 #define IGN7_COMPARE (TIM4)->CCR3 #define IGN8_COMPARE (TIM4)->CCR4 #define FUEL1_TIMER_ENABLE() (TIM3)->CR1 |= TIM_CR1_CEN; (TIM3)->SR = ~TIM_FLAG_CC1; (TIM3)->DIER |= TIM_DIER_CC1IE #define FUEL2_TIMER_ENABLE() (TIM3)->CR1 |= TIM_CR1_CEN; (TIM3)->SR = ~TIM_FLAG_CC2; (TIM3)->DIER |= TIM_DIER_CC2IE #define FUEL3_TIMER_ENABLE() (TIM3)->CR1 |= TIM_CR1_CEN; (TIM3)->SR = ~TIM_FLAG_CC3; (TIM3)->DIER |= TIM_DIER_CC3IE #define FUEL4_TIMER_ENABLE() (TIM3)->CR1 |= TIM_CR1_CEN; (TIM3)->SR = ~TIM_FLAG_CC4; (TIM3)->DIER |= TIM_DIER_CC4IE #define FUEL1_TIMER_DISABLE() (TIM3)->DIER &= ~TIM_DIER_CC1IE #define FUEL2_TIMER_DISABLE() (TIM3)->DIER &= ~TIM_DIER_CC2IE #define FUEL3_TIMER_DISABLE() (TIM3)->DIER &= ~TIM_DIER_CC3IE #define FUEL4_TIMER_DISABLE() (TIM3)->DIER &= ~TIM_DIER_CC4IE #define IGN1_TIMER_ENABLE() (TIM2)->CR1 |= TIM_CR1_CEN; (TIM2)->SR = ~TIM_FLAG_CC1; (TIM2)->DIER |= TIM_DIER_CC1IE #define IGN2_TIMER_ENABLE() (TIM2)->CR1 |= TIM_CR1_CEN; (TIM2)->SR = ~TIM_FLAG_CC2; (TIM2)->DIER |= TIM_DIER_CC2IE #define IGN3_TIMER_ENABLE() (TIM2)->CR1 |= TIM_CR1_CEN; (TIM2)->SR = ~TIM_FLAG_CC3; (TIM2)->DIER |= TIM_DIER_CC3IE #define IGN4_TIMER_ENABLE() (TIM2)->CR1 |= TIM_CR1_CEN; (TIM2)->SR = ~TIM_FLAG_CC4; (TIM2)->DIER |= TIM_DIER_CC4IE #define IGN1_TIMER_DISABLE() (TIM2)->DIER &= ~TIM_DIER_CC1IE #define IGN2_TIMER_DISABLE() (TIM2)->DIER &= ~TIM_DIER_CC2IE #define IGN3_TIMER_DISABLE() (TIM2)->DIER &= ~TIM_DIER_CC3IE #define IGN4_TIMER_DISABLE() (TIM2)->DIER &= ~TIM_DIER_CC4IE #define FUEL5_TIMER_ENABLE() (TIM5)->CR1 |= TIM_CR1_CEN; (TIM5)->CR1 |= TIM_CR1_CEN; (TIM5)->SR = ~TIM_FLAG_CC1; (TIM5)->DIER |= TIM_DIER_CC1IE #define FUEL6_TIMER_ENABLE() (TIM5)->CR1 |= TIM_CR1_CEN; (TIM5)->CR1 |= TIM_CR1_CEN; (TIM5)->SR = ~TIM_FLAG_CC2; (TIM5)->DIER |= TIM_DIER_CC2IE #define FUEL7_TIMER_ENABLE() (TIM5)->CR1 |= TIM_CR1_CEN; (TIM5)->CR1 |= TIM_CR1_CEN; (TIM5)->SR = ~TIM_FLAG_CC3; (TIM5)->DIER |= TIM_DIER_CC3IE #define FUEL8_TIMER_ENABLE() (TIM5)->CR1 |= TIM_CR1_CEN; (TIM5)->CR1 |= TIM_CR1_CEN; (TIM5)->SR = ~TIM_FLAG_CC4; (TIM5)->DIER |= TIM_DIER_CC4IE #define FUEL5_TIMER_DISABLE() (TIM5)->DIER &= ~TIM_DIER_CC1IE #define FUEL6_TIMER_DISABLE() (TIM5)->DIER &= ~TIM_DIER_CC2IE #define FUEL7_TIMER_DISABLE() (TIM5)->DIER &= ~TIM_DIER_CC3IE #define FUEL8_TIMER_DISABLE() (TIM5)->DIER &= ~TIM_DIER_CC4IE #define IGN5_TIMER_ENABLE() (TIM4)->CR1 |= TIM_CR1_CEN; (TIM4)->SR = ~TIM_FLAG_CC1; (TIM4)->DIER |= TIM_DIER_CC1IE #define IGN6_TIMER_ENABLE() (TIM4)->CR1 |= TIM_CR1_CEN; (TIM4)->SR = ~TIM_FLAG_CC2; (TIM4)->DIER |= TIM_DIER_CC2IE #define IGN7_TIMER_ENABLE() (TIM4)->CR1 |= TIM_CR1_CEN; (TIM4)->SR = ~TIM_FLAG_CC3; (TIM4)->DIER |= TIM_DIER_CC3IE #define IGN8_TIMER_ENABLE() (TIM4)->CR1 |= TIM_CR1_CEN; (TIM4)->SR = ~TIM_FLAG_CC4; (TIM4)->DIER |= TIM_DIER_CC4IE #define IGN5_TIMER_DISABLE() (TIM4)->DIER &= ~TIM_DIER_CC1IE #define IGN6_TIMER_DISABLE() (TIM4)->DIER &= ~TIM_DIER_CC2IE #define IGN7_TIMER_DISABLE() (TIM4)->DIER &= ~TIM_DIER_CC3IE #define IGN8_TIMER_DISABLE() (TIM4)->DIER &= ~TIM_DIER_CC4IE /* *********************************************************************************************************** * Auxiliaries */ #define ENABLE_BOOST_TIMER() (TIM1)->SR = ~TIM_FLAG_CC2; (TIM1)->DIER |= TIM_DIER_CC2IE; (TIM1)->CR1 |= TIM_CR1_CEN; #define DISABLE_BOOST_TIMER() (TIM1)->DIER &= ~TIM_DIER_CC2IE #define ENABLE_VVT_TIMER() (TIM1)->SR = ~TIM_FLAG_CC3; (TIM1)->DIER |= TIM_DIER_CC3IE; (TIM1)->CR1 |= TIM_CR1_CEN; #define DISABLE_VVT_TIMER() (TIM1)->DIER &= ~TIM_DIER_CC3IE #define ENABLE_FAN_TIMER() (TIM1)->SR = ~TIM_FLAG_CC1; (TIM1)->DIER |= TIM_DIER_CC1IE; (TIM1)->CR1 |= TIM_CR1_CEN; #define DISABLE_FAN_TIMER() (TIM1)->DIER &= ~TIM_DIER_CC1IE #define BOOST_TIMER_COMPARE (TIM1)->CCR2 #define BOOST_TIMER_COUNTER (TIM1)->CNT #define VVT_TIMER_COMPARE (TIM1)->CCR3 #define VVT_TIMER_COUNTER (TIM1)->CNT #define FAN_TIMER_COMPARE (TIM1)->CCR1 #define FAN_TIMER_COUNTER (TIM1)->CNT /* *********************************************************************************************************** * Idle */ #define IDLE_COUNTER (TIM1)->CNT #define IDLE_COMPARE (TIM1)->CCR4 #define IDLE_TIMER_ENABLE() (TIM1)->SR = ~TIM_FLAG_CC4; (TIM1)->DIER |= TIM_DIER_CC4IE; (TIM1)->CR1 |= TIM_CR1_CEN; #define IDLE_TIMER_DISABLE() (TIM1)->DIER &= ~TIM_DIER_CC4IE /* *********************************************************************************************************** * Timers */ extern HardwareTimer Timer1; extern HardwareTimer Timer2; extern HardwareTimer Timer3; extern HardwareTimer Timer4; #if !defined(ARDUINO_BLUEPILL_F103C8) && !defined(ARDUINO_BLUEPILL_F103CB) //F103 just have 4 timers extern HardwareTimer Timer5; #if defined(TIM11) extern HardwareTimer Timer11; #elif defined(TIM7) extern HardwareTimer Timer11; #endif #endif #if ((STM32_CORE_VERSION_MINOR<=8) & (STM32_CORE_VERSION_MAJOR==1)) void oneMSInterval(HardwareTimer*); void boostInterrupt(HardwareTimer*); void fuelSchedule1Interrupt(HardwareTimer*); void fuelSchedule2Interrupt(HardwareTimer*); void fuelSchedule3Interrupt(HardwareTimer*); void fuelSchedule4Interrupt(HardwareTimer*); #if (INJ_CHANNELS >= 5) void fuelSchedule5Interrupt(HardwareTimer*); #endif #if (INJ_CHANNELS >= 6) void fuelSchedule6Interrupt(HardwareTimer*); #endif #if (INJ_CHANNELS >= 7) void fuelSchedule7Interrupt(HardwareTimer*); #endif #if (INJ_CHANNELS >= 8) void fuelSchedule8Interrupt(HardwareTimer*); #endif void idleInterrupt(HardwareTimer*); void vvtInterrupt(HardwareTimer*); void fanInterrupt(HardwareTimer*); void ignitionSchedule1Interrupt(HardwareTimer*); void ignitionSchedule2Interrupt(HardwareTimer*); void ignitionSchedule3Interrupt(HardwareTimer*); void ignitionSchedule4Interrupt(HardwareTimer*); #if (IGN_CHANNELS >= 5) void ignitionSchedule5Interrupt(HardwareTimer*); #endif #if (IGN_CHANNELS >= 6) void ignitionSchedule6Interrupt(HardwareTimer*); #endif #if (IGN_CHANNELS >= 7) void ignitionSchedule7Interrupt(HardwareTimer*); #endif #if (IGN_CHANNELS >= 8) void ignitionSchedule8Interrupt(HardwareTimer*); #endif #endif //End core<=1.8 /* *********************************************************************************************************** * CAN / Second serial */ #if HAL_CAN_MODULE_ENABLED #define NATIVE_CAN_AVAILABLE #include <src/STM32_CAN/STM32_CAN.h> //This activates CAN1 interface on STM32, but it's named as Can0, because that's how Teensy implementation is done extern STM32_CAN Can0; static CAN_message_t outMsg; static CAN_message_t inMsg; #endif #endif //CORE_STM32 #endif //STM32_H
13,407
C++
.h
294
43.77551
194
0.673637
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,163
logger.h
oelprinz-org_BlitzboxBL49sp/software/202310/speeduino-202310/speeduino/logger.h
/** \file logger.h * @brief File for generating log files and meta data * @author Josh Stewart * * This file contains functions for creating a log file for use with by TunerStudio directly or to be written to an SD card * */ #ifndef LOGGER_H #define LOGGER_H #include <assert.h> #include "globals.h" // Needed for FPU_MAX_SIZE #ifndef UNIT_TEST // Scope guard for unit testing #define LOG_ENTRY_SIZE 127 /**< The size of the live data packet. This MUST match ochBlockSize setting in the ini file */ #define SD_LOG_ENTRY_SIZE 127 /**< The size of the live data packet used by the SD card.*/ #else #define LOG_ENTRY_SIZE 1 /**< The size of the live data packet. This MUST match ochBlockSize setting in the ini file */ #define SD_LOG_ENTRY_SIZE 1 /**< The size of the live data packet used by the SD card.*/ #endif #define SD_LOG_NUM_FIELDS 91 /**< The number of fields that are in the log. This is always smaller than the entry size due to some fields being 2 bytes */ byte getTSLogEntry(uint16_t byteNum); int16_t getReadableLogEntry(uint16_t logIndex); #if FPU_MAX_SIZE >= 32 float getReadableFloatLogEntry(uint16_t logIndex); #endif bool is2ByteEntry(uint8_t key); void startToothLogger(void); void stopToothLogger(void); void startCompositeLogger(void); void stopCompositeLogger(void); void startCompositeLoggerTertiary(void); void stopCompositeLoggerTertiary(void); void startCompositeLoggerCams(void); void stopCompositeLoggerCams(void); // This array indicates which index values from the log are 2 byte values // This array MUST remain in ascending order // !!!! WARNING: If any value above 255 is required in this array, changes MUST be made to is2ByteEntry() function !!!! const byte PROGMEM fsIntIndex[] = {4, 14, 17, 22, 26, 28, 33, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 76, 78, 80, 82, 86, 88, 90, 93, 95, 99, 104, 111, 121, 125 }; //List of logger field names. This must be in the same order and length as logger_updateLogdataCSV() const char header_0[] PROGMEM = "secl"; const char header_1[] PROGMEM = "status1"; const char header_2[] PROGMEM = "engine"; const char header_3[] PROGMEM = "Sync Loss #"; const char header_4[] PROGMEM = "MAP"; const char header_5[] PROGMEM = "IAT(C)"; const char header_6[] PROGMEM = "CLT(C)"; const char header_7[] PROGMEM = "Battery Correction"; const char header_8[] PROGMEM = "Battery V"; const char header_9[] PROGMEM = "AFR"; const char header_10[] PROGMEM = "EGO Correction"; const char header_11[] PROGMEM = "IAT Correction"; const char header_12[] PROGMEM = "WUE Correction"; const char header_13[] PROGMEM = "RPM"; const char header_14[] PROGMEM = "Accel. Correction"; const char header_15[] PROGMEM = "Gamma Correction"; const char header_16[] PROGMEM = "VE1"; const char header_17[] PROGMEM = "VE2"; const char header_18[] PROGMEM = "AFR Target"; const char header_19[] PROGMEM = "TPSdot"; const char header_20[] PROGMEM = "Advance Current"; const char header_21[] PROGMEM = "TPS"; const char header_22[] PROGMEM = "Loops/S"; const char header_23[] PROGMEM = "Free RAM"; const char header_24[] PROGMEM = "Boost Target"; const char header_25[] PROGMEM = "Boost Duty"; const char header_26[] PROGMEM = "status2"; const char header_27[] PROGMEM = "rpmDOT"; const char header_28[] PROGMEM = "Eth%"; const char header_29[] PROGMEM = "Flex Fuel Correction"; const char header_30[] PROGMEM = "Flex Adv Correction"; const char header_31[] PROGMEM = "IAC Steps/Duty"; const char header_32[] PROGMEM = "testoutputs"; const char header_33[] PROGMEM = "AFR2"; const char header_34[] PROGMEM = "Baro"; const char header_35[] PROGMEM = "AUX_IN 0"; const char header_36[] PROGMEM = "AUX_IN 1"; const char header_37[] PROGMEM = "AUX_IN 2"; const char header_38[] PROGMEM = "AUX_IN 3"; const char header_39[] PROGMEM = "AUX_IN 4"; const char header_40[] PROGMEM = "AUX_IN 5"; const char header_41[] PROGMEM = "AUX_IN 6"; const char header_42[] PROGMEM = "AUX_IN 7"; const char header_43[] PROGMEM = "AUX_IN 8"; const char header_44[] PROGMEM = "AUX_IN 9"; const char header_45[] PROGMEM = "AUX_IN 10"; const char header_46[] PROGMEM = "AUX_IN 11"; const char header_47[] PROGMEM = "AUX_IN 12"; const char header_48[] PROGMEM = "AUX_IN 13"; const char header_49[] PROGMEM = "AUX_IN 14"; const char header_50[] PROGMEM = "AUX_IN 15"; const char header_51[] PROGMEM = "TPS ADC"; const char header_52[] PROGMEM = "Errors"; const char header_53[] PROGMEM = "PW"; const char header_54[] PROGMEM = "PW2"; const char header_55[] PROGMEM = "PW3"; const char header_56[] PROGMEM = "PW4"; const char header_57[] PROGMEM = "status3"; const char header_58[] PROGMEM = "Engine Protect"; const char header_59[] PROGMEM = ""; const char header_60[] PROGMEM = "Fuel Load"; const char header_61[] PROGMEM = "Ign Load"; const char header_62[] PROGMEM = "Dwell Requested"; const char header_63[] PROGMEM = "Idle Target (RPM)"; const char header_64[] PROGMEM = "MAP DOT"; const char header_65[] PROGMEM = "VVT1 Angle"; const char header_66[] PROGMEM = "VVT1 Target"; const char header_67[] PROGMEM = "VVT1 Duty"; const char header_68[] PROGMEM = "Flex Boost Adj"; const char header_69[] PROGMEM = "Baro Correction"; const char header_70[] PROGMEM = "VE Current"; const char header_71[] PROGMEM = "ASE Correction"; const char header_72[] PROGMEM = "Vehicle Speed"; const char header_73[] PROGMEM = "Gear"; const char header_74[] PROGMEM = "Fuel Pressure"; const char header_75[] PROGMEM = "Oil Pressure"; const char header_76[] PROGMEM = "WMI PW"; const char header_77[] PROGMEM = "status4"; const char header_78[] PROGMEM = "VVT2 Angle"; const char header_79[] PROGMEM = "VVT2 Target"; const char header_80[] PROGMEM = "VVT2 Duty"; const char header_81[] PROGMEM = "outputs"; const char header_82[] PROGMEM = "Fuel Temp"; const char header_83[] PROGMEM = "Fuel Temp Correction"; const char header_84[] PROGMEM = "Advance 1"; const char header_85[] PROGMEM = "Advance 2"; const char header_86[] PROGMEM = "SD Status"; const char header_87[] PROGMEM = "EMAP"; const char header_88[] PROGMEM = "Fan Duty"; const char header_89[] PROGMEM = "AirConStatus"; const char header_90[] PROGMEM = "Dwell Actual"; /* const char header_91[] PROGMEM = ""; const char header_92[] PROGMEM = ""; const char header_93[] PROGMEM = ""; const char header_94[] PROGMEM = ""; const char header_95[] PROGMEM = ""; const char header_96[] PROGMEM = ""; const char header_97[] PROGMEM = ""; const char header_98[] PROGMEM = ""; const char header_99[] PROGMEM = ""; const char header_100[] PROGMEM = ""; const char header_101[] PROGMEM = ""; const char header_102[] PROGMEM = ""; const char header_103[] PROGMEM = ""; const char header_104[] PROGMEM = ""; const char header_105[] PROGMEM = ""; const char header_106[] PROGMEM = ""; const char header_107[] PROGMEM = ""; const char header_108[] PROGMEM = ""; const char header_109[] PROGMEM = ""; const char header_110[] PROGMEM = ""; const char header_111[] PROGMEM = ""; const char header_112[] PROGMEM = ""; const char header_113[] PROGMEM = ""; const char header_114[] PROGMEM = ""; const char header_115[] PROGMEM = ""; const char header_116[] PROGMEM = ""; const char header_117[] PROGMEM = ""; const char header_118[] PROGMEM = ""; const char header_119[] PROGMEM = ""; const char header_120[] PROGMEM = ""; const char header_121[] PROGMEM = ""; */ const char* const header_table[] PROGMEM = { header_0,\ header_1,\ header_2,\ header_3,\ header_4,\ header_5,\ header_6,\ header_7,\ header_8,\ header_9,\ header_10,\ header_11,\ header_12,\ header_13,\ header_14,\ header_15,\ header_16,\ header_17,\ header_18,\ header_19,\ header_20,\ header_21,\ header_22,\ header_23,\ header_24,\ header_25,\ header_26,\ header_27,\ header_28,\ header_29,\ header_30,\ header_31,\ header_32,\ header_33,\ header_34,\ header_35,\ header_36,\ header_37,\ header_38,\ header_39,\ header_40,\ header_41,\ header_42,\ header_43,\ header_44,\ header_45,\ header_46,\ header_47,\ header_48,\ header_49,\ header_50,\ header_51,\ header_52,\ header_53,\ header_54,\ header_55,\ header_56,\ header_57,\ header_58,\ header_59,\ header_60,\ header_61,\ header_62,\ header_63,\ header_64,\ header_65,\ header_66,\ header_67,\ header_68,\ header_69,\ header_70,\ header_71,\ header_72,\ header_73,\ header_74,\ header_75,\ header_76,\ header_77,\ header_78,\ header_79,\ header_80,\ header_81,\ header_82,\ header_83,\ header_84,\ header_85,\ header_86,\ header_87,\ header_88,\ header_89,\ header_90,\ /* header_91,\ header_92,\ header_93,\ header_94,\ header_95,\ header_96,\ header_97,\ header_98,\ header_99,\ header_100,\ header_101,\ header_102,\ header_103,\ header_104,\ header_105,\ header_106,\ header_107,\ header_108,\ header_109,\ header_110,\ header_111,\ header_112,\ header_113,\ header_114,\ header_115,\ header_116,\ header_117,\ header_118,\ header_119,\ header_120,\ header_121,\ */ }; static_assert(sizeof(header_table) == (sizeof(char*) * SD_LOG_NUM_FIELDS), "Number of header table titles must match number of log fields"); #endif
14,750
C++
.h
289
30.197232
187
0.433239
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,164
table2d.h
oelprinz-org_BlitzboxBL49sp/software/202310/speeduino-202310/speeduino/table2d.h
/* This file is used for everything related to maps/tables including their definition, functions etc */ #ifndef TABLE_H #define TABLE_H #define SIZE_SIGNED_BYTE 4 #define SIZE_BYTE 8 #define SIZE_INT 16 /* The 2D table can contain either 8-bit (byte) or 16-bit (int) values The valueSize variable should be set to either 8 or 16 to indicate this BEFORE the table is used */ struct table2D { //Used 5414 RAM with original version byte valueSize; byte axisSize; byte xSize; void *values; void *axisX; //int16_t *values16; //int16_t *axisX16; //Store the last X and Y coordinates in the table. This is used to make the next check faster int16_t lastXMax; int16_t lastXMin; //Store the last input and output for caching int16_t lastInput; int16_t lastOutput; byte cacheTime; //Tracks when the last cache value was set so it can expire after x seconds. A timeout is required to pickup when a tuning value is changed, otherwise the old cached value will continue to be returned as the X value isn't changing. }; int16_t table2D_getAxisValue(struct table2D *fromTable, byte X_in); int16_t table2D_getRawValue(struct table2D *fromTable, byte X_index); int table2D_getValue(struct table2D *fromTable, int X_in); #endif // TABLE_H
1,285
C++
.h
33
36.727273
250
0.754626
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,165
comms_secondary.h
oelprinz-org_BlitzboxBL49sp/software/202310/speeduino-202310/speeduino/comms_secondary.h
#ifndef COMMS_SECONDARY_H #define COMMS_SECONDARY_H #define NEW_CAN_PACKET_SIZE 123 #define CAN_PACKET_SIZE 75 #define SECONDARY_SERIAL_PROTO_GENERIC 0 #define SECONDARY_SERIAL_PROTO_CAN 1 #define SECONDARY_SERIAL_PROTO_MSDROID 2 #define SECONDARY_SERIAL_PROTO_REALDASH 3 #if ( defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) ) #define secondarySerial_AVAILABLE extern HardwareSerial &secondarySerial; #elif defined(CORE_STM32) #define secondarySerial_AVAILABLE #ifndef HAVE_HWSERIAL2 //Hack to get the code to compile on BlackPills #define Serial2 Serial1 #endif #if defined(STM32GENERIC) // STM32GENERIC core extern SerialUART &secondarySerial; #else //libmaple core aka STM32DUINO extern HardwareSerial &secondarySerial; #endif #elif defined(CORE_TEENSY) #define secondarySerial_AVAILABLE extern HardwareSerial &secondarySerial; #endif void secondserial_Command(void);//This is the heart of the Command Line Interpreter. All that needed to be done was to make it human readable. void can_Command(void); void sendCancommand(uint8_t cmdtype , uint16_t canadddress, uint8_t candata1, uint8_t candata2, uint16_t sourcecanAddress); void obd_response(uint8_t therequestedPID , uint8_t therequestedPIDlow, uint8_t therequestedPIDhigh); void readAuxCanBus(); #endif // COMMS_SECONDARY_H
1,342
C++
.h
31
41.096774
143
0.796325
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,166
schedule_calcs.h
oelprinz-org_BlitzboxBL49sp/software/202310/speeduino-202310/speeduino/schedule_calcs.h
#pragma once #include <stdint.h> #include "scheduler.h" extern byte channelInjEnabled; extern int ignition1StartAngle; extern int ignition1EndAngle; extern int channel1IgnDegrees; /**< The number of crank degrees until cylinder 1 is at TDC (This is obviously 0 for virtually ALL engines, but there's some weird ones) */ extern int ignition2StartAngle; extern int ignition2EndAngle; extern int channel2IgnDegrees; /**< The number of crank degrees until cylinder 2 (and 5/6/7/8) is at TDC */ extern int ignition3StartAngle; extern int ignition3EndAngle; extern int channel3IgnDegrees; /**< The number of crank degrees until cylinder 2 (and 5/6/7/8) is at TDC */ extern int ignition4StartAngle; extern int ignition4EndAngle; extern int channel4IgnDegrees; /**< The number of crank degrees until cylinder 2 (and 5/6/7/8) is at TDC */ #if (IGN_CHANNELS >= 5) extern int ignition5StartAngle; extern int ignition5EndAngle; extern int channel5IgnDegrees; /**< The number of crank degrees until cylinder 2 (and 5/6/7/8) is at TDC */ #endif #if (IGN_CHANNELS >= 6) extern int ignition6StartAngle; extern int ignition6EndAngle; extern int channel6IgnDegrees; /**< The number of crank degrees until cylinder 2 (and 5/6/7/8) is at TDC */ #endif #if (IGN_CHANNELS >= 7) extern int ignition7StartAngle; extern int ignition7EndAngle; extern int channel7IgnDegrees; /**< The number of crank degrees until cylinder 2 (and 5/6/7/8) is at TDC */ #endif #if (IGN_CHANNELS >= 8) extern int ignition8StartAngle; extern int ignition8EndAngle; extern int channel8IgnDegrees; /**< The number of crank degrees until cylinder 2 (and 5/6/7/8) is at TDC */ #endif extern int channel1InjDegrees; /**< The number of crank degrees until cylinder 1 is at TDC (This is obviously 0 for virtually ALL engines, but there's some weird ones) */ extern int channel2InjDegrees; /**< The number of crank degrees until cylinder 2 (and 5/6/7/8) is at TDC */ extern int channel3InjDegrees; /**< The number of crank degrees until cylinder 3 (and 5/6/7/8) is at TDC */ extern int channel4InjDegrees; /**< The number of crank degrees until cylinder 4 (and 5/6/7/8) is at TDC */ #if (INJ_CHANNELS >= 5) extern int channel5InjDegrees; /**< The number of crank degrees until cylinder 5 is at TDC */ #endif #if (INJ_CHANNELS >= 6) extern int channel6InjDegrees; /**< The number of crank degrees until cylinder 6 is at TDC */ #endif #if (INJ_CHANNELS >= 7) extern int channel7InjDegrees; /**< The number of crank degrees until cylinder 7 is at TDC */ #endif #if (INJ_CHANNELS >= 8) extern int channel8InjDegrees; /**< The number of crank degrees until cylinder 8 is at TDC */ #endif inline uint16_t __attribute__((always_inline)) calculateInjectorStartAngle(uint16_t PWdivTimerPerDegree, int16_t injChannelDegrees, uint16_t injAngle); inline uint32_t __attribute__((always_inline)) calculateInjectorTimeout(const FuelSchedule &schedule, int channelInjDegrees, int injectorStartAngle, int crankAngle); inline void __attribute__((always_inline)) calculateIgnitionAngle(const int dwellAngle, const uint16_t channelIgnDegrees, int8_t advance, int *pEndAngle, int *pStartAngle); // Ignition for rotary. inline void __attribute__((always_inline)) calculateIgnitionTrailingRotary(int dwellAngle, int rotarySplitDegrees, int leadIgnitionAngle, int *pEndAngle, int *pStartAngle); inline uint32_t __attribute__((always_inline)) calculateIgnitionTimeout(const Schedule &schedule, int startAngle, int channelIgnDegrees, int crankAngle); #include "schedule_calcs.hpp"
3,515
C++
.h
59
58.355932
173
0.779843
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,167
crankMaths.h
oelprinz-org_BlitzboxBL49sp/software/202310/speeduino-202310/speeduino/crankMaths.h
#ifndef CRANKMATHS_H #define CRANKMATHS_H #include "maths.h" #define CRANKMATH_METHOD_INTERVAL_DEFAULT 0 #define CRANKMATH_METHOD_INTERVAL_REV 1 #define CRANKMATH_METHOD_INTERVAL_TOOTH 2 #define CRANKMATH_METHOD_ALPHA_BETA 3 #define CRANKMATH_METHOD_2ND_DERIVATIVE 4 #define SECOND_DERIV_ENABLED 0 //#define fastDegreesToUS(targetDegrees) ((targetDegrees) * (unsigned long)timePerDegree) #define fastDegreesToUS(targetDegrees) (((targetDegrees) * (unsigned long)timePerDegreex16) >> 4) /*#define fastTimeToAngle(time) (((unsigned long)time * degreesPeruSx2048) / 2048) */ //Divide by 2048 will be converted at compile time to bitshift #define fastTimeToAngle(time) (((unsigned long)(time) * degreesPeruSx32768) / 32768) //Divide by 32768 will be converted at compile time to bitshift #define ignitionLimits(angle) ( (((int16_t)(angle)) >= CRANK_ANGLE_MAX_IGN) ? ((angle) - CRANK_ANGLE_MAX_IGN) : ( ((int16_t)(angle) < 0) ? ((angle) + CRANK_ANGLE_MAX_IGN) : (angle)) ) unsigned long angleToTime(uint16_t angle, byte method); inline unsigned long angleToTimeIntervalRev(uint16_t angle) { return div360(angle * revolutionTime); } uint16_t timeToAngle(unsigned long time, byte method); void doCrankSpeedCalcs(void); extern volatile uint16_t timePerDegree; extern volatile uint16_t timePerDegreex16; extern volatile unsigned long degreesPeruSx32768; #endif
1,408
C++
.h
24
56.75
183
0.760174
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,168
scheduler.h
oelprinz-org_BlitzboxBL49sp/software/202310/speeduino-202310/speeduino/scheduler.h
/** @file Injector and Ignition (on/off) scheduling (structs). This scheduler is designed to maintain 2 schedules for use by the fuel and ignition systems. It functions by waiting for the overflow vectors from each of the timers in use to overflow, which triggers an interrupt. ## Technical Currently I am prescaling the 16-bit timers to 256 for injection and 64 for ignition. This means that the counter increments every 16us (injection) / 4uS (ignition) and will overflow every 1048576uS. Max Period = (Prescale)*(1/Frequency)*(2^17) For more details see https://playground.arduino.cc/Code/Timer1/ (OLD: http://playground.arduino.cc/code/timer1 ). This means that the precision of the scheduler is: - 16uS (+/- 8uS of target) for fuel - 4uS (+/- 2uS) for ignition ## Features This differs from most other schedulers in that its calls are non-recurring (ie when you schedule an event at a certain time and once it has occurred, it will not reoccur unless you explicitly ask/re-register for it). Each timer can have only 1 callback associated with it at any given time. If you call the setCallback function a 2nd time, the original schedule will be overwritten and not occur. ## Timer identification Arduino timers usage for injection and ignition schedules: - timer3 is used for schedule 1(?) (fuel 1,2,3,4 ign 7,8) - timer4 is used for schedule 2(?) (fuel 5,6 ign 4,5,6) - timer5 is used ... (fuel 7,8, ign 1,2,3) Timers 3,4 and 5 are 16-bit timers (ie count to 65536). See page 136 of the processors datasheet: http://www.atmel.com/Images/doc2549.pdf . 256 prescale gives tick every 16uS. 256 prescale gives overflow every 1048576uS (This means maximum wait time is 1.0485 seconds). */ #ifndef SCHEDULER_H #define SCHEDULER_H #include "globals.h" #define USE_IGN_REFRESH #define IGNITION_REFRESH_THRESHOLD 30 //Time in uS that the refresh functions will check to ensure there is enough time before changing the end compare #define DWELL_AVERAGE_ALPHA 30 #define DWELL_AVERAGE(input) (((long)input * (256 - DWELL_AVERAGE_ALPHA) + ((long)currentStatus.actualDwell * DWELL_AVERAGE_ALPHA))) >> 8 //#define DWELL_AVERAGE(input) (currentStatus.dwell) //Can be use to disable the above for testing extern void (*inj1StartFunction)(void); extern void (*inj1EndFunction)(void); extern void (*inj2StartFunction)(void); extern void (*inj2EndFunction)(void); extern void (*inj3StartFunction)(void); extern void (*inj3EndFunction)(void); extern void (*inj4StartFunction)(void); extern void (*inj4EndFunction)(void); extern void (*inj5StartFunction)(void); extern void (*inj5EndFunction)(void); extern void (*inj6StartFunction)(void); extern void (*inj6EndFunction)(void); extern void (*inj7StartFunction)(void); extern void (*inj7EndFunction)(void); extern void (*inj8StartFunction)(void); extern void (*inj8EndFunction)(void); /** @name IgnitionCallbacks * These are the (global) function pointers that get called to begin and end the ignition coil charging. * They are required for the various spark output modes. * @{ */ extern void (*ign1StartFunction)(void); extern void (*ign1EndFunction)(void); extern void (*ign2StartFunction)(void); extern void (*ign2EndFunction)(void); extern void (*ign3StartFunction)(void); extern void (*ign3EndFunction)(void); extern void (*ign4StartFunction)(void); extern void (*ign4EndFunction)(void); extern void (*ign5StartFunction)(void); extern void (*ign5EndFunction)(void); extern void (*ign6StartFunction)(void); extern void (*ign6EndFunction)(void); extern void (*ign7StartFunction)(void); extern void (*ign7EndFunction)(void); extern void (*ign8StartFunction)(void); extern void (*ign8EndFunction)(void); /** @} */ void initialiseSchedulers(void); void beginInjectorPriming(void); void setFuelSchedule1(unsigned long timeout, unsigned long duration); void setFuelSchedule2(unsigned long timeout, unsigned long duration); void setFuelSchedule3(unsigned long timeout, unsigned long duration); void setFuelSchedule4(unsigned long timeout, unsigned long duration); //void setFuelSchedule5(void (*startCallback)(), unsigned long timeout, unsigned long duration, void(*endCallback)()); //Schedule 5 remains a special case for now due to the way it's implemented void setFuelSchedule5(unsigned long timeout, unsigned long duration); void setFuelSchedule6(unsigned long timeout, unsigned long duration); void setFuelSchedule7(unsigned long timeout, unsigned long duration); void setFuelSchedule8(unsigned long timeout, unsigned long duration); void setIgnitionSchedule1(void (*startCallback)(), unsigned long timeout, unsigned long duration, void(*endCallback)()); void setIgnitionSchedule2(void (*startCallback)(), unsigned long timeout, unsigned long duration, void(*endCallback)()); void setIgnitionSchedule3(void (*startCallback)(), unsigned long timeout, unsigned long duration, void(*endCallback)()); void setIgnitionSchedule4(void (*startCallback)(), unsigned long timeout, unsigned long duration, void(*endCallback)()); void setIgnitionSchedule5(void (*startCallback)(), unsigned long timeout, unsigned long duration, void(*endCallback)()); void setIgnitionSchedule6(void (*startCallback)(), unsigned long timeout, unsigned long duration, void(*endCallback)()); void setIgnitionSchedule7(void (*startCallback)(), unsigned long timeout, unsigned long duration, void(*endCallback)()); void setIgnitionSchedule8(void (*startCallback)(), unsigned long timeout, unsigned long duration, void(*endCallback)()); void disablePendingFuelSchedule(byte channel); void disablePendingIgnSchedule(byte channel); inline void refreshIgnitionSchedule1(unsigned long timeToEnd) __attribute__((always_inline)); //The ARM cores use separate functions for their ISRs #if defined(ARDUINO_ARCH_STM32) || defined(CORE_TEENSY) inline void fuelSchedule1Interrupt(void); inline void fuelSchedule2Interrupt(void); inline void fuelSchedule3Interrupt(void); inline void fuelSchedule4Interrupt(void); #if (INJ_CHANNELS >= 5) inline void fuelSchedule5Interrupt(void); #endif #if (INJ_CHANNELS >= 6) inline void fuelSchedule6Interrupt(void); #endif #if (INJ_CHANNELS >= 7) inline void fuelSchedule7Interrupt(void); #endif #if (INJ_CHANNELS >= 8) inline void fuelSchedule8Interrupt(void); #endif #if (IGN_CHANNELS >= 1) inline void ignitionSchedule1Interrupt(void); #endif #if (IGN_CHANNELS >= 2) inline void ignitionSchedule2Interrupt(void); #endif #if (IGN_CHANNELS >= 3) inline void ignitionSchedule3Interrupt(void); #endif #if (IGN_CHANNELS >= 4) inline void ignitionSchedule4Interrupt(void); #endif #if (IGN_CHANNELS >= 5) inline void ignitionSchedule5Interrupt(void); #endif #if (IGN_CHANNELS >= 6) inline void ignitionSchedule6Interrupt(void); #endif #if (IGN_CHANNELS >= 7) inline void ignitionSchedule7Interrupt(void); #endif #if (IGN_CHANNELS >= 8) inline void ignitionSchedule8Interrupt(void); #endif #endif /** Schedule statuses. * - OFF - Schedule turned off and there is no scheduled plan * - PENDING - There's a scheduled plan, but is has not started to run yet * - STAGED - (???, Not used) * - RUNNING - Schedule is currently running */ enum ScheduleStatus {OFF, PENDING, STAGED, RUNNING}; //The statuses that a schedule can have /** Ignition schedule. */ struct Schedule { volatile unsigned long duration;///< Scheduled duration (uS ?) volatile ScheduleStatus Status; ///< Schedule status: OFF, PENDING, STAGED, RUNNING volatile byte schedulesSet; ///< A counter of how many times the schedule has been set void (*StartCallback)(); ///< Start Callback function for schedule void (*EndCallback)(); ///< End Callback function for schedule volatile unsigned long startTime; /**< The system time (in uS) that the schedule started, used by the overdwell protection in timers.ino */ volatile COMPARE_TYPE startCompare; ///< The counter value of the timer when this will start volatile COMPARE_TYPE endCompare; ///< The counter value of the timer when this will end COMPARE_TYPE nextStartCompare; ///< Planned start of next schedule (when current schedule is RUNNING) COMPARE_TYPE nextEndCompare; ///< Planned end of next schedule (when current schedule is RUNNING) volatile bool hasNextSchedule = false; ///< Enable flag for planned next schedule (when current schedule is RUNNING) volatile bool endScheduleSetByDecoder = false; }; /** Fuel injection schedule. * Fuel schedules don't use the callback pointers, or the startTime/endScheduleSetByDecoder variables. * They are removed in this struct to save RAM. */ struct FuelSchedule { volatile unsigned long duration;///< Scheduled duration (uS ?) volatile ScheduleStatus Status; ///< Schedule status: OFF, PENDING, STAGED, RUNNING volatile byte schedulesSet; ///< A counter of how many times the schedule has been set volatile COMPARE_TYPE startCompare; ///< The counter value of the timer when this will start volatile COMPARE_TYPE endCompare; ///< The counter value of the timer when this will end COMPARE_TYPE nextStartCompare; COMPARE_TYPE nextEndCompare; volatile bool hasNextSchedule = false; }; //volatile Schedule *timer3Aqueue[4]; //Schedule *timer3Bqueue[4]; //Schedule *timer3Cqueue[4]; extern FuelSchedule fuelSchedule1; extern FuelSchedule fuelSchedule2; extern FuelSchedule fuelSchedule3; extern FuelSchedule fuelSchedule4; extern FuelSchedule fuelSchedule5; extern FuelSchedule fuelSchedule6; extern FuelSchedule fuelSchedule7; extern FuelSchedule fuelSchedule8; extern Schedule ignitionSchedule1; extern Schedule ignitionSchedule2; extern Schedule ignitionSchedule3; extern Schedule ignitionSchedule4; extern Schedule ignitionSchedule5; extern Schedule ignitionSchedule6; extern Schedule ignitionSchedule7; extern Schedule ignitionSchedule8; //IgnitionSchedule nullSchedule; //This is placed at the end of the queue. It's status will always be set to OFF and hence will never perform any action within an ISR static inline COMPARE_TYPE setQueue(volatile Schedule *queue[], Schedule *schedule1, Schedule *schedule2, unsigned int CNT) { //Create an array of all the upcoming targets, relative to the current count on the timer unsigned int tmpQueue[4]; //Set the initial queue state. This order matches the tmpQueue order if(schedule1->Status == OFF) { queue[0] = schedule2; queue[1] = schedule2; tmpQueue[0] = schedule2->startCompare - CNT; tmpQueue[1] = schedule2->endCompare - CNT; } else { queue[0] = schedule1; queue[1] = schedule1; tmpQueue[0] = schedule1->startCompare - CNT; tmpQueue[1] = schedule1->endCompare - CNT; } if(schedule2->Status == OFF) { queue[2] = schedule1; queue[3] = schedule1; tmpQueue[2] = schedule1->startCompare - CNT; tmpQueue[3] = schedule1->endCompare - CNT; } else { queue[2] = schedule2; queue[3] = schedule2; tmpQueue[2] = schedule2->startCompare - CNT; tmpQueue[3] = schedule2->endCompare - CNT; } //Sort the queues. Both queues are kept in sync. //This implements a sorting networking based on the Bose-Nelson sorting network //See: pages.ripco.net/~jgamble/nw.html #define SWAP(x,y) if(tmpQueue[y] < tmpQueue[x]) { unsigned int tmp = tmpQueue[x]; tmpQueue[x] = tmpQueue[y]; tmpQueue[y] = tmp; volatile Schedule *tmpS = queue[x]; queue[x] = queue[y]; queue[y] = tmpS; } /*SWAP(0, 1); */ //Likely not needed /*SWAP(2, 3); */ //Likely not needed SWAP(0, 2); SWAP(1, 3); SWAP(1, 2); //Return the next compare time in the queue return tmpQueue[0] + CNT; //Return the } /* * Moves all the Schedules in a queue forward one position. * The current item (0) is discarded * The final queue slot is set to nullSchedule to indicate that no action should be taken */ static inline unsigned int popQueue(volatile Schedule *queue[]) { queue[0] = queue[1]; queue[1] = queue[2]; queue[2] = queue[3]; //queue[3] = &nullSchedule; unsigned int returnCompare; if( queue[0]->Status == PENDING ) { returnCompare = queue[0]->startCompare; } else { returnCompare = queue[0]->endCompare; } return returnCompare; } #endif // SCHEDULER_H
12,121
C++
.h
257
45.143969
205
0.768691
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,169
schedule_calcs.hpp
oelprinz-org_BlitzboxBL49sp/software/202310/speeduino-202310/speeduino/schedule_calcs.hpp
// Note that all functions with an underscore prefix are NOT part // of the public API. They are only here so we can inline them. #include "scheduler.h" #include "crankMaths.h" inline uint16_t calculateInjectorStartAngle(uint16_t pwDegrees, int16_t injChannelDegrees, uint16_t injAngle) { // 0<=injAngle<=720° // 0<=injChannelDegrees<=720° // 0<pwDegrees<=??? (could be many crank rotations in the worst case!) // 45<=CRANK_ANGLE_MAX_INJ<=720 // (CRANK_ANGLE_MAX_INJ can be as small as 360/nCylinders. E.g. 45° for 8 cylinder) uint16_t startAngle = injAngle + injChannelDegrees; // Avoid underflow while (startAngle<pwDegrees) { startAngle = startAngle + CRANK_ANGLE_MAX_INJ; } // Guarenteed to be >=0. startAngle = startAngle - pwDegrees; // Clamp to 0<=startAngle<=CRANK_ANGLE_MAX_INJ while (startAngle>(uint16_t)CRANK_ANGLE_MAX_INJ) { startAngle = startAngle - CRANK_ANGLE_MAX_INJ; } return startAngle; } inline uint32_t _calculateInjectorTimeout(const FuelSchedule &schedule, uint16_t openAngle, uint16_t crankAngle) { int16_t delta = openAngle - crankAngle; if (delta<0) { if ((schedule.Status == RUNNING) && (delta>-CRANK_ANGLE_MAX_INJ)) { // Guarenteed to be >0 delta = delta + CRANK_ANGLE_MAX_INJ; } else { return 0; } } return ((uint32_t)(delta) * (uint32_t)timePerDegree); } static inline int _adjustToInjChannel(int angle, int channelInjDegrees) { angle = angle - channelInjDegrees; if( angle < 0) { return angle + CRANK_ANGLE_MAX_INJ; } return angle; } inline uint32_t calculateInjectorTimeout(const FuelSchedule &schedule, int channelInjDegrees, int openAngle, int crankAngle) { if (channelInjDegrees==0) { return _calculateInjectorTimeout(schedule, openAngle, crankAngle); } return _calculateInjectorTimeout(schedule, _adjustToInjChannel(openAngle, channelInjDegrees), _adjustToInjChannel(crankAngle, channelInjDegrees)); } inline void calculateIgnitionAngle(const int dwellAngle, const uint16_t channelIgnDegrees, int8_t advance, int *pEndAngle, int *pStartAngle) { *pEndAngle = (channelIgnDegrees==0 ? CRANK_ANGLE_MAX_IGN : channelIgnDegrees) - advance; if(*pEndAngle > CRANK_ANGLE_MAX_IGN) {*pEndAngle -= CRANK_ANGLE_MAX_IGN;} *pStartAngle = *pEndAngle - dwellAngle; if(*pStartAngle < 0) {*pStartAngle += CRANK_ANGLE_MAX_IGN;} } inline void calculateIgnitionTrailingRotary(int dwellAngle, int rotarySplitDegrees, int leadIgnitionAngle, int *pEndAngle, int *pStartAngle) { *pEndAngle = leadIgnitionAngle + rotarySplitDegrees; *pStartAngle = *pEndAngle - dwellAngle; if(*pStartAngle > CRANK_ANGLE_MAX_IGN) {*pStartAngle -= CRANK_ANGLE_MAX_IGN;} if(*pStartAngle < 0) {*pStartAngle += CRANK_ANGLE_MAX_IGN;} } inline uint32_t _calculateIgnitionTimeout(const Schedule &schedule, int16_t startAngle, int16_t crankAngle) { int16_t delta = startAngle - crankAngle; if (delta<0) { if ((schedule.Status == RUNNING) && (delta>-CRANK_ANGLE_MAX_IGN)) { // Msut be >0 delta = delta + CRANK_ANGLE_MAX_IGN; } else { return 0; } } return angleToTimeIntervalRev(delta); } static inline uint16_t _adjustToIgnChannel(int angle, int channelInjDegrees) { angle = angle - channelInjDegrees; if( angle < 0) { return angle + CRANK_ANGLE_MAX_IGN; } return angle; } inline uint32_t calculateIgnitionTimeout(const Schedule &schedule, int startAngle, int channelIgnDegrees, int crankAngle) { if (channelIgnDegrees==0) { return _calculateIgnitionTimeout(schedule, startAngle, crankAngle); } return _calculateIgnitionTimeout(schedule, _adjustToIgnChannel(startAngle, channelIgnDegrees), _adjustToIgnChannel(crankAngle, channelIgnDegrees)); }
3,730
C++
.h
90
38.188889
149
0.740066
oelprinz-org/BlitzboxBL49sp
36
12
0
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,170
hermes-3.cxx
bendudson_hermes-3/hermes-3.cxx
/* Copyright B.Dudson, J.Leddy, University of York, 2016-2020 email: benjamin.dudson@york.ac.uk This file is part of Hermes-3 (Hot ion, multifluid) Hermes is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Hermes is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Hermes. If not, see <http://www.gnu.org/licenses/>. */ #include "hermes-3.hxx" #include "revision.hxx" #include "include/adas_carbon.hxx" #include "include/adas_neon.hxx" #include "include/adas_lithium.hxx" #include "include/amjuel_helium.hxx" #include "include/amjuel_hyd_ionisation.hxx" #include "include/amjuel_hyd_recombination.hxx" #include "include/anomalous_diffusion.hxx" #include "include/classical_diffusion.hxx" #include "include/binormal_stpm.hxx" #include "include/collisions.hxx" #include "include/diamagnetic_drift.hxx" #include "include/electromagnetic.hxx" #include "include/electron_force_balance.hxx" #include "include/electron_viscosity.hxx" #include "include/evolve_density.hxx" #include "include/evolve_energy.hxx" #include "include/evolve_momentum.hxx" #include "include/evolve_pressure.hxx" #include "include/fixed_density.hxx" #include "include/fixed_fraction_ions.hxx" #include "include/fixed_fraction_radiation.hxx" #include "include/fixed_temperature.hxx" #include "include/fixed_velocity.hxx" #include "include/hydrogen_charge_exchange.hxx" #include "include/ion_viscosity.hxx" #include "include/ionisation.hxx" #include "include/isothermal.hxx" #include "include/neutral_boundary.hxx" #include "include/neutral_mixed.hxx" #include "include/neutral_parallel_diffusion.hxx" #include "include/noflow_boundary.hxx" #include "include/polarisation_drift.hxx" #include "include/quasineutral.hxx" #include "include/recycling.hxx" #include "include/relax_potential.hxx" #include "include/scale_timederivs.hxx" #include "include/set_temperature.hxx" #include "include/sheath_boundary.hxx" #include "include/sheath_boundary_insulating.hxx" #include "include/sheath_boundary_simple.hxx" #include "include/sheath_closure.hxx" #include "include/simple_conduction.hxx" #include "include/snb_conduction.hxx" #include "include/solkit_hydrogen_charge_exchange.hxx" #include "include/solkit_neutral_parallel_diffusion.hxx" #include "include/sound_speed.hxx" #include "include/thermal_force.hxx" #include "include/transform.hxx" #include "include/upstream_density_feedback.hxx" #include "include/temperature_feedback.hxx" #include "include/detachment_controller.hxx" #include "include/vorticity.hxx" #include "include/zero_current.hxx" #include "include/simple_pump.hxx" #include <bout/constants.hxx> #include <bout/boundary_factory.hxx> #include <bout/boundary_op.hxx> #include <bout/field_factory.hxx> #include "include/loadmetric.hxx" class DecayLengthBoundary : public BoundaryOp { public: DecayLengthBoundary() : gen(nullptr) {} DecayLengthBoundary(BoundaryRegion* region, std::shared_ptr<FieldGenerator> g) : BoundaryOp(region), gen(std::move(g)) {} using BoundaryOp::clone; /// Create a copy of this boundary condition /// This is called by the Boundary Factory BoundaryOp* clone(BoundaryRegion* region, const std::list<std::string>& args) override { std::shared_ptr<FieldGenerator> newgen; if (!args.empty()) { // First argument should be an expression newgen = FieldFactory::get()->parse(args.front()); } return new DecayLengthBoundary(region, newgen); } // Only implementing for Field3D, no time dependence void apply(Field3D& f) override { // Ensure that field and boundary are on the same mesh Mesh* mesh = bndry->localmesh; ASSERT1(mesh == f.getMesh()); // Get cell radial length Coordinates *coord = mesh->getCoordinates(); Field2D dx = coord->dx; Field2D g11 = coord->g11; Field2D dr = dx / sqrt(g11); // cell radial length. dr = dx/(Bpol * R) and g11 = (Bpol*R)**2 // Only implemented for cell centre quantities ASSERT1(f.getLocation() == CELL_CENTRE); // This loop goes over the first row of boundary cells (in X and Y) for (bndry->first(); !bndry->isDone(); bndry->next1d()) { for (int zk = 0; zk < mesh->LocalNz; zk++) { // Loop over Z points BoutReal decay_length = 3; // Default decay length is 3 normalised units (usually ~3mm) if (gen) { // Pick up the boundary condition setting from the input file // Must be specified in normalised units like the other BCs inputs decay_length = gen->generate(bout::generator::Context(bndry, zk, CELL_CENTRE, 0.0, mesh)); } // Set value in inner guard cell f(bndry->x, bndry->y, zk) // using the final domain cell value f(bndry->x - bndry->bx, bndry->y - bndry->by, zk) // Note: (bx, by) is the direction into the boundary, so // (1, 0) X outer boundary (SOL) // (-1, 0) X inner boundary (Core or PF) // (0, 1) Y upper boundary (outer lower target) // (0, -1) Y lower boundary (inner lower target) // Distance between final cell centre and inner guard cell centre in normalised units BoutReal distance = 0.5 * (dr(bndry->x, bndry->y) + dr(bndry->x - bndry->bx, bndry->y - bndry->by)); // Exponential decay f(bndry->x, bndry->y, zk) = f(bndry->x - bndry->bx, bndry->y - bndry->by, zk) * exp(-1 * distance / decay_length); // Set any remaining guard cells (i.e. the outer guards) to the same value // Should the outer guards have the decay continue, or just copy what the inners have? for (int i = 1; i < bndry->width; i++) { f(bndry->x + i * bndry->bx, bndry->y + i * bndry->by, zk) = f(bndry->x, bndry->y, zk); } } } } void apply(Field2D& f) override { throw BoutException("DecayLengthBoundary not implemented for Field2D"); } private: std::shared_ptr<FieldGenerator> gen; // Generator }; int Hermes::init(bool restarting) { auto &options = Options::root()["hermes"]; output.write("\nGit Version of Hermes: {:s}\n", hermes::version::revision); options["revision"] = hermes::version::revision; options["revision"].setConditionallyUsed(); output.write("Slope limiter: {}\n", hermes::limiter_typename); options["slope_limiter"] = hermes::limiter_typename; options["slope_limiter"].setConditionallyUsed(); // Choose normalisations Tnorm = options["Tnorm"].doc("Reference temperature [eV]").withDefault(100.); Nnorm = options["Nnorm"].doc("Reference density [m^-3]").withDefault(1e19); Bnorm = options["Bnorm"].doc("Reference magnetic field [T]").withDefault(1.0); Cs0 = sqrt(SI::qe * Tnorm / SI::Mp); // Reference sound speed [m/s] Omega_ci = SI::qe * Bnorm / SI::Mp; // Ion cyclotron frequency [1/s] rho_s0 = Cs0 / Omega_ci; // Length scale [m] // Put normalisation quantities into an Options to use later units["inv_meters_cubed"] = Nnorm; units["eV"] = Tnorm; units["Tesla"] = Bnorm; units["seconds"] = 1./Omega_ci; units["meters"] = rho_s0; // Put into the options tree, so quantities can be normalised // when creating components Options::root()["units"] = units.copy(); Options::root()["units"].setConditionallyUsed(); // Add the decay length boundary condition to the boundary factory // This will make it available as an input option // e.g. bndry_sol = decaylength(0.003 / rho_s0) sets up a decay length of 3mm BoundaryFactory::getInstance()->add(new DecayLengthBoundary(), "decaylength"); ///////////////////////////////////////////////////////// // Load metric tensor from the mesh, passing length and B // field normalisations TRACE("Loading metric tensor"); if (options["loadmetric"] .doc("Load Rxy, Bpxy etc. to create orthogonal metric?") .withDefault(true)) { LoadMetric(rho_s0, Bnorm); } else if (options["normalise_metric"] .doc("Normalise input metric tensor? (assumes input is in SI units)") .withDefault<bool>(true)) { Coordinates *coord = mesh->getCoordinates(); // To use non-orthogonal metric // Normalise coord->dx /= rho_s0 * rho_s0 * Bnorm; coord->Bxy /= Bnorm; // Metric is in grid file - just need to normalise coord->g11 /= SQ(Bnorm * rho_s0); coord->g22 *= SQ(rho_s0); coord->g33 *= SQ(rho_s0); coord->g12 /= Bnorm; coord->g13 /= Bnorm; coord->g23 *= SQ(rho_s0); coord->J *= Bnorm / rho_s0; coord->g_11 *= SQ(Bnorm * rho_s0); coord->g_22 /= SQ(rho_s0); coord->g_33 /= SQ(rho_s0); coord->g_12 *= Bnorm; coord->g_13 *= Bnorm; coord->g_23 /= SQ(rho_s0); coord->geometry(); // Calculate other metrics } // Tell the components if they are restarting options["restarting"] = restarting; options["restarting"].setConditionallyUsed(); TRACE("Creating components"); // Create the components // Here options is passed as the scheduler configuration, so that // settings in [hermes] are used. // Options::root() is passed as the root of the component options, so that // individual components use their own sections, rather than subsections of [hermes]. scheduler = ComponentScheduler::create(options, Options::root(), solver); // Preconditioner setPrecon((preconfunc)&Hermes::precon); return 0; } int Hermes::rhs(BoutReal time) { // Need to reset the state, since fields may be modified in transform steps state = Options(); set(state["time"], time); state["units"] = units.copy(); // Call all the components scheduler->transform(state); return 0; } /*! * Preconditioner. Solves the heat conduction * * @param[in] t The simulation time * @param[in] gamma Factor in front of the Jacobian in (I - gamma*J). Related * to timestep * @param[in] delta Not used here */ int Hermes::precon(BoutReal t, BoutReal gamma, BoutReal UNUSED(delta)) { state["time"] = t; scheduler->precon(state, gamma); return 0; } void Hermes::outputVars(Options& options) { AUTO_TRACE(); // Save the Hermes version in the output dump files options["HERMES_REVISION"].force(hermes::version::revision); options["HERMES_SLOPE_LIMITER"].force(hermes::limiter_typename); // Save normalisation quantities. These may be used by components // to calculate conversion factors to SI units set_with_attrs(options["Tnorm"], Tnorm, { {"units", "eV"}, {"conversion", 1}, // Already in SI units {"standard_name", "temperature normalisation"}, {"long_name", "temperature normalisation"} }); set_with_attrs(options["Nnorm"], Nnorm, { {"units", "m^-3"}, {"conversion", 1}, {"standard_name", "density normalisation"}, {"long_name", "Number density normalisation"} }); set_with_attrs(options["Bnorm"], Bnorm, { {"units", "T"}, {"conversion", 1}, {"standard_name", "magnetic field normalisation"}, {"long_name", "Magnetic field normalisation"} }); set_with_attrs(options["Cs0"], Cs0, { {"units", "m/s"}, {"conversion", 1}, {"standard_name", "velocity normalisation"}, {"long_name", "Sound speed normalisation"} }); set_with_attrs(options["Omega_ci"], Omega_ci, { {"units", "s^-1"}, {"conversion", 1}, {"standard_name", "frequency normalisation"}, {"long_name", "Cyclotron frequency normalisation"} }); set_with_attrs(options["rho_s0"], rho_s0, { {"units", "m"}, {"conversion", 1}, {"standard_name", "length normalisation"}, {"long_name", "Gyro-radius length normalisation"} }); scheduler->outputVars(options); } void Hermes::restartVars(Options& options) { AUTO_TRACE(); set_with_attrs(options["Tnorm"], Tnorm, { {"units", "eV"}, {"conversion", 1}, // Already in SI units {"standard_name", "temperature normalisation"}, {"long_name", "temperature normalisation"} }); set_with_attrs(options["Nnorm"], Nnorm, { {"units", "m^-3"}, {"conversion", 1}, {"standard_name", "density normalisation"}, {"long_name", "Number density normalisation"} }); set_with_attrs(options["Bnorm"], Bnorm, { {"units", "T"}, {"conversion", 1}, {"standard_name", "magnetic field normalisation"}, {"long_name", "Magnetic field normalisation"} }); set_with_attrs(options["Cs0"], Cs0, { {"units", "m/s"}, {"conversion", 1}, {"standard_name", "velocity normalisation"}, {"long_name", "Sound speed normalisation"} }); set_with_attrs(options["Omega_ci"], Omega_ci, { {"units", "s^-1"}, {"conversion", 1}, {"standard_name", "frequency normalisation"}, {"long_name", "Cyclotron frequency normalisation"} }); set_with_attrs(options["rho_s0"], rho_s0, { {"units", "m"}, {"conversion", 1}, {"standard_name", "length normalisation"}, {"long_name", "Gyro-radius length normalisation"} }); scheduler->restartVars(options); } // Standard main() function BOUTMAIN(Hermes);
13,483
C++
.cxx
324
37.228395
100
0.677382
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,171
test_sound_speed.cxx
bendudson_hermes-3/tests/unit/test_sound_speed.cxx
#include "gtest/gtest.h" #include "test_extras.hxx" // FakeMesh #include "../../include/sound_speed.hxx" /// Global mesh namespace bout{ namespace globals{ extern Mesh *mesh; } // namespace globals } // namespace bout // The unit tests use the global mesh using namespace bout::globals; // Reuse the "standard" fixture for FakeMesh using SoundSpeedTest = FakeMeshFixture; TEST_F(SoundSpeedTest, CreateComponent) { Options options; SoundSpeed component("test", options, nullptr); } TEST_F(SoundSpeedTest, OneSpecies) { Options options; SoundSpeed component("test", options, nullptr); options["species"]["e"]["density"] = 2.0; options["species"]["e"]["pressure"] = 1.2; options["species"]["e"]["AA"] = 1.5; component.transform(options); ASSERT_TRUE(options.isSet("sound_speed")); ASSERT_TRUE(IsFieldEqual(get<Field3D>(options["sound_speed"]), sqrt(1.2 / (2.0 * 1.5)), "RGN_NOBNDRY")); } TEST_F(SoundSpeedTest, TwoSpecies) { Options options; SoundSpeed component("test", options, nullptr); options["species"]["e"]["density"] = 2.0; options["species"]["e"]["pressure"] = 1.2; options["species"]["e"]["AA"] = 1.5; options["species"]["h"]["density"] = 3.0; options["species"]["h"]["pressure"] = 2.5; options["species"]["h"]["AA"] = 0.9; component.transform(options); ASSERT_TRUE(options.isSet("sound_speed")); ASSERT_TRUE(IsFieldEqual(get<Field3D>(options["sound_speed"]), sqrt((1.2 + 2.5) / (2.0 * 1.5 + 3.0 * 0.9)), "RGN_NOBNDRY")); }
1,554
C++
.cxx
42
33.071429
89
0.661953
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,172
test_fixed_density.cxx
bendudson_hermes-3/tests/unit/test_fixed_density.cxx
#include "gtest/gtest.h" #include "test_extras.hxx" // FakeMesh #include "../../include/fixed_density.hxx" /// Global mesh namespace bout{ namespace globals{ extern Mesh *mesh; } // namespace globals } // namespace bout // The unit tests use the global mesh using namespace bout::globals; // Reuse the "standard" fixture for FakeMesh using FixedDensityTest = FakeMeshFixture; TEST_F(FixedDensityTest, CreateComponent) { Options options = {{"units", {{"inv_meters_cubed", 1.0}}}, {"test", {{"density", 1.0}, {"charge", 1.0}, {"AA", 2.0}}}}; FixedDensity component("test", options, nullptr); } TEST_F(FixedDensityTest, MustSetDensity) { Options options = {{"units", {{"inv_meters_cubed", 1.0}}}, {"test", {{"charge", 1.0}, {"AA", 2.0}}}}; // Density isn't set, so this should throw ASSERT_THROW(FixedDensity component("test", options, nullptr), BoutException); } TEST_F(FixedDensityTest, SetValues) { Options options = {{"units", {{"inv_meters_cubed", 1e10}}}, {"e", {{"density", 2.4e11}, {"charge", 2}, {"AA", 3}}}}; FixedDensity component("e", options, nullptr); Options state; component.transform(state); ASSERT_FLOAT_EQ(2, state["species"]["e"]["charge"].as<BoutReal>()); ASSERT_FLOAT_EQ(3, state["species"]["e"]["AA"].as<BoutReal>()); // Check that density has been normalised ASSERT_TRUE( IsFieldEqual(state["species"]["e"]["density"].as<Field3D>(), 24.0, "RGN_ALL")); }
1,632
C++
.cxx
41
32.536585
85
0.589987
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,173
test_recycling.cxx
bendudson_hermes-3/tests/unit/test_recycling.cxx
#include "gtest/gtest.h" #include "test_extras.hxx" // FakeMesh #include "../../include/recycling.hxx" /// Global mesh namespace bout{ namespace globals{ extern Mesh *mesh; } // namespace globals } // namespace bout // The unit tests use the global mesh using namespace bout::globals; #include <bout/field_factory.hxx> // For generating functions // Reuse the "standard" fixture for FakeMesh using RecyclingTest = FakeMeshFixture; TEST_F(RecyclingTest, CreateComponent) { Options options; options["units"]["eV"] = 5; // Normalisation temperature options["recycling"]["species"] = ""; // No species to recycle Recycling component("recycling", options, nullptr); }
683
C++
.cxx
20
32.25
65
0.750383
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,174
test_diamagnetic_drift.cxx
bendudson_hermes-3/tests/unit/test_diamagnetic_drift.cxx
#include "gtest/gtest.h" #include "test_extras.hxx" // FakeMesh #include "../../include/diamagnetic_drift.hxx" /// Global mesh namespace bout{ namespace globals{ extern Mesh *mesh; } // namespace globals } // namespace bout // The unit tests use the global mesh using namespace bout::globals; // Reuse the "standard" fixture for FakeMesh using DiamagneticDriftTest = FakeMeshFixture; TEST_F(DiamagneticDriftTest, CreateComponent) { Options options; mesh->getCoordinates()->Bxy = 1.0; options["units"]["Tesla"] = 1.0; options["units"]["meters"] = 1.0; DiamagneticDrift component("test", options, nullptr); }
628
C++
.cxx
20
29.35
55
0.748744
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,175
test_integrate.cxx
bendudson_hermes-3/tests/unit/test_integrate.cxx
#include "gtest/gtest.h" #include "../../include/integrate.hxx" #include "test_extras.hxx" // FakeMesh /// Global mesh namespace bout{ namespace globals{ extern Mesh *mesh; } // namespace globals } // namespace bout // The unit tests use the global mesh using namespace bout::globals; // Reuse the "standard" fixture for FakeMesh using CellAverageTest = FakeMeshFixture; TEST_F(CellAverageTest, ConstantValue) { Field3D field{1.0}; Field3D result = cellAverage([](BoutReal) { return 3.0; }, field.getRegion("RGN_NOBNDRY"))(field); ASSERT_TRUE(result.isAllocated()); ASSERT_TRUE(areFieldsCompatible(field, result)); ASSERT_TRUE(IsFieldEqual(result, 3.0, "RGN_NOBNDRY")); } TEST_F(CellAverageTest, ConstantField) { Field3D field{1.0}; Field3D result = cellAverage([](BoutReal val) { return val * 2.0; }, field.getRegion("RGN_NOBNDRY"))(field); ASSERT_TRUE(result.isAllocated()); ASSERT_TRUE(areFieldsCompatible(field, result)); ASSERT_TRUE(IsFieldEqual(result, 2.0, "RGN_NOBNDRY")); }
1,077
C++
.cxx
29
32.896552
71
0.701349
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,176
test_zero_current.cxx
bendudson_hermes-3/tests/unit/test_zero_current.cxx
#include "gtest/gtest.h" #include "test_extras.hxx" // FakeMesh #include "../../include/zero_current.hxx" /// Global mesh namespace bout{ namespace globals{ extern Mesh *mesh; } // namespace globals } // namespace bout // The unit tests use the global mesh using namespace bout::globals; #include <bout/field_factory.hxx> // For generating functions // Reuse the "standard" fixture for FakeMesh using ZeroCurrentTest = FakeMeshFixture; TEST_F(ZeroCurrentTest, CreateComponent) { Options options; options["test"]["charge"] = 1.0; // Must be a charged species ZeroCurrent component("test", options, nullptr); } TEST_F(ZeroCurrentTest, ElectronFlowVelocity) { Options options; options["e"]["charge"] = -1.0; ZeroCurrent component("e", options, nullptr); options["species"]["e"]["charge"] = -1.0; options["species"]["e"]["density"] = 2.0; options["species"]["ion"]["density"] = 1.0; options["species"]["ion"]["charge"] = 2.0; // Set ion velocity Field3D Vi = FieldFactory::get()->create3D("y - x", &options, mesh); options["species"]["ion"]["velocity"] = Vi; component.transform(options); // Electron velocity should be equal to ion velocity Field3D Ve = get<Field3D>(options["species"]["e"]["velocity"]); BOUT_FOR_SERIAL(i, Ve.getRegion("RGN_NOBNDRY")) { ASSERT_DOUBLE_EQ(Ve[i], Vi[i]) << "Electron velocity not equal to ion velocity at " << i; } }
1,405
C++
.cxx
37
35.432432
93
0.700222
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,177
test_fixed_fraction_ions.cxx
bendudson_hermes-3/tests/unit/test_fixed_fraction_ions.cxx
#include "gtest/gtest.h" #include "test_extras.hxx" // FakeMesh #include "../../include/fixed_fraction_ions.hxx" /// Global mesh namespace bout{ namespace globals{ extern Mesh *mesh; } // namespace globals } // namespace bout // The unit tests use the global mesh using namespace bout::globals; // Reuse the "standard" fixture for FakeMesh using FixedFractionIonsTest = FakeMeshFixture; TEST_F(FixedFractionIonsTest, CreateComponent) { Options options; options["test"]["fractions"] = "h @ 1"; FixedFractionIons component("test", options, nullptr); } TEST_F(FixedFractionIonsTest, MissingFractions) { Options options; ASSERT_THROW(FixedFractionIons component("test", options, nullptr), BoutException); } TEST_F(FixedFractionIonsTest, MalformedFraction) { Options options; options["test"]["fractions"] = "h 1"; ASSERT_THROW(FixedFractionIons component("test", options, nullptr), BoutException); } TEST_F(FixedFractionIonsTest, TrailingCommaNoThrow) { Options options; options["test"]["fractions"] = "h @ 1,"; FixedFractionIons component("test", options, nullptr); } TEST_F(FixedFractionIonsTest, MissingElecDensity) { Options options; options["test"]["fractions"] = "h @ 1"; FixedFractionIons component("test", options, nullptr); Options state; ASSERT_THROW(component.transform(state), BoutException); } TEST_F(FixedFractionIonsTest, SingleIon) { Options options; options["test"]["fractions"] = "h @ 0.6"; FixedFractionIons component("test", options, nullptr); Options state; state["species"]["e"]["density"] = 1.4; component.transform(state); ASSERT_TRUE(IsFieldEqual(state["species"]["h"]["density"].as<Field3D>(), 0.6 * 1.4, "RGN_NOBNDRY")); } TEST_F(FixedFractionIonsTest, TwoIons) { Options options; options["test"]["fractions"] = "some_thing @ 0.4, ne @ 0.05"; FixedFractionIons component("test", options, nullptr); Options state; state["species"]["e"]["density"] = 1.4; component.transform(state); ASSERT_TRUE(IsFieldEqual(state["species"]["some_thing"]["density"].as<Field3D>(), 0.4 * 1.4, "RGN_NOBNDRY")); ASSERT_TRUE(IsFieldEqual(state["species"]["ne"]["density"].as<Field3D>(), 0.05 * 1.4, "RGN_NOBNDRY")); }
2,337
C++
.cxx
63
32.619048
83
0.697038
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,178
test_component.cxx
bendudson_hermes-3/tests/unit/test_component.cxx
#include "gtest/gtest.h" #include "../../include/component.hxx" #include <algorithm> // std::any_of namespace { struct TestComponent : public Component { TestComponent(const std::string&, Options&, Solver *) {} void transform(Options &state) { state["answer"] = 42; } }; RegisterComponent<TestComponent> registertestcomponent("testcomponent"); } // namespace TEST(ComponentTest, InAvailableList) { // Check that the test component is in the list of available components auto available = ComponentFactory::getInstance().listAvailable(); ASSERT_TRUE(std::any_of( available.begin(), available.end(), [](const std::string &str) { return str == "testcomponent"; })); } TEST(ComponentTest, CanCreate) { Options options; auto component = Component::create("testcomponent", "species", options, nullptr); EXPECT_FALSE(options.isSet("answer")); component->transform(options); ASSERT_TRUE(options.isSet("answer")); ASSERT_TRUE(options["answer"] == 42); } TEST(ComponentTest, GetThrowsNoValue) { Options option; // No value throws ASSERT_THROW(get<int>(option), BoutException); // Compatible value doesn't throw option = 42; ASSERT_TRUE(option == 42); } TEST(ComponentTest, GetThrowsIncompatibleValue) { Options option; option = "hello"; // Invalid value throws ASSERT_THROW(get<int>(option), BoutException); } TEST(ComponentTest, SetInteger) { Options option; set<int>(option, 3); ASSERT_EQ(getNonFinal<int>(option), 3); } #if CHECKLEVEL >= 1 TEST(ComponentTest, SetAfterGetThrows) { Options option; option = 42; ASSERT_EQ(get<int>(option), 42); // Setting after get should fail ASSERT_THROW(set<int>(option, 3), BoutException); } #endif TEST(ComponentTest, SetAfterGetNonFinal) { Options option; option = 42; ASSERT_EQ(getNonFinal<int>(option), 42); set<int>(option, 3); // Doesn't throw ASSERT_EQ(getNonFinal<int>(option), 3); } #if CHECKLEVEL >= 1 TEST(ComponentTest, SetBoundaryAfterGetThrows) { Options option; option = 42; ASSERT_EQ(get<int>(option), 42); // Setting after get should fail because get indicates an assumption // that all values are final including boundary cells. ASSERT_THROW(setBoundary<int>(option, 3), BoutException); } #endif TEST(ComponentTest, SetBoundaryAfterGetNoBoundary) { Options option; option = 42; ASSERT_EQ(getNoBoundary<int>(option), 42); setBoundary<int>(option, 3); // ok because boundary not assumed final ASSERT_EQ(getNonFinal<int>(option), 3); } TEST(ComponentTest, IsSetFinalStaysFalse) { Options option; ASSERT_EQ(isSetFinal(option["test"]), false); // Shouldn't change if called again ASSERT_EQ(isSetFinal(option["test"]), false); } TEST(ComponentTest, GetAfterIsSetFinal) { Options option; option["test"] = 1; ASSERT_EQ(isSetFinal(option["test"]), true); // Can get the value ASSERT_EQ(get<int>(option["test"]), 1); } #if CHECKLEVEL >= 1 TEST(ComponentTest, SetAfterIsSetFinal) { Options option; ASSERT_EQ(isSetFinal(option["test"]), false); // Can't now set the value ASSERT_THROW(set<int>(option["test"], 3), BoutException); } #endif
3,150
C++
.cxx
98
29.336735
83
0.733267
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,179
test_electron_force_balance.cxx
bendudson_hermes-3/tests/unit/test_electron_force_balance.cxx
#include "gtest/gtest.h" #include "test_extras.hxx" // FakeMesh #include "../../include/electron_force_balance.hxx" /// Global mesh namespace bout{ namespace globals{ extern Mesh *mesh; } // namespace globals } // namespace bout // The unit tests use the global mesh using namespace bout::globals; #include <bout/field_factory.hxx> // For generating functions // Reuse the "standard" fixture for FakeMesh using ElectronForceBalanceTest = FakeMeshFixture; TEST_F(ElectronForceBalanceTest, CreateComponent) { Options options; ElectronForceBalance component("test", options, nullptr); } TEST_F(ElectronForceBalanceTest, MissingElectronPressure) { Options options; ElectronForceBalance component("test", options, nullptr); ASSERT_THROW(component.transform(options), BoutException); } TEST_F(ElectronForceBalanceTest, ZeroPressureGradient) { Options options; ElectronForceBalance component("test", options, nullptr); options["species"]["e"]["pressure"] = 1.0; options["species"]["e"]["density"] = 1.0; options["species"]["e"]["charge"] = -1.0; options["species"]["h+"]["density"] = 1.0; options["species"]["h+"]["charge"] = 1.0; component.transform(options); // Should have a momentum source, but zero because no pressure gradient ASSERT_TRUE(options["species"]["h+"].isSet("momentum_source")); ASSERT_TRUE(IsFieldEqual(get<Field3D>(options["species"]["h+"]["momentum_source"]), 0.0, "RGN_NOBNDRY")); } TEST_F(ElectronForceBalanceTest, WithPressureGradient) { Options options; ElectronForceBalance component("test", options, nullptr); // Create a function which increases in y options["species"]["e"]["pressure"] = FieldFactory::get()->create3D("y", &options, mesh); options["species"]["e"]["density"] = 1.0; options["species"]["e"]["charge"] = -1.0; options["species"]["h+"]["density"] = 1.0; options["species"]["h+"]["charge"] = 1.0; component.transform(options); // Should have a momentum source ASSERT_TRUE(options["species"]["h+"].isSet("momentum_source")); // Force on ions should be in negative y direction Field3D F = get<Field3D>(options["species"]["h+"]["momentum_source"]); BOUT_FOR_SERIAL(i, F.getRegion("RGN_NOBNDRY")) { ASSERT_LT(F[i], 0.0) << "Force on ions (h+) not negative at " << i; } } TEST_F(ElectronForceBalanceTest, ForceBalance) { Options options; ElectronForceBalance component("test", options, nullptr); options["species"]["e"]["pressure"] =1.0; options["species"]["e"]["density"] = 2.0; options["species"]["e"]["charge"] = -1.0; options["species"]["e"]["momentum_source"] = 0.5; // Should have E = momentum_source / density = 0.5 / 2.0 options["species"]["ion"]["density"] = 1.0; options["species"]["ion"]["charge"] = 3.0; component.transform(options); // Should give ion momentum source charge * E = 3 * 0.5 / 2.0 Field3D F = get<Field3D>(options["species"]["ion"]["momentum_source"]); BOUT_FOR_SERIAL(i, F.getRegion("RGN_NOBNDRY")) { ASSERT_DOUBLE_EQ(F[i], 3. * 0.5 / 2.0) << "Momentum source not correct at " << i; } }
3,111
C++
.cxx
73
39.342466
90
0.689977
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,180
test_hydrogen_charge_exchange.cxx
bendudson_hermes-3/tests/unit/test_hydrogen_charge_exchange.cxx
#include "gtest/gtest.h" #include "test_extras.hxx" // FakeMesh #include "../../include/hydrogen_charge_exchange.hxx" /// Global mesh namespace bout { namespace globals { extern Mesh* mesh; } // namespace globals } // namespace bout // The unit tests use the global mesh using namespace bout::globals; #include <bout/constants.hxx> #include <bout/field_factory.hxx> // For generating functions // Reuse the "standard" fixture for FakeMesh using HydrogenCXTest = FakeMeshFixture; TEST_F(HydrogenCXTest, CreateComponent) { Options options{{"units", {{"eV", 1.0}, {"inv_meters_cubed", 1.0}, {"seconds", 1.0}}}}; HydrogenChargeExchangeIsotope<'h', 'h'> component("test", options, nullptr); } TEST_F(HydrogenCXTest, RateAt1eV) { Options options{{"units", {{"eV", 1.0}, {"inv_meters_cubed", 1.0}, {"seconds", 1.0}}}}; HydrogenChargeExchangeIsotope<'h', 'h'> component("test", options, nullptr); Options state{{"species", {{"h", {{"AA", 1.0}, {"density", 1.0}, {"temperature", 0.0}, // cold atoms {"velocity", 0.0}}}, {"h+", {{"AA", 1.0}, {"density", 1.0}, {"temperature", 1.0}, // lnT = 0.0 {"velocity", 0.0}}}}}}; component.transform(state); // Should have set momentum and energy sources ASSERT_TRUE(state["species"]["h"].isSet("momentum_source")); ASSERT_TRUE(state["species"]["h"].isSet("energy_source")); ASSERT_TRUE(state["species"]["h+"].isSet("momentum_source")); ASSERT_TRUE(state["species"]["h+"].isSet("energy_source")); // Since here lnT = 0, we're only testing the b0 coefficient // <σv> should be exp(-18.5028) cm^3/s // Should appear as a source of energy in the atoms ASSERT_TRUE(IsFieldEqual(get<Field3D>(state["species"]["h"]["energy_source"]), (3. / 2) * exp(-18.5028) * 1e-6, "RGN_NOBNDRY")); }
1,976
C++
.cxx
45
37
89
0.601567
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,181
test_noflow_boundary.cxx
bendudson_hermes-3/tests/unit/test_noflow_boundary.cxx
#include "gtest/gtest.h" #include "test_extras.hxx" // FakeMesh #include "../../include/noflow_boundary.hxx" /// Global mesh namespace bout{ namespace globals{ extern Mesh *mesh; } // namespace globals } // namespace bout // The unit tests use the global mesh using namespace bout::globals; #include <bout/constants.hxx> #include <bout/field_factory.hxx> // For generating functions // Reuse the "standard" fixture for FakeMesh using NoFlowBoundaryTest = FakeMeshFixture; TEST_F(NoFlowBoundaryTest, CreateComponent) { Options options; NoFlowBoundary component("test", options, nullptr); }
605
C++
.cxx
19
30.052632
62
0.77913
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,182
test_sheath_closure.cxx
bendudson_hermes-3/tests/unit/test_sheath_closure.cxx
#include "gtest/gtest.h" #include "test_extras.hxx" // FakeMesh #include "../../include/sheath_closure.hxx" /// Global mesh namespace bout{ namespace globals{ extern Mesh *mesh; } // namespace globals } // namespace bout // The unit tests use the global mesh using namespace bout::globals; // Reuse the "standard" fixture for FakeMesh using SheathClosureTest = FakeMeshFixture; TEST_F(SheathClosureTest, CreateComponent) { Options options; options["units"]["meters"] = 1.0; options["test"]["connection_length"] = 10; SheathClosure component("test", options, nullptr); } TEST_F(SheathClosureTest, NeedsDensity) { Options options; options["units"]["meters"] = 1.0; options["test"]["connection_length"] = 10; SheathClosure component("test", options, nullptr); Options state; state["fields"]["phi"] = Field3D(2.0); // Needs electron density ASSERT_THROW(component.transform(state), BoutException); } TEST_F(SheathClosureTest, PhiAndDensity) { Options options; options["units"]["meters"] = 1.0; options["test"]["connection_length"] = 10; SheathClosure component("test", options, nullptr); Options state; state["fields"]["phi"] = Field3D(2.0); state["species"]["e"]["density"] = Field3D(1.5); component.transform(state); ASSERT_TRUE(state["fields"].isSet("DivJextra")); ASSERT_TRUE(state["species"]["e"].isSet("density_source")); } TEST_F(SheathClosureTest, Temperature) { Options options; options["units"]["meters"] = 1.0; options["test"]["connection_length"] = 10; SheathClosure component("test", options, nullptr); Options state; state["fields"]["phi"] = Field3D(2.0); state["species"]["e"]["density"] = Field3D(1.5); state["species"]["e"]["temperature"] = Field3D(1.2); component.transform(state); ASSERT_TRUE(state["fields"].isSet("DivJextra")); ASSERT_TRUE(state["species"]["e"].isSet("density_source")); ASSERT_TRUE(state["species"]["e"].isSet("energy_source")); Field3D energy_source = get<Field3D>(state["species"]["e"]["energy_source"]); BOUT_FOR_SERIAL(i, energy_source.getRegion("RGN_NOBNDRY")) { ASSERT_TRUE(energy_source[i] <= 0.0); // Always a sink } }
2,172
C++
.cxx
59
33.949153
79
0.705911
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,183
test_extras.cxx
bendudson_hermes-3/tests/unit/test_extras.cxx
#include "gtest/gtest.h" #include "test_extras.hxx" #include <cmath> // Need to provide a redundant declaration because C++ constexpr int FakeMeshFixture::nx; constexpr int FakeMeshFixture::ny; constexpr int FakeMeshFixture::nz; ::testing::AssertionResult IsSubString(const std::string &str, const std::string &substring) { if (str.find(substring) != std::string::npos) { return ::testing::AssertionSuccess(); } else { return ::testing::AssertionFailure() << '"' << substring << "\" not found in " << str; } } void fillField(Field3D& f, std::vector<std::vector<std::vector<BoutReal>>> values) { f.allocate(); Ind3D i{0}; for (auto& x : values) { for (auto& y : x) { for (auto& z : y) { f[i] = z; ++i; } } } } void fillField(Field2D& f, std::vector<std::vector<BoutReal>> values) { f.allocate(); Ind2D i{0}; for (auto& x : values) { for (auto& y : x) { f[i] = y; ++i; } } }
1,003
C++
.cxx
37
22.594595
90
0.600416
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,184
test_ionisation.cxx
bendudson_hermes-3/tests/unit/test_ionisation.cxx
#include "gtest/gtest.h" #include "test_extras.hxx" // FakeMesh #include "../../include/ionisation.hxx" /// Global mesh namespace bout{ namespace globals{ extern Mesh *mesh; } // namespace globals } // namespace bout // The unit tests use the global mesh using namespace bout::globals; // Reuse the "standard" fixture for FakeMesh using IonisationTest = FakeMeshFixture; TEST_F(IonisationTest, CreateComponent) { Options options; options["units"]["eV"] = 1.0; options["units"]["inv_meters_cubed"] = 1.0; options["units"]["seconds"] = 1.0; Ionisation component("test", options, nullptr); } TEST_F(IonisationTest, MissingData) { Options options; options["units"]["eV"] = 1.0; options["units"]["inv_meters_cubed"] = 1.0; options["units"]["seconds"] = 1.0; Ionisation component("test", options, nullptr); ASSERT_THROW(component.transform(options), BoutException); } TEST_F(IonisationTest, SourcesSanityCheck) { Options options; options["units"]["eV"] = 1.0; options["units"]["inv_meters_cubed"] = 1.0; options["units"]["seconds"] = 1.0; Ionisation component("test", options, nullptr); // Set atom properties options["species"]["h"]["density"] = 1e19; options["species"]["h"]["temperature"] = 3.5; options["species"]["h"]["velocity"] = 10.0; options["species"]["h"]["AA"] = 2.0; // Ion properties options["species"]["h+"]["AA"] = 2.0; // Electron properties options["species"]["e"]["density"] = 1e18; options["species"]["e"]["temperature"] = 5.; // Do the calculation component.transform(options); Field3D h_density_source = get<Field3D>(options["species"]["h"]["density_source"]); Field3D hp_density_source = get<Field3D>(options["species"]["h+"]["density_source"]); BOUT_FOR_SERIAL(i, h_density_source.getRegion("RGN_NOBNDRY")) { ASSERT_LT(h_density_source[i], 0.0) << "Atom (h) density source not negative at " << i; ASSERT_GT(hp_density_source[i], 0.0) << "Ion (h+) density source not positive at " << i; } Field3D h_momentum_source = get<Field3D>(options["species"]["h"]["momentum_source"]); Field3D hp_momentum_source = get<Field3D>(options["species"]["h+"]["momentum_source"]); BOUT_FOR_SERIAL(i, h_momentum_source.getRegion("RGN_NOBNDRY")) { ASSERT_LT(h_momentum_source[i], 0.0) << "Atom (h) momentum source not negative at " << i; ASSERT_GT(hp_momentum_source[i], 0.0) << "Ion (h+) momentum source not positive at " << i; } Field3D h_energy_source = get<Field3D>(options["species"]["h"]["energy_source"]); Field3D hp_energy_source = get<Field3D>(options["species"]["h+"]["energy_source"]); BOUT_FOR_SERIAL(i, h_energy_source.getRegion("RGN_NOBNDRY")) { ASSERT_LT(h_energy_source[i], 0.0) << "Atom (h) energy source not negative at " << i; ASSERT_GT(hp_energy_source[i], 0.0) << "Ion (h+) energy source not positive at " << i; } Field3D e_energy_source = get<Field3D>(options["species"]["e"]["energy_source"]); BOUT_FOR_SERIAL(i, h_energy_source.getRegion("RGN_NOBNDRY")) { ASSERT_LT(e_energy_source[i], 0.0) << "Electron (e) energy source not negative at " << i; } }
3,123
C++
.cxx
69
42.057971
94
0.675066
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,185
test_isothermal.cxx
bendudson_hermes-3/tests/unit/test_isothermal.cxx
#include "gtest/gtest.h" #include "test_extras.hxx" // FakeMesh #include "../../include/isothermal.hxx" /// Global mesh namespace bout{ namespace globals{ extern Mesh *mesh; } // namespace globals } // namespace bout // The unit tests use the global mesh using namespace bout::globals; // Reuse the "standard" fixture for FakeMesh using IsothermalTest = FakeMeshFixture; TEST_F(IsothermalTest, CreateComponent) { Options options; options["units"]["eV"] = 1.0; options["test"]["temperature"] = 1.0; Isothermal component("test", options, nullptr); } TEST_F(IsothermalTest, NoDensity) { Options options; options["units"]["eV"] = 5.0; // Tnorm options["test"]["temperature"] = 1.0; // 1eV Isothermal component("test", options, nullptr); Options state; // No density component.transform(state); auto T = get<Field3D>(state["species"]["test"]["temperature"]); BOUT_FOR_SERIAL(i, T.getRegion("RGN_ALL")) { ASSERT_DOUBLE_EQ(T[i], 0.2); // Normalised 1eV/Tnorm } // No pressure ASSERT_FALSE(state["species"]["test"]["pressure"].isSet()); } TEST_F(IsothermalTest, GivenTandN) { Options options; options["units"]["eV"] = 5.0; options["e"]["temperature"] = 15.0; // In eV -> Normalised Te = 3 Isothermal component("e", options, nullptr); Field3D Ne = 2.0; Options state; state["species"]["e"]["density"] = Ne; component.transform(state); // Temperature should be a scalar, and normalised to 1 auto Te = get<Field3D>(state["species"]["e"]["temperature"]); BOUT_FOR_SERIAL(i, Te.getRegion("RGN_ALL")) { ASSERT_DOUBLE_EQ(Te[i], 3.0); } auto Pe = get<Field3D>(state["species"]["e"]["pressure"]); BOUT_FOR_SERIAL(i, Pe.getRegion("RGN_ALL")) { ASSERT_DOUBLE_EQ(Pe[i], 6.0); } }
1,761
C++
.cxx
52
31
67
0.682304
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,186
test_anomalous_diffusion.cxx
bendudson_hermes-3/tests/unit/test_anomalous_diffusion.cxx
#include "gtest/gtest.h" #include "test_extras.hxx" // FakeMesh #include "../../include/anomalous_diffusion.hxx" /// Global mesh namespace bout{ namespace globals{ extern Mesh *mesh; } // namespace globals } // namespace bout // The unit tests use the global mesh using namespace bout::globals; #include <bout/field_factory.hxx> // For generating functions // Reuse the "standard" fixture for FakeMesh using AnomalousDiffusionTest = FakeMeshFixture; TEST_F(AnomalousDiffusionTest, CreateComponent) { Options options; options["units"]["meters"] = 1.0; options["units"]["seconds"] = 1.0; AnomalousDiffusion component("test", options, nullptr); } TEST_F(AnomalousDiffusionTest, NoDiffusion) { Options options; options["units"]["meters"] = 1.0; options["units"]["seconds"] = 1.0; AnomalousDiffusion component("h", options, nullptr); Field3D N = FieldFactory::get()->create3D("1 + y * (x - 0.5)", &options, mesh); mesh->communicate(N); Options state; state["species"]["h"]["density"] = N; // If D is not set, then the diffusion should not be calculated component.transform(state); ASSERT_FALSE(state["species"]["h"].isSet("density_source")); ASSERT_FALSE(state["species"]["h"].isSet("momentum_source")); ASSERT_FALSE(state["species"]["h"].isSet("energy_source")); } TEST_F(AnomalousDiffusionTest, ParticleDiffusion) { Coordinates *coords = mesh->getCoordinates(); coords->Bxy = 1.0; // Note: This is non-finite or zero? Options options; options["units"]["meters"] = 1.0; options["units"]["seconds"] = 1.0; options["h"]["anomalous_D"] = 1.0; // Set particle diffusion for "h" species AnomalousDiffusion component("h", options, nullptr); Options state; state["species"]["h"]["density"] = FieldFactory::get()->create3D("1 + y * (x - 0.5)", &options, mesh); state["species"]["h"]["AA"] = 1.0; // Atomic mass number component.transform(state); // Expect all sources to be set ASSERT_TRUE(state["species"]["h"].isSet("density_source")); ASSERT_TRUE(state["species"]["h"].isSet("momentum_source")); ASSERT_TRUE(state["species"]["h"].isSet("energy_source")); // Expect momentum and energy sources to be zero ASSERT_TRUE(IsFieldEqual(get<Field3D>(state["species"]["h"]["momentum_source"]), 0.0, "RGN_NOBNDRY")); ASSERT_TRUE(IsFieldEqual(get<Field3D>(state["species"]["h"]["energy_source"]), 0.0, "RGN_NOBNDRY")); // Expect the sum over all cells of density source to be zero Field2D dV = coords->J * coords->dx * coords->dy * coords->dz; // Cell volume Field3D source = get<Field3D>(state["species"]["h"]["density_source"]); BoutReal integral = 0.0; BOUT_FOR_SERIAL(i, source.getRegion("RGN_NOBNDRY")) { ASSERT_TRUE(std::isfinite(dV[i])) << "Volume element not finite at " << i.x() << ", " << i.y() << ", " << i.z(); ASSERT_TRUE(std::isfinite(source[i])) << "Density source not finite at " << i.x() << ", " << i.y() << ", " << i.z(); integral += source[i] * dV[i]; } ASSERT_LT(abs(integral), 1e-3) << "Integral of density source should be close to zero"; }
3,135
C++
.cxx
68
42.308824
120
0.666777
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,187
test_component_scheduler.cxx
bendudson_hermes-3/tests/unit/test_component_scheduler.cxx
#include "gtest/gtest.h" #include "../../include/component_scheduler.hxx" namespace { struct TestComponent : public Component { TestComponent(const std::string&, Options&, Solver *) {} void transform(Options &state) { state["answer"] = 42; } }; struct TestMultiply : public Component { TestMultiply(const std::string&, Options&, Solver *) {} void transform(Options &state) { // Note: Using set<>() and get<>() for quicker access, avoiding printing // getNonFinal needs to be used because we set the value afterwards set(state["answer"], getNonFinal<int>(state["answer"]) * 2); } }; RegisterComponent<TestComponent> registertestcomponent("testcomponent"); RegisterComponent<TestMultiply> registertestcomponent2("multiply"); } // namespace TEST(SchedulerTest, OneComponent) { Options options; options["components"] = "testcomponent"; auto scheduler = ComponentScheduler::create(options, options, nullptr); EXPECT_FALSE(options.isSet("answer")); scheduler->transform(options); ASSERT_TRUE(options.isSet("answer")); ASSERT_TRUE(options["answer"] == 42); } TEST(SchedulerTest, TwoComponents) { Options options; options["components"] = "testcomponent, multiply"; auto scheduler = ComponentScheduler::create(options, options, nullptr); EXPECT_FALSE(options.isSet("answer")); scheduler->transform(options); ASSERT_TRUE(options.isSet("answer")); ASSERT_TRUE(options["answer"] == 42 * 2); } TEST(SchedulerTest, SubComponents) { Options options; options["components"] = "species"; options["species"]["type"] = "testcomponent, multiply"; auto scheduler = ComponentScheduler::create(options, options, nullptr); EXPECT_FALSE(options.isSet("answer")); scheduler->transform(options); ASSERT_TRUE(options.isSet("answer")); ASSERT_TRUE(options["answer"] == 42 * 2); }
1,848
C++
.cxx
47
36.361702
77
0.732473
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,188
test_fixed_velocity.cxx
bendudson_hermes-3/tests/unit/test_fixed_velocity.cxx
#include "gtest/gtest.h" #include "test_extras.hxx" // FakeMesh #include "../../include/fixed_velocity.hxx" /// Global mesh namespace bout{ namespace globals{ extern Mesh *mesh; } // namespace globals } // namespace bout // The unit tests use the global mesh using namespace bout::globals; // Reuse the "standard" fixture for FakeMesh using FixedVelocityTest = FakeMeshFixture; TEST_F(FixedVelocityTest, CreateComponent) { Options options = {{"units", {{"meters", 1.0}, {"seconds", 1.0}}}, {"test", {{"velocity", 1.0}}}}; FixedVelocity component("test", options, nullptr); } TEST_F(FixedVelocityTest, MustSetVelocity) { Options options = {{"units", {{"meters", 1.0}, {"seconds", 1.0}}}, {"test", {{"charge", 1.0}}}}; // Density isn't set, so this should throw ASSERT_THROW(FixedVelocity component("test", options, nullptr), BoutException); } TEST_F(FixedVelocityTest, SetValues) { Options options = {{"units", {{"meters", 10.0}, {"seconds", 2.0}}}, {"e", {{"velocity", 3}}}}; FixedVelocity component("e", options, nullptr); Options state = {{"species", {{"e", {{"AA", 2}, {"density", 7}}}}}}; component.transform(state); // Check that velocity has been normalised ASSERT_TRUE(IsFieldEqual(state["species"]["e"]["velocity"].as<Field3D>(), 3 / (10. / 2), "RGN_ALL")); // Check that momentum is calculated ASSERT_TRUE(IsFieldEqual(state["species"]["e"]["momentum"].as<Field3D>(), 2 * 7 * 3 / (10. / 2), "RGN_ALL",1e-8)); }
1,712
C++
.cxx
41
33.634146
90
0.573325
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,189
test_snb_conduction.cxx
bendudson_hermes-3/tests/unit/test_snb_conduction.cxx
#include "gtest/gtest.h" #include "test_extras.hxx" // FakeMesh #include "../../include/snb_conduction.hxx" /// Global mesh namespace bout{ namespace globals{ extern Mesh *mesh; } // namespace globals } // namespace bout // The unit tests use the global mesh using namespace bout::globals; #include <bout/field_factory.hxx> // For generating functions // Reuse the "standard" fixture for FakeMesh using SNBConductionTest = FakeMeshFixture; TEST_F(SNBConductionTest, CreateComponent) { Options options; SNBConduction component("test", options, nullptr); } TEST_F(SNBConductionTest, Transform) { Options options; SNBConduction component("test", options, nullptr); Options state {{"units", {{"meters", 1.0}, {"eV", 1.0}, {"inv_meters_cubed", 1e19}, {"seconds", 1e-6}}}, {"species", {{"e", {{"temperature", 1.0}, {"density", 1.0}}}}}}; component.transform(state); ASSERT_TRUE(state["species"]["e"].isSet("energy_source")); // Zero temperature gradient everywhere -> No divergence of heat flux auto source = get<Field3D>(state["species"]["e"]["energy_source"]); BOUT_FOR_SERIAL(i, source.getRegion("RGN_NOBNDRY")) { ASSERT_LT(abs(source[i]), 1e-20); } }
1,324
C++
.cxx
35
31.857143
71
0.63878
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,190
test_collisions.cxx
bendudson_hermes-3/tests/unit/test_collisions.cxx
#include "gtest/gtest.h" #include "test_extras.hxx" // FakeMesh #include "../../include/collisions.hxx" /// Global mesh namespace bout{ namespace globals{ extern Mesh *mesh; } // namespace globals } // namespace bout // The unit tests use the global mesh using namespace bout::globals; // Reuse the "standard" fixture for FakeMesh using CollisionsTest = FakeMeshFixture; TEST_F(CollisionsTest, CreateComponent) { Options options; options["units"]["eV"] = 1.0; options["units"]["meters"] = 1.0; options["units"]["seconds"] = 1.0; options["units"]["inv_meters_cubed"] = 1e19; Collisions component("test", options, nullptr); } TEST_F(CollisionsTest, OnlyElectrons) { Options options; options["units"]["eV"] = 1.0; options["units"]["meters"] = 1.0; options["units"]["seconds"] = 1.0; options["units"]["inv_meters_cubed"] = 1.0; Collisions component("test", options, nullptr); Options state; state["species"]["e"]["density"] = 1e19; state["species"]["e"]["temperature"] = 10.; component.transform(state); ASSERT_TRUE(state["species"]["e"].isSet("collision_frequency")); } TEST_F(CollisionsTest, OneOrTwoSpeciesCharged) { Options options; options["units"]["eV"] = 1.0; options["units"]["meters"] = 1.0; options["units"]["seconds"] = 1.0; options["units"]["inv_meters_cubed"] = 1.0; Collisions component("test", options, nullptr); Options state1; state1["species"]["s1"]["density"] = 1e19; state1["species"]["s1"]["temperature"] = 10; state1["species"]["s1"]["charge"] = 1; state1["species"]["s1"]["AA"] = 2; // State with two species, both the same but half the density Options state2; state2["species"]["s1"]["density"] = 5e18; // Half density state2["species"]["s1"]["temperature"] = 10; state2["species"]["s1"]["charge"] = 1; state2["species"]["s1"]["AA"] = 2; state2["species"]["s2"] = state2["species"]["s1"].copy(); // Run calculations component.transform(state1); component.transform(state2); Field3D nu1 = get<Field3D>(state1["species"]["s1"]["collision_frequency"]); Field3D nu21 = get<Field3D>(state2["species"]["s1"]["collision_frequency"]); Field3D nu22 = get<Field3D>(state2["species"]["s2"]["collision_frequency"]); BOUT_FOR_SERIAL(i, nu1.getRegion("RGN_ALL")) { // Collision rates for species1 and species2 should be equal ASSERT_DOUBLE_EQ(nu21[i], nu22[i]); // Whether one or two species, the collision rates should be similar // Note: Not exactly the same, because coulomb logarithm is slightly different ASSERT_TRUE(abs(nu1[i] - nu21[i]) / (nu1[i] + nu21[i]) < 0.05 ); } } TEST_F(CollisionsTest, TnormDependence) { // Calculate rates with normalisation factors 1 Options options {{"units", {{"eV", 1.0}, {"meters", 1.0}, {"seconds", 1.0}, {"inv_meters_cubed", 1.0}}}, {"test", {{"electron_neutral", true}, {"ion_neutral", true}, {"electron_electron", true}, {"ion_ion", true}, {"neutral_neutral", true}}}}; Collisions component("test", options, nullptr); Options state {{"species", {{"e", {{"density", 1e19}, {"temperature", 10}, {"charge", -1}, {"AA", 1./1836}}}, {"d+", {{"density", 2e19}, {"temperature", 20}, {"charge", 1}, {"AA", 2}}}, {"d", {{"density", 1e18}, {"temperature", 3}, {"AA", 2}}}}}}; component.transform(state); ASSERT_TRUE(state["species"]["e"].isSet("collision_frequency")); ASSERT_TRUE(state["species"]["d"].isSet("collision_frequency")); ASSERT_TRUE(state["species"]["d+"].isSet("collision_frequency")); // Collision frequencies should be positive, non-zero ASSERT_GT(get<Field3D>(state["species"]["e"]["collision_frequency"])(0,0,0), 0.0); ASSERT_GT(get<Field3D>(state["species"]["d"]["collision_frequency"])(0,0,0), 0.0); ASSERT_GT(get<Field3D>(state["species"]["d+"]["collision_frequency"])(0,0,0), 0.0); // Re-calculate with Tnorm != 1 // To keep frequency normalisation fixed, rho_s0 scales like sqrt(Tnorm) const BoutReal Tnorm = 100; Options options2 {{"units", {{"eV", Tnorm}, {"meters", sqrt(Tnorm)}, {"seconds", 1.0}, {"inv_meters_cubed", 1.0}}}, {"test", {{"electron_neutral", true}, {"ion_neutral", true}, {"electron_electron", true}, {"ion_ion", true}, {"neutral_neutral", true}}}}; Collisions component2("test", options2, nullptr); Options state2 {{"species", {{"e", {{"density", 1e19}, {"temperature", 10 / Tnorm}, {"charge", -1}, {"AA", 1./1836}}}, {"d+", {{"density", 2e19}, {"temperature", 20 / Tnorm}, {"charge", 1}, {"AA", 2}}}, {"d", {{"density", 1e18}, {"temperature", 3 / Tnorm}, {"AA", 2}}}}}}; component2.transform(state2); // Normalised frequencies should be unchanged ASSERT_FLOAT_EQ(get<Field3D>(state["species"]["e"]["collision_frequency"])(0,0,0), get<Field3D>(state2["species"]["e"]["collision_frequency"])(0,0,0)); ASSERT_FLOAT_EQ(get<Field3D>(state["species"]["d"]["collision_frequency"])(0,0,0), get<Field3D>(state2["species"]["d"]["collision_frequency"])(0,0,0)); ASSERT_FLOAT_EQ(get<Field3D>(state["species"]["d+"]["collision_frequency"])(0,0,0), get<Field3D>(state2["species"]["d+"]["collision_frequency"])(0,0,0)); }
6,325
C++
.cxx
131
36.328244
87
0.527069
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,191
test_sheath_boundary.cxx
bendudson_hermes-3/tests/unit/test_sheath_boundary.cxx
#include "gtest/gtest.h" #include "test_extras.hxx" // FakeMesh #include "../../include/sheath_boundary.hxx" /// Global mesh namespace bout{ namespace globals{ extern Mesh *mesh; } // namespace globals } // namespace bout // The unit tests use the global mesh using namespace bout::globals; #include <bout/constants.hxx> #include <bout/field_factory.hxx> // For generating functions // Reuse the "standard" fixture for FakeMesh using SheathBoundaryTest = FakeMeshFixture; TEST_F(SheathBoundaryTest, CreateComponent) { Options options; options["units"]["eV"] = 1.0; // Voltage normalisation SheathBoundary component("test", options, nullptr); } TEST_F(SheathBoundaryTest, DontSetPotential) { Options options; options["units"]["eV"] = 1.0; // Voltage normalisation SheathBoundary component("test", options, nullptr); Field3D N = FieldFactory::get()->create3D("1 + y", &options, mesh); BoutReal Te = 2.0; BoutReal Ti = 3.0; BoutReal Zi = 1.1; BoutReal si = 0.5; Options state {{"species", {// Electrons {"e", {{"density", N}, {"temperature", Te}, {"velocity", 0.0}}}, // Ion species {"h", {{"density", si*N}, {"temperature", Ti}, {"AA", 1.0}, {"charge", Zi}, {"velocity", 0.0}}}}}}; component.transform(state); // Should have calculated, but not set potential ASSERT_FALSE(state["fields"].isSet("phi")); } TEST_F(SheathBoundaryTest, CalculatePotential) { Options options{{"test", {{"always_set_phi", true}}}}; options["units"]["eV"] = 1.0; // Voltage normalisation SheathBoundary component("test", options, nullptr); Field3D N = FieldFactory::get()->create3D("1 + y", &options, mesh); BoutReal Te = 2.0; BoutReal Ti = 3.0; BoutReal Zi = 1.1; BoutReal si = 0.5; Options state{{"species", {// Electrons {"e", {{"density", N}, {"temperature", Te}, {"velocity", 0.0}}}, // Ion species {"h", {{"density", si * N}, {"temperature", Ti}, {"AA", 1.0}, {"charge", Zi}, {"velocity", 0.0}}}}}}; component.transform(state); // Should have calculated, but not set potential ASSERT_TRUE(state["fields"].isSet("phi")); // Calculate the expected value of phi const BoutReal adiabatic = 5./3; BoutReal Vzi = sqrt(adiabatic * Ti + Zi * Te); BoutReal phi_ref = Te * log(sqrt(Te * SI::Mp / SI::Me / TWOPI) / (si * Zi * Vzi)); output.write("TEST: {:e} {:e} {:e}\n", Te, si * Zi * Vzi, phi_ref); output.write("ION: {:e} {:e} {:e}\n", adiabatic * Ti, Zi * Te * si / (si + 1), Vzi); Field3D phi = state["fields"]["phi"]; for (RangeIterator r = mesh->iterateBndryUpperY(); !r.isDone(); r++) { for (int jz = 0; jz < mesh->LocalNz; jz++) { ASSERT_DOUBLE_EQ(phi_ref, phi(r.ind, mesh->yend, jz)); } } }
3,095
C++
.cxx
79
31.544304
86
0.569752
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,192
test_amjuel_hyd_recombination.cxx
bendudson_hermes-3/tests/unit/test_amjuel_hyd_recombination.cxx
#include "gtest/gtest.h" #include "test_extras.hxx" // FakeMesh #include "../../include/amjuel_hyd_recombination.hxx" /// Global mesh namespace bout { namespace globals { extern Mesh* mesh; } // namespace globals } // namespace bout // The unit tests use the global mesh using namespace bout::globals; #include <bout/constants.hxx> #include <bout/field_factory.hxx> // For generating functions // Reuse the "standard" fixture for FakeMesh using HydrogenRCTest = FakeMeshFixture; TEST_F(HydrogenRCTest, CreateComponent) { Options options{{"units", {{"eV", 1.0}, {"inv_meters_cubed", 1.0}, {"seconds", 1.0}}}}; AmjuelHydRecombinationIsotope<'h'> component("test", options, nullptr); } // Check that recombination is a sink of ions, source of neutrals TEST_F(HydrogenRCTest, DensitySourceSigns) { Options options{{"units", {{"eV", 1.0}, {"inv_meters_cubed", 1.0}, {"seconds", 1.0}}}}; AmjuelHydRecombinationIsotope<'h'> component("test", options, nullptr); Options state{{"species", {{"e", {{"density", 1.0}, {"temperature", 1.0}}}, {"h", {{"AA", 1.0}, {"density", 1.0}, {"temperature", 1.0}, {"velocity", 1.0}}}, {"h+", {{"AA", 1.0}, {"charge", 1.0}, {"density", 1.0}, {"temperature", 1.0}, {"velocity", 1.0}}}}}}; component.transform(state); ASSERT_TRUE(state["species"]["e"].isSet("energy_source")); auto atom_density_source = get<Field3D>(state["species"]["h"]["density_source"]); auto ion_density_source = get<Field3D>(state["species"]["h+"]["density_source"]); auto electron_density_source = get<Field3D>(state["species"]["e"]["density_source"]); auto atom_momentum_source = get<Field3D>(state["species"]["h"]["momentum_source"]); auto ion_momentum_source = get<Field3D>(state["species"]["h+"]["momentum_source"]); auto atom_energy_source = get<Field3D>(state["species"]["h"]["energy_source"]); auto ion_energy_source = get<Field3D>(state["species"]["h+"]["energy_source"]); BOUT_FOR_SERIAL(i, atom_density_source.getRegion("RGN_NOBNDRY")) { output.write("{}: {}\n", i.ind, atom_density_source[i]); ASSERT_TRUE(atom_density_source[i] > 0.0); ASSERT_TRUE(ion_density_source[i] < 0.0); ASSERT_FLOAT_EQ(electron_density_source[i], ion_density_source[i]); ASSERT_TRUE(atom_momentum_source[i] > 0.0); ASSERT_TRUE(ion_momentum_source[i] < 0.0); ASSERT_TRUE(atom_energy_source[i] > 0.0); ASSERT_TRUE(ion_energy_source[i] < 0.0); } }
2,683
C++
.cxx
58
39.155172
89
0.610749
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,193
state_speed_test.cxx
bendudson_hermes-3/performance/state_speed_test.cxx
// // Test the speed of passing state between components // // Result: (Intel(R) Core(TM) i5-7200U CPU @ 2.50GHz) // // Global state: 4.58632e-05s // Options state: 6.65891e-05s // Options state with resets: 6.48178e-05s // -> Overhead of around 20 us, re-using state doesn't seem to improve time #include <bout.hxx> #include <field3d.hxx> #include <options.hxx> #include <chrono> //////////////////////////////////////////////// // 1. Global state // // This is a baseline case with minimal/no overhead namespace globalstate { Field3D a, b, c, d, e, f, g, h, i, j, k, l; BoutReal x, y, z; void component1() { a = 1.0; b = 2.0; c = 3.0; d = 4.0; x = -5.2; } void component2() { e = 2 * a + b; f = 5.0 * x; g = d - c; h = 6.0; y = 42; } void component3() { i = 7.0; j = d + f + g; l = h - a * y; k = a + e + i; z = 32; } void component4() { l = b + f + j * y; } /// Run components in order void run() { component1(); component2(); component3(); component4(); } } // globalstate //////////////////////////////////////////////// // Options class, with some nesting #include "../include/component.hxx" namespace optionstate { Options state; void component1(Options &state) { state["a"] = Field3D(1.0); state["b"] = Field3D(2.0); state["c"] = Field3D(3.0); state["d"] = Field3D(4.0); state["x"] = -5.2; } void component2(Options &state) { state["e"] = 2 * get<Field3D>(state["a"]) + get<Field3D>(state["b"]); state["f"] = 5.0 * get<BoutReal>(state["x"]); state["g"] = get<Field3D>(state["d"]) - get<Field3D>(state["c"]); state["h"] = 6.0; state["y"] = 42.0; } void component3(Options &state) { state["i"] = 7.0; state["j"] = get<Field3D>(state["d"]) + get<Field3D>(state["f"]) + get<Field3D>(state["g"]); state["l"] = get<Field3D>(state["h"]) - get<Field3D>(state["a"]) * get<BoutReal>(state["y"]); state["k"] = get<Field3D>(state["a"]) + get<Field3D>(state["e"]) + get<Field3D>(state["i"]); state["z"] = 32.0; } void component4(Options &state) { state["l"] = get<Field3D>(state["b"]) + get<Field3D>(state["f"]) + get<Field3D>(state["j"]) * get<BoutReal>(state["y"]); } /// Run components in order void run() { component1(state); component2(state); component3(state); component4(state); } } // optionstate int main(int argc, char** argv) { BoutInitialise(argc, argv); int N = 10000; globalstate::run(); { auto start = std::chrono::steady_clock::now(); for(int i = 0; i < N; i++) { globalstate::run(); } auto end = std::chrono::steady_clock::now(); std::chrono::duration<double> elapsed_seconds = end - start; output << "Global state: " << elapsed_seconds.count() / N << "s\n"; } optionstate::run(); { auto start = std::chrono::steady_clock::now(); for(int i = 0; i < N; i++) { optionstate::run(); } auto end = std::chrono::steady_clock::now(); std::chrono::duration<double> elapsed_seconds = end - start; output << "Options state: " << elapsed_seconds.count() / N << "s\n"; } // Try resetting the state between runs { auto start = std::chrono::steady_clock::now(); for(int i = 0; i < N; i++) { optionstate::run(); optionstate::state = Options{}; // reset state } auto end = std::chrono::steady_clock::now(); std::chrono::duration<double> elapsed_seconds = end - start; output << "Options state with resets: " << elapsed_seconds.count() / N << "s\n"; } BoutFinalise(); }
3,640
C++
.cxx
125
25.12
124
0.566407
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,194
classical_diffusion.cxx
bendudson_hermes-3/src/classical_diffusion.cxx
#include "classical_diffusion.hxx" #include <bout/fv_ops.hxx> ClassicalDiffusion::ClassicalDiffusion(std::string name, Options& alloptions, Solver*) { AUTO_TRACE(); Options& options = alloptions[name]; Bsq = SQ(bout::globals::mesh->getCoordinates()->Bxy); diagnose = options["diagnose"].doc("Output additional diagnostics?").withDefault<bool>(false); custom_D = options["custom_D"].doc("Custom diffusion coefficient override. -1: Off, calculate D normally").withDefault<BoutReal>(-1); } void ClassicalDiffusion::transform(Options &state) { AUTO_TRACE(); Options& allspecies = state["species"]; // Particle diffusion coefficient // The only term here comes from the resistive drift Field3D Ptotal = 0.0; for (auto& kv : allspecies.getChildren()) { const auto& species = kv.second; if (!(species.isSet("charge") and IS_SET(species["pressure"]))) { continue; // Skip, go to next species } auto q = get<BoutReal>(species["charge"]); if (fabs(q) < 1e-5) { continue; } Ptotal += GET_VALUE(Field3D, species["pressure"]); } auto& electrons = allspecies["e"]; const auto me = get<BoutReal>(electrons["AA"]); const Field3D Ne = GET_VALUE(Field3D, electrons["density"]); // Particle diffusion coefficient. Applied to all charged species // so that net transport is ambipolar if (custom_D > 0) { // User-set Dn = custom_D; } else { // Calculated from collisions const Field3D nu_e = floor(GET_VALUE(Field3D, electrons["collision_frequency"]), 1e-10); Dn = floor(Ptotal, 1e-5) * me * nu_e / (floor(Ne, 1e-5) * Bsq); } // Set D to zero in all guard cells BOUT_FOR(i, Dn.getRegion("RGN_GUARDS")) { Dn[i] = 0.0; } for (auto& kv : allspecies.getChildren()) { Options& species = allspecies[kv.first]; // Note: Need non-const if (!(species.isSet("charge") and IS_SET(species["density"]))) { continue; // Skip, go to next species } auto q = get<BoutReal>(species["charge"]); if (fabs(q) < 1e-5) { continue; } const auto N = GET_VALUE(Field3D, species["density"]); add(species["density_source"], FV::Div_a_Grad_perp(Dn, N)); if (IS_SET(species["velocity"])) { const auto V = GET_VALUE(Field3D, species["velocity"]); const auto AA = GET_VALUE(BoutReal, species["AA"]); add(species["momentum_source"], FV::Div_a_Grad_perp(Dn * AA * V, N)); } if (IS_SET(species["temperature"])) { const auto T = GET_VALUE(Field3D, species["temperature"]); add(species["energy_source"], FV::Div_a_Grad_perp(Dn * (3. / 2) * T, N)); // Cross-field heat conduction // kappa_perp = 2 * n * nu_ii * rho_i^2 const auto P = GET_VALUE(Field3D, species["pressure"]); const auto AA = GET_VALUE(BoutReal, species["AA"]); // TODO: Figure out what to do with the below if(custom_D < 0) { const Field3D nu = floor(GET_VALUE(Field3D, species["collision_frequency"]), 1e-10); add(species["energy_source"], FV::Div_a_Grad_perp(2. * floor(P, 1e-5) * nu * AA / Bsq, T)); } } } } void ClassicalDiffusion::outputVars(Options &state) { AUTO_TRACE(); if (diagnose) { // Normalisations auto Omega_ci = get<BoutReal>(state["Omega_ci"]); auto rho_s0 = get<BoutReal>(state["rho_s0"]); set_with_attrs(state["D_classical"], Dn, {{"time_dimension", "t"}, {"units", "m^2 s^-1"}, {"conversion", rho_s0 * rho_s0 * Omega_ci}, {"standard_name", "Classical particle diffusion"}, {"long_name", "Classical cross-field particle diffusion coefficient"}, {"source", "classical_diffusion"}}); } }
3,763
C++
.cxx
87
37.321839
135
0.623733
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,195
full_velocity.cxx
bendudson_hermes-3/src/full_velocity.cxx
#include "../include/full_velocity.hxx" #include "../include/div_ops.hxx" #include "bout/mesh.hxx" #include "bout/solver.hxx" using bout::globals::mesh; NeutralFullVelocity::NeutralFullVelocity(const std::string& name, Options& options, Solver *solver) : name(name) { // This is used in both transform and finally functions coord = mesh->getCoordinates(); AA = options["AA"].doc("Atomic mass number").withDefault(2.0); gamma_ratio = options["gamma_ratio"].doc("Ratio of specific heats").withDefault(5. / 3); neutral_viscosity = options["viscosity"] .doc("Normalised kinematic viscosity") .withDefault(1e-2); neutral_bulk = options["bulk"].doc("Normalised bulk viscosity").withDefault(1e-2); neutral_conduction = options["conduction"].doc("Normalised heat conduction").withDefault(1e-2); outflow_ydown = options["outflow_ydown"] .doc("Allow outflowing neutrals?") .withDefault<bool>(false); neutral_gamma = options["neutral_gamma"] .doc("Surface heat transmission coefficient") .withDefault(5. / 4); // Get the normalisations auto& units = Options::root()["units"]; BoutReal Lnorm = units["meters"]; BoutReal Bnorm = units["Tesla"]; Tnorm = units["eV"]; // Evolve 2D density, pressure, and velocity solver->add(Nn2D, "Nn"); solver->add(Pn2D, "Pn"); solver->add(Vn2D, "Vn"); DivV2D.setBoundary("Pn"); // Same boundary condition as Pn // Load necessary metrics for non-orth calculation Field2D etaxy, cosbeta; if (mesh->get(etaxy, "etaxy")) { etaxy = 0.0; } cosbeta = sqrt(1. - SQ(etaxy)); // Calculate transformation to Cartesian coordinates Field2D Rxy, Zxy, hthe, Bpxy; if (mesh->get(Rxy, "Rxy")) { throw BoutException("Fluid neutrals model requires Rxy"); } if (mesh->get(Zxy, "Zxy")) { throw BoutException("Fluid neutrals model requires Zxy"); } if (mesh->get(hthe, "hthe")) { throw BoutException("Fluid neutrals model requires hthe"); } if (mesh->get(Bpxy, "Bpxy")) { throw BoutException("Fluid neutrals model requires Bpxy"); } // Normalise Rxy /= Lnorm; Zxy /= Lnorm; hthe /= Lnorm; Bpxy /= Bnorm; // Axisymmetric neutrals simplifies things considerably... Urx.allocate(); Ury.allocate(); Uzx.allocate(); Uzy.allocate(); Txr.allocate(); Txz.allocate(); Tyr.allocate(); Tyz.allocate(); for (int i = 0; i < mesh->LocalNx; i++) for (int j = mesh->ystart; j <= mesh->yend; j++) { // Central differencing of coordinates BoutReal dRdtheta, dZdtheta; if (j == mesh->ystart) { dRdtheta = (Rxy(i, j + 1) - Rxy(i, j)) / (coord->dy(i, j)); dZdtheta = (Zxy(i, j + 1) - Zxy(i, j)) / (coord->dy(i, j)); } else if (j == mesh->yend) { dRdtheta = (Rxy(i, j) - Rxy(i, j - 1)) / (coord->dy(i, j)); dZdtheta = (Zxy(i, j) - Zxy(i, j - 1)) / (coord->dy(i, j)); } else { dRdtheta = (Rxy(i, j + 1) - Rxy(i, j - 1)) / (2. * coord->dy(i, j)); dZdtheta = (Zxy(i, j + 1) - Zxy(i, j - 1)) / (2. * coord->dy(i, j)); } // Match to hthe, 1/|Grad y| BoutReal h = sqrt(SQ(dRdtheta) + SQ(dZdtheta)); BoutReal grady = 1.0 / hthe(i, j); dRdtheta = dRdtheta / grady / h; dZdtheta = dZdtheta / grady / h; BoutReal dRdpsi, dZdpsi; if (i == 0) { // One-sided differences dRdpsi = (Rxy(i + 1, j) - Rxy(i, j)) / (coord->dx(i, j)); dZdpsi = (Zxy(i + 1, j) - Zxy(i, j)) / (coord->dx(i, j)); } else if (i == (mesh->LocalNx - 1)) { // One-sided differences dRdpsi = (Rxy(i, j) - Rxy(i - 1, j)) / (coord->dx(i, j)); dZdpsi = (Zxy(i, j) - Zxy(i - 1, j)) / (coord->dx(i, j)); } else { dRdpsi = (Rxy(i + 1, j) - Rxy(i - 1, j)) / (2. * coord->dx(i, j)); dZdpsi = (Zxy(i + 1, j) - Zxy(i - 1, j)) / (2. * coord->dx(i, j)); } // Match to Bp, |Grad psi|. NOTE: this only works if // X and Y are orthogonal. BoutReal dldpsi = sqrt(SQ(dRdpsi) + SQ(dZdpsi)) * cosbeta(i, j); // ~ 1/(R*Bp) dRdpsi /= dldpsi * Bpxy(i, j) * Rxy(i, j); dZdpsi /= dldpsi * Bpxy(i, j) * Rxy(i, j); Urx(i, j) = dRdpsi; Ury(i, j) = dRdtheta; Uzx(i, j) = dZdpsi; Uzy(i, j) = dZdtheta; // Poloidal (R,Z) transformation Jacobian BoutReal J = dRdpsi * dZdtheta - dZdpsi * dRdtheta; Txr(i, j) = dZdtheta / J; Txz(i, j) = -dRdtheta / J; Tyr(i, j) = -dZdpsi / J; Tyz(i, j) = dRdpsi / J; } Urx.applyBoundary("neumann"); Ury.applyBoundary("neumann"); Uzx.applyBoundary("neumann"); Uzy.applyBoundary("neumann"); Txr.applyBoundary("neumann"); Txz.applyBoundary("neumann"); Tyr.applyBoundary("neumann"); Tyz.applyBoundary("neumann"); } /// Modify the given simulation state void NeutralFullVelocity::transform(Options &state) { mesh->communicate(Nn2D, Vn2D, Pn2D); // Navier-Stokes for axisymmetric neutral gas profiles // Nn2D, Pn2D and Tn2D are unfloored Tn2D = Pn2D / Nn2D; // Floored fields, used for rate coefficients Field2D Nn = floor(Nn2D, 1e-8); Field2D Tn = floor(Tn2D, 0.01 / Tnorm); ////////////////////////////////////////////////////// // 2D (X-Y) full velocity model // // Evolves density Nn2D, velocity vector Vn2D and pressure Pn2D // if (outflow_ydown) { // Outflowing boundaries at ydown. If flow direction is // into domain then zero value is set. If flow is out of domain // then Neumann conditions are set for (RangeIterator idwn = mesh->iterateBndryLowerY(); !idwn.isDone(); idwn.next()) { if (Vn2D.y(idwn.ind, mesh->ystart) < 0.0) { // Flowing out of domain Vn2D.y(idwn.ind, mesh->ystart - 1) = Vn2D.y(idwn.ind, mesh->ystart); } else { // Flowing into domain Vn2D.y(idwn.ind, mesh->ystart - 1) = -Vn2D.y(idwn.ind, mesh->ystart); } // Neumann boundary condition on X and Z components Vn2D.x(idwn.ind, mesh->ystart - 1) = Vn2D.x(idwn.ind, mesh->ystart); Vn2D.z(idwn.ind, mesh->ystart - 1) = Vn2D.z(idwn.ind, mesh->ystart); // Neumann conditions on density and pressure Nn2D(idwn.ind, mesh->ystart - 1) = Nn2D(idwn.ind, mesh->ystart); Pn2D(idwn.ind, mesh->ystart - 1) = Pn2D(idwn.ind, mesh->ystart); } } // Exchange of parallel momentum. This could be done // in a couple of ways, but here we use the fact that // Vn2D is covariant and b = e_y / (JB) to write: // // V_{||n} = b dot V_n = Vn2D.y / (JB) Field2D Vnpar = Vn2D.y / (coord->J * coord->Bxy); // Set values in the state auto& localstate = state["species"][name]; set(localstate["density"], Nn); set(localstate["pressure"], Pn2D); set(localstate["momentum"], Vnpar * Nn * AA); set(localstate["velocity"], Vnpar); // Parallel velocity set(localstate["temperature"], Tn); } /// Use the final simulation state to update internal state /// (e.g. time derivatives) void NeutralFullVelocity::finally(const Options &state) { // Density ddt(Nn2D) = -Div(Vn2D, Nn2D); Field2D Nn2D_floor = floor(Nn2D, 1e-2); // Velocity ddt(Vn2D) = -Grad(Pn2D) / (AA * Nn2D_floor); ////////////////////////////////////////////////////// // Momentum advection // Convert to cylindrical coordinates for velocity // advection term. This is to avoid Christoffel symbol // terms in curvilinear geometry Field2D vr = Txr * Vn2D.x + Tyr * Vn2D.y; // Grad R component Field2D vz = Txz * Vn2D.x + Tyz * Vn2D.y; // Grad Z component // Advect as scalars (no Christoffel symbols needed) ddt(vr) = -V_dot_Grad(Vn2D, vr); ddt(vz) = -V_dot_Grad(Vn2D, vz); // Convert back to field-aligned coordinates ddt(Vn2D).x += Urx * ddt(vr) + Uzx * ddt(vz); ddt(Vn2D).y += Ury * ddt(vr) + Uzy * ddt(vz); ////////////////////////////////////////////////////// // Viscosity // This includes dynamic ( neutral_viscosity) // and bulk/volume viscosity ( neutral_bulk ) ddt(vr) = Laplace_FV(neutral_viscosity, vr); ddt(vz) = Laplace_FV(neutral_viscosity, vz); ddt(Vn2D).x += Urx * ddt(vr) + Uzx * ddt(vz); ddt(Vn2D).y += Ury * ddt(vr) + Uzy * ddt(vz); DivV2D = Div(Vn2D); DivV2D.applyBoundary(0.0); mesh->communicate(DivV2D); // ddt(Vn2D) += Grad( (neutral_viscosity/3. + neutral_bulk) * DivV2D ) / // Nn2D_floor; ////////////////////////////////////////////////////// // Pressure ddt(Pn2D) = -Div(Vn2D, Pn2D) - (gamma_ratio - 1.) * Pn2D * DivV2D * floor(Nn2D, 0) / Nn2D_floor + Laplace_FV(neutral_conduction, Pn2D / Nn2D); /////////////////////////////////////////////////////////////////// // Boundary condition on fluxes for (RangeIterator r = mesh->iterateBndryLowerY(); !r.isDone(); r++) { // Loss of thermal energy to the target. // This depends on the reflection coefficient // and is controlled by the option neutral_gamma // q = neutral_gamma * n * T * cs // Density at the target BoutReal Nnout = 0.5 * (Nn2D(r.ind, mesh->ystart) + Nn2D(r.ind, mesh->ystart - 1)); if (Nnout < 0.0) Nnout = 0.0; // Temperature at the target BoutReal Tnout = 0.5 * (Tn2D(r.ind, mesh->ystart) + Tn2D(r.ind, mesh->ystart - 1)); if (Tnout < 0.0) Tnout = 0.0; // gamma * n * T * cs BoutReal q = neutral_gamma * Nnout * Tnout * sqrt(Tnout); // Multiply by cell area to get power BoutReal heatflux = q * (coord->J(r.ind, mesh->ystart) + coord->J(r.ind, mesh->ystart - 1)) / (sqrt(coord->g_22(r.ind, mesh->ystart)) + sqrt(coord->g_22(r.ind, mesh->ystart - 1))); // Divide by volume of cell, and multiply by 2/3 to get pressure ddt(Pn2D)(r.ind, mesh->ystart) -= (2. / 3) * heatflux / (coord->dy(r.ind, mesh->ystart) * coord->J(r.ind, mesh->ystart)); } for (RangeIterator r = mesh->iterateBndryUpperY(); !r.isDone(); r++) { // Loss of thermal energy to the target. // This depends on the reflection coefficient // and is controlled by the option neutral_gamma // q = neutral_gamma * n * T * cs // Density at the target BoutReal Nnout = 0.5 * (Nn2D(r.ind, mesh->yend) + Nn2D(r.ind, mesh->yend + 1)); if (Nnout < 0.0) Nnout = 0.0; // Temperature at the target BoutReal Tnout = 0.5 * (Tn2D(r.ind, mesh->yend) + Tn2D(r.ind, mesh->yend + 1)); if (Tnout < 0.0) Tnout = 0.0; // gamma * n * T * cs BoutReal q = neutral_gamma * Nnout * Tnout * sqrt(Tnout); // Multiply by cell area to get power BoutReal heatflux = q * (coord->J(r.ind, mesh->yend) + coord->J(r.ind, mesh->yend + 1)) / (sqrt(coord->g_22(r.ind, mesh->yend)) + sqrt(coord->g_22(r.ind, mesh->yend + 1))); // Divide by volume of cell, and multiply by 2/3 to get pressure ddt(Pn2D)(r.ind, mesh->yend) -= (2. / 3) * heatflux / (coord->dy(r.ind, mesh->yend) * coord->J(r.ind, mesh->yend)); } ///////////////////////////////////////////////////// // Atomic processes auto& localstate = state["species"][name]; // Particles if (localstate.isSet("density_source")) { ddt(Nn2D) += get<Field2D>(localstate["density_source"]); } // Momentum. Note need to turn back into covariant form if (localstate.isSet("momentum_source")) { ddt(Vn2D).y += get<Field2D>(localstate["momentum_source"]) * (coord->J * coord->Bxy) / (AA * Nn2D_floor); } // Energy if (localstate.isSet("energy_source")) { ddt(Pn2D) += (2. / 3) * get<Field2D>(localstate["energy_source"]); } // Density evolution for (auto &i : Nn2D.getRegion("RGN_ALL")) { if ((Nn2D[i] < 1e-8) && (ddt(Nn2D)[i] < 0.0)) { ddt(Nn2D)[i] = 0.0; } } } /// Add extra fields for output, or set attributes e.g docstrings void NeutralFullVelocity::outputVars(Options &state) { // Normalisations auto Nnorm = get<BoutReal>(state["Nnorm"]); auto Tnorm = get<BoutReal>(state["Tnorm"]); auto Omega_ci = get<BoutReal>(state["Omega_ci"]); auto Cs0 = get<BoutReal>(state["Cs0"]); set_with_attrs(state["DivV2D"], DivV2D, { {"time_dimension", "t"}, {"units", "s^-1"}, {"conversion", Omega_ci} }); set_with_attrs(state["Urx"], Urx, {}); set_with_attrs(state["Ury"], Ury, {}); set_with_attrs(state["Uzx"], Uzx, {}); set_with_attrs(state["Uzy"], Uzy, {}); set_with_attrs(state["Txr"], Txr, {}); set_with_attrs(state["Txz"], Txz, {}); set_with_attrs(state["Tyr"], Tyr, {}); set_with_attrs(state["Tyz"], Tyz, {}); }
12,665
C++
.cxx
314
35.031847
114
0.587132
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,196
neutral_parallel_diffusion.cxx
bendudson_hermes-3/src/neutral_parallel_diffusion.cxx
#include "../include/neutral_parallel_diffusion.hxx" #include <bout/constants.hxx> #include <bout/fv_ops.hxx> using bout::globals::mesh; void NeutralParallelDiffusion::transform(Options& state) { AUTO_TRACE(); Options& allspecies = state["species"]; for (auto& kv : allspecies.getChildren()) { const auto& species_name = kv.first; // Get non-const reference auto& species = allspecies[species_name]; if (species.isSet("charge") and (get<BoutReal>(species["charge"]) != 0.0)) { // Skip charged species continue; } auto nu = GET_VALUE(Field3D, species["collision_frequency"]); const BoutReal AA = GET_VALUE(BoutReal, species["AA"]); // Atomic mass const Field3D Nn = GET_VALUE(Field3D, species["density"]); const Field3D Tn = GET_VALUE(Field3D, species["temperature"]); const Field3D Pn = IS_SET(species["pressure"]) ? GET_VALUE(Field3D, species["pressure"]) : Nn * Tn; BoutReal advection_factor = 0; BoutReal kappa_factor = 0; if (equation_fix) { advection_factor = (5. / 2); // This is equivalent to 5/3 if on pressure basis kappa_factor = (5. / 2); } else { advection_factor = (3. / 2); kappa_factor = 1; } // Pressure-diffusion coefficient Field3D Dn = dneut * Tn / (AA * nu); Dn.applyBoundary("dirichlet_o2"); mesh->communicate(Dn); // Cross-field diffusion calculated from pressure gradient // This is the pressure-diffusion approximation Field3D logPn = log(floor(Pn, 1e-7)); logPn.applyBoundary("neumann"); // Particle advection Field3D S = FV::Div_par_K_Grad_par(Dn * Nn, logPn); add(species["density_source"], S); Field3D kappa_n = kappa_factor * Nn * Dn; kappa_n.applyBoundary("neumann"); // Heat transfer Field3D E = + FV::Div_par_K_Grad_par( Dn * advection_factor * Pn, logPn); // Pressure advection if (thermal_conduction) { E += FV::Div_par_K_Grad_par(kappa_n, Tn); // Conduction } add(species["energy_source"], E); Field3D F = 0.0; if (IS_SET(species["velocity"]) and viscosity) { // Relationship between heat conduction and viscosity for neutral // gas Chapman, Cowling "The Mathematical Theory of Non-Uniform // Gases", CUP 1952 Ferziger, Kaper "Mathematical Theory of // Transport Processes in Gases", 1972 // Field3D Vn = GET_VALUE(Field3D, species["velocity"]); Field3D NVn = GET_VALUE(Field3D, species["momentum"]); Field3D eta_n = (2. / 5) * kappa_n; // Momentum diffusion F = FV::Div_par_K_Grad_par(NVn * Dn, logPn) + FV::Div_par_K_Grad_par(eta_n, Vn); add(species["momentum_source"], F); } if (diagnose) { // Find the diagnostics struct for this species auto search = diagnostics.find(species_name); if (search == diagnostics.end()) { // First time, create diagnostic diagnostics.emplace(species_name, Diagnostics {Dn, S, E, F}); } else { // Update diagnostic values auto& d = search->second; d.Dn = Dn; d.S = S; d.E = E; d.F = F; } } } } void NeutralParallelDiffusion::outputVars(Options &state) { AUTO_TRACE(); if (diagnose) { // Normalisations auto Nnorm = get<BoutReal>(state["Nnorm"]); auto Tnorm = get<BoutReal>(state["Tnorm"]); auto Omega_ci = get<BoutReal>(state["Omega_ci"]); auto Cs0 = get<BoutReal>(state["Cs0"]); auto rho_s0 = get<BoutReal>(state["rho_s0"]); for (const auto& it : diagnostics) { const std::string& species_name = it.first; const auto& d = it.second; set_with_attrs(state[std::string("D") + species_name + std::string("_Dpar")], d.Dn, {{"time_dimension", "t"}, {"units", "m^2/s"}, {"conversion", rho_s0 * Cs0}, {"standard_name", "diffusion coefficient"}, {"long_name", species_name + " particle diffusion coefficient"}, {"species", species_name}, {"source", "neutral_parallel_diffusion"}}); set_with_attrs(state[std::string("S") + species_name + std::string("_Dpar")], d.S, {{"time_dimension", "t"}, {"units", "s^-1"}, {"conversion", Nnorm * Omega_ci}, {"standard_name", "particle diffusion"}, {"long_name", species_name + " particle source due to diffusion"}, {"species", species_name}, {"source", "neutral_parallel_diffusion"}}); set_with_attrs(state[std::string("E") + species_name + std::string("_Dpar")], d.E, {{"time_dimension", "t"}, {"units", "W / m^3"}, {"conversion", SI::qe * Tnorm * Nnorm * Omega_ci}, {"standard_name", "energy diffusion"}, {"long_name", species_name + " energy source due to diffusion"}, {"species", species_name}, {"source", "neutral_parallel_diffusion"}}); set_with_attrs(state[std::string("F") + species_name + std::string("_Dpar")], d.F, {{"time_dimension", "t"}, {"units", "kg m^-2 s^-2"}, {"conversion", SI::Mp * Nnorm * Cs0 * Omega_ci}, {"standard_name", "momentum diffusion"}, {"long_name", species_name + " momentum source due to diffusion"}, {"species", species_name}, {"source", "neutral_parallel_diffusion"}}); } } }
5,651
C++
.cxx
128
35.109375
89
0.572286
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,197
electron_force_balance.cxx
bendudson_hermes-3/src/electron_force_balance.cxx
#include <bout/difops.hxx> #include "../include/electron_force_balance.hxx" using bout::globals::mesh; void ElectronForceBalance::transform(Options &state) { AUTO_TRACE(); if (IS_SET(state["fields"]["phi"])) { // Here we use electron force balance to calculate the parallel electric field // rather than the electrostatic potential throw BoutException("Cannot calculate potential and use electron force balance\n"); } // Get the electron pressure, with boundary condition applied Options& electrons = state["species"]["e"]; Field3D Pe = GET_VALUE(Field3D, electrons["pressure"]); Field3D Ne = GET_NOBOUNDARY(Field3D, electrons["density"]); ASSERT1(get<BoutReal>(electrons["charge"]) == -1.0); // Force balance, E = (-∇p + F) / n Field3D force_density = - Grad_par(Pe); if (IS_SET(electrons["momentum_source"])) { // Balance other forces from e.g. collisions // Note: marked as final so can't be changed later force_density += GET_VALUE(Field3D, electrons["momentum_source"]); } const Field3D Epar = force_density / floor(Ne, 1e-5); // Now calculate forces on other species Options& allspecies = state["species"]; for (auto& kv : allspecies.getChildren()) { if (kv.first == "e") { continue; // Skip electrons } Options& species = allspecies[kv.first]; // Note: Need non-const if (!(IS_SET(species["density"]) and IS_SET(species["charge"]))) { continue; // Needs both density and charge to experience a force } const Field3D N = GET_NOBOUNDARY(Field3D, species["density"]); const BoutReal charge = get<BoutReal>(species["charge"]); add(species["momentum_source"], charge * N * Epar); } }
1,711
C++
.cxx
39
39.717949
87
0.688366
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,198
collisions.cxx
bendudson_hermes-3/src/collisions.cxx
#include <iterator> #include <bout/constants.hxx> #include <bout/output_bout_types.hxx> #include "../include/collisions.hxx" namespace { BoutReal floor(BoutReal value, BoutReal min) { if (value < min) return min; return value; } } // namespace Collisions::Collisions(std::string name, Options& alloptions, Solver*) { AUTO_TRACE(); const Options& units = alloptions["units"]; // Normalisations Tnorm = units["eV"]; Nnorm = units["inv_meters_cubed"]; rho_s0 = units["meters"]; Omega_ci = 1. / units["seconds"].as<BoutReal>(); Options& options = alloptions[name]; electron_electron = options["electron_electron"] .doc("Include electron-electron collisions?") .withDefault<bool>(true); electron_ion = options["electron_ion"] .doc("Include electron-ion collisions?") .withDefault<bool>(true); electron_neutral = options["electron_neutral"] .doc("Include electron-neutral elastic collisions?") .withDefault<bool>(false); ion_ion = options["ion_ion"] .doc("Include ion-ion elastic collisions?") .withDefault<bool>(true); ion_neutral = options["ion_neutral"] .doc("Include ion-neutral elastic collisions?") .withDefault<bool>(false); neutral_neutral = options["neutral_neutral"] .doc("Include neutral-neutral elastic collisions?") .withDefault<bool>(true); frictional_heating = options["frictional_heating"] .doc("Include R dot v heating term as energy source?") .withDefault<bool>(true); ei_multiplier = options["ei_multiplier"] .doc("User-set arbitrary multiplier on electron-ion collision rate") .withDefault<BoutReal>(1.0); diagnose = options["diagnose"].doc("Output additional diagnostics?").withDefault<bool>(false); } /// Calculate transfer of momentum and energy between species1 and species2 /// nu_12 normalised frequency /// /// Modifies /// species1 and species2 /// - collision_frequency /// - momentum_source if species1 or species2 velocity is set /// - energy_source if species1 or species2 temperature is set /// or velocity is set and frictional_heating /// /// Note: A* variables are used for atomic mass numbers; /// mass* variables are species masses in kg void Collisions::collide(Options& species1, Options& species2, const Field3D& nu_12, BoutReal momentum_coefficient) { AUTO_TRACE(); add(species1["collision_frequency"], nu_12); set(collision_rates[species1.name()][species2.name()], nu_12); if (&species1 != &species2) { // For collisions between different species // m_a n_a \nu_{ab} = m_b n_b \nu_{ba} const BoutReal A1 = get<BoutReal>(species1["AA"]); const BoutReal A2 = get<BoutReal>(species2["AA"]); const Field3D density1 = GET_NOBOUNDARY(Field3D, species1["density"]); const Field3D density2 = GET_NOBOUNDARY(Field3D, species2["density"]); const Field3D nu = filledFrom(nu_12, [&](auto& i) { return nu_12[i] * (A1 / A2) * density1[i] / floor(density2[i], 1e-5); }); add(species2["collision_frequency"], nu); set(collision_rates[species2.name()][species1.name()], nu); // Momentum exchange if (isSetFinalNoBoundary(species1["velocity"]) or isSetFinalNoBoundary(species2["velocity"])) { const Field3D velocity1 = species1.isSet("velocity") ? GET_NOBOUNDARY(Field3D, species1["velocity"]) : 0.0; const Field3D velocity2 = species2.isSet("velocity") ? GET_NOBOUNDARY(Field3D, species2["velocity"]) : 0.0; // F12 is the force on species 1 due to species 2 (normalised) const Field3D F12 = momentum_coefficient * nu_12 * A1 * density1 * (velocity2 - velocity1); add(species1["momentum_source"], F12); subtract(species2["momentum_source"], F12); if (frictional_heating) { // Heating due to friction and energy transfer // // In the pressure (thermal energy) equation we have a term // that transfers translational kinetic energy to thermal // energy, and an energy transfer between species: // // d/dt(3/2p_1) = ... - F_12 v_1 + W_12 // // The energy transfer term W_12 is chosen to make the // pressure change frame invariant: // // W_12 = (m_1 v_1 + m_2 v_2) / (m_1 + m_2) * F_12 // // The sum of these two terms is: // // - F_12 v_1 + W_12 = m_2 (v_2 - v_1) / (m_1 + m_2) * F_12 // // Note: // 1) This term is always positive: Collisions don't lead to cooling // 2) In the limit that m_2 << m_1 (e.g. electron-ion collisions), // the lighter species is heated more than the heavy species. add(species1["energy_source"], (A2 / (A1 + A2)) * (velocity2 - velocity1) * F12); add(species2["energy_source"], (A1 / (A1 + A2)) * (velocity2 - velocity1) * F12); } } // Energy exchange if (species1.isSet("temperature") or species2.isSet("temperature")) { // Q12 is heat transferred to species2 (normalised) const Field3D temperature1 = GET_NOBOUNDARY(Field3D, species1["temperature"]); const Field3D temperature2 = GET_NOBOUNDARY(Field3D, species2["temperature"]); const Field3D Q12 = nu_12 * 3. * density1 * (A1 / (A1 + A2)) * (temperature2 - temperature1); add(species1["energy_source"], Q12); subtract(species2["energy_source"], Q12); } } } void Collisions::transform(Options& state) { AUTO_TRACE(); Options& allspecies = state["species"]; // Treat electron collisions specially // electron-ion and electron-neutral collisions if (allspecies.isSection("e")) { Options& electrons = allspecies["e"]; const Field3D Te = GET_NOBOUNDARY(Field3D, electrons["temperature"]) * Tnorm; // eV const Field3D Ne = GET_NOBOUNDARY(Field3D, electrons["density"]) * Nnorm; // In m^-3 for (auto& kv : allspecies.getChildren()) { if (kv.first == "e") { //////////////////////////////////// // electron-electron collisions if (!electron_electron) continue; const Field3D nu_ee = filledFrom(Ne, [&](auto& i) { const BoutReal Telim = floor(Te[i], 0.1); const BoutReal Nelim = floor(Ne[i], 1e10); const BoutReal logTe = log(Telim); // From NRL formulary 2019, page 34 // Coefficient 30.4 from converting cm^-3 to m^-3 // Note that this breaks when coulomb_log falls below 1 const BoutReal coulomb_log = 30.4 - 0.5 * log(Nelim) + (5. / 4) * logTe - sqrt(1e-5 + SQ(logTe - 2) / 16.); const BoutReal v1sq = 2 * Telim * SI::qe / SI::Me; // Collision frequency const BoutReal nu = SQ(SQ(SI::qe)) * floor(Ne[i], 0.0) * floor(coulomb_log, 1.0) * 2 / (3 * pow(PI * 2 * v1sq, 1.5) * SQ(SI::e0 * SI::Me)); ASSERT2(std::isfinite(nu)); return nu; }); collide(electrons, electrons, nu_ee / Omega_ci, 1.0); continue; } Options& species = allspecies[kv.first]; // Note: Need non-const if (species.isSet("charge") and (get<BoutReal>(species["charge"]) > 0.0)) { //////////////////////////////////// // electron-positive ion collisions if (!electron_ion) continue; const Field3D Ti = GET_NOBOUNDARY(Field3D, species["temperature"]) * Tnorm; // eV const Field3D Ni = GET_NOBOUNDARY(Field3D, species["density"]) * Nnorm; // In m^-3 const BoutReal Zi = get<BoutReal>(species["charge"]); const BoutReal Ai = get<BoutReal>(species["AA"]); const BoutReal me_mi = SI::Me / (SI::Mp * Ai); // m_e / m_i const Field3D nu_ei = filledFrom(Ne, [&](auto& i) { // NRL formulary 2019, page 34 const BoutReal coulomb_log = ((Te[i] < 0.1) || (Ni[i] < 1e10) || (Ne[i] < 1e10)) ? 10 : (Te[i] < Ti[i] * me_mi) ? 23 - 0.5 * log(Ni[i]) + 1.5 * log(Ti[i]) - log(SQ(Zi) * Ai) : (Te[i] < exp(2) * SQ(Zi)) // Fix to ei coulomb log from S.Mijin ReMKiT1D // Ti m_e/m_i < Te < 10 Z^2 ? 30.0 - 0.5 * log(Ne[i]) - log(Zi) + 1.5 * log(Te[i]) // Ti m_e/m_i < 10 Z^2 < Te : 31.0 - 0.5 * log(Ne[i]) + log(Te[i]); // Calculate v_a^2, v_b^2 const BoutReal vesq = 2 * floor(Te[i], 0.1) * SI::qe / SI::Me; const BoutReal visq = 2 * floor(Ti[i], 0.1) * SI::qe / (SI::Mp * Ai); // Collision frequency const BoutReal nu = SQ(SQ(SI::qe) * Zi) * floor(Ni[i], 0.0) * floor(coulomb_log, 1.0) * (1. + me_mi) / (3 * pow(PI * (vesq + visq), 1.5) * SQ(SI::e0 * SI::Me)) * ei_multiplier; #if CHECK >= 2 if (!std::isfinite(nu)) { throw BoutException("Collisions 195 {}: {} at {}: Ni {}, Ne {}, Clog {}, vesq {}, visq {}, Te {}, Ti {}\n", kv.first, nu, i, Ni[i], Ne[i], coulomb_log, vesq, visq, Te[i], Ti[i]); } #endif return nu; }); // Coefficient in front of parallel momentum exchange // This table is from Braginskii 1965 BoutReal mom_coeff = Zi == 1 ? 0.51 : Zi == 2 ? 0.44 : Zi == 3 ? 0.40 : 0.38; // Note: 0.38 is for Zi=4; tends to 0.29 for Zi->infty collide(electrons, species, nu_ei / Omega_ci, mom_coeff); } else if (species.isSet("charge") and (get<BoutReal>(species["charge"]) < 0.0)) { //////////////////////////////////// // electron-negative ion collisions static bool first_time = true; if (first_time) { output_warn.write("Warning: Not calculating e - {} collisions", kv.first); first_time = false; } } else { //////////////////////////////////// // electron-neutral collisions if (!electron_neutral) continue; // Neutral density Field3D Nn = GET_NOBOUNDARY(Field3D, species["density"]); BoutReal a0 = 5e-19; // Cross-section [m^2] const Field3D nu_en = filledFrom(Ne, [&](auto& i) { // Electron thermal speed (normalised) const BoutReal vth_e = sqrt((SI::Mp / SI::Me) * Te[i] / Tnorm); // Electron-neutral collision rate return vth_e * Nnorm * Nn[i] * a0 * rho_s0; }); collide(electrons, species, nu_en, 1.0); } } } // Iterate through other species // To avoid double counting, this needs to iterate over pairs // i.e. the diagonal and above // // Iterators kv1 and kv2 over the species map // // kv2 -> // species1 species2 species3 // kv1 species1 X X X // || species2 X X // \/ species3 X // const std::map<std::string, Options>& children = allspecies.getChildren(); for (auto kv1 = std::begin(children); kv1 != std::end(children); ++kv1) { if (kv1->first == "e" or kv1->first == "ebeam") continue; // Skip electrons Options& species1 = allspecies[kv1->first]; // If temperature isn't set, assume zero. in eV const Field3D temperature1 = species1.isSet("temperature") ? GET_NOBOUNDARY(Field3D, species1["temperature"]) * Tnorm : 0.0; const Field3D density1 = GET_NOBOUNDARY(Field3D, species1["density"]) * Nnorm; const BoutReal AA1 = get<BoutReal>(species1["AA"]); const BoutReal mass1 = AA1 * SI::Mp; // in Kg if (species1.isSet("charge") and (get<BoutReal>(species1["charge"]) != 0.0)) { // Charged species const BoutReal Z1 = get<BoutReal>(species1["charge"]); const BoutReal charge1 = Z1 * SI::qe; // in Coulombs // Copy the iterator, so we don't iterate over the // lower half of the matrix, but start at the diagonal for (std::map<std::string, Options>::const_iterator kv2 = kv1; kv2 != std::end(children); ++kv2) { if (kv2->first == "e" or kv2->first == "ebeam") continue; // Skip electrons Options& species2 = allspecies[kv2->first]; // Note: Here species1 could be equal to species2 // If temperature isn't set, assume zero. in eV const Field3D temperature2 = species2.isSet("temperature") ? GET_NOBOUNDARY(Field3D, species2["temperature"]) * Tnorm : 0.0; const Field3D density2 = GET_NOBOUNDARY(Field3D, species2["density"]) * Nnorm; const BoutReal AA2 = get<BoutReal>(species2["AA"]); const BoutReal mass2 = AA2 * SI::Mp; // in Kg if (species2.isSet("charge") and (get<BoutReal>(species2["charge"]) != 0.0)) { ////////////////////////////// // Both charged species if (!ion_ion) continue; const BoutReal Z2 = get<BoutReal>(species2["charge"]); const BoutReal charge2 = Z2 * SI::qe; // in Coulombs // Ion-ion collisions Field3D nu_12 = filledFrom(density1, [&](auto& i) { const BoutReal Tlim1 = floor(temperature1[i], 0.1); const BoutReal Tlim2 = floor(temperature2[i], 0.1); const BoutReal Nlim1 = floor(density1[i], 1e10); const BoutReal Nlim2 = floor(density2[i], 1e10); // Coulomb logarithm BoutReal coulomb_log = 29.91 - log((Z1 * Z2 * (AA1 + AA2)) / (AA1 * Tlim2 + AA2 * Tlim1) * sqrt(Nlim1 * SQ(Z1) / Tlim1 + Nlim2 * SQ(Z2) / Tlim2)); // Calculate v_a^2, v_b^2 const BoutReal v1sq = 2 * Tlim1 * SI::qe / mass1; const BoutReal v2sq = 2 * Tlim2 * SI::qe / mass2; // Collision frequency const BoutReal nu = SQ(charge1 * charge2) * Nlim2 * floor(coulomb_log, 1.0) * (1. + mass1 / mass2) / (3 * pow(PI * (v1sq + v2sq), 1.5) * SQ(SI::e0 * mass1)); ASSERT2(std::isfinite(nu)); return nu; }); // Update the species collision rates, momentum & energy exchange collide(species1, species2, nu_12 / Omega_ci, 1.0); } else { // species1 charged, species2 neutral // Scattering of charged species 1 // Neutral density Field3D Nn = GET_NOBOUNDARY(Field3D, species2["density"]); BoutReal a0 = 5e-19; // Cross-section [m^2] const Field3D nu_12 = filledFrom(density1, [&](auto& i) { // Relative velocity is sqrt( v1^2 + v2^2 ) const BoutReal vrel = sqrt(temperature1[i] / (Tnorm * AA1) + temperature2[i] / (Tnorm * AA2)); // Ion-neutral collision rate // Units: density [m^-3], a0 [m^2], rho_s0 [m] return vrel * density2[i] * a0 * rho_s0; }); collide(species1, species2, nu_12, 1.0); } } } else { // species1 neutral // Copy the iterator, so we don't iterate over the // lower half of the matrix, but start at the diagonal for (std::map<std::string, Options>::const_iterator kv2 = kv1; kv2 != std::end(children); ++kv2) { if (kv2->first == "e") continue; // Skip electrons Options& species2 = allspecies[kv2->first]; // Note: Here species1 could be equal to species2 // If temperature isn't set, assume zero const Field3D temperature2 = species2.isSet("temperature") ? GET_NOBOUNDARY(Field3D, species2["temperature"]) * Tnorm : 0.0; const BoutReal AA2 = get<BoutReal>(species2["AA"]); const Field3D density2 = GET_NOBOUNDARY(Field3D, species2["density"]) * Nnorm; if (species2.isSet("charge")) { // species1 neutral, species2 charged if (!ion_neutral) continue; // Scattering of charged species 2 // This is from NRL. The cross-section can vary significantly BoutReal a0 = 5e-19; // Cross-section [m^2] const Field3D nu_12 = filledFrom(density1, [&](auto& i) { // Relative velocity is sqrt( v1^2 + v2^2 ) const BoutReal vrel = sqrt(temperature1[i] / (Tnorm * AA1) + temperature2[i] / (Tnorm * AA2)); // Ion-neutral collision rate // Units: density [m^-3], a0 [m^2], rho_s0 [m] return vrel * density2[i] * a0 * rho_s0; }); collide(species1, species2, nu_12, 1.0); } else { // Both species neutral if (!neutral_neutral) continue; // The cross section is given by π ( (d1 + d2)/2 )^2 // where d is the kinetic diameter // // Typical values [m] // H2 2.89e-10 // He 2.60e-10 // Ne 2.75e-10 // BoutReal a0 = PI * SQ(2.8e-10); // Cross-section [m^2] const Field3D nu_12 = filledFrom(density1, [&](auto& i) { // Relative velocity is sqrt( v1^2 + v2^2 ) const BoutReal vrel = sqrt(temperature1[i] / (Tnorm * AA1) + temperature2[i] / (Tnorm * AA2)); // Ion-neutral collision rate // Units: density [m^-3], a0 [m^2], rho_s0 [m] return vrel * density2[i] * a0 * rho_s0; }); collide(species1, species2, nu_12, 1.0); } } } } } void Collisions::outputVars(Options& state) { AUTO_TRACE(); if (!diagnose) { return; // Don't save diagnostics } // Normalisations auto Omega_ci = get<BoutReal>(state["Omega_ci"]); /// Iterate through the first species in each collision pair const std::map<std::string, Options>& level1 = collision_rates.getChildren(); for (auto s1 = std::begin(level1); s1 != std::end(level1); ++s1) { const Options& section = collision_rates[s1->first]; /// Iterate through the second species in each collision pair const std::map<std::string, Options>& level2 = section.getChildren(); for (auto s2 = std::begin(level2); s2 != std::end(level2); ++s2) { std::string name = s1->first + s2->first; set_with_attrs(state[std::string("K") + name + std::string("_coll")], getNonFinal<Field3D>(section[s2->first]), {{"time_dimension", "t"}, {"units", "s-1"}, {"conversion", Omega_ci}, {"standard_name", "collision frequency"}, {"long_name", name + " collision frequency"}, {"species", name}, {"source", "collisions"}}); } } }
19,287
C++
.cxx
411
37.055961
117
0.553608
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,199
detachment_controller.cxx
bendudson_hermes-3/src/detachment_controller.cxx
#include "../include/detachment_controller.hxx" #include <bout/mesh.hxx> using bout::globals::mesh; #include <algorithm> // Include for std::max #include <iostream> #include <iomanip> #include <numeric> BoutReal calculateGradient(const std::vector<BoutReal>& x, const std::vector<BoutReal>& y) { size_t N = x.size(); BoutReal sum_x = std::accumulate(x.begin(), x.end(), 0.0); BoutReal sum_y = std::accumulate(y.begin(), y.end(), 0.0); BoutReal sum_xy = 0.0; BoutReal sum_x_squared = 0.0; for (size_t i = 0; i < N; ++i) { sum_xy += x[i] * y[i]; sum_x_squared += x[i] * x[i]; } BoutReal numerator = N * sum_xy - sum_x * sum_y; BoutReal denominator = N * sum_x_squared - sum_x * sum_x; if (denominator == 0) { return 0.0; // Handle division by zero or return an error code } return numerator / denominator; } void DetachmentController::transform(Options& state) { std::cout << std::fixed << std::setprecision(15); // Part 1: compute the detachment front location Field3D neutral_density = getNoBoundary<Field3D>(state["species"][neutral_species]["density"]); Field3D electron_density = getNoBoundary<Field3D>(state["species"]["e"]["density"]); Coordinates *coord = mesh->getCoordinates(); // Set the initial value so that if no point has Nn > Ne, the detachment front is // at the target. bool detachment_front_found = false; BoutReal distance_from_upstream = -(coord->dy(0, mesh->ystart - 1, 0) + coord->dy(0, mesh->ystart, 0)) / 4.0; // Looking at https://github.com/boutproject/xhermes/blob/main/xhermes/accessors.py#L58 // dy from the first two cells cancels out for (int j = mesh->ystart; j <= mesh->yend; ++j) { BoutReal x1 = distance_from_upstream; //y position of previous point BoutReal a1 = neutral_density(0, j-1, 0); //Nn at previous point BoutReal b1 = electron_density(0, j-1, 0); //Ne at previous point distance_from_upstream = distance_from_upstream + 0.5 * coord->dy(0, j-1, 0) + 0.5 * coord->dy(0, j, 0); BoutReal x2 = distance_from_upstream; //y position of current point BoutReal a2 = neutral_density(0, j, 0); //Nn at current point BoutReal b2 = electron_density(0, j, 0); //Ne at current point // Find the first point where Nn > Ne, when iterating from upstream to target if (a2 > b2) { // Compute the x-value of the intersection between // (x1, a1)->(x2, a2) and (x1, b1)->(x2, b2) // https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection // // This gives a linear approximation of the detachment front position distance_from_upstream = ((x1*b2 - b1*x2) - (x1*a2 - a1*x2)) / ((a1 - a2) - (b1 - b2)); if (debug >= 3) { std::cout << std::endl; std::cout << "x1: " << x1 << std::endl; std::cout << "x2: " << x2 << std::endl; std::cout << "xp: " << distance_from_upstream << std::endl; std::cout << "a1: " << a1 << std::endl; std::cout << "a2: " << a2 << std::endl; std::cout << "b1: " << b1 << std::endl; std::cout << "b2: " << b2 << std::endl; std::cout << "detachment_front_location: " << (connection_length - distance_from_upstream) << std::endl; std::cout << std::endl; } // Make sure that the linear interpolation returns a point between the two sample // points ASSERT2(((x1 < distance_from_upstream) && (distance_from_upstream < x2))); ASSERT2(((0.0 < distance_from_upstream) && (distance_from_upstream < connection_length))); detachment_front_found = true; break; } } // Apply corrections in case something funky happened in the linear interpolation distance_from_upstream = std::max(distance_from_upstream, 0.0); distance_from_upstream = std::min(distance_from_upstream, connection_length); detachment_front_location = connection_length - distance_from_upstream; // Part 2: compute the response // Get the time in real units time = get<BoutReal>(state["time"]) * time_normalisation; // Compute the error error = detachment_front_setpoint - detachment_front_location; if ((((time - previous_time) > min_time_for_change) and (debug >= 2)) or (debug >= 3)) { output << endl; output << "detachment_front_location: " << detachment_front_location << endl; output << "time: " << time << endl; output << "time - previous_time " << (time - previous_time) << endl; output << "error - previous_error " << (error - previous_error) << endl; output << "time threshold met? " << ((time - previous_time) >= min_time_for_change) << endl; output << "error threshold met? " << (fabs(error - previous_error) >= min_error_for_change) << endl; output << "passed threshold time? " << (time > settling_time) << endl; output << "reevaluate control? " << ((time > settling_time) && ((time - previous_time) >= min_time_for_change) && (fabs(error - previous_error) >= min_error_for_change)) << endl; output << "control: " << control << endl; output << endl; } if ((time > settling_time) && ((time - previous_time) >= min_time_for_change) && (fabs(error - previous_error) >= min_error_for_change)) { change_in_time = time - previous_time; if (time_buffer.size() >= buffer_size) { time_buffer.erase(time_buffer.begin()); error_buffer.erase(error_buffer.begin()); } time_buffer.push_back(time); error_buffer.push_back(error); derivative = calculateGradient(time_buffer, error_buffer); change_in_error = first_step ? 0.0 : error - previous_error; change_in_derivative = first_step ? 0.0 : derivative - previous_derivative; error_integral = first_step ? 0.0 : error_integral + change_in_time * 0.5 * (error + previous_error); if (velocity_form) { proportional_term = response_sign * controller_gain * change_in_error; integral_term = response_sign * controller_gain * (change_in_time / integral_time) * error; derivative_term = response_sign * controller_gain * derivative_time * change_in_derivative; change_in_control = proportional_term + integral_term + derivative_term; control = previous_control + change_in_control; } else { proportional_term = response_sign * controller_gain * error; integral_term = response_sign * controller_gain * error_integral / integral_time; derivative_term = response_sign * controller_gain * derivative_time * derivative; control = control_offset + proportional_term + integral_term + derivative_term; change_in_control = control - previous_control; } control = std::max(control, minval_for_source_multiplier); control = std::min(control, maxval_for_source_multiplier); if (debug >= 1) { output << endl; output << "detachment_front_location: " << detachment_front_location << endl; output << "previous_time: " << previous_time << endl; output << "change_in_time: " << change_in_time << endl; output << "time: " << time << endl; output << "previous_error: " << previous_error << endl; output << "change_in_error: " << change_in_error << endl; output << "error: " << error << endl; output << "error_integral: " << error_integral << endl; output << "previous_derivative: " << previous_derivative << endl; output << "change_in_derivative: " << change_in_derivative << endl; output << "derivative: " << derivative << endl; output << "previous_control: " << previous_control << endl; output << "change_in_control: " << change_in_control << endl; output << "control: " << control << endl; output << endl; } if (((error < 0.0) && (previous_error > 0.0)) || ((error > 0.0) && (previous_error < 0.0))) { // Detachment front has crossed the setpoint location. if ((number_of_crossings < 1.0) && reset_integral_on_first_crossing) { error_integral = 0.0; if (debug >= 1) { output << endl; output << "Resetting error integral" << endl; output << endl; } } number_of_crossings = number_of_crossings + 1.0; if (debug >= 1) { output << endl; output << "Number of crossings: " << number_of_crossings << endl; output << endl; } } previous_time = time; previous_error = error; previous_control = control; previous_derivative = derivative; first_step = false; } ASSERT2(std::isfinite(control)); // Part 3: Apply the source detachment_source_feedback = control * source_shape; auto species_it = species_list.begin(); auto scaling_factor_it = scaling_factors_list.begin(); while (species_it != species_list.end() && scaling_factor_it != scaling_factors_list.end()) { std::string trimmed_species = trim(*species_it); std::string trimmed_scaling_factor = trim(*scaling_factor_it); if (trimmed_species.empty() || trimmed_scaling_factor.empty()) { ++species_it; ++scaling_factor_it; continue; // Skip this iteration if either trimmed string is empty } BoutReal scaling_factor = stringToReal(trimmed_scaling_factor); if (control_mode == control_power) { add(state["species"][trimmed_species]["energy_source"], scaling_factor * detachment_source_feedback); } else if (control_mode == control_particles) { add(state["species"][trimmed_species]["density_source"], scaling_factor * detachment_source_feedback); } else { ASSERT2(false); } ++species_it; ++scaling_factor_it; } }
10,614
C++
.cxx
187
46.652406
193
0.576502
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,200
thermal_force.cxx
bendudson_hermes-3/src/thermal_force.cxx
#include <bout/difops.hxx> #include "../include/thermal_force.hxx" void ThermalForce::transform(Options& state) { AUTO_TRACE(); Options& allspecies = state["species"]; if (electron_ion && allspecies.isSection("e")) { // Electron-ion collisions Options& electrons = allspecies["e"]; // Need Te boundary to take gradient const Field3D Te = GET_VALUE(Field3D, electrons["temperature"]); const Field3D Grad_Te = Grad_par(Te); for (auto& kv : allspecies.getChildren()) { if (kv.first == "e") { continue; // Omit electron-electron } Options& species = allspecies[kv.first]; if (!species.isSet("charge")) { continue; // Only considering charged particle interactions } const BoutReal Z = get<BoutReal>(species["charge"]); // Don't need density boundary const Field3D nz = GET_NOBOUNDARY(Field3D, species["density"]); Field3D ion_force = nz * (0.71 * SQ(Z)) * Grad_Te; add(species["momentum_source"], ion_force); subtract(electrons["momentum_source"], ion_force); } } if (ion_ion) { // Iterate through other species // To avoid double counting, this needs to iterate over pairs // not including the same species. i.e. above the diagonal // // Iterators kv1 and kv2 over the species map // // kv2 -> // species1 species2 species3 // kv1 species1 X X // || species2 X // \/ species3 // const std::map<std::string, Options>& children = allspecies.getChildren(); for (auto kv1 = std::begin(children); kv1 != std::end(children); ++kv1) { Options& species1 = allspecies[kv1->first]; if (kv1->first == "e" or !species1.isSet("charge")) { continue; // Only considering charged particle interactions } // Copy the iterator, so we don't iterate over the // lower half of the matrix or the diagonal but start the diagonal for (std::map<std::string, Options>::const_iterator kv2 = std::next(kv1); kv2 != std::end(children); ++kv2) { Options& species2 = allspecies[kv2->first]; if (kv2->first == "e" or !species2.isSet("charge")) { continue; // Only considering charged particle interactions } // Now have two different ion species, species1 and species2 // Only including one majority light species, and one trace heavy species Options *light, *heavy; if ((get<BoutReal>(species1["AA"]) < 4) and (get<BoutReal>(species2["AA"]) > 10)) { // species1 light, species2 heavy light = &species1; heavy = &species2; } else if (((get<BoutReal>(species1["AA"]) > 10) and (get<BoutReal>(species2["AA"]) < 4))) { // species1 heavy, species2 light light = &species2; heavy = &species1; } else { // Ignore this combination if (first_time) { // Print warnings the first time output_warn.write( "ThermalForce: Not calculating thermal force between {} and {} species\n", kv1->first, kv2->first); } continue; } // Force on heavy (trace) ion due to light species // This follows Stangeby, page 298 and following const BoutReal mi = get<BoutReal>((*light)["AA"]); const Field3D Ti = GET_VALUE(Field3D, (*light)["temperature"]); const BoutReal mz = get<BoutReal>((*heavy)["AA"]); const BoutReal Z = get<BoutReal>((*heavy)["charge"]); const Field3D nz = GET_NOBOUNDARY(Field3D, (*heavy)["density"]); if (Z == 0.0) { continue; // Check that the charge is not zero } const BoutReal mu = mz / (mi + mz); const BoutReal beta = 3 * (mu + 5 * sqrt(2) * SQ(Z) * (1.1 * pow(mu, 5. / 2) - 0.35 * pow(mu, 3. / 2)) - 1) / (2.6 - 2 * mu + 5.4 * SQ(mu)); const Field3D heavy_force = nz * beta * Grad_par(Ti); add((*heavy)["momentum_source"], heavy_force); subtract((*light)["momentum_source"], heavy_force); } } } first_time = false; // Don't print warnings every time }
4,319
C++
.cxx
101
34.633663
90
0.577015
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,201
evolve_momentum.cxx
bendudson_hermes-3/src/evolve_momentum.cxx
#include <bout/derivs.hxx> #include <bout/difops.hxx> #include <bout/constants.hxx> #include <bout/fv_ops.hxx> #include <bout/output_bout_types.hxx> #include "../include/evolve_momentum.hxx" #include "../include/div_ops.hxx" #include "../include/hermes_build_config.hxx" namespace { BoutReal floor(BoutReal value, BoutReal min) { if (value < min) return min; return value; } } using bout::globals::mesh; EvolveMomentum::EvolveMomentum(std::string name, Options &alloptions, Solver *solver) : name(name) { AUTO_TRACE(); // Evolve the momentum in time solver->add(NV, std::string("NV") + name); auto& options = alloptions[name]; density_floor = options["density_floor"].doc("Minimum density floor").withDefault(1e-5); low_n_diffuse_perp = options["low_n_diffuse_perp"] .doc("Perpendicular diffusion at low density") .withDefault<bool>(false); pressure_floor = density_floor * (1./get<BoutReal>(alloptions["units"]["eV"])); low_p_diffuse_perp = options["low_p_diffuse_perp"] .doc("Perpendicular diffusion at low pressure") .withDefault<bool>(false); bndry_flux = options["bndry_flux"] .doc("Allow flows through radial boundaries") .withDefault<bool>(true); poloidal_flows = options["poloidal_flows"] .doc("Include poloidal ExB flow") .withDefault<bool>(true); hyper_z = options["hyper_z"].doc("Hyper-diffusion in Z").withDefault(-1.0); V.setBoundary(std::string("V") + name); diagnose = options["diagnose"] .doc("Output additional diagnostics?") .withDefault<bool>(false); fix_momentum_boundary_flux = options["fix_momentum_boundary_flux"] .doc("Fix Y boundary momentum flux to boundary midpoint value?") .withDefault<bool>(false); // Set to zero so set for output momentum_source = 0.0; } void EvolveMomentum::transform(Options &state) { AUTO_TRACE(); mesh->communicate(NV); auto& species = state["species"][name]; // Not using density boundary condition auto N = getNoBoundary<Field3D>(species["density"]); Field3D Nlim = floor(N, density_floor); BoutReal AA = get<BoutReal>(species["AA"]); // Atomic mass V = NV / (AA * Nlim); V.applyBoundary(); set(species["velocity"], V); NV_solver = NV; // Save the momentum as calculated by the solver NV = AA * N * V; // Re-calculate consistent with V and N // Note: Now NV and NV_solver will differ when N < density_floor NV_err = NV - NV_solver; // This is used in the finally() function set(species["momentum"], NV); } void EvolveMomentum::finally(const Options &state) { AUTO_TRACE(); auto& species = state["species"][name]; BoutReal AA = get<BoutReal>(species["AA"]); // Get updated momentum with boundary conditions // Note: This momentum may be modified by electromagnetic terms NV = get<Field3D>(species["momentum"]); // Get the species density Field3D N = get<Field3D>(species["density"]); // Apply a floor to the density Field3D Nlim = floor(N, density_floor); // Typical wave speed used for numerical diffusion Field3D fastest_wave; if (state.isSet("fastest_wave")) { fastest_wave = get<Field3D>(state["fastest_wave"]); } else { Field3D T = get<Field3D>(species["temperature"]); fastest_wave = sqrt(T / AA); } // Parallel flow V = get<Field3D>(species["velocity"]); if (state.isSection("fields") and state["fields"].isSet("phi") and species.isSet("charge")) { const BoutReal Z = get<BoutReal>(species["charge"]); if (Z != 0.0) { // Electrostatic potential set and species has charge // -> include ExB flow and parallel force const Field3D phi = get<Field3D>(state["fields"]["phi"]); ddt(NV) = -Div_n_bxGrad_f_B_XPPM(NV, phi, bndry_flux, poloidal_flows, true); // ExB drift // Parallel electric field // Force density = - Z N ∇ϕ ddt(NV) -= Z * N * Grad_par(phi); if (state["fields"].isSet("Apar")) { // Include a correction term for electromagnetic simulations const Field3D Apar = get<Field3D>(state["fields"]["Apar"]); const Field3D density_source = species.isSet("density_source") ? get<Field3D>(species["density_source"]) : zeroFrom(Apar); Field3D dummy; // This is Z * Apar * dn/dt, keeping just leading order terms Field3D dndt = density_source - FV::Div_par_mod<hermes::Limiter>(N, V, fastest_wave, dummy) - Div_n_bxGrad_f_B_XPPM(N, phi, bndry_flux, poloidal_flows, true) ; if (low_n_diffuse_perp) { dndt += Div_Perp_Lap_FV_Index(density_floor / floor(N, 1e-3 * density_floor), N, bndry_flux); } ddt(NV) += Z * Apar * dndt; } } else { ddt(NV) = 0.0; } } else { ddt(NV) = 0.0; } // Note: // - Density floor should be consistent with calculation of V // otherwise energy conservation is affected // - using the same operator as in density and pressure equations doesn't work ddt(NV) -= AA * FV::Div_par_fvv<hermes::Limiter>(Nlim, V, fastest_wave, fix_momentum_boundary_flux); // Parallel pressure gradient if (species.isSet("pressure")) { Field3D P = get<Field3D>(species["pressure"]); ddt(NV) -= Grad_par(P); } if (state.isSection("fields") and state["fields"].isSet("Apar_flutter")) { // Magnetic flutter term const Field3D Apar_flutter = get<Field3D>(state["fields"]["Apar_flutter"]); ddt(NV) -= Div_n_g_bxGrad_f_B_XZ(NV, V, -Apar_flutter); if (species.isSet("pressure")) { Field3D P = get<Field3D>(species["pressure"]); ddt(NV) -= bracket(P, Apar_flutter, BRACKET_ARAKAWA); } } if (species.isSet("low_n_coeff")) { // Low density parallel diffusion Field3D low_n_coeff = get<Field3D>(species["low_n_coeff"]); ddt(NV) += FV::Div_par_K_Grad_par(low_n_coeff * V, N) + FV::Div_par_K_Grad_par(low_n_coeff * Nlim, V); } if (low_n_diffuse_perp) { ddt(NV) += Div_Perp_Lap_FV_Index(density_floor / floor(N, 1e-3 * density_floor), NV, true); } if (low_p_diffuse_perp) { Field3D Plim = floor(get<Field3D>(species["pressure"]), 1e-3 * pressure_floor); ddt(NV) += Div_Perp_Lap_FV_Index(pressure_floor / Plim, NV, true); } if (hyper_z > 0.) { auto* coord = N.getCoordinates(); ddt(NV) -= hyper_z * SQ(SQ(coord->dz)) * D4DZ4(NV); } // Other sources/sinks if (species.isSet("momentum_source")) { momentum_source = get<Field3D>(species["momentum_source"]); ddt(NV) += momentum_source; } // If N < density_floor then NV and NV_solver may differ // -> Add term to force NV_solver towards NV // Note: This correction is calculated in transform() // because NV may be modified by electromagnetic terms ddt(NV) += NV_err; // Scale time derivatives if (state.isSet("scale_timederivs")) { ddt(NV) *= get<Field3D>(state["scale_timederivs"]); } #if CHECKLEVEL >= 1 for (auto& i : NV.getRegion("RGN_NOBNDRY")) { if (!std::isfinite(ddt(NV)[i])) { throw BoutException("ddt(NV{}) non-finite at {}\n", name, i); } } #endif if (diagnose) { // Save flows if they are set if (species.isSet("momentum_flow_xlow")) { flow_xlow = get<Field3D>(species["momentum_flow_xlow"]); } if (species.isSet("momentum_flux_ylow")) { flow_ylow = get<Field3D>(species["momentum_flow_ylow"]); } } // Restore NV to the value returned by the solver // so that restart files contain the correct values // Note: Copy boundary condition so dump file has correct boundary. NV_solver.setBoundaryTo(NV); NV = NV_solver; } void EvolveMomentum::outputVars(Options &state) { AUTO_TRACE(); // Normalisations auto Nnorm = get<BoutReal>(state["Nnorm"]); auto Omega_ci = get<BoutReal>(state["Omega_ci"]); auto Cs0 = get<BoutReal>(state["Cs0"]); state[std::string("NV") + name].setAttributes( {{"time_dimension", "t"}, {"units", "kg / m^2 / s"}, {"conversion", SI::Mp * Nnorm * Cs0}, {"standard_name", "momentum"}, {"long_name", name + " parallel momentum"}, {"species", name}, {"source", "evolve_momentum"}}); if (diagnose) { set_with_attrs(state[std::string("V") + name], V, {{"time_dimension", "t"}, {"units", "m / s"}, {"conversion", Cs0}, {"long_name", name + " parallel velocity"}, {"standard_name", "velocity"}, {"species", name}, {"source", "evolve_momentum"}}); set_with_attrs(state[std::string("ddt(NV") + name + std::string(")")], ddt(NV), {{"time_dimension", "t"}, {"units", "kg m^-2 s^-2"}, {"conversion", SI::Mp * Nnorm * Cs0 * Omega_ci}, {"long_name", std::string("Rate of change of ") + name + " momentum"}, {"species", name}, {"source", "evolve_momentum"}}); set_with_attrs(state[std::string("SNV") + name], momentum_source, {{"time_dimension", "t"}, {"units", "kg m^-2 s^-2"}, {"conversion", SI::Mp * Nnorm * Cs0 * Omega_ci}, {"standard_name", "momentum source"}, {"long_name", name + " momentum source"}, {"species", name}, {"source", "evolve_momentum"}}); // If fluxes have been set then add them to the output auto rho_s0 = get<BoutReal>(state["rho_s0"]); if (flow_xlow.isAllocated()) { set_with_attrs(state[fmt::format("mf{}_tot_xlow", name)], flow_xlow, {{"time_dimension", "t"}, {"units", "N"}, {"conversion", rho_s0 * SQ(rho_s0) * SI::Mp * Nnorm * Cs0 * Omega_ci}, {"standard_name", "momentum flow"}, {"long_name", name + " momentum flow in X. Note: May be incomplete."}, {"species", name}, {"source", "evolve_momentum"}}); } if (flow_ylow.isAllocated()) { set_with_attrs(state[fmt::format("mf{}_tot_ylow", name)], flow_ylow, {{"time_dimension", "t"}, {"units", "N"}, {"conversion", rho_s0 * SQ(rho_s0) * SI::Mp * Nnorm * Cs0 * Omega_ci}, {"standard_name", "momentum flow"}, {"long_name", name + " momentum flow in Y. Note: May be incomplete."}, {"species", name}, {"source", "evolve_momentum"}}); } } }
10,828
C++
.cxx
253
35.079051
106
0.591658
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,202
adas_reaction.cxx
bendudson_hermes-3/src/adas_reaction.cxx
/// /// Read and interpolate OpenADAS rate coefficients /// /// Parts of this code are based on atomic++ by Thomas Body (2017) /// https://github.com/TBody/atomicpp /// Copyright (c) 2017 Tom Body /// That was based on the TBody/atomic1D code, /// https://github.com/TBody/atomicpp /// which is in turn based on the cfe316/atomic code /// https://github.com/cfe316/atomic /// Copyright (c) 2016 David Wagner <wagdav@gmail.com> /// Copyright (c) 2016 Jacob Schwartz <jschwart@pppl.gov> /// #include "../include/adas_reaction.hxx" #include "../include/integrate.hxx" #include "../external/json.hxx" #include <fstream> #include <iterator> namespace { BoutReal floor(BoutReal value, BoutReal min) { if (value < min) return min; return value; } } OpenADASRateCoefficient::OpenADASRateCoefficient(const std::string& filename, int level) { AUTO_TRACE(); // Read the rate file std::ifstream json_file(filename); if (!json_file.good()) { throw BoutException("Could not read ADAS file '{}'", filename); } nlohmann::json data; json_file >> data; // Get the log coefficients std::vector<std::vector<std::vector<double>>> extract_log_coeff = data["log_coeff"]; std::vector<double> extract_log_temperature = data["log_temperature"]; std::vector<double> extract_log_density = data["log_density"]; log_coeff = extract_log_coeff[level]; log_temperature = extract_log_temperature; log_density = extract_log_density; // Store the range of parameters Tmin = pow(10, log_temperature.front()); Tmax = pow(10, log_temperature.back()); nmin = pow(10, log_density.front()); nmax = pow(10, log_density.back()); } namespace { BoutReal clip(BoutReal value, BoutReal min, BoutReal max) { if (value < min) return min; if (value > max) return max; return value; } int get_high_index(const std::vector<BoutReal>& vec, BoutReal value) { ASSERT2(vec.size() > 1); // Need at least two elements // Iterator pointing to the first element greater than or equal to log10T auto high_it = lower_bound(vec.begin(), vec.end(), value); if (high_it == vec.end()) { --high_it; // Shift to the last element } else if (high_it == vec.begin()) { ++high_it; // Shift to the second element } int high_index = std::distance(vec.begin(), high_it); ASSERT2((high_index > 0) and (high_index < static_cast<int>(vec.size()))); return high_index; } } // namespace BoutReal OpenADASRateCoefficient::evaluate(BoutReal T, BoutReal n) { AUTO_TRACE(); // Ensure that the inputs are in range BoutReal log10T = log10(clip(T, Tmin, Tmax)); BoutReal log10n = log10(clip(n, nmin, nmax)); // Get the upper index. Between 1 and size-1 inclusive int high_T_index = get_high_index(log_temperature, log10T); int high_n_index = get_high_index(log_density, log10n); // Construct the simple interpolation grid // Find weightings based on linear distance // w01 ------ w11 ne -> y // | \ / | | // | w(x,y) | --/--Te -> x // | / \ | | // w00 ------ w10 int low_T_index = high_T_index - 1; BoutReal x = (log10T - log_temperature[low_T_index]) / (log_temperature[high_T_index] - log_temperature[low_T_index]); int low_n_index = high_n_index - 1; BoutReal y = (log10n - log_density[low_n_index]) / (log_density[high_n_index] - log_density[low_n_index]); BoutReal eval_log_coef = (log_coeff[low_T_index][low_n_index] * (1 - y) + log_coeff[low_T_index][high_n_index] * y) * (1 - x) + (log_coeff[high_T_index][low_n_index] * (1 - y) + log_coeff[high_T_index][high_n_index] * y) * x; return pow(10., eval_log_coef); } void OpenADAS::calculate_rates(Options& electron, Options& from_ion, Options& to_ion) { AUTO_TRACE(); Field3D Ne = GET_VALUE(Field3D, electron["density"]); Field3D Te = GET_VALUE(Field3D, electron["temperature"]); Field3D N1 = GET_VALUE(Field3D, from_ion["density"]); Field3D T1 = GET_VALUE(Field3D, from_ion["temperature"]); Field3D V1 = GET_VALUE(Field3D, from_ion["velocity"]); auto AA = get<BoutReal>(from_ion["AA"]); ASSERT1(AA == get<BoutReal>(to_ion["AA"])); const BoutReal from_charge = from_ion.isSet("charge") ? get<BoutReal>(from_ion["charge"]) : 0.0; const BoutReal to_charge = to_ion.isSet("charge") ? get<BoutReal>(to_ion["charge"]) : 0.0; Field3D reaction_rate = cellAverage( [&](BoutReal ne, BoutReal n1, BoutReal te) { // Note: densities can be (slightly) negative return floor(ne, 0.0) * floor(n1, 0.0) * rate_coef.evaluate(te * Tnorm, ne * Nnorm) * Nnorm / FreqNorm; }, Ne.getRegion("RGN_NOBNDRY"))(Ne, N1, Te); // Particles subtract(from_ion["density_source"], reaction_rate); add(to_ion["density_source"], reaction_rate); if (from_charge != to_charge) { // To ensure quasineutrality, add electron density source add(electron["density_source"], (to_charge - from_charge) * reaction_rate); } // Momentum Field3D momentum_exchange = reaction_rate * AA * V1; subtract(from_ion["momentum_source"], momentum_exchange); add(to_ion["momentum_source"], momentum_exchange); // Ion energy Field3D energy_exchange = reaction_rate * (3. / 2) * T1; subtract(from_ion["energy_source"], energy_exchange); add(to_ion["energy_source"], energy_exchange); // Electron energy loss (radiation, ionisation potential) Field3D energy_loss = cellAverage( [&](BoutReal ne, BoutReal n1, BoutReal te) { return floor(ne, 0.0) * floor(n1, 0.0) * radiation_coef.evaluate(te * Tnorm, ne * Nnorm) * Nnorm / (Tnorm * FreqNorm); }, Ne.getRegion("RGN_NOBNDRY"))(Ne, N1, Te); // Loss is reduced by heating energy_loss -= (electron_heating / Tnorm) * reaction_rate; subtract(electron["energy_source"], energy_loss); } void OpenADASChargeExchange::calculate_rates(Options& electron, Options& from_A, Options& from_B, Options& to_A, Options& to_B) { AUTO_TRACE(); // Check that the reaction conserves mass and charge ASSERT1(get<BoutReal>(from_A["AA"]) == get<BoutReal>(to_A["AA"])); ASSERT1(get<BoutReal>(from_B["AA"]) == get<BoutReal>(to_B["AA"])); // ASSERT1(get<BoutReal>(from_A["charge"]) + get<BoutReal>(from_B["charge"]) // == get<BoutReal>(to_A["charge"]) + get<BoutReal>(to_B["charge"])); // Note: Using electron temperature and density, // because ADAS website states that all rates are a function of Te const Field3D Te = GET_VALUE(Field3D, electron["temperature"]); const Field3D Ne = GET_VALUE(Field3D, electron["density"]); const Field3D Na = GET_VALUE(Field3D, from_A["density"]); const Field3D Nb = GET_VALUE(Field3D, from_B["density"]); const Field3D reaction_rate = cellAverage( [&](BoutReal na, BoutReal nb, BoutReal ne, BoutReal te) { return floor(na, 0.0) * floor(nb, 0.0) * rate_coef.evaluate(te * Tnorm, ne * Nnorm) * Nnorm / FreqNorm; }, Ne.getRegion("RGN_NOBNDRY"))(Na, Nb, Ne, Te); // from_A -> to_A { // Particles subtract(from_A["density_source"], reaction_rate); add(to_A["density_source"], reaction_rate); // Momentum const Field3D momentum_exchange = reaction_rate * get<BoutReal>(from_A["AA"]) * get<Field3D>(from_A["velocity"]); subtract(from_A["momentum_source"], momentum_exchange); add(to_A["momentum_source"], momentum_exchange); // Energy const Field3D energy_exchange = reaction_rate * (3. / 2) * GET_VALUE(Field3D, from_A["temperature"]); subtract(from_A["energy_source"], energy_exchange); add(to_A["energy_source"], energy_exchange); } // from_B -> to_B { // Particles subtract(from_B["density_source"], reaction_rate); add(to_B["density_source"], reaction_rate); // Momentum const Field3D momentum_exchange = reaction_rate * get<BoutReal>(from_B["AA"]) * GET_VALUE(Field3D, from_B["velocity"]); subtract(from_B["momentum_source"], momentum_exchange); add(to_B["momentum_source"], momentum_exchange); // Energy const Field3D energy_exchange = reaction_rate * (3. / 2) * GET_VALUE(Field3D, from_B["temperature"]); subtract(from_B["energy_source"], energy_exchange); add(to_B["energy_source"], energy_exchange); } }
8,527
C++
.cxx
198
37.989899
111
0.646128
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,203
sheath_closure.cxx
bendudson_hermes-3/src/sheath_closure.cxx
#include "../include/sheath_closure.hxx" SheathClosure::SheathClosure(std::string name, Options &alloptions, Solver *) { Options& options = alloptions[name]; BoutReal Lnorm = alloptions["units"]["meters"]; // Length normalisation factor L_par = options["connection_length"] .doc("Field-line connection length in meters") .as<BoutReal>() / Lnorm; sheath_gamma = options["sheath_gamma"] .doc("Sheath heat transmission coefficient (dimensionless)") .withDefault<BoutReal>(6.5); sheath_gamma_ions = options["sheath_gamma_ions"] .doc("Sheath heat transmission coefficient for ions (dimensionless)") .withDefault<BoutReal>(2.0); // Value suggested by Stangeby's book, between eqs. // (2.92) and (2.93) offset = options["potential_offset"] .doc("Potential at which the sheath current is zero") .withDefault<BoutReal>(0.0); sinks = options["sinks"] .doc("Include sinks of density and energy?") .withDefault<bool>(false); output.write("\tL_par = {:e} (normalised)\n", L_par); } void SheathClosure::transform(Options &state) { AUTO_TRACE(); // Get electrostatic potential auto phi = get<Field3D>(state["fields"]["phi"]); auto& electrons = state["species"]["e"]; // Electron density auto n = get<Field3D>(electrons["density"]); // Divergence of current through the sheath Field3D DivJsh = n * (phi - offset) / L_par; add(state["fields"]["DivJextra"], // Used in vorticity DivJsh); add(electrons["density_source"], DivJsh); // Electron heat conduction if (electrons.isSet("temperature")) { // Assume attached, sheath-limited regime // Sheath heat transmission gamma * n * T * cs auto Te = get<Field3D>(electrons["temperature"]); Field3D qsheath = floor(sheath_gamma * n * Te * sqrt(Te), 0.0); subtract(electrons["energy_source"], qsheath / L_par); } if (sinks) { // Add sinks of density and energy. Allows source-driven 2d turbulence simulations. // Calculate a sound speed from total pressure and total mass density. // [Not sure if this is correct or the best thing in general, but reduces to the // standard Bohm boundary conditions for a pure, hydrogenic plasma.] Field3D P_total = 0.0; Field3D rho_total = 0.0; // mass density Options& allspecies = state["species"]; for (auto& kv : allspecies.getChildren()) { Options& species = allspecies[kv.first]; const BoutReal A = get<BoutReal>(species["AA"]); Field3D Ns = get<Field3D>(species["density"]); Field3D Ts = get<Field3D>(species["temperature"]); P_total += Ns * Ts; rho_total += A * Ns; } Field3D c_s = sqrt(P_total / rho_total); for (auto& kv : allspecies.getChildren()) { Options& species = allspecies[kv.first]; Field3D Ns = get<Field3D>(species["density"]); Field3D sheath_flux = floor(Ns * c_s, 0.0); subtract(species["density_source"], sheath_flux / L_par); if (kv.first != "e") { // Electron sheath heat flux has different gamma-factor than ions, and was already // handled above auto Ts = get<Field3D>(species["temperature"]); Field3D qsheath = floor(sheath_gamma_ions * Ts * sheath_flux, 0.0); subtract(species["energy_source"], qsheath / L_par); } } } }
3,464
C++
.cxx
75
39.133333
90
0.64384
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,204
amjuel_helium.cxx
bendudson_hermes-3/src/amjuel_helium.cxx
#include "../include/amjuel_helium.hxx" //////////////////////////////////////////////////////////// // e + he -> he+ + 2e /// Coefficients to calculate the reaction rate <σv> /// Amjuel reaction 2.3.9a, page 161 static constexpr const BoutReal he01_rate_coefs[9][9] = { {-42.27118452798, 0.1294554451998, -0.08433979538052, 0.04910721979375, -0.01454047282438, 0.002178105605879, -0.0001657512355348, 6.161429564793e-06, -8.910615590909e-08}, {24.11668100975, -0.08121999208281, 0.04052570160482, -0.02367924962508, 0.008488392041366, -0.001452752408581, 0.0001170902182939, -4.410479245308e-06, 6.297315949647e-08}, {-12.03181133667, -0.003998282970932, -0.00281991919306, -0.00190488772724, -0.0002390948585334, 0.0001844484422285, -1.97272802786e-05, 7.779440219801e-07, -1.033814145233e-08}, {3.829444688521, 0.02546414073266, 0.002654490306111, 0.001087493205419, -0.0004469192206896, 3.71553815559e-05, -1.595144154431e-06, 6.311039124056e-08, -1.48598916668e-09}, {-0.7945839257175, -0.0149359787485, -0.001018320076497, 0.0002821927325759, 3.269264854581e-05, -5.937518354028e-06, 4.714656637197e-07, -2.433462923993e-08, 5.307423532159e-10}, {0.1054334178555, 0.004338821244147, -0.0001483560478208, -6.901574689672e-05, 6.350490312899e-06, -4.414167358057e-07, 1.266603603049e-08, 8.049435558339e-10, -3.807796193572e-11}, {-0.008578643565653, -0.0006689202603525, 9.084162487421e-05, -4.184111347149e-06, 1.153919327151e-07, 3.797435455934e-08, -4.123383037275e-09, 1.095960078746e-10, -5.109801608123e-14}, {0.0003886232727181, 5.180805123476e-05, -1.125453787291e-05, 1.536214841434e-06, -1.632601398517e-07, 8.948177075796e-09, -1.853674996294e-10, 1.342166707999e-14, 1.184569645146e-14}, {-7.487575233223e-06, -1.58297743374e-06, 4.413792107083e-07, -7.832095176637e-08, 9.58697477495e-09, -6.73907617081e-10, 2.565598443992e-11, -4.994625098807e-13, 4.12404880445e-15}}; /// Effective electron cooling rate due to ionization of Helium atoms. /// Fujimoto Formulation II (only ground level transported, no meta-stables kept /// explicitly) static constexpr const BoutReal he01_radiation_coefs[9][9] = { {-35.35258393674, -0.03428249311738, 0.06378071832382, -0.02849818870377, 0.006041903480645, -0.000686453216556, 4.251155616815e-05, -1.351759350582e-06, 1.728801977101e-08}, {19.81855871044, 0.04854482688892, -0.05088928946831, 0.01732110218818, -0.002781419068092, 0.0002244804771683, -8.875290574348e-06, 1.399429819761e-07, -1.38977874051e-10}, {-9.334355651224, -0.04524206463148, 0.02103002869692, -0.004463941003028, 0.0002900917070658, 2.482449118881e-05, -4.278064413224e-06, 2.040570181783e-07, -3.324224092217e-09}, {2.80031425041, 0.0247435078798, -0.006012991773715, 0.0008918009845745, -2.616249899141e-05, -6.885545577757e-06, 7.013616309712e-07, -2.570063437935e-08, 3.573487194914e-10}, {-0.5489088598705, -0.007339538872774, 0.0007783071302508, -4.483274558979e-05, 1.900991581685e-06, -9.747171692727e-07, 1.349829568374e-07, -5.815812094637e-09, 6.686532777575e-11}, {0.06902095610357, 0.001234159378604, 2.989745411104e-05, -3.04090620334e-05, 2.951386149372e-06, 7.592185107575e-08, -1.805060230413e-08, 3.156859219121e-10, 1.07116869734e-11}, {-0.00534294006913, -0.0001223169549107, -1.500790305823e-05, 5.253922160283e-06, -4.468905893926e-07, 7.483496971361e-09, -9.777558713428e-10, 1.770619394125e-10, -6.050995244427e-12}, {0.0002313175089975, 6.966436907981e-06, 8.94496290981e-07, -1.712024596447e-07, -9.782015167261e-09, 2.499416349949e-09, 4.731973382221e-11, -1.845161957843e-11, 6.01107014323e-13}, {-4.279800193256e-06, -1.81546666991e-07, -2.282174576618e-09, -6.972920569943e-09, 2.60719149454e-09, -2.870919514967e-10, 8.059675146168e-12, 3.704316808942e-13, -1.713225271579e-14}}; void AmjuelHeIonisation01::calculate_rates(Options& state, Field3D &reaction_rate, Field3D &momentum_exchange, Field3D &energy_exchange, Field3D &energy_loss, BoutReal &rate_multiplier, BoutReal &radiation_multiplier) { electron_reaction(state["species"]["e"], state["species"]["he"], // From helium atoms state["species"]["he+"], // To helium ions he01_rate_coefs, he01_radiation_coefs, 0.0, // Note: Ionisation potential included in radiation_coefs, reaction_rate, momentum_exchange, energy_exchange, energy_loss, rate_multiplier, radiation_multiplier ); } //////////////////////////////////////////////////////////// // e + he+ -> he /// Coefficients to calculate the reaction rate <σv> /// Amjuel reaction 2.3.13a static constexpr const BoutReal he10_rate_coefs[9][9] = { {-28.72754373123, -0.006171082987797, 0.02414548639597, -0.007188662067622, 0.0009481268604767, -1.958887458637e-05, -5.507786383328e-06, 4.35828868693e-07, -9.50327209101e-09}, {1.564233603544, -0.03972220721457, -0.04466712599181, 0.01247359158796, -0.001660591942878, 6.019181402025e-05, 3.800156798817e-06, -3.377807793756e-07, 6.828447501225e-09}, {-6.182140631482, 0.1626641668186, 0.03366589582541, -0.007413737965595, 0.001220189896183, -9.50529572475e-05, 4.459492214068e-06, -1.552772441333e-07, 2.866586118879e-09}, {5.459428677778, -0.1700323494998, -0.01540106384088, 0.0009524545793262, -8.734341535385e-05, -2.796027477899e-06, 4.561981097438e-07, 4.940311502014e-09, -6.52572501076e-10}, {-2.128115924661, 0.07233939709414, 0.005819196258503, -7.655935845761e-05, -1.83794906705e-05, 4.72578983298e-06, -3.99778241186e-07, 1.036731541123e-08, -3.373845712183e-11}, {0.4373730373037, -0.01574917019835, -0.001456253436544, 4.772491845078e-05, -1.827059132463e-06, -6.94116329271e-08, 2.716740135949e-08, -1.143121626264e-09, 1.295139027087e-11}, {-0.04972257208732, 0.001866175274689, 0.0002047337498511, -1.004438052808e-05, 7.59073486585e-07, -6.771179147667e-08, 1.218720257518e-09, 6.78702447954e-11, -2.432253541918e-12}, {0.002967287371427, -0.0001147811325052, -1.460813593905e-05, 7.422385993164e-07, -3.281946488134e-08, 2.164459880579e-09, 1.113868237282e-10, -1.513922678655e-11, 3.951084520871e-13}, {-7.271204747116e-05, 2.874049670122e-06, 4.124421172202e-07, -1.689203971933e-08, -9.071172814458e-10, 1.844295219334e-10, -2.055023511556e-11, 1.101902611511e-12, -2.206082129473e-14}}; /// Radiation energy loss from helium recombination /// The potential energy (24.586eV per event) should be added to the electrons /// so that the process may be a net energy source for the electrons static constexpr const BoutReal he10_radiation_coefs[9][9] = { {-25.38377692766, -0.04826880987619, 0.0679657596731, -0.0240171002139, 0.004130156138736, -0.0003494803122018, 1.34502510054e-05, -1.323917127568e-07, -2.551716207606e-09}, {2.472758419513, 0.1668058989207, -0.1265192781981, 0.02938171777028, -0.00221652505507, -0.0001261523686946, 2.701401918133e-05, -1.370446267883e-06, 2.313673787201e-08}, {-8.864417999957, -0.1882326730037, 0.119402867431, -0.02382836629119, 0.001134820469638, 0.0001782113978272, -2.305554399898e-05, 9.43029409318e-07, -1.305188423829e-08}, {8.394970578944, 0.08397993216045, -0.0579697281374, 0.01158600348753, -0.0007504743150582, -2.602911694939e-05, 4.568209602293e-06, -1.458110560501e-07, 9.826599911934e-10}, {-3.465864794112, -0.0157268418022, 0.01398192327776, -0.002700181027443, 0.0001902304157269, -1.534387905925e-06, -1.03206007926e-07, -1.355858638619e-08, 5.917279771473e-10}, {0.7479071085372, 0.0005997666028811, -0.001614053457119, 0.0002620866439317, -1.103039382799e-05, -4.215447554819e-07, -9.926133276192e-09, 4.148813674084e-09, -1.207867670158e-10}, {-0.08863575102304, 0.0001901540166344, 6.941090299375e-05, -3.042043168371e-06, -1.677907209787e-06, 2.153652742395e-07, -6.354480058307e-09, -1.223103792568e-10, 5.54305794673e-12}, {0.005484926807853, -2.510359436743e-05, 1.123735445147e-06, -9.198494797723e-07, 2.058851315121e-07, -1.866416375894e-08, 7.564835556537e-10, -1.622993472948e-11, 2.428986170198e-13}, {-0.0001388441945179, 9.1419955967e-07, -1.16891589033e-07, 3.485370731777e-08, -5.086412415216e-09, 3.674153797642e-10, -1.621809988343e-11, 6.737654534264e-13, -1.678705755876e-14}}; void AmjuelHeRecombination10::calculate_rates(Options& state, Field3D &reaction_rate, Field3D &momentum_exchange, Field3D &energy_exchange, Field3D &energy_loss, BoutReal &rate_multiplier, BoutReal &radiation_multiplier) { electron_reaction(state["species"]["e"], state["species"]["he+"], // From helium ions state["species"]["he"], // To helium atoms he10_rate_coefs, he10_radiation_coefs, 24.586, // Ionisation potential heating of electrons reaction_rate, momentum_exchange, energy_exchange, energy_loss, rate_multiplier, radiation_multiplier ); }
9,457
C++
.cxx
149
56.422819
154
0.703022
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,205
sheath_boundary_simple.cxx
bendudson_hermes-3/src/sheath_boundary_simple.cxx
#include "../include/sheath_boundary_simple.hxx" #include "bout/constants.hxx" #include "bout/mesh.hxx" using bout::globals::mesh; namespace { BoutReal clip(BoutReal value, BoutReal min, BoutReal max) { if (value < min) return min; if (value > max) return max; return value; } BoutReal floor(BoutReal value, BoutReal min) { if (value < min) return min; return value; } Ind3D indexAt(const Field3D& f, int x, int y, int z) { int ny = f.getNy(); int nz = f.getNz(); return Ind3D{(x * ny + y) * nz + z, ny, nz}; } /// Limited free gradient of log of a quantity /// This ensures that the guard cell values remain positive /// while also ensuring that the quantity never increases /// /// fm fc | fp /// ^ boundary /// /// exp( 2*log(fc) - log(fm) ) /// Mode 0: default (exponential extrapolation if decreases, Neumann if increases) /// Mode 1: always exponential extrapolation /// Mode 2: always linear extrapolation BoutReal limitFree(BoutReal fm, BoutReal fc, BoutReal mode) { if ((fm < fc) && (mode == 0)) { return fc; // Neumann rather than increasing into boundary } if (fm < 1e-10) { return fc; // Low / no density condition } BoutReal fp = 0; if ((mode == 0) || (mode == 1)) { fp = SQ(fc) / fm; // Exponential } else if (mode == 2) { fp = 2.0 * fc - fm; // Linear } else { throw BoutException("Unknown boundary mode"); } return fp; // Extrapolation #if CHECKLEVEL >= 2 if (!std::isfinite(fp)) { throw BoutException("SheathBoundary limitFree: {}, {} -> {}", fm, fc, fp); } #endif return fp; } } // namespace SheathBoundarySimple::SheathBoundarySimple(std::string name, Options& alloptions, Solver*) { AUTO_TRACE(); Options& options = alloptions[name]; Ge = options["secondary_electron_coef"] .doc("Effective secondary electron emission coefficient") .withDefault(0.0); if ((Ge < 0.0) or (Ge > 1.0)) { throw BoutException("Secondary electron emission must be between 0 and 1 ({:e})", Ge); } sin_alpha = options["sin_alpha"] .doc("Sin of the angle between magnetic field line and wall surface. " "Should be between 0 and 1") .withDefault(1.0); if ((sin_alpha < 0.0) or (sin_alpha > 1.0)) { throw BoutException("Range of sin_alpha must be between 0 and 1"); } gamma_e = options["gamma_e"] .doc("Electron sheath heat transmission coefficient") .withDefault(3.5); gamma_i = options["gamma_i"] .doc("Ion sheath heat transmission coefficient") .withDefault(3.5); sheath_ion_polytropic = options["sheath_ion_polytropic"] .doc("Ion polytropic coefficient in Bohm sound speed") .withDefault(1.0); lower_y = options["lower_y"].doc("Boundary on lower y?").withDefault<bool>(true); upper_y = options["upper_y"].doc("Boundary on upper y?").withDefault<bool>(true); always_set_phi = options["always_set_phi"] .doc("Always set phi field? Default is to only modify if already set") .withDefault<bool>(false); const Options& units = alloptions["units"]; const BoutReal Tnorm = units["eV"]; // Read wall voltage, convert to normalised units wall_potential = options["wall_potential"] .doc("Voltage of the wall [Volts]") .withDefault(Field3D(0.0)) / Tnorm; // Convert to field aligned coordinates wall_potential = toFieldAligned(wall_potential); no_flow = options["no_flow"] .doc("Set zero particle flow, keeping energy flow") .withDefault<bool>(false); density_boundary_mode = options["density_boundary_mode"] .doc("BC mode: 0=LimitFree, 1=ExponentialFree, 2=LinearFree") .withDefault<BoutReal>(1); pressure_boundary_mode = options["pressure_boundary_mode"] .doc("BC mode: 0=LimitFree, 1=ExponentialFree, 2=LinearFree") .withDefault<BoutReal>(1); temperature_boundary_mode = options["temperature_boundary_mode"] .doc("BC mode: 0=LimitFree, 1=ExponentialFree, 2=LinearFree") .withDefault<BoutReal>(1); } void SheathBoundarySimple::transform(Options& state) { AUTO_TRACE(); Options& allspecies = state["species"]; Options& electrons = allspecies["e"]; // Need electron properties // Not const because boundary conditions will be set Field3D Ne = toFieldAligned(floor(GET_NOBOUNDARY(Field3D, electrons["density"]), 0.0)); Field3D Te = toFieldAligned(GET_NOBOUNDARY(Field3D, electrons["temperature"])); Field3D Pe = IS_SET_NOBOUNDARY(electrons["pressure"]) ? toFieldAligned(getNoBoundary<Field3D>(electrons["pressure"])) : Te * Ne; // Mass, normalised to proton mass const BoutReal Me = IS_SET(electrons["AA"]) ? get<BoutReal>(electrons["AA"]) : SI::Me / SI::Mp; // This is for applying boundary conditions Field3D Ve = IS_SET_NOBOUNDARY(electrons["velocity"]) ? toFieldAligned(getNoBoundary<Field3D>(electrons["velocity"])) : zeroFrom(Ne); Field3D NVe = IS_SET_NOBOUNDARY(electrons["momentum"]) ? toFieldAligned(getNoBoundary<Field3D>(electrons["momentum"])) : zeroFrom(Ne); Coordinates* coord = mesh->getCoordinates(); ////////////////////////////////////////////////////////////////// // Electrostatic potential // If phi is set, use free boundary condition // If phi not set, calculate assuming zero current Field3D phi; if (IS_SET_NOBOUNDARY(state["fields"]["phi"])) { phi = toFieldAligned(getNoBoundary<Field3D>(state["fields"]["phi"])); } else { // Calculate potential phi assuming zero current // Need to sum n_i Z_i C_i over all ion species // // To avoid looking up species for every grid point, this // loops over the boundaries once per species. Field3D ion_sum = 0.0; // Iterate through charged ion species for (auto& kv : allspecies.getChildren()) { const Options& species = kv.second; if ((kv.first == "e") or !species.isSet("charge") or (get<BoutReal>(species["charge"]) == 0.0)) { continue; // Skip electrons and non-charged ions } const Field3D Ni = getNoBoundary<Field3D>(species["density"]); const Field3D Ti = getNoBoundary<Field3D>(species["temperature"]); const BoutReal Mi = getNoBoundary<BoutReal>(species["AA"]); const BoutReal Zi = getNoBoundary<BoutReal>(species["charge"]); Field3D Vi = species.isSet("velocity") ? toFieldAligned(getNoBoundary<Field3D>(species["velocity"])) : zeroFrom(Ni); if (lower_y) { // Sum values, put result in mesh->ystart for (RangeIterator r = mesh->iterateBndryLowerY(); !r.isDone(); r++) { for (int jz = 0; jz < mesh->LocalNz; jz++) { auto i = indexAt(Ni, r.ind, mesh->ystart, jz); auto ip = i.yp(); // Free gradient of log density and temperature // This ensures that the guard cell values remain positive // exp( 2*log(N[i]) - log(N[ip]) ) const BoutReal Ni_im = limitFree(Ni[ip], Ni[i], density_boundary_mode); const BoutReal Ti_im = limitFree(Ti[ip], Ti[i], temperature_boundary_mode); const BoutReal Te_im = limitFree(Te[ip], Te[i], temperature_boundary_mode); // Calculate sheath values at half-way points (cell edge) const BoutReal nisheath = 0.5 * (Ni_im + Ni[i]); const BoutReal tesheath = floor(0.5 * (Te_im + Te[i]), 1e-5); // electron temperature const BoutReal tisheath = floor(0.5 * (Ti_im + Ti[i]), 1e-5); // ion temperature // Sound speed squared BoutReal C_i_sq = (sheath_ion_polytropic * tisheath + Zi * tesheath) / Mi; BoutReal visheath = -sqrt(C_i_sq); if (Vi[i] < visheath) { visheath = Vi[i]; } ion_sum[i] -= Zi * nisheath * visheath; } } } if (upper_y) { // Sum values, put results in mesh->yend for (RangeIterator r = mesh->iterateBndryUpperY(); !r.isDone(); r++) { for (int jz = 0; jz < mesh->LocalNz; jz++) { auto i = indexAt(Ni, r.ind, mesh->yend, jz); auto im = i.ym(); const BoutReal Ni_ip = limitFree(Ni[im], Ni[i], density_boundary_mode); const BoutReal Ti_ip = limitFree(Ti[im], Ti[i], temperature_boundary_mode); const BoutReal Te_ip = limitFree(Te[im], Te[i], temperature_boundary_mode); // Calculate sheath values at half-way points (cell edge) const BoutReal nisheath = 0.5 * (Ni_ip + Ni[i]); const BoutReal tesheath = floor(0.5 * (Te_ip + Te[i]), 1e-5); // electron temperature const BoutReal tisheath = floor(0.5 * (Ti_ip + Ti[i]), 1e-5); // ion temperature BoutReal C_i_sq = (sheath_ion_polytropic * tisheath + Zi * tesheath) / Mi; BoutReal visheath = sqrt(C_i_sq); if (Vi[i] > visheath) { visheath = Vi[i]; } ion_sum[i] += Zi * nisheath * visheath; } } } } phi.allocate(); // ion_sum now contains the ion current, sum Z_i n_i C_i over all ion species // at mesh->ystart and mesh->yend indices if (lower_y) { for (RangeIterator r = mesh->iterateBndryLowerY(); !r.isDone(); r++) { for (int jz = 0; jz < mesh->LocalNz; jz++) { auto i = indexAt(phi, r.ind, mesh->ystart, jz); auto ip = i.yp(); const BoutReal Ne_im = limitFree(Ne[ip], Ne[i], density_boundary_mode); const BoutReal Te_im = limitFree(Te[ip], Te[i], temperature_boundary_mode); // Calculate sheath values at half-way points (cell edge) const BoutReal nesheath = 0.5 * (Ne_im + Ne[i]); const BoutReal tesheath = floor(0.5 * (Te_im + Te[i]), 1e-5); phi[i] = tesheath * log(sqrt(tesheath / (Me * TWOPI)) * (1. - Ge) * nesheath / ion_sum[i]); const BoutReal phi_wall = wall_potential[i]; phi[i] += phi_wall; // Add bias potential phi[i.yp()] = phi[i.ym()] = phi[i]; // Constant into sheath } } } if (upper_y) { for (RangeIterator r = mesh->iterateBndryUpperY(); !r.isDone(); r++) { for (int jz = 0; jz < mesh->LocalNz; jz++) { auto i = indexAt(phi, r.ind, mesh->yend, jz); auto im = i.ym(); const BoutReal Ne_ip = limitFree(Ne[im], Ne[i], density_boundary_mode); const BoutReal Te_ip = limitFree(Te[im], Te[i], temperature_boundary_mode); // Calculate sheath values at half-way points (cell edge) const BoutReal nesheath = 0.5 * (Ne_ip + Ne[i]); const BoutReal tesheath = floor(0.5 * (Te_ip + Te[i]), 1e-5); phi[i] = tesheath * log(sqrt(tesheath / (Me * TWOPI)) * (1. - Ge) * nesheath / ion_sum[i]); const BoutReal phi_wall = wall_potential[i]; phi[i] += phi_wall; // Add bias potential phi[i.yp()] = phi[i.ym()] = phi[i]; } } } } // Field to capture total sheath heat flux for diagnostics Field3D electron_sheath_power_ylow = zeroFrom(Ne); ////////////////////////////////////////////////////////////////// // Electrons Field3D electron_energy_source = electrons.isSet("energy_source") ? toFieldAligned(getNonFinal<Field3D>(electrons["energy_source"])) : zeroFrom(Ne); if (lower_y) { for (RangeIterator r = mesh->iterateBndryLowerY(); !r.isDone(); r++) { for (int jz = 0; jz < mesh->LocalNz; jz++) { auto i = indexAt(Ne, r.ind, mesh->ystart, jz); auto ip = i.yp(); auto im = i.ym(); // Free gradient of log electron density and temperature // Limited so that the values don't increase into the sheath // This ensures that the guard cell values remain positive // exp( 2*log(N[i]) - log(N[ip]) ) Ne[im] = limitFree(Ne[ip], Ne[i], density_boundary_mode); Te[im] = limitFree(Te[ip], Te[i], temperature_boundary_mode); Pe[im] = limitFree(Pe[ip], Pe[i], pressure_boundary_mode); // Free boundary potential linearly extrapolated phi[im] = 2 * phi[i] - phi[ip]; const BoutReal nesheath = 0.5 * (Ne[im] + Ne[i]); const BoutReal tesheath = 0.5 * (Te[im] + Te[i]); // electron temperature const BoutReal phi_wall = wall_potential[i]; const BoutReal phisheath = floor(0.5 * (phi[im] + phi[i]), phi_wall); // Electron saturation at phi = phi_wall // Electron velocity into sheath (< 0) BoutReal vesheath = -sqrt(tesheath / (TWOPI * Me)) * (1. - Ge) * exp(-(phisheath - phi_wall) / floor(tesheath, 1e-5)); // Heat flux. Note: Here this is negative because vesheath < 0 BoutReal q = gamma_e * tesheath * nesheath * vesheath; if (no_flow) { vesheath = 0.0; } Ve[im] = 2 * vesheath - Ve[i]; NVe[im] = 2 * Me * nesheath * vesheath - NVe[i]; // Take into account the flow of energy due to fluid flow // This is additional energy flux through the sheath q -= (2.5 * tesheath + 0.5 * Me * SQ(vesheath)) * nesheath * vesheath; // Multiply by cell area to get power BoutReal heatflow = q * (coord->J[i] + coord->J[im]) / (sqrt(coord->g_22[i]) + sqrt(coord->g_22[im])); // This omits dx*dz because we divide by dx*dz next // Divide by volume of cell to get energy loss rate (< 0) BoutReal power = heatflow / (coord->dy[i] * coord->J[i]); electron_energy_source[i] += power; electron_sheath_power_ylow[i] += heatflow * coord->dx[i] * coord->dz[i]; // lower Y, so power placed in final domain cell } } } if (upper_y) { // This is essentially the same as at the lower y boundary // except ystart -> yend, ip <-> im // for (RangeIterator r = mesh->iterateBndryUpperY(); !r.isDone(); r++) { for (int jz = 0; jz < mesh->LocalNz; jz++) { auto i = indexAt(Ne, r.ind, mesh->yend, jz); auto ip = i.yp(); auto im = i.ym(); // Free gradient of log electron density and temperature // This ensures that the guard cell values remain positive // exp( 2*log(N[i]) - log(N[ip]) ) Ne[ip] = limitFree(Ne[im], Ne[i], density_boundary_mode); Te[ip] = limitFree(Te[im], Te[i], temperature_boundary_mode); Pe[ip] = limitFree(Pe[im], Pe[i], pressure_boundary_mode); // Free boundary potential linearly extrapolated. phi[ip] = 2 * phi[i] - phi[im]; const BoutReal nesheath = 0.5 * (Ne[ip] + Ne[i]); const BoutReal tesheath = 0.5 * (Te[ip] + Te[i]); // electron temperature const BoutReal phi_wall = wall_potential[i]; const BoutReal phisheath = floor(0.5 * (phi[ip] + phi[i]), phi_wall); // Electron saturation at phi = phi_wall // Electron velocity into sheath (> 0) BoutReal vesheath = sqrt(tesheath / (TWOPI * Me)) * (1. - Ge) * exp(-(phisheath - phi_wall) / floor(tesheath, 1e-5)); BoutReal q = gamma_e * tesheath * nesheath * vesheath; if (no_flow) { vesheath = 0.0; } Ve[ip] = 2 * vesheath - Ve[i]; NVe[ip] = 2. * Me * nesheath * vesheath - NVe[i]; // Take into account the flow of energy due to fluid flow // This is additional energy flux through the sheath // Note: Here this is positive because vesheath > 0 q -= (2.5 * tesheath + 0.5 * Me * SQ(vesheath)) * nesheath * vesheath; // Multiply by cell area to get power BoutReal heatflow = q * (coord->J[i] + coord->J[ip]) / (sqrt(coord->g_22[i]) + sqrt(coord->g_22[ip])); // This omits dx*dz because we divide by dx*dz next // Divide by volume of cell to get energy loss rate (> 0) BoutReal power = heatflow / (coord->dy[i] * coord->J[i]); electron_energy_source[i] -= power; // Diagnostic contains energy removed in the sheath electron_sheath_power_ylow[ip] += heatflow * coord->dx[i] * coord->dz[i]; // upper Y, so power placed in first guard cell } } } // Set electron density and temperature, now with boundary conditions // Note: Clear parallel slices because they do not contain boundary conditions. Ne.clearParallelSlices(); Te.clearParallelSlices(); Pe.clearParallelSlices(); setBoundary(electrons["density"], fromFieldAligned(Ne)); setBoundary(electrons["temperature"], fromFieldAligned(Te)); setBoundary(electrons["pressure"], fromFieldAligned(Pe)); // Set energy source (negative in cell next to sheath) // Note: electron_energy_source includes any sources previously set in other components set(electrons["energy_source"], fromFieldAligned(electron_energy_source)); // Add the total sheath power flux to the tracker of y power flows add(electrons["energy_flow_ylow"], fromFieldAligned(electron_sheath_power_ylow)); if (IS_SET_NOBOUNDARY(electrons["velocity"])) { Ve.clearParallelSlices(); setBoundary(electrons["velocity"], fromFieldAligned(Ve)); } if (IS_SET_NOBOUNDARY(electrons["momentum"])) { NVe.clearParallelSlices(); setBoundary(electrons["momentum"], fromFieldAligned(NVe)); } if (always_set_phi or (state.isSection("fields") and state["fields"].isSet("phi"))) { // Set the potential, including boundary conditions phi.clearParallelSlices(); setBoundary(state["fields"]["phi"], fromFieldAligned(phi)); } ////////////////////////////////////////////////////////////////// // Iterate through all ions for (auto& kv : allspecies.getChildren()) { if (kv.first == "e") { continue; // Skip electrons } Options& species = allspecies[kv.first]; // Note: Need non-const // Ion charge const BoutReal Zi = species.isSet("charge") ? get<BoutReal>(species["charge"]) : 0.0; if (Zi == 0.0) { continue; // Neutral -> skip } // Characteristics of this species const BoutReal Mi = get<BoutReal>(species["AA"]); // Density and temperature boundary conditions will be imposed (free) Field3D Ni = toFieldAligned(floor(getNoBoundary<Field3D>(species["density"]), 0.0)); Field3D Ti = toFieldAligned(getNoBoundary<Field3D>(species["temperature"])); Field3D Pi = species.isSet("pressure") ? toFieldAligned(getNoBoundary<Field3D>(species["pressure"])) : Ni * Ti; // Get the velocity and momentum // These will be modified at the boundaries // and then put back into the state Field3D Vi = species.isSet("velocity") ? toFieldAligned(getNoBoundary<Field3D>(species["velocity"])) : zeroFrom(Ni); Field3D NVi = species.isSet("momentum") ? toFieldAligned(getNoBoundary<Field3D>(species["momentum"])) : Mi * Ni * Vi; // Energy source will be modified in the domain Field3D energy_source = species.isSet("energy_source") ? toFieldAligned(getNonFinal<Field3D>(species["energy_source"])) : zeroFrom(Ni); // Field to capture total sheath heat flux for diagnostics Field3D ion_sheath_power_ylow = zeroFrom(Ne); if (lower_y) { for (RangeIterator r = mesh->iterateBndryLowerY(); !r.isDone(); r++) { for (int jz = 0; jz < mesh->LocalNz; jz++) { auto i = indexAt(Ne, r.ind, mesh->ystart, jz); auto ip = i.yp(); auto im = i.ym(); // Free gradient of log electron density and temperature // This ensures that the guard cell values remain positive // exp( 2*log(N[i]) - log(N[ip]) ) Ni[im] = limitFree(Ni[ip], Ni[i], density_boundary_mode); Ti[im] = limitFree(Ti[ip], Ti[i], temperature_boundary_mode); Pi[im] = limitFree(Pi[ip], Pi[i], pressure_boundary_mode); // Calculate sheath values at half-way points (cell edge) const BoutReal nesheath = 0.5 * (Ne[im] + Ne[i]); const BoutReal nisheath = 0.5 * (Ni[im] + Ni[i]); const BoutReal tesheath = floor(0.5 * (Te[im] + Te[i]), 1e-5); // electron temperature const BoutReal tisheath = floor(0.5 * (Ti[im] + Ti[i]), 1e-5); // ion temperature // Ion speed into sheath BoutReal C_i_sq = (sheath_ion_polytropic * tisheath + Zi * tesheath) / Mi; BoutReal visheath = -sqrt(C_i_sq); // Negative -> into sheath if (Vi[i] < visheath) { visheath = Vi[i]; } // Note: Here this is negative because visheath < 0 BoutReal q = gamma_i * tisheath * nisheath * visheath; if (no_flow) { visheath = 0.0; } // Set boundary conditions on flows Vi[im] = 2. * visheath - Vi[i]; NVi[im] = 2. * Mi * nisheath * visheath - NVi[i]; // Take into account the flow of energy due to fluid flow // This is additional energy flux through the sheath q -= (2.5 * tisheath + 0.5 * Mi * SQ(visheath)) * nisheath * visheath; // Multiply by cell area to get power BoutReal heatflow = q * (coord->J[i] + coord->J[im]) / (sqrt(coord->g_22[i]) + sqrt(coord->g_22[im])); // This omits dx*dz because we divide by dx*dz next // Divide by volume of cell to get energy loss rate (< 0) BoutReal power = heatflow / (coord->dy[i] * coord->J[i]); energy_source[i] += power; ion_sheath_power_ylow[i] += heatflow * coord->dx[i] * coord->dz[i]; // lower Y, so power placed in final domain cell } } } if (upper_y) { // Note: This is essentially the same as the lower boundary, // but with directions reversed e.g. ystart -> yend, ip <-> im // for (RangeIterator r = mesh->iterateBndryUpperY(); !r.isDone(); r++) { for (int jz = 0; jz < mesh->LocalNz; jz++) { auto i = indexAt(Ne, r.ind, mesh->yend, jz); auto ip = i.yp(); auto im = i.ym(); // Free gradient of log electron density and temperature // This ensures that the guard cell values remain positive // exp( 2*log(N[i]) - log(N[ip]) ) Ni[ip] = limitFree(Ni[im], Ni[i], density_boundary_mode); Ti[ip] = limitFree(Ti[im], Ti[i], temperature_boundary_mode); Pi[ip] = limitFree(Pi[im], Pi[i], pressure_boundary_mode); // Calculate sheath values at half-way points (cell edge) const BoutReal nesheath = 0.5 * (Ne[ip] + Ne[i]); const BoutReal nisheath = 0.5 * (Ni[ip] + Ni[i]); const BoutReal tesheath = floor(0.5 * (Te[ip] + Te[i]), 1e-5); // electron temperature const BoutReal tisheath = floor(0.5 * (Ti[ip] + Ti[i]), 1e-5); // ion temperature // Ion speed into sheath BoutReal C_i_sq = (sheath_ion_polytropic * tisheath + Zi * tesheath) / Mi; BoutReal visheath = sqrt(C_i_sq); // Positive -> into sheath if (Vi[i] > visheath) { visheath = Vi[i]; } BoutReal q = gamma_i * tisheath * nisheath * visheath; if (no_flow) { visheath = 0.0; } // Set boundary conditions on flows Vi[ip] = 2. * visheath - Vi[i]; NVi[ip] = 2. * Mi * nisheath * visheath - NVi[i]; // Take into account the flow of energy due to fluid flow // This is additional energy flux through the sheath // Note: Here this is positive because visheath > 0 q -= (2.5 * tisheath + 0.5 * Mi * SQ(visheath)) * nisheath * visheath; // Multiply by cell area to get power BoutReal heatflow = q * (coord->J[i] + coord->J[ip]) / (sqrt(coord->g_22[i]) + sqrt(coord->g_22[ip])); // This omits dx*dz because we divide by dx*dz next // Divide by volume of cell to get energy loss rate (> 0) BoutReal power = heatflow / (coord->dy[i] * coord->J[i]); ASSERT2(std::isfinite(power)); energy_source[i] -= power; // Note: Sign negative because power > 0 ion_sheath_power_ylow[ip] += heatflow * coord->dx[i] * coord->dz[i]; // Upper Y, so power placed in first guard cell } } } // Finished boundary conditions for this species // Put the modified fields back into the state. Ni.clearParallelSlices(); Ti.clearParallelSlices(); Pi.clearParallelSlices(); setBoundary(species["density"], fromFieldAligned(Ni)); setBoundary(species["temperature"], fromFieldAligned(Ti)); setBoundary(species["pressure"], fromFieldAligned(Pi)); if (species.isSet("velocity")) { Vi.clearParallelSlices(); setBoundary(species["velocity"], fromFieldAligned(Vi)); } if (species.isSet("momentum")) { NVi.clearParallelSlices(); setBoundary(species["momentum"], fromFieldAligned(NVi)); } // Additional loss of energy through sheath // Note: energy_source already includes previously set values set(species["energy_source"], fromFieldAligned(energy_source)); // Add the total sheath power flux to the tracker of y power flows add(species["energy_flow_ylow"], fromFieldAligned(ion_sheath_power_ylow)); } }
25,515
C++
.cxx
532
40.026316
136
0.602441
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,206
neutral_boundary.cxx
bendudson_hermes-3/src/neutral_boundary.cxx
#include "bout/mesh.hxx" #include <bout/constants.hxx> using bout::globals::mesh; #include "../include/neutral_boundary.hxx" NeutralBoundary::NeutralBoundary(std::string name, Options& alloptions, Solver* solver) : name(name) { AUTO_TRACE(); auto& options = alloptions[name]; const Options& units = alloptions["units"]; Tnorm = units["eV"]; diagnose = options["diagnose"].doc("Save additional diagnostics?").withDefault<bool>(false); lower_y = options["neutral_boundary_lower_y"].doc("Boundary on lower y?").withDefault<bool>(true); upper_y = options["neutral_boundary_upper_y"].doc("Boundary on upper y?").withDefault<bool>(true); sol = options["neutral_boundary_sol"].doc("Boundary on SOL?").withDefault<bool>(false); pfr = options["neutral_boundary_pfr"].doc("Boundary on PFR?").withDefault<bool>(false); target_energy_refl_factor = options["target_energy_refl_factor"] .doc("Fraction of energy retained by neutral particles after wall reflection at target") .withDefault<BoutReal>(0.75); sol_energy_refl_factor = options["sol_energy_refl_factor"] .doc("Fraction of energy retained by neutral particles after wall reflection at SOL") .withDefault<BoutReal>(0.75); pfr_energy_refl_factor = options["pfr_energy_refl_factor"] .doc("Fraction of energy retained by neutral particles after wall reflection at PFR") .withDefault<BoutReal>(0.75); target_fast_refl_fraction = options["target_fast_refl_fraction"] .doc("Fraction of neutrals that are undergoing fast reflection at the target") .withDefault<BoutReal>(0.8); sol_fast_refl_fraction = options["sol_fast_refl_fraction"] .doc("Fraction of neutrals that are undergoing fast reflection at the sol") .withDefault<BoutReal>(0.8); pfr_fast_refl_fraction = options["pfr_fast_refl_fraction"] .doc("Fraction of neutrals that are undergoing fast reflection at the pfr") .withDefault<BoutReal>(0.8); } void NeutralBoundary::transform(Options& state) { AUTO_TRACE(); auto& species = state["species"][name]; const BoutReal AA = get<BoutReal>(species["AA"]); Field3D Nn = toFieldAligned(GET_NOBOUNDARY(Field3D, species["density"])); Field3D Pn = toFieldAligned(GET_NOBOUNDARY(Field3D, species["pressure"])); Field3D Tn = toFieldAligned(GET_NOBOUNDARY(Field3D, species["temperature"])); Field3D Vn = IS_SET_NOBOUNDARY(species["velocity"]) ? toFieldAligned(getNoBoundary<Field3D>(species["velocity"])) : zeroFrom(Nn); Field3D NVn = IS_SET_NOBOUNDARY(species["momentum"]) ? toFieldAligned(getNoBoundary<Field3D>(species["momentum"])) : zeroFrom(Nn); // Get the energy source, or create if not set Field3D energy_source = species.isSet("energy_source") ? toFieldAligned(getNonFinal<Field3D>(species["energy_source"])) : zeroFrom(Nn); Coordinates* coord = mesh->getCoordinates(); target_energy_source = 0; wall_energy_source = 0; // Targets if (lower_y) { for (RangeIterator r = mesh->iterateBndryLowerY(); !r.isDone(); r++) { for (int jz = 0; jz < mesh->LocalNz; jz++) { auto i = indexAt(Nn, r.ind, mesh->ystart, jz); auto im = i.ym(); auto ip = i.yp(); // Free boundary condition on Nn, Pn, Tn // This is problematic when Nn, Pn or Tn are zero // Nn[im] = SQ(Nn[i]) / Nn[ip]; // Pn[im] = SQ(Pn[i]) / Pn[ip]; // Tn[im] = SQ(Tn[i]) / Tn[ip]; // Neumann boundary condition: do not extrapolate, but // assume the target value is same as the final cell centre. // Shouldn't affect results much and more resilient to positivity issues Nn[im] = Nn[i]; Pn[im] = Pn[i]; Tn[im] = Tn[i]; // No-flow boundary condition Vn[im] = -Vn[i]; NVn[im] = -NVn[i]; // Calculate midpoint values at wall const BoutReal nnsheath = 0.5 * (Nn[im] + Nn[i]); const BoutReal tnsheath = 0.5 * (Tn[im] + Tn[i]); // Thermal speed const BoutReal v_th = 0.25 * sqrt( 8*tnsheath / (PI*AA) ); // Stangeby p.69 eqns. 2.21, 2.24 // Approach adapted from D. Power thesis 2023 BoutReal T_FC = 3 / Tnorm; // Franck-Condon temp (hardcoded for now) // Outgoing neutral heat flux [W/m^2] // This is rearranged from Power for clarity - note definition of v_th. // Uses standard Stangeby 1D static Maxwellian particle/heat fluxes for fast terms and simply Q = T * particle flux // for the monoenergetic thermal reflected population. BoutReal q = 2 * nnsheath * tnsheath * v_th // Incident energy - (target_energy_refl_factor * target_fast_refl_fraction ) * 2 * nnsheath * tnsheath * v_th // Fast reflected energy - (1 - target_fast_refl_fraction) * T_FC * nnsheath * v_th; // Thermal reflected energy // Cross-sectional area in XZ plane: BoutReal da = (coord->J[i] + coord->J[im]) / (sqrt(coord->g_22[i]) + sqrt(coord->g_22[im])) * 0.5*(coord->dx[i] + coord->dx[im]) * 0.5*(coord->dz[i] + coord->dz[im]); // [m^2] // Multiply by area to get energy flow (power) BoutReal flow = q * da; // [W] // Divide by cell volume to get source [W/m^3] BoutReal cooling_source = flow / (coord->dx[i] * coord->dy[i] * coord->dz[i] * coord->J[i]); // Subtract from cell next to boundary energy_source[i] -= cooling_source; target_energy_source[i] -= cooling_source; } } } if (upper_y) { for (RangeIterator r = mesh->iterateBndryUpperY(); !r.isDone(); r++) { for (int jz = 0; jz < mesh->LocalNz; jz++) { auto i = indexAt(Nn, r.ind, mesh->yend, jz); auto im = i.ym(); auto ip = i.yp(); // Free boundary condition on Nn, Pn, Tn // This is problematic when Nn, Pn or Tn are zero // Nn[ip] = SQ(Nn[i]) / Nn[im]; // Pn[ip] = SQ(Pn[i]) / Pn[im]; // Tn[ip] = SQ(Tn[i]) / Tn[im]; // Neumann boundary condition: do not extrapolate, but // assume the target value is same as the final cell centre. // Shouldn't affect results much and more resilient to positivity issues Nn[ip] = Nn[i]; Pn[ip] = Pn[i]; Tn[ip] = Tn[i]; // No-flow boundary condition Vn[ip] = -Vn[i]; NVn[ip] = -NVn[i]; // Calculate midpoint values at wall const BoutReal nnsheath = 0.5 * (Nn[ip] + Nn[i]); const BoutReal tnsheath = 0.5 * (Tn[ip] + Tn[i]); // Thermal speed const BoutReal v_th = 0.25 * sqrt( 8*tnsheath / (PI*AA) ); // Stangeby p.69 eqns. 2.21, 2.24 // Approach adapted from D. Power thesis 2023 BoutReal T_FC = 3 / Tnorm; // Franck-Condon temp (hardcoded for now) // Outgoing neutral heat flux [W/m^2] // This is rearranged from Power for clarity - note definition of v_th. BoutReal q = 2 * nnsheath * tnsheath * v_th // Incident energy - (target_energy_refl_factor * target_fast_refl_fraction ) * 2 * nnsheath * tnsheath * v_th // Fast reflected energy - (1 - target_fast_refl_fraction) * T_FC * nnsheath * v_th; // Thermal reflected energy // Cross-sectional area in XZ plane: BoutReal da = (coord->J[i] + coord->J[ip]) / (sqrt(coord->g_22[i]) + sqrt(coord->g_22[ip])) * 0.5*(coord->dx[i] + coord->dx[ip]) * 0.5*(coord->dz[i] + coord->dz[ip]); // [m^2] // Multiply by area to get energy flow (power) BoutReal flow = q * da; // [W] // Divide by cell volume to get source [W/m^3] BoutReal cooling_source = flow / (coord->dx[i] * coord->dy[i] * coord->dz[i] * coord->J[i]); // Subtract from cell next to boundary energy_source[i] -= cooling_source; target_energy_source[i] -= cooling_source; } } } // SOL edge if (sol) { if(mesh->lastX()){ // Only do this for the processor which has the edge region for(int iy=0; iy < mesh->LocalNy ; iy++){ for(int iz=0; iz < mesh->LocalNz; iz++){ auto i = indexAt(Nn, mesh->xend, iy, iz); // Final domain cell auto ig = indexAt(Nn, mesh->xend+1, iy, iz); // Guard cell // Calculate midpoint values at wall const BoutReal nnsheath = 0.5 * (Nn[ig] + Nn[i]); const BoutReal tnsheath = 0.5 * (Tn[ig] + Tn[i]); // Thermal speed of static Maxwellian in one direction const BoutReal v_th = 0.25 * sqrt( 8*tnsheath / (PI*AA) ); // Stangeby p.69 eqns. 2.21, 2.24 // Approach adapted from D. Power thesis 2023 BoutReal T_FC = 3 / Tnorm; // Franck-Condon temp (hardcoded for now) // Outgoing neutral heat flux [W/m^2] // This is rearranged from Power for clarity - note definition of v_th. BoutReal q = 2 * nnsheath * tnsheath * v_th // Incident energy - (target_energy_refl_factor * target_fast_refl_fraction ) * 2 * nnsheath * tnsheath * v_th // Fast reflected energy - (1 - target_fast_refl_fraction) * T_FC * nnsheath * v_th; // Thermal reflected energy // Multiply by radial cell area to get power // Expanded form of the calculation for clarity // Converts dy to poloidal length: dl = dy / sqrt(g22) = dy * h_theta BoutReal dpol = 0.5*(coord->dy[i] + coord->dy[ig]) * 1/( 0.5*(sqrt(coord->g22[i]) + sqrt(coord->g22[ig])) ); // Converts dz to toroidal length: = dz*sqrt(g_33) = dz * R = 2piR BoutReal dtor = 0.5*(coord->dz[i] + coord->dz[ig]) * 0.5*(sqrt(coord->g_33[i]) + sqrt(coord->g_33[ig])); BoutReal da = dpol * dtor; // [m^2] // Multiply by area to get energy flow (power) BoutReal flow = q * da; // [W] // Divide by cell volume to get source [W/m^3] BoutReal cooling_source = flow / (coord->J[i] * coord->dx[i] * coord->dy[i] * coord->dz[i]); // [W m^-3] // Subtract from cell next to boundary energy_source[i] -= cooling_source; wall_energy_source[i] -= cooling_source; } } } } // PFR edge if (pfr) { if ((mesh->firstX()) and (!mesh->periodicY(mesh->xstart))) { // do loop if inner edge and not periodic (i.e. PFR) for(int iy=0; iy < mesh->LocalNy ; iy++){ for(int iz=0; iz < mesh->LocalNz; iz++){ auto i = indexAt(Nn, mesh->xstart, iy, iz); // Final domain cell auto ig = indexAt(Nn, mesh->xstart-1, iy, iz); // Guard cell // Calculate midpoint values at wall const BoutReal nnsheath = 0.5 * (Nn[ig] + Nn[i]); const BoutReal tnsheath = 0.5 * (Tn[ig] + Tn[i]); // Thermal speed of static Maxwellian in one direction const BoutReal v_th = 0.25 * sqrt( 8*tnsheath / (PI*AA) ); // Stangeby p.69 eqns. 2.21, 2.24 // Approach adapted from D. Power thesis 2023 BoutReal T_FC = 3 / Tnorm; // Franck-Condon temp (hardcoded for now) // Outgoing neutral heat flux [W/m^2] // This is rearranged from Power for clarity - note definition of v_th. BoutReal q = 2 * nnsheath * tnsheath * v_th // Incident energy - (target_energy_refl_factor * target_fast_refl_fraction ) * 2 * nnsheath * tnsheath * v_th // Fast reflected energy - (1 - target_fast_refl_fraction) * T_FC * nnsheath * v_th; // Thermal reflected energy // Multiply by radial cell area to get power // Expanded form of the calculation for clarity // Converts dy to poloidal length: dl = dy / sqrt(g22) = dy * h_theta BoutReal dpol = 0.5*(coord->dy[i] + coord->dy[ig]) * 1/( 0.5*(sqrt(coord->g22[i]) + sqrt(coord->g22[ig])) ); // Converts dz to toroidal length: = dz*sqrt(g_33) = dz * R = 2piR BoutReal dtor = 0.5*(coord->dz[i] + coord->dz[ig]) * 0.5*(sqrt(coord->g_33[i]) + sqrt(coord->g_33[ig])); BoutReal da = dpol * dtor; // [m^2] // Multiply by area to get energy flow (power) BoutReal flow = q * da; // [W] // Divide by cell volume to get source [W/m^3] BoutReal cooling_source = flow / (coord->J[i] * coord->dx[i] * coord->dy[i] * coord->dz[i]); // [W m^-3] // Subtract from cell next to boundary energy_source[i] -= cooling_source; wall_energy_source[i] -= cooling_source; } } } } // Set density, pressure and temperature, now with boundary conditions setBoundary(species["density"], fromFieldAligned(Nn)); setBoundary(species["temperature"], fromFieldAligned(Tn)); setBoundary(species["pressure"], fromFieldAligned(Pn)); if (IS_SET_NOBOUNDARY(species["velocity"])) { setBoundary(species["velocity"], fromFieldAligned(Vn)); } if (IS_SET_NOBOUNDARY(species["momentum"])) { setBoundary(species["momentum"], fromFieldAligned(NVn)); } // Set energy source (negative in cell next to sheath) // Note: energy_source includes any sources previously set in other components set(species["energy_source"], fromFieldAligned(energy_source)); } void NeutralBoundary::outputVars(Options& state) { AUTO_TRACE(); // Normalisations auto Nnorm = get<BoutReal>(state["Nnorm"]); auto Omega_ci = get<BoutReal>(state["Omega_ci"]); auto Tnorm = get<BoutReal>(state["Tnorm"]); BoutReal Pnorm = SI::qe * Tnorm * Nnorm; // Pressure normalisation if (diagnose) { AUTO_TRACE(); // Save particle and energy source for the species created during recycling // Target recycling if ((sol) or (pfr)) { set_with_attrs(state[{std::string("E") + name + std::string("_wall_refl")}], wall_energy_source, {{"time_dimension", "t"}, {"units", "W m^-3"}, {"conversion", Pnorm * Omega_ci}, {"standard_name", "energy source"}, {"long_name", std::string("Wall reflection energy source of ") + name}, {"source", "neutral_boundary"}}); } set_with_attrs(state[{std::string("E") + name + std::string("_target_refl")}], target_energy_source, {{"time_dimension", "t"}, {"units", "W m^-3"}, {"conversion", Pnorm * Omega_ci}, {"standard_name", "energy source"}, {"long_name", std::string("Wall reflection energy source of ") + name}, {"source", "neutral_boundary"}}); } }
15,371
C++
.cxx
275
46.141818
142
0.572392
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,207
isothermal.cxx
bendudson_hermes-3/src/isothermal.cxx
#include <bout/constants.hxx> #include "../include/isothermal.hxx" Isothermal::Isothermal(std::string name, Options &alloptions, Solver *UNUSED(solver)) : name(name) { AUTO_TRACE(); Options& options = alloptions[name]; auto Tnorm = get<BoutReal>(alloptions["units"]["eV"]); T = options["temperature"].doc("Constant temperature [eV]").as<BoutReal>() / Tnorm; // Normalise diagnose = options["diagnose"] .doc("Save additional output diagnostics") .withDefault<bool>(false); } void Isothermal::transform(Options &state) { AUTO_TRACE(); Options& species = state["species"][name]; set(species["temperature"], T); // If density is set, also set pressure if (isSetFinalNoBoundary(species["density"])) { // Note: The boundary of N may not be set yet auto N = GET_NOBOUNDARY(Field3D, species["density"]); P = N * T; set(species["pressure"], P); } } void Isothermal::outputVars(Options& state) { AUTO_TRACE(); auto Tnorm = get<BoutReal>(state["Tnorm"]); auto Nnorm = get<BoutReal>(state["Nnorm"]); // Save the temperature to the output files set_with_attrs(state[std::string("T") + name], T, {{"units", "eV"}, {"conversion", Tnorm}, {"long_name", name + " temperature"}, {"standard_name", "temperature"}, {"species", name}, {"source", "isothermal"}}); if (diagnose) { // Save pressure as time-varying field set_with_attrs(state[std::string("P") + name], P, {{"time_dimension", "t"}, {"units", "Pa"}, {"conversion", SI::qe * Tnorm * Nnorm}, {"long_name", name + " pressure"}, {"standard_name", "pressure"}, {"species", name}, {"source", "isothermal"}}); } }
1,907
C++
.cxx
50
29.94
76
0.568022
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,208
amjuel_hyd_recombination.cxx
bendudson_hermes-3/src/amjuel_hyd_recombination.cxx
#include "../include/amjuel_hyd_recombination.hxx" /// Coefficients to calculate the effective reaction rate <σv> /// Reaction 2.1.8, Amjuel page 141 (section H.4) /// E-index varies fastest, so coefficient is [T][n] static constexpr const BoutReal rate_coefs[9][9] = { {-28.58858570847, 0.02068671746773, -0.007868331504755, 0.003843362133859, -0.0007411492158905, 9.273687892997e-05, -7.063529824805e-06, 3.026539277057e-07, -5.373940838104e-09}, {-0.7676413320499, 0.0127800603259, -0.01870326896978, 0.00382855504889, -0.0003627770385335, 4.401007253801e-07, 1.932701779173e-06, -1.176872895577e-07, 2.215851843121e-09}, {0.002823851790251, -0.001907812518731, 0.01121251125171, -0.003711328186517, 0.0006617485083301, -6.860774445002e-05, 4.508046989099e-06, -1.723423509284e-07, 2.805361431741e-09}, {-0.01062884273731, -0.01010719783828, 0.004208412930611, -0.00100574441054, 0.0001013652422369, -2.044691594727e-06, -4.431181498017e-07, 3.457903389784e-08, -7.374639775683e-10}, {0.001582701550903, 0.002794099401979, -0.002024796037098, 0.0006250304936976, -9.224891301052e-05, 7.546853961575e-06, -3.682709551169e-07, 1.035928615391e-08, -1.325312585168e-10}, {-0.0001938012790522, 0.0002148453735781, 3.393285358049e-05, -3.746423753955e-05, 7.509176112468e-06, -8.688365258514e-07, 7.144767938783e-08, -3.367897014044e-09, 6.250111099227e-11}, {6.041794354114e-06, -0.0001421502819671, 6.14387907608e-05, -1.232549226121e-05, 1.394562183496e-06, -6.434833988001e-08, -2.746804724917e-09, 3.564291012995e-10, -8.55170819761e-12}, {1.742316850715e-06, 1.595051038326e-05, -7.858419208668e-06, 1.774935420144e-06, -2.187584251561e-07, 1.327090702659e-08, -1.386720240985e-10, -1.946206688519e-11, 5.745422385081e-13}, {-1.384927774988e-07, -5.664673433879e-07, 2.886857762387e-07, -6.591743182569e-08, 8.008790343319e-09, -4.805837071646e-10, 6.459706573699e-12, 5.510729582791e-13, -1.680871303639e-14}}; /// Coefficients to calculate the radiation energy loss /// Reaction 2.1.8, Amjuel page 284 (section H.10) /// E-index varies fastest, so coefficient is [T][n] static constexpr const BoutReal radiation_coefs[9][9] = { {-25.92450349909, 0.01222097271874, 4.278499401907e-05, 0.001943967743593, -0.0007123474602102, 0.0001303523395892, -1.186560752561e-05, 5.334455630031e-07, -9.349857887253e-09}, {-0.7290670236493, -0.01540323930666, -0.00340609377919, 0.001532243431817, -0.0004658423772784, 5.972448753445e-05, -4.070843294052e-06, 1.378709880644e-07, -1.818079729166e-09}, {0.02363925869096, 0.01164453346305, -0.005845209334594, 0.002854145868307, -0.0005077485291132, 4.211106637742e-05, -1.251436618314e-06, -1.626555745259e-08, 1.073458810743e-09}, {0.003645333930947, -0.001005820792983, 0.0006956352274249, -0.0009305056373739, 0.0002584896294384, -3.294643898894e-05, 2.112924018518e-06, -6.544682842175e-08, 7.8102930757e-10}, {0.001594184648757, -1.582238007548e-05, 0.0004073695619272, -9.379169243859e-05, 1.490890502214e-06, 2.245292872209e-06, -3.150901014513e-07, 1.631965635818e-08, -2.984093025695e-10}, {-0.001216668033378, -0.0003503070140126, 0.0001043500296633, 9.536162767321e-06, -6.908681884097e-06, 8.232019008169e-07, -2.905331051259e-08, -3.169038517749e-10, 2.442765766167e-11}, {0.0002376115895241, 0.0001172709777146, -6.695182045674e-05, 1.18818400621e-05, -4.381514364966e-07, -6.936267173079e-08, 6.592249255001e-09, -1.778887958831e-10, 1.160762106747e-12}, {-1.930977636766e-05, -1.318401491304e-05, 8.848025453481e-06, -2.07237071139e-06, 2.055919993599e-07, -7.489632654212e-09, -7.073797030749e-11, 1.047087505147e-11, -1.87744627135e-13}, {5.599257775146e-07, 4.977823319311e-07, -3.615013823092e-07, 9.466989306497e-08, -1.146485227699e-08, 6.772338917155e-10, -1.776496344763e-11, 7.199195061382e-14, 3.929300283002e-15}}; void AmjuelHydRecombination::calculate_rates( Options& electron, Options& atom, Options& ion, Field3D &reaction_rate, Field3D &momentum_exchange, Field3D &energy_exchange, Field3D &energy_loss, BoutReal &rate_multiplier, BoutReal &radiation_multiplier) { electron_reaction(electron, ion, atom, rate_coefs, radiation_coefs, 13.6, // Potential energy loss [eV] heats electrons reaction_rate, momentum_exchange, energy_exchange, energy_loss, rate_multiplier, radiation_multiplier ); }
4,571
C++
.cxx
72
58.236111
121
0.738212
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,209
quasineutral.cxx
bendudson_hermes-3/src/quasineutral.cxx
#include <numeric> // for accumulate #include "../include/quasineutral.hxx" Quasineutral::Quasineutral(std::string name, Options &alloptions, Solver *UNUSED(solver)) : name(name) { Options &options = alloptions[name]; // Need to have a charge and mass charge = options["charge"].doc("Particle charge. electrons = -1"); AA = options["AA"].doc("Particle atomic mass. Proton = 1"); ASSERT0(charge != 0.0); } void Quasineutral::transform(Options &state) { AUTO_TRACE(); // Iterate through all subsections Options &allspecies = state["species"]; // Add charge density of other species const Field3D rho = std::accumulate( // Iterate through species begin(allspecies.getChildren()), end(allspecies.getChildren()), // Start with no charge Field3D(0.0), [this](Field3D value, const std::map<std::string, Options>::value_type &name_species) { const Options &species = name_species.second; // Add other species which have density and charge if (name_species.first != name and species.isSet("charge") and species.isSet("density")) { // Note: Not assuming that the boundary has been set return value + getNoBoundary<Field3D>(species["density"]) * get<BoutReal>(species["charge"]); } return value; }); // Set quantites for this species Options &species = allspecies[name]; // Calculate density required. Floor so that density is >= 0 density = floor(rho / (-charge), 0.0); set(species["density"], density); set(species["charge"], charge); set(species["AA"], AA); } void Quasineutral::finally(const Options &state) { // Density may have had boundary conditions applied density = get<Field3D>(state["species"][name]["density"]); } void Quasineutral::outputVars(Options &state) { AUTO_TRACE(); auto Nnorm = get<BoutReal>(state["Nnorm"]); // Save the density set_with_attrs(state[std::string("N") + name], density, {{"time_dimension", "t"}, {"units", "m^-3"}, {"conversion", Nnorm}, {"long_name", name + " number density"}, {"standard_name", "density"}, {"species", name}, {"source", "quasineutral"}}); }
2,354
C++
.cxx
58
33.275862
78
0.618755
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,210
diamagnetic_drift.cxx
bendudson_hermes-3/src/diamagnetic_drift.cxx
#include <bout/fv_ops.hxx> #include <bout/vecops.hxx> #include "../include/diamagnetic_drift.hxx" using bout::globals::mesh; DiamagneticDrift::DiamagneticDrift(std::string name, Options& alloptions, Solver* UNUSED(solver)) { // Get options for this component auto& options = alloptions[name]; bndry_flux = options["bndry_flux"].doc("Allow fluxes through boundary?").withDefault<bool>(true); diamag_form = options["diamag_form"] .doc("Form of diamagnetic drift: 0 = gradient; 1 = divergence") .withDefault(Field2D(1.0)); // Read curvature vector Curlb_B.covariant = false; // Contravariant if (mesh->get(Curlb_B, "bxcv")) { Curlb_B.x = Curlb_B.y = Curlb_B.z = 0.0; } Options& paralleltransform = Options::root()["mesh"]["paralleltransform"]; if (paralleltransform.isSet("type") and paralleltransform["type"].as<std::string>() == "shifted") { Field2D I; if (mesh->get(I, "sinty")) { I = 0.0; } Curlb_B.z += I * Curlb_B.x; } // Normalise // Get the units const auto& units = alloptions["units"]; BoutReal Bnorm = get<BoutReal>(units["Tesla"]); BoutReal Lnorm = get<BoutReal>(units["meters"]); Curlb_B.x /= Bnorm; Curlb_B.y *= SQ(Lnorm); Curlb_B.z *= SQ(Lnorm); Curlb_B *= 2. / mesh->getCoordinates()->Bxy; // Set drift to zero through sheath boundaries. // Flux through those cell faces should be set by sheath. for (RangeIterator r = mesh->iterateBndryLowerY(); !r.isDone(); r++) { Curlb_B.y(r.ind, mesh->ystart - 1) = -Curlb_B.y(r.ind, mesh->ystart); } for (RangeIterator r = mesh->iterateBndryUpperY(); !r.isDone(); r++) { Curlb_B.y(r.ind, mesh->yend + 1) = -Curlb_B.y(r.ind, mesh->yend); } } void DiamagneticDrift::transform(Options& state) { // Iterate through all subsections Options& allspecies = state["species"]; for (auto& kv : allspecies.getChildren()) { Options& species = allspecies[kv.first]; // Note: Need non-const if (!(species.isSet("charge") and species.isSet("temperature"))) continue; // Skip, go to next species // Calculate diamagnetic drift velocity for this species auto q = get<BoutReal>(species["charge"]); if (fabs(q) < 1e-5) { continue; } auto T = GET_VALUE(Field3D, species["temperature"]); // Diamagnetic drift velocity Vector3D vD = (T / q) * Curlb_B; if (IS_SET(species["density"])) { auto N = GET_VALUE(Field3D, species["density"]); // Divergence form: Div(n v_D) Field3D div_form = FV::Div_f_v(N, vD, bndry_flux); // Gradient form: Curlb_B dot Grad(N T / q) Field3D grad_form = Curlb_B * Grad(N * T / q); subtract(species["density_source"], diamag_form * div_form + (1. - diamag_form) * grad_form); } if (IS_SET(species["pressure"])) { auto P = get<Field3D>(species["pressure"]); Field3D div_form = FV::Div_f_v(P, vD, bndry_flux); Field3D grad_form = Curlb_B * Grad(P * T / q); subtract(species["energy_source"], (5. / 2) * (diamag_form * div_form + (1. - diamag_form) * grad_form)); } if (IS_SET(species["momentum"])) { auto NV = get<Field3D>(species["momentum"]); Field3D div_form = FV::Div_f_v(NV, vD, bndry_flux); Field3D grad_form = Curlb_B * Grad(NV * T / q); subtract(species["momentum_source"], diamag_form * div_form + (1. - diamag_form) * grad_form); } } }
3,428
C++
.cxx
82
36.792683
111
0.63245
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,211
solkit_neutral_parallel_diffusion.cxx
bendudson_hermes-3/src/solkit_neutral_parallel_diffusion.cxx
#include "../include/solkit_neutral_parallel_diffusion.hxx" #include <bout/fv_ops.hxx> #include <numeric> using bout::globals::mesh; void SOLKITNeutralParallelDiffusion::transform(Options& state) { AUTO_TRACE(); Options& allspecies = state["species"]; for (auto& kv : allspecies.getChildren()) { // Get non-const reference auto& species = allspecies[kv.first]; if (species.isSet("charge") and (get<BoutReal>(species["charge"]) != 0.0)) { // Skip charged species continue; } // Sum inverse mean free path with other species Field3D inv_mfp = std::accumulate( // Iterate through species begin(allspecies.getChildren()), end(allspecies.getChildren()), // Start with no collisions Field3D(0.0), [this](Field3D value, const std::map<std::string, Options>::value_type &name_species) { const Options &species = name_species.second; if (name_species.first == "e") { // Electrons const Field3D Ne = GET_VALUE(Field3D, species["density"]); return value + (8.8e-21 / area_norm) * Ne; } else if (species.isSet("charge") and (get<BoutReal>(species["charge"]) != 0.0)) { // Charged ion species const Field3D Ni = GET_VALUE(Field3D, species["density"]); return value + (3e-19 / area_norm) * Ni; } else { // Neutral species, including self const Field3D Nn = GET_VALUE(Field3D, species["density"]); return value + (8.8e-21 / area_norm) * Nn; } }); // Diffusion coefficient const BoutReal AA = get<BoutReal>(species["AA"]); // Atomic mass // Notes: // - neutral_temperature already normalised // - vth,n = sqrt(2kT/m_i) Field3D Dn = sqrt(2 * neutral_temperature / AA) / (2 * inv_mfp); Dn.applyBoundary("dirichlet_o2"); mesh->communicate(Dn); // Cross-field diffusion calculated from pressure gradient const Field3D Nn = GET_VALUE(Field3D, species["density"]); const Field3D Pn = Nn * neutral_temperature; // Pressure Field3D logPn = log(floor(Pn, 1e-7)); logPn.applyBoundary("neumann"); // Particle diffusion add(species["density_source"], FV::Div_par_K_Grad_par(Dn * Nn, logPn)); } }
2,285
C++
.cxx
55
34.818182
80
0.62968
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,212
evolve_energy.cxx
bendudson_hermes-3/src/evolve_energy.cxx
#include <bout/constants.hxx> #include <bout/fv_ops.hxx> #include <bout/invert_pardiv.hxx> #include <bout/output_bout_types.hxx> #include <bout/derivs.hxx> #include <bout/difops.hxx> #include <bout/initialprofiles.hxx> #include "../include/div_ops.hxx" #include "../include/evolve_energy.hxx" #include "../include/hermes_utils.hxx" #include "../include/hermes_build_config.hxx" using bout::globals::mesh; EvolveEnergy::EvolveEnergy(std::string name, Options& alloptions, Solver* solver) : name(name) { AUTO_TRACE(); auto& options = alloptions[name]; adiabatic_index = options["adiabatic_index"] .doc("Ratio of specific heats γ = Cp/Cv [5/3 for monatomic ideal gas]") .withDefault(5. / 3); Cv = 1. / (adiabatic_index - 1.); evolve_log = options["evolve_log"] .doc("Evolve the logarithm of energy?") .withDefault<bool>(false); density_floor = options["density_floor"].doc("Minimum density floor").withDefault(1e-5); if (evolve_log) { // Evolve logarithm of energy solver->add(logE, std::string("logE") + name); // Save the pressure to the restart file // so the simulation can be restarted evolving energy // get_restart_datafile()->addOnce(E, std::string("E") + name); if (!alloptions["hermes"]["restarting"]) { // Set logE from E input options initial_profile(std::string("E") + name, E); logE = log(E); } else { // Ignore these settings Options::root()[std::string("E") + name].setConditionallyUsed(); } } else { // Evolve the energy in time solver->add(E, std::string("E") + name); } bndry_flux = options["bndry_flux"] .doc("Allow flows through radial boundaries") .withDefault<bool>(true); poloidal_flows = options["poloidal_flows"].doc("Include poloidal ExB flow").withDefault<bool>(true); thermal_conduction = options["thermal_conduction"] .doc("Include parallel heat conduction?") .withDefault<bool>(true); kappa_coefficient = options["kappa_coefficient"] .doc("Numerical coefficient in parallel heat conduction. " "Default is 3.16 for electrons, 3.9 otherwise") .withDefault((name == "e") ? 3.16 : 3.9); kappa_limit_alpha = options["kappa_limit_alpha"] .doc("Flux limiter factor. < 0 means no limit. Typical is 0.2 " "for electrons, 1 for ions.") .withDefault(-1.0); hyper_z = options["hyper_z"].doc("Hyper-diffusion in Z").withDefault(-1.0); diagnose = options["diagnose"] .doc("Save additional output diagnostics") .withDefault<bool>(false); enable_precon = options["precondition"] .doc("Enable preconditioner? (Note: solver may not use it)") .withDefault<bool>(true); const Options& units = alloptions["units"]; const BoutReal Nnorm = units["inv_meters_cubed"]; const BoutReal Tnorm = units["eV"]; const BoutReal Omega_ci = 1. / units["seconds"].as<BoutReal>(); // Try to read the pressure source from the mesh source = 0.0; mesh->get(source, std::string("P") + name + "_src"); // Units of Pascals per second source *= Cv; // Convert to W/m^3 // Allow the user to override the source source = alloptions[std::string("E") + name]["source"] .doc(std::string("Source term in ddt(E") + name + std::string("). Units [W/m^3]")) .withDefault(source) / (SI::qe * Nnorm * Tnorm * Omega_ci); if (alloptions[std::string("E") + name]["source_only_in_core"] .doc("Zero the source outside the closed field-line region?") .withDefault<bool>(false)) { for (int x = mesh->xstart; x <= mesh->xend; x++) { if (!mesh->periodicY(x)) { // Not periodic, so not in core for (int y = mesh->ystart; y <= mesh->yend; y++) { for (int z = mesh->zstart; z <= mesh->zend; z++) { source(x, y, z) = 0.0; } } } } } neumann_boundary_average_z = alloptions[std::string("E") + name]["neumann_boundary_average_z"] .doc("Apply neumann boundary with Z average?") .withDefault<bool>(false); } void EvolveEnergy::transform(Options& state) { AUTO_TRACE(); if (evolve_log) { // Evolving logE, but most calculations use E E = exp(logE); } mesh->communicate(E); auto& species = state["species"][name]; N = getNoBoundary<Field3D>(species["density"]); const Field3D V = getNoBoundary<Field3D>(species["velocity"]); const BoutReal AA = get<BoutReal>(species["AA"]); // Calculate pressure // E = Cv * P + (1/2) m n v^2 P.allocate(); BOUT_FOR(i, P.getRegion("RGN_ALL")) { P[i] = (E[i] - 0.5 * AA * N[i] * SQ(V[i])) / Cv; if (P[i] < 0.0) { P[i] = 0.0; } } P.applyBoundary("neumann"); if (neumann_boundary_average_z) { // Take Z (usually toroidal) average and apply as X (radial) boundary condition if (mesh->firstX()) { for (int j = mesh->ystart; j <= mesh->yend; j++) { BoutReal Pavg = 0.0; // Average P in Z for (int k = 0; k < mesh->LocalNz; k++) { Pavg += P(mesh->xstart, j, k); } Pavg /= mesh->LocalNz; // Apply boundary condition for (int k = 0; k < mesh->LocalNz; k++) { P(mesh->xstart - 1, j, k) = 2. * Pavg - P(mesh->xstart, j, k); P(mesh->xstart - 2, j, k) = P(mesh->xstart - 1, j, k); } } } if (mesh->lastX()) { for (int j = mesh->ystart; j <= mesh->yend; j++) { BoutReal Pavg = 0.0; // Average P in Z for (int k = 0; k < mesh->LocalNz; k++) { Pavg += P(mesh->xend, j, k); } Pavg /= mesh->LocalNz; for (int k = 0; k < mesh->LocalNz; k++) { P(mesh->xend + 1, j, k) = 2. * Pavg - P(mesh->xend, j, k); P(mesh->xend + 2, j, k) = P(mesh->xend + 1, j, k); } } } } // Calculate temperature T = P / floor(N, density_floor); P = N * T; // Ensure consistency set(species["pressure"], P); set(species["temperature"], T); } void EvolveEnergy::finally(const Options& state) { AUTO_TRACE(); /// Get the section containing this species const auto& species = state["species"][name]; // Get updated pressure and temperature with boundary conditions P = get<Field3D>(species["pressure"]); T = get<Field3D>(species["temperature"]); N = get<Field3D>(species["density"]); const Field3D V = get<Field3D>(species["velocity"]); const BoutReal AA = get<BoutReal>(species["AA"]); // Update boundaries of E from boundaries of P and V E = toFieldAligned(E); for (RangeIterator r = mesh->iterateBndryLowerY(); !r.isDone(); r++) { for (int jz = 0; jz < mesh->LocalNz; jz++) { auto i = indexAt(N, r.ind, mesh->ystart, jz); auto im = i.ym(); const BoutReal psheath = 0.5 * (P[im] + P[i]); const BoutReal nsheath = 0.5 * (N[im] + N[i]); const BoutReal vsheath = 0.5 * (V[im] + V[i]); const BoutReal Esheath = Cv * psheath + 0.5 * AA * nsheath * SQ(vsheath); E[im] = 2 * Esheath - E[i]; } } for (RangeIterator r = mesh->iterateBndryUpperY(); !r.isDone(); r++) { for (int jz = 0; jz < mesh->LocalNz; jz++) { auto i = indexAt(N, r.ind, mesh->yend, jz); auto ip = i.yp(); const BoutReal psheath = 0.5 * (P[ip] + P[i]); const BoutReal nsheath = 0.5 * (N[ip] + N[i]); const BoutReal vsheath = 0.5 * (V[ip] + V[i]); const BoutReal Esheath = Cv * psheath + 0.5 * AA * nsheath * SQ(vsheath); E[ip] = 2 * Esheath - E[i]; } } E = fromFieldAligned(E); Field3D Pfloor = P; if (species.isSet("charge") and (fabs(get<BoutReal>(species["charge"])) > 1e-5) and state.isSection("fields") and state["fields"].isSet("phi")) { // Electrostatic potential set -> include ExB flow Field3D phi = get<Field3D>(state["fields"]["phi"]); ddt(E) = -Div_n_bxGrad_f_B_XPPM(E, phi, bndry_flux, poloidal_flows, true); } else { ddt(E) = 0.0; } if (species.isSet("velocity")) { Field3D V = get<Field3D>(species["velocity"]); // Typical wave speed used for numerical diffusion Field3D fastest_wave; if (state.isSet("fastest_wave")) { fastest_wave = get<Field3D>(state["fastest_wave"]); } else { const BoutReal AA = get<BoutReal>(species["AA"]); fastest_wave = sqrt(T / AA); } ddt(E) -= FV::Div_par_mod<hermes::Limiter>(E + P, V, fastest_wave, flow_ylow); if (state.isSection("fields") and state["fields"].isSet("Apar_flutter")) { // Magnetic flutter term const Field3D Apar_flutter = get<Field3D>(state["fields"]["Apar_flutter"]); ddt(E) -= Div_n_g_bxGrad_f_B_XZ(E + P, V, -Apar_flutter); } } if (species.isSet("low_n_coeff")) { // Low density parallel diffusion Field3D low_n_coeff = get<Field3D>(species["low_n_coeff"]); ddt(E) += FV::Div_par_K_Grad_par(low_n_coeff * T, N) + FV::Div_par_K_Grad_par(low_n_coeff, P); } // Parallel heat conduction if (thermal_conduction) { // Calculate ion collision times const Field3D tau = 1. / floor(get<Field3D>(species["collision_frequency"]), 1e-10); const BoutReal AA = get<BoutReal>(species["AA"]); // Atomic mass // Parallel heat conduction // Braginskii expression for parallel conduction // kappa ~ n * v_th^2 * tau // // Note: Coefficient is slightly different for electrons (3.16) and ions (3.9) kappa_par = kappa_coefficient * Pfloor * tau / AA; if (kappa_limit_alpha > 0.0) { /* * Flux limiter, as used in SOLPS. * * Calculate the heat flux from Spitzer-Harm and flux limit * * Typical value of alpha ~ 0.2 for electrons * * R.Schneider et al. Contrib. Plasma Phys. 46, No. 1-2, 3 – 191 (2006) * DOI 10.1002/ctpp.200610001 */ // Spitzer-Harm heat flux Field3D q_SH = kappa_par * Grad_par(T); // Free-streaming flux Field3D q_fl = kappa_limit_alpha * N * T * sqrt(T / AA); // This results in a harmonic average of the heat fluxes kappa_par = kappa_par / (1. + abs(q_SH / floor(q_fl, 1e-10))); // Values of kappa on cell boundaries are needed for fluxes mesh->communicate(kappa_par); } for (RangeIterator r = mesh->iterateBndryLowerY(); !r.isDone(); r++) { for (int jz = 0; jz < mesh->LocalNz; jz++) { auto i = indexAt(kappa_par, r.ind, mesh->ystart, jz); auto im = i.ym(); kappa_par[im] = kappa_par[i]; } } for (RangeIterator r = mesh->iterateBndryUpperY(); !r.isDone(); r++) { for (int jz = 0; jz < mesh->LocalNz; jz++) { auto i = indexAt(kappa_par, r.ind, mesh->yend, jz); auto ip = i.yp(); kappa_par[ip] = kappa_par[i]; } } // Note: Flux through boundary turned off, because sheath heat flux // is calculated and removed separately Field3D flow_ylow_conduction; ddt(E) += Div_par_K_Grad_par_mod(kappa_par, T, flow_ylow_conduction, false); flow_ylow += flow_ylow_conduction; if (state.isSection("fields") and state["fields"].isSet("Apar_flutter")) { // Magnetic flutter term. The operator splits into 4 pieces: // Div(k b b.Grad(T)) = Div(k b0 b0.Grad(T)) + Div(k d0 db.Grad(T)) // + Div(k db b0.Grad(T)) + Div(k db db.Grad(T)) // The first term is already calculated above. // Here we add the terms containing db const Field3D Apar_flutter = get<Field3D>(state["fields"]["Apar_flutter"]); Field3D db_dot_T = bracket(T, Apar_flutter, BRACKET_ARAKAWA); Field3D b0_dot_T = Grad_par(T); mesh->communicate(db_dot_T, b0_dot_T); ddt(E) += Div_par(kappa_par * db_dot_T) - Div_n_g_bxGrad_f_B_XZ(kappa_par, db_dot_T + b0_dot_T, Apar_flutter); } } if (hyper_z > 0.) { auto* coord = N.getCoordinates(); ddt(E) -= hyper_z * SQ(SQ(coord->dz)) * D4DZ4(E); } ////////////////////// // Other sources Se = source; if (species.isSet("energy_source")) { Se += get<Field3D>(species["energy_source"]); // For diagnostic output } #if CHECKLEVEL >= 1 if (species.isSet("pressure_source")) { throw BoutException("Components must evolve `energy_source` rather then `pressure_source`"); } #endif if (species.isSet("momentum_source")) { Se += V * get<Field3D>(species["momentum_source"]); } ddt(E) += Se; // Scale time derivatives if (state.isSet("scale_timederivs")) { ddt(E) *= get<Field3D>(state["scale_timederivs"]); } if (evolve_log) { ddt(logE) = ddt(E) / E; } #if CHECKLEVEL >= 1 for (auto& i : E.getRegion("RGN_NOBNDRY")) { if (!std::isfinite(ddt(E)[i])) { throw BoutException("ddt(E{}) non-finite at {}. Se={}\n", name, i, Se[i]); } } #endif if (diagnose) { // Save flows of energy if they are set if (species.isSet("energy_flow_xlow")) { flow_xlow = get<Field3D>(species["energy_flow_xlow"]); } if (species.isSet("energy_flow_ylow")) { flow_ylow += get<Field3D>(species["energy_flow_ylow"]); } } } void EvolveEnergy::outputVars(Options& state) { AUTO_TRACE(); // Normalisations auto Nnorm = get<BoutReal>(state["Nnorm"]); auto Tnorm = get<BoutReal>(state["Tnorm"]); auto Omega_ci = get<BoutReal>(state["Omega_ci"]); auto rho_s0 = get<BoutReal>(state["rho_s0"]); BoutReal Pnorm = SI::qe * Tnorm * Nnorm; // Pressure normalisation if (evolve_log) { state[std::string("E") + name].force(E); } state[std::string("E") + name].setAttributes({{"time_dimension", "t"}, {"units", "J/m^3"}, {"conversion", Pnorm}, {"standard_name", "energy density"}, {"long_name", name + " energy density"}, {"species", name}, {"source", "evolve_energy"}}); set_with_attrs(state[std::string("P") + name], P, {{"time_dimension", "t"}, {"units", "Pa"}, {"conversion", Pnorm}, {"standard_name", "pressure"}, {"long_name", name + " pressure"}, {"species", name}, {"source", "evolve_energy"}}); if (diagnose) { if (thermal_conduction) { set_with_attrs(state[std::string("kappa_par_") + name], kappa_par, {{"time_dimension", "t"}, {"units", "W / m / eV"}, {"conversion", Pnorm * Omega_ci * SQ(rho_s0)}, {"long_name", name + " heat conduction coefficient"}, {"species", name}, {"source", "evolve_energy"}}); } set_with_attrs(state[std::string("T") + name], T, {{"time_dimension", "t"}, {"units", "eV"}, {"conversion", Tnorm}, {"standard_name", "temperature"}, {"long_name", name + " temperature"}, {"species", name}, {"source", "evolve_energy"}}); set_with_attrs( state[std::string("ddt(E") + name + std::string(")")], ddt(E), {{"time_dimension", "t"}, {"units", "J/m^3/s"}, {"conversion", Pnorm * Omega_ci}, {"long_name", std::string("Rate of change of ") + name + " energy density"}, {"species", name}, {"source", "evolve_energy"}}); set_with_attrs(state[std::string("SE") + name], Se, {{"time_dimension", "t"}, {"units", "W/m^3"}, {"conversion", Pnorm * Omega_ci}, {"standard_name", "energy source"}, {"long_name", name + " energy source"}, {"species", name}, {"source", "evolve_energy"}}); set_with_attrs(state[std::string("E") + name + std::string("_src")], source, {{"time_dimension", "t"}, {"units", "W/m^3"}, {"conversion", Pnorm * Omega_ci}, {"standard_name", "energy source"}, {"long_name", name + " energy source"}, {"species", name}, {"source", "evolve_energy"}}); if (flow_xlow.isAllocated()) { set_with_attrs(state[fmt::format("ef{}_tot_xlow", name)], flow_xlow, {{"time_dimension", "t"}, {"units", "W"}, {"conversion", rho_s0 * SQ(rho_s0) * Pnorm * Omega_ci}, {"standard_name", "power"}, {"long_name", name + " power through X cell face. Note: May be incomplete."}, {"species", name}, {"source", "evolve_energy"}}); } if (flow_ylow.isAllocated()) { set_with_attrs(state[fmt::format("ef{}_tot_ylow", name)], flow_ylow, {{"time_dimension", "t"}, {"units", "W"}, {"conversion", rho_s0 * SQ(rho_s0) * Pnorm * Omega_ci}, {"standard_name", "power"}, {"long_name", name + " power through Y cell face. Note: May be incomplete."}, {"species", name}, {"source", "evolve_energy"}}); } } } void EvolveEnergy::precon(const Options& state, BoutReal gamma) { if (!(enable_precon and thermal_conduction)) { return; // Disabled } static std::unique_ptr<InvertParDiv> inv; if (!inv) { // Initialise parallel inversion class inv = InvertParDiv::create(); inv->setCoefA(1.0); } const auto& species = state["species"][name]; const Field3D N = get<Field3D>(species["density"]); // Set the coefficient in Div_par( B * Grad_par ) Field3D coef = -gamma * kappa_par / floor(N, density_floor); if (state.isSet("scale_timederivs")) { coef *= get<Field3D>(state["scale_timederivs"]); } inv->setCoefB(coef); Field3D dT = ddt(P); dT.applyBoundary("neumann"); ddt(P) = inv->solve(dT); }
18,486
C++
.cxx
442
33.452489
97
0.554071
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,213
div_ops.cxx
bendudson_hermes-3/src/div_ops.cxx
/* Copyright B.Dudson, J.Leddy, University of York, September 2016 email: benjamin.dudson@york.ac.uk This file is part of Hermes. Hermes is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Hermes is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Hermes. If not, see <http://www.gnu.org/licenses/>. */ #include <mpi.h> #include "../include/div_ops.hxx" #include <bout/fv_ops.hxx> #include <bout/assert.hxx> #include <bout/mesh.hxx> #include <bout/derivs.hxx> #include <bout/globals.hxx> #include <bout/output.hxx> #include <bout/utils.hxx> #include <cmath> using bout::globals::mesh; const Field3D Div_par_diffusion_index(const Field3D &f, bool bndry_flux) { Field3D result; result = 0.0; Coordinates *coord = mesh->getCoordinates(); for (int i = mesh->xstart; i <= mesh->xend; i++) for (int j = mesh->ystart - 1; j <= mesh->yend; j++) for (int k = 0; k < mesh->LocalNz; k++) { // Calculate flux at upper surface if (!bndry_flux && !mesh->periodicY(i)) { if ((j == mesh->yend) && mesh->lastY(i)) continue; if ((j == mesh->ystart - 1) && mesh->firstY(i)) continue; } BoutReal J = 0.5 * (coord->J(i, j) + coord->J(i, j + 1)); // Jacobian at boundary BoutReal gradient = f(i, j + 1, k) - f(i, j, k); BoutReal flux = J * gradient; result(i, j, k) += flux / coord->J(i, j); result(i, j + 1, k) -= flux / coord->J(i, j + 1); } return result; } //////////////////////////////////////////////////////////////////////////////////////////////// // XPPM methods BoutReal BOUTMIN(const BoutReal &a, const BoutReal &b, const BoutReal &c, const BoutReal &d) { BoutReal r1 = (a < b) ? a : b; BoutReal r2 = (c < d) ? c : d; return (r1 < r2) ? r1 : r2; } struct Stencil1D { // Cell centre values BoutReal c, m, p, mm, pp; // Left and right cell face values BoutReal L, R; }; // First order upwind for testing void Upwind(Stencil1D &n, const BoutReal h) { n.L = n.R = n.c; } // Fromm method void Fromm(Stencil1D &n, const BoutReal h) { n.L = n.c - 0.25 * (n.p - n.m); n.R = n.c + 0.25 * (n.p - n.m); } /// The minmod function returns the value with the minimum magnitude /// If the inputs have different signs then returns zero BoutReal minmod(BoutReal a, BoutReal b) { if (a * b <= 0.0) return 0.0; if (fabs(a) < fabs(b)) return a; return b; } BoutReal minmod(BoutReal a, BoutReal b, BoutReal c) { // If any of the signs are different, return zero gradient if ((a * b <= 0.0) || (a * c <= 0.0)) { return 0.0; } // Return the minimum absolute value return SIGN(a) * BOUTMIN(fabs(a), fabs(b), fabs(c)); } void MinMod(Stencil1D &n, const BoutReal h) { // Choose the gradient within the cell // as the minimum (smoothest) solution BoutReal slope = minmod(n.p - n.c, n.c - n.m); n.L = n.c - 0.5 * slope; // 0.25*(n.p - n.m); n.R = n.c + 0.5 * slope; // 0.25*(n.p - n.m); } // Monotonized Central limiter (Van-Leer) void MC(Stencil1D &n, const BoutReal h) { BoutReal slope = minmod(2. * (n.p - n.c), 0.5 * (n.p - n.m), 2. * (n.c - n.m)); n.L = n.c - 0.5 * slope; n.R = n.c + 0.5 * slope; } void XPPM(Stencil1D &n, const BoutReal h) { // 4th-order PPM interpolation in X const BoutReal C = 1.25; // Limiter parameter BoutReal h2 = h * h; n.R = (7. / 12) * (n.c + n.p) - (1. / 12) * (n.m + n.pp); n.L = (7. / 12) * (n.c + n.m) - (1. / 12) * (n.mm + n.p); // Apply limiters if ((n.c - n.R) * (n.p - n.R) > 0.0) { // Calculate approximations to second derivative BoutReal D2 = (3. / h2) * (n.c - 2 * n.R + n.p); BoutReal D2L = (1. / h2) * (n.m - 2 * n.c + n.p); BoutReal D2R = (1. / h2) * (n.c - 2. * n.p + n.pp); BoutReal D2lim; // Value to be used in limiter // Check if they all have the same sign if ((D2 * D2L > 0.0) && (D2 * D2R > 0.0)) { // Same sign D2lim = SIGN(D2) * BOUTMIN(C * fabs(D2L), C * fabs(D2R), fabs(D2)); } else { // Different sign D2lim = 0.0; } n.R = 0.5 * (n.c + n.p) - (h2 / 6) * D2lim; } if ((n.m - n.L) * (n.c - n.L) > 0.0) { // Calculate approximations to second derivative BoutReal D2 = (3. / h2) * (n.m - 2 * n.L + n.c); BoutReal D2L = (1. / h2) * (n.mm - 2 * n.m + n.c); BoutReal D2R = (1. / h2) * (n.m - 2. * n.c + n.p); BoutReal D2lim; // Value to be used in limiter // Check if they all have the same sign if ((D2 * D2L > 0.0) && (D2 * D2R > 0.0)) { // Same sign D2lim = SIGN(D2) * BOUTMIN(C * fabs(D2L), C * fabs(D2R), fabs(D2)); } else { // Different sign D2lim = 0.0; } n.L = 0.5 * (n.m + n.c) - (h2 / 6) * D2lim; } if (((n.R - n.c) * (n.c - n.L) <= 0.0) || ((n.m - n.c) * (n.c - n.p) <= 0.0)) { // At a local maximum or minimum BoutReal D2 = (6. / h2) * (n.L - 2. * n.c + n.R); if (fabs(D2) < 1e-10) { n.R = n.L = n.c; } else { BoutReal D2C = (1. / h2) * (n.m - 2. * n.c + n.p); BoutReal D2L = (1. / h2) * (n.mm - 2 * n.m + n.c); BoutReal D2R = (1. / h2) * (n.c - 2. * n.p + n.pp); BoutReal D2lim; // Check if they all have the same sign if ((D2 * D2C > 0.0) && (D2 * D2L > 0.0) && (D2 * D2R > 0.0)) { // Same sign D2lim = SIGN(D2) * BOUTMIN(C * fabs(D2L), C * fabs(D2R), C * fabs(D2C), fabs(D2)); n.R = n.c + (n.R - n.c) * D2lim / D2; n.L = n.c + (n.L - n.c) * D2lim / D2; } else { // Different signs n.R = n.L = n.c; } } } } /* ***USED*** * Div (n * b x Grad(f)/B) * * * poloidal - If true, includes X-Y flows * positive - If true, limit advected quantity (n_in) to be positive */ const Field3D Div_n_bxGrad_f_B_XPPM(const Field3D &n, const Field3D &f, bool bndry_flux, bool poloidal, bool positive) { Field3D result{0.0}; Coordinates *coord = mesh->getCoordinates(); ////////////////////////////////////////// // X-Z advection. // // Z // | // // fmp --- vU --- fpp // | nU | // | | // vL nL nR vR -> X // | | // | nD | // fmm --- vD --- fpm // int nz = mesh->LocalNz; for (int i = mesh->xstart; i <= mesh->xend; i++) for (int j = mesh->ystart; j <= mesh->yend; j++) for (int k = 0; k < nz; k++) { int kp = (k + 1) % nz; int kpp = (kp + 1) % nz; int km = (k - 1 + nz) % nz; int kmm = (km - 1 + nz) % nz; // 1) Interpolate stream function f onto corners fmp, fpp, fpm BoutReal fmm = 0.25 * (f(i, j, k) + f(i - 1, j, k) + f(i, j, km) + f(i - 1, j, km)); BoutReal fmp = 0.25 * (f(i, j, k) + f(i, j, kp) + f(i - 1, j, k) + f(i - 1, j, kp)); // 2nd order accurate BoutReal fpp = 0.25 * (f(i, j, k) + f(i, j, kp) + f(i + 1, j, k) + f(i + 1, j, kp)); BoutReal fpm = 0.25 * (f(i, j, k) + f(i + 1, j, k) + f(i, j, km) + f(i + 1, j, km)); // 2) Calculate velocities on cell faces BoutReal vU = coord->J(i, j) * (fmp - fpp) / coord->dx(i, j); // -J*df/dx BoutReal vD = coord->J(i, j) * (fmm - fpm) / coord->dx(i, j); // -J*df/dx BoutReal vR = 0.5 * (coord->J(i, j) + coord->J(i + 1, j)) * (fpp - fpm) / coord->dz(i, j); // J*df/dz BoutReal vL = 0.5 * (coord->J(i, j) + coord->J(i - 1, j)) * (fmp - fmm) / coord->dz(i, j); // J*df/dz // 3) Calculate n on the cell faces. The sign of the // velocity determines which side is used. // X direction Stencil1D s; s.c = n(i, j, k); s.m = n(i - 1, j, k); s.mm = n(i - 2, j, k); s.p = n(i + 1, j, k); s.pp = n(i + 2, j, k); // Upwind(s, mesh->dx(i,j)); // XPPM(s, mesh->dx(i,j)); // Fromm(s, coord->dx(i, j)); MC(s, coord->dx(i, j)); // Right side if ((i == mesh->xend) && (mesh->lastX())) { // At right boundary in X if (bndry_flux) { BoutReal flux; if (vR > 0.0) { // Flux to boundary flux = vR * s.R; } else { // Flux in from boundary flux = vR * 0.5 * (n(i + 1, j, k) + n(i, j, k)); } result(i, j, k) += flux / (coord->dx(i, j) * coord->J(i, j)); result(i + 1, j, k) -= flux / (coord->dx(i + 1, j) * coord->J(i + 1, j)); } } else { // Not at a boundary if (vR > 0.0) { // Flux out into next cell BoutReal flux = vR * s.R; result(i, j, k) += flux / (coord->dx(i, j) * coord->J(i, j)); result(i + 1, j, k) -= flux / (coord->dx(i + 1, j) * coord->J(i + 1, j)); // if(i==mesh->xend) // output.write("Setting flux (%d,%d) : %e\n", // j,k,result(i+1,j,k)); } } // Left side if ((i == mesh->xstart) && (mesh->firstX())) { // At left boundary in X if (bndry_flux) { BoutReal flux; if (vL < 0.0) { // Flux to boundary flux = vL * s.L; } else { // Flux in from boundary flux = vL * 0.5 * (n(i - 1, j, k) + n(i, j, k)); } result(i, j, k) -= flux / (coord->dx(i, j) * coord->J(i, j)); result(i - 1, j, k) += flux / (coord->dx(i - 1, j) * coord->J(i - 1, j)); } } else { // Not at a boundary if (vL < 0.0) { BoutReal flux = vL * s.L; result(i, j, k) -= flux / (coord->dx(i, j) * coord->J(i, j)); result(i - 1, j, k) += flux / (coord->dx(i - 1, j) * coord->J(i - 1, j)); } } /// NOTE: Need to communicate fluxes // Z direction s.m = n(i, j, km); s.mm = n(i, j, kmm); s.p = n(i, j, kp); s.pp = n(i, j, kpp); // Upwind(s, coord->dz(i, j)); // XPPM(s, coord->dz(i, j)); // Fromm(s, coord->dz(i, j)); MC(s, coord->dz(i, j)); if (vU > 0.0) { BoutReal flux = vU * s.R / (coord->J(i, j) * coord->dz(i, j)); result(i, j, k) += flux; result(i, j, kp) -= flux; } if (vD < 0.0) { BoutReal flux = vD * s.L / (coord->J(i, j) * coord->dz(i, j)); result(i, j, k) -= flux; result(i, j, km) += flux; } } FV::communicateFluxes(result); ////////////////////////////////////////// // X-Y advection. // // // This code does not deal with corners correctly. This may or may not be // important. // // 1/J d/dx ( J n (g^xx g^yz / B^2) df/dy) - 1/J d/dy( J n (g^xx g^yz / B^2) // df/dx ) // // Interpolating stream function f_in onto corners fmm, fmp, fpp, fpm // is complicated because the corner point in X-Y is not communicated // and at an X-point it is shared with 8 cells, rather than 4 // (being at the X-point itself) // Corners also need to be shifted to the correct toroidal angle if (poloidal) { // X flux Field3D dfdy = DDY(f); mesh->communicate(dfdy); dfdy.applyBoundary("neumann"); int xs = mesh->xstart - 1; int xe = mesh->xend; if (!bndry_flux) { // No boundary fluxes if (mesh->firstX()) { // At an inner boundary xs = mesh->xstart; } if (mesh->lastX()) { // At outer boundary xe = mesh->xend - 1; } } for (int i = xs; i <= xe; i++) for (int j = mesh->ystart - 1; j <= mesh->yend; j++) for (int k = 0; k < mesh->LocalNz; k++) { // Average dfdy to right X boundary BoutReal f_R = 0.5 * ((coord->g11(i + 1, j) * coord->g23(i + 1, j) / SQ(coord->Bxy(i + 1, j))) * dfdy(i + 1, j, k) + (coord->g11(i, j) * coord->g23(i, j) / SQ(coord->Bxy(i, j))) * dfdy(i, j, k)); // Advection velocity across cell face BoutReal Vx = 0.5 * (coord->J(i + 1, j) + coord->J(i, j)) * f_R; // Fromm method BoutReal flux = Vx; if (Vx > 0) { // Right boundary of cell (i,j,k) BoutReal nval = n(i, j, k) + 0.25 * (n(i + 1, j, k) - n(i - 1, j, k)); if (positive && (nval < 0.0)) { // Limit value to positive nval = 0.0; } flux *= nval; } else { // Left boundary of cell (i+1,j,k) BoutReal nval = n(i + 1, j, k) - 0.25 * (n(i + 2, j, k) - n(i, j, k)); if (positive && (nval < 0.0)) { nval = 0.0; } flux *= nval; } result(i, j, k) += flux / (coord->dx(i, j) * coord->J(i, j)); result(i + 1, j, k) -= flux / (coord->dx(i + 1, j) * coord->J(i + 1, j)); } } if (poloidal) { // Y flux Field3D dfdx = DDX(f); mesh->communicate(dfdx); dfdx.applyBoundary("neumann"); // This calculation is in field aligned coordinates dfdx = toFieldAligned(dfdx); Field3D n_fa = toFieldAligned(n); Field3D yresult{zeroFrom(n_fa)}; for (int i = mesh->xstart; i <= mesh->xend; i++) { int ys = mesh->ystart - 1; int ye = mesh->yend; if (!bndry_flux && !mesh->periodicY(i)) { // No boundary fluxes if (mesh->firstY(i)) { // At an inner boundary ys = mesh->ystart; } if (mesh->lastY(i)) { // At outer boundary ye = mesh->yend - 1; } } for (int j = ys; j <= ye; j++) { for (int k = 0; k < mesh->LocalNz; k++) { // Y flow // Average dfdx to upper Y boundary BoutReal f_U = 0.5 * ((coord->g11(i, j + 1) * coord->g23(i, j + 1) / SQ(coord->Bxy(i, j + 1))) * dfdx(i, j + 1, k) + (coord->g11(i, j) * coord->g23(i, j) / SQ(coord->Bxy(i, j))) * dfdx(i, j, k)); BoutReal Vy = -0.5 * (coord->J(i, j + 1) + coord->J(i, j)) * f_U; if (mesh->firstY(i) && !mesh->periodicY(i) && (j == mesh->ystart - 1)) { // Lower y boundary. Allow flows out of the domain only if (Vy > 0.0) Vy = 0.0; } if (mesh->lastY(i) && !mesh->periodicY(i) && (j == mesh->yend)) { // Upper y boundary if (Vy < 0.0) Vy = 0.0; } // Fromm method BoutReal flux = Vy; if (Vy > 0) { // Right boundary of cell (i,j,k) BoutReal nval = n_fa(i, j, k) + 0.25 * (n_fa(i, j + 1, k) - n_fa(i, j - 1, k)); if (positive && (nval < 0.0)) { nval = 0.0; } flux *= nval; } else { // Left boundary of cell (i,j+1,k) BoutReal nval = n_fa(i, j + 1, k) - 0.25 * (n_fa(i, j + 2, k) - n_fa(i, j, k)); if (positive && (nval < 0.0)) { nval = 0.0; } flux *= nval; } yresult(i, j, k) += flux / (coord->dy(i, j) * coord->J(i, j)); yresult(i, j + 1, k) -= flux / (coord->dy(i, j + 1) * coord->J(i, j + 1)); } } } result += fromFieldAligned(yresult); } return result; } /// *** USED *** const Field3D Div_Perp_Lap_FV_Index(const Field3D &as, const Field3D &fs, bool xflux) { Field3D result = 0.0; ////////////////////////////////////////// // X-Z diffusion in index space // // Z // | // // o --- gU --- o // | nU | // | | // gL nL nR gR -> X // | | // | nD | // o --- gD --- o // Coordinates *coord = mesh->getCoordinates(); for (int i = mesh->xstart; i <= mesh->xend; i++) for (int j = mesh->ystart; j <= mesh->yend; j++) for (int k = 0; k < mesh->LocalNz; k++) { int kp = (k + 1) % mesh->LocalNz; int km = (k - 1 + mesh->LocalNz) % mesh->LocalNz; // Calculate gradients on cell faces BoutReal gR = fs(i + 1, j, k) - fs(i, j, k); BoutReal gL = fs(i, j, k) - fs(i - 1, j, k); BoutReal gD = fs(i, j, k) - fs(i, j, km); BoutReal gU = fs(i, j, kp) - fs(i, j, k); // Flow right BoutReal flux = gR * 0.25 * (coord->J(i + 1, j) + coord->J(i, j)) * (coord->dx(i + 1, j) + coord->dx(i, j)) * (as(i + 1, j, k) + as(i, j, k)); result(i, j, k) += flux / (coord->dx(i, j) * coord->J(i, j)); // Flow left flux = gL * 0.25 * (coord->J(i - 1, j) + coord->J(i, j)) * (coord->dx(i - 1, j) + coord->dx(i, j)) * (as(i - 1, j, k) + as(i, j, k)); result(i, j, k) -= flux / (coord->dx(i, j) * coord->J(i, j)); // Flow up flux = gU * 0.5 * (as(i, j, k) + as(i, j, kp)); result(i, j, k) += flux; flux = gD * 0.5 * (as(i, j, k) + as(i, j, km)); result(i, j, k) -= flux; } return result; } /// Z diffusion in index space const Field3D Div_Z_FV_Index(const Field3D &as, const Field3D &fs) { Field3D result = 0.0; Coordinates *coord = mesh->getCoordinates(); for (int i = mesh->xstart; i <= mesh->xend; i++) for (int j = mesh->ystart; j <= mesh->yend; j++) for (int k = 0; k < mesh->LocalNz; k++) { int kp = (k + 1) % mesh->LocalNz; int km = (k - 1 + mesh->LocalNz) % mesh->LocalNz; // Calculate gradients on cell faces BoutReal gD = fs(i, j, k) - fs(i, j, km); BoutReal gU = fs(i, j, kp) - fs(i, j, k); result(i, j, k) += gU * 0.5 * (as(i, j, k) + as(i, j, kp)); result(i, j, k) -= gD * 0.5 * (as(i, j, k) + as(i, j, km)); } return result; } // *** USED *** const Field3D D4DX4_FV_Index(const Field3D &f, bool bndry_flux) { Field3D result = 0.0; Coordinates *coord = mesh->getCoordinates(); for (int i = mesh->xstart; i <= mesh->xend; i++) for (int j = mesh->ystart; j <= mesh->yend; j++) { for (int k = 0; k < mesh->LocalNz; k++) { // 3rd derivative at right boundary BoutReal d3fdx3 = (f(i + 2, j, k) - 3. * f(i + 1, j, k) + 3. * f(i, j, k) - f(i - 1, j, k)); BoutReal flux = 0.25 * (coord->dx(i, j) + coord->dx(i + 1, j)) * (coord->J(i, j) + coord->J(i + 1, j)) * d3fdx3; if (mesh->lastX() && (i == mesh->xend)) { // Boundary if (bndry_flux) { // Use a one-sided difference formula d3fdx3 = -((16. / 5) * 0.5 * (f(i + 1, j, k) + f(i, j, k)) // Boundary value f_b - 6. * f(i, j, k) // f_0 + 4. * f(i - 1, j, k) // f_1 - (6. / 5) * f(i - 2, j, k) // f_2 ); flux = 0.25 * (coord->dx(i, j) + coord->dx(i + 1, j)) * (coord->J(i, j) + coord->J(i + 1, j)) * d3fdx3; } else { // No fluxes through boundary flux = 0.0; } } result(i, j, k) += flux / (coord->J(i, j) * coord->dx(i, j)); result(i + 1, j, k) -= flux / (coord->J(i + 1, j) * coord->dx(i + 1, j)); if (j == mesh->xstart) { // Left cell boundary, no flux through boundaries if (mesh->firstX()) { // On an X boundary if (bndry_flux) { d3fdx3 = -(-(16. / 5) * 0.5 * (f(i - 1, j, k) + f(i, j, k)) // Boundary value f_b + 6. * f(i, j, k) // f_0 - 4. * f(i + 1, j, k) // f_1 + (6. / 5) * f(i + 2, j, k) // f_2 ); flux = 0.25 * (coord->dx(i, j) + coord->dx(i + 1, j)) * (coord->J(i, j) + coord->J(i + 1, j)) * d3fdx3; result(i, j, k) -= flux / (coord->J(i, j) * coord->dx(i, j)); result(i - 1, j, k) += flux / (coord->J(i - 1, j) * coord->dx(i - 1, j)); } } else { // Not on a boundary d3fdx3 = (f(i + 1, j, k) - 3. * f(i, j, k) + 3. * f(i - 1, j, k) - f(i - 2, j, k)); flux = 0.25 * (coord->dx(i, j) + coord->dx(i + 1, j)) * (coord->J(i, j) + coord->J(i + 1, j)) * d3fdx3; result(i, j, k) -= flux / (coord->J(i, j) * coord->dx(i, j)); result(i - 1, j, k) += flux / (coord->J(i - 1, j) * coord->dx(i - 1, j)); } } } } return result; } const Field3D D4DZ4_Index(const Field3D& f) { Field3D result; result.allocate(); BOUT_FOR(i, f.getRegion("RGN_NOBNDRY")) { result[i] = f[i.zp(2)] - 4.*f[i.zp()] + 6 * f[i] - 4 * f[i.zm()] + f[i.zm(2)]; } return result; } /*! *** USED *** * X-Y diffusion * * NOTE: Assumes g^12 = 0, so X and Y are orthogonal. Otherwise * we would need the corner cell values to take Y derivatives along X edges * */ const Field2D Laplace_FV(const Field2D &k, const Field2D &f) { Field2D result; result.allocate(); Coordinates *coord = mesh->getCoordinates(); for (int i = mesh->xstart; i <= mesh->xend; i++) for (int j = mesh->ystart; j <= mesh->yend; j++) { // Calculate gradients on cell faces BoutReal gR = (coord->g11(i, j) + coord->g11(i + 1, j)) * (f(i + 1, j) - f(i, j)) / (coord->dx(i + 1, j) + coord->dx(i, j)); BoutReal gL = (coord->g11(i - 1, j) + coord->g11(i, j)) * (f(i, j) - f(i - 1, j)) / (coord->dx(i - 1, j) + coord->dx(i, j)); BoutReal gU = (coord->g22(i, j) + coord->g22(i, j + 1)) * (f(i, j + 1) - f(i, j)) / (coord->dy(i, j + 1) + coord->dy(i, j)); BoutReal gD = (coord->g22(i, j - 1) + coord->g22(i, j)) * (f(i, j) - f(i, j - 1)) / (coord->dy(i, j) + coord->dy(i, j - 1)); // Flow right BoutReal flux = gR * 0.25 * (coord->J(i + 1, j) + coord->J(i, j)) * (k(i + 1, j) + k(i, j)); result(i, j) = flux / (coord->dx(i, j) * coord->J(i, j)); // Flow left flux = gL * 0.25 * (coord->J(i - 1, j) + coord->J(i, j)) * (k(i - 1, j) + k(i, j)); result(i, j) -= flux / (coord->dx(i, j) * coord->J(i, j)); // Flow up flux = gU * 0.25 * (coord->J(i, j + 1) + coord->J(i, j)) * (k(i, j + 1) + k(i, j)); result(i, j) += flux / (coord->dy(i, j) * coord->J(i, j)); // Flow down flux = gD * 0.25 * (coord->J(i, j - 1) + coord->J(i, j)) * (k(i, j - 1) + k(i, j)); result(i, j) -= flux / (coord->dy(i, j) * coord->J(i, j)); } return result; } // Div ( a Grad_perp(f) ) -- diffusion const Field3D Div_a_Grad_perp_upwind(const Field3D& a, const Field3D& f) { ASSERT2(a.getLocation() == f.getLocation()); Mesh* mesh = a.getMesh(); Field3D result{zeroFrom(f)}; Coordinates* coord = f.getCoordinates(); // Flux in x int xs = mesh->xstart - 1; int xe = mesh->xend; for (int i = xs; i <= xe; i++) for (int j = mesh->ystart; j <= mesh->yend; j++) { for (int k = 0; k < mesh->LocalNz; k++) { // Calculate flux from i to i+1 const BoutReal gradient = (coord->J(i, j) * coord->g11(i, j) + coord->J(i + 1, j) * coord->g11(i + 1, j)) * (f(i + 1, j, k) - f(i, j, k)) / (coord->dx(i, j) + coord->dx(i + 1, j)); // Use the upwind coefficient const BoutReal fout = gradient * ((gradient > 0) ? a(i + 1, j, k) : a(i, j, k)); result(i, j, k) += fout / (coord->dx(i, j) * coord->J(i, j)); result(i + 1, j, k) -= fout / (coord->dx(i + 1, j) * coord->J(i + 1, j)); } } // Y and Z fluxes require Y derivatives // Fields containing values along the magnetic field Field3D fup(mesh), fdown(mesh); Field3D aup(mesh), adown(mesh); // Values on this y slice (centre). // This is needed because toFieldAligned may modify the field Field3D fc = f; Field3D ac = a; // Result of the Y and Z fluxes Field3D yzresult(mesh); yzresult.allocate(); if (f.hasParallelSlices() && a.hasParallelSlices()) { // Both inputs have yup and ydown fup = f.yup(); fdown = f.ydown(); aup = a.yup(); adown = a.ydown(); } else { // At least one input doesn't have yup/ydown fields. // Need to shift to/from field aligned coordinates fup = fdown = fc = toFieldAligned(f); aup = adown = ac = toFieldAligned(a); yzresult.setDirectionY(YDirectionType::Aligned); } // Y flux for (int i = mesh->xstart; i <= mesh->xend; i++) { for (int j = mesh->ystart; j <= mesh->yend; j++) { BoutReal coef_u = 0.5 * (coord->g_23(i, j) / SQ(coord->J(i, j) * coord->Bxy(i, j)) + coord->g_23(i, j + 1) / SQ(coord->J(i, j + 1) * coord->Bxy(i, j + 1))); BoutReal coef_d = 0.5 * (coord->g_23(i, j) / SQ(coord->J(i, j) * coord->Bxy(i, j)) + coord->g_23(i, j - 1) / SQ(coord->J(i, j - 1) * coord->Bxy(i, j - 1))); for (int k = 0; k < mesh->LocalNz; k++) { // Calculate flux between j and j+1 int kp = (k + 1) % mesh->LocalNz; int km = (k - 1 + mesh->LocalNz) % mesh->LocalNz; // Calculate Z derivative at y boundary BoutReal dfdz = 0.25 * (fc(i, j, kp) - fc(i, j, km) + fup(i, j + 1, kp) - fup(i, j + 1, km)) / coord->dz(i, j); // Y derivative BoutReal dfdy = 2. * (fup(i, j + 1, k) - fc(i, j, k)) / (coord->dy(i, j + 1) + coord->dy(i, j)); BoutReal fout = 0.25 * (ac(i, j, k) + aup(i, j + 1, k)) * (coord->J(i, j) * coord->g23(i, j) + coord->J(i, j + 1) * coord->g23(i, j + 1)) * (dfdz - coef_u * dfdy); yzresult(i, j, k) = fout / (coord->dy(i, j) * coord->J(i, j)); // Calculate flux between j and j-1 dfdz = 0.25 * (fc(i, j, kp) - fc(i, j, km) + fdown(i, j - 1, kp) - fdown(i, j - 1, km)) / coord->dz(i, j); dfdy = 2. * (fc(i, j, k) - fdown(i, j - 1, k)) / (coord->dy(i, j) + coord->dy(i, j - 1)); fout = 0.25 * (ac(i, j, k) + adown(i, j - 1, k)) * (coord->J(i, j) * coord->g23(i, j) + coord->J(i, j - 1) * coord->g23(i, j - 1)) * (dfdz - coef_d * dfdy); yzresult(i, j, k) -= fout / (coord->dy(i, j) * coord->J(i, j)); } } } // Z flux // Easier since all metrics constant in Z for (int i = mesh->xstart; i <= mesh->xend; i++) { for (int j = mesh->ystart; j <= mesh->yend; j++) { // Coefficient in front of df/dy term BoutReal coef = coord->g_23(i, j) / (coord->dy(i, j + 1) + 2. * coord->dy(i, j) + coord->dy(i, j - 1)) / SQ(coord->J(i, j) * coord->Bxy(i, j)); for (int k = 0; k < mesh->LocalNz; k++) { // Calculate flux between k and k+1 int kp = (k + 1) % mesh->LocalNz; BoutReal gradient = // df/dz (fc(i, j, kp) - fc(i, j, k)) / coord->dz(i, j) // - g_yz * df/dy / SQ(J*B) - coef * (fup(i, j + 1, k) + fup(i, j + 1, kp) - fdown(i, j - 1, k) - fdown(i, j - 1, kp)); BoutReal fout = gradient * ((gradient > 0) ? ac(i, j, kp) : ac(i, j, k)); yzresult(i, j, k) += fout / coord->dz(i, j); yzresult(i, j, kp) -= fout / coord->dz(i, j); } } } // Check if we need to transform back if (f.hasParallelSlices() && a.hasParallelSlices()) { result += yzresult; } else { result += fromFieldAligned(yzresult); } return result; } /// Div ( a Grad_perp(f) ) -- diffusion /// /// Returns the flows in the final arguments /// /// Flows are always in the positive {x,y} direction /// i.e xlow(i,j) is the flow into cell (i,j) from the left, /// and the flow out of cell (i-1,j) to the right /// /// ylow(i,j+1) /// ^ /// +---|---+ /// | | /// xlow(i,j) -> (i,j) -> xlow(i+1,j) /// | ^ | /// +---|---+ /// ylow(i,j) /// /// const Field3D Div_a_Grad_perp_upwind_flows(const Field3D& a, const Field3D& f, Field3D &flow_xlow, Field3D &flow_ylow) { ASSERT2(a.getLocation() == f.getLocation()); Mesh* mesh = a.getMesh(); Field3D result{zeroFrom(f)}; Coordinates* coord = f.getCoordinates(); // Zero all flows flow_xlow = 0.0; flow_ylow = 0.0; // Flux in x int xs = mesh->xstart - 1; int xe = mesh->xend; for (int i = xs; i <= xe; i++) for (int j = mesh->ystart; j <= mesh->yend; j++) { for (int k = 0; k < mesh->LocalNz; k++) { // Calculate flux from i to i+1 const BoutReal gradient = (coord->J(i, j) * coord->g11(i, j) + coord->J(i + 1, j) * coord->g11(i + 1, j)) * (f(i + 1, j, k) - f(i, j, k)) / (coord->dx(i, j) + coord->dx(i + 1, j)); // Use the upwind coefficient const BoutReal fout = gradient * ((gradient > 0) ? a(i + 1, j, k) : a(i, j, k)); result(i, j, k) += fout / (coord->dx(i, j) * coord->J(i, j)); result(i + 1, j, k) -= fout / (coord->dx(i + 1, j) * coord->J(i + 1, j)); // Flow will be positive in the positive coordinate direction flow_xlow(i + 1, j, k) = -1.0 * fout * coord->dy(i, j) * coord->dz(i, j); } } // Y and Z fluxes require Y derivatives // Fields containing values along the magnetic field Field3D fup(mesh), fdown(mesh); Field3D aup(mesh), adown(mesh); // Values on this y slice (centre). // This is needed because toFieldAligned may modify the field Field3D fc = f; Field3D ac = a; // Result of the Y and Z fluxes Field3D yzresult(mesh); yzresult.allocate(); if (f.hasParallelSlices() && a.hasParallelSlices()) { // Both inputs have yup and ydown fup = f.yup(); fdown = f.ydown(); aup = a.yup(); adown = a.ydown(); } else { // At least one input doesn't have yup/ydown fields. // Need to shift to/from field aligned coordinates fup = fdown = fc = toFieldAligned(f); aup = adown = ac = toFieldAligned(a); yzresult.setDirectionY(YDirectionType::Aligned); flow_ylow.setDirectionY(YDirectionType::Aligned); } // Y flux for (int i = mesh->xstart; i <= mesh->xend; i++) { for (int j = mesh->ystart; j <= mesh->yend; j++) { BoutReal coef_u = 0.5 * (coord->g_23(i, j) / SQ(coord->J(i, j) * coord->Bxy(i, j)) + coord->g_23(i, j + 1) / SQ(coord->J(i, j + 1) * coord->Bxy(i, j + 1))); BoutReal coef_d = 0.5 * (coord->g_23(i, j) / SQ(coord->J(i, j) * coord->Bxy(i, j)) + coord->g_23(i, j - 1) / SQ(coord->J(i, j - 1) * coord->Bxy(i, j - 1))); for (int k = 0; k < mesh->LocalNz; k++) { // Calculate flux between j and j+1 int kp = (k + 1) % mesh->LocalNz; int km = (k - 1 + mesh->LocalNz) % mesh->LocalNz; // Calculate Z derivative at y boundary BoutReal dfdz = 0.25 * (fc(i, j, kp) - fc(i, j, km) + fup(i, j + 1, kp) - fup(i, j + 1, km)) / coord->dz(i, j); // Y derivative BoutReal dfdy = 2. * (fup(i, j + 1, k) - fc(i, j, k)) / (coord->dy(i, j + 1) + coord->dy(i, j)); BoutReal fout = 0.25 * (ac(i, j, k) + aup(i, j + 1, k)) * (coord->J(i, j) * coord->g23(i, j) + coord->J(i, j + 1) * coord->g23(i, j + 1)) * (dfdz - coef_u * dfdy); yzresult(i, j, k) = fout / (coord->dy(i, j) * coord->J(i, j)); // Calculate flux between j and j-1 dfdz = 0.25 * (fc(i, j, kp) - fc(i, j, km) + fdown(i, j - 1, kp) - fdown(i, j - 1, km)) / coord->dz(i, j); dfdy = 2. * (fc(i, j, k) - fdown(i, j - 1, k)) / (coord->dy(i, j) + coord->dy(i, j - 1)); fout = 0.25 * (ac(i, j, k) + adown(i, j - 1, k)) * (coord->J(i, j) * coord->g23(i, j) + coord->J(i, j - 1) * coord->g23(i, j - 1)) * (dfdz - coef_d * dfdy); yzresult(i, j, k) -= fout / (coord->dy(i, j) * coord->J(i, j)); // Flow will be positive in the positive coordinate direction flow_ylow(i, j, k) = -1.0 * fout * coord->dx(i, j) * coord->dz(i, j); } } } // Z flux // Easier since all metrics constant in Z for (int i = mesh->xstart; i <= mesh->xend; i++) { for (int j = mesh->ystart; j <= mesh->yend; j++) { // Coefficient in front of df/dy term BoutReal coef = coord->g_23(i, j) / (coord->dy(i, j + 1) + 2. * coord->dy(i, j) + coord->dy(i, j - 1)) / SQ(coord->J(i, j) * coord->Bxy(i, j)); for (int k = 0; k < mesh->LocalNz; k++) { // Calculate flux between k and k+1 int kp = (k + 1) % mesh->LocalNz; BoutReal gradient = // df/dz (fc(i, j, kp) - fc(i, j, k)) / coord->dz(i, j) // - g_yz * df/dy / SQ(J*B) - coef * (fup(i, j + 1, k) + fup(i, j + 1, kp) - fdown(i, j - 1, k) - fdown(i, j - 1, kp)); BoutReal fout = gradient * ((gradient > 0) ? ac(i, j, kp) : ac(i, j, k)); yzresult(i, j, k) += fout / coord->dz(i, j); yzresult(i, j, kp) -= fout / coord->dz(i, j); } } } // Check if we need to transform back if (f.hasParallelSlices() && a.hasParallelSlices()) { result += yzresult; } else { result += fromFieldAligned(yzresult); flow_ylow = fromFieldAligned(flow_ylow); } return result; } const Field3D Div_n_g_bxGrad_f_B_XZ(const Field3D &n, const Field3D &g, const Field3D &f, bool bndry_flux, bool positive) { Field3D result{0.0}; Coordinates *coord = mesh->getCoordinates(); ////////////////////////////////////////// // X-Z advection. // // Z // | // // fmp --- vU --- fpp // | nU | // | | // vL nL nR vR -> X // | | // | nD | // fmm --- vD --- fpm // int nz = mesh->LocalNz; for (int i = mesh->xstart; i <= mesh->xend; i++) { for (int j = mesh->ystart; j <= mesh->yend; j++) { for (int k = 0; k < nz; k++) { int kp = (k + 1) % nz; int kpp = (kp + 1) % nz; int km = (k - 1 + nz) % nz; int kmm = (km - 1 + nz) % nz; // 1) Interpolate stream function f onto corners fmp, fpp, fpm BoutReal fmm = 0.25 * (f(i, j, k) + f(i - 1, j, k) + f(i, j, km) + f(i - 1, j, km)); BoutReal fmp = 0.25 * (f(i, j, k) + f(i, j, kp) + f(i - 1, j, k) + f(i - 1, j, kp)); // 2nd order accurate BoutReal fpp = 0.25 * (f(i, j, k) + f(i, j, kp) + f(i + 1, j, k) + f(i + 1, j, kp)); BoutReal fpm = 0.25 * (f(i, j, k) + f(i + 1, j, k) + f(i, j, km) + f(i + 1, j, km)); // 2) Calculate velocities on cell faces BoutReal vU = coord->J(i, j) * (fmp - fpp) / coord->dx(i, j); // -J*df/dx BoutReal vD = coord->J(i, j) * (fmm - fpm) / coord->dx(i, j); // -J*df/dx BoutReal vR = 0.5 * (coord->J(i, j) + coord->J(i + 1, j)) * (fpp - fpm) / coord->dz(i, j); // J*df/dz BoutReal vL = 0.5 * (coord->J(i, j) + coord->J(i - 1, j)) * (fmp - fmm) / coord->dz(i, j); // J*df/dz // 3) Calculate g on cell faces BoutReal gU = 0.5 * (g(i, j, kp) + g(i, j, k)); BoutReal gD = 0.5 * (g(i, j, km) + g(i, j, k)); BoutReal gR = 0.5 * (g(i + 1, j, k) + g(i, j, k)); BoutReal gL = 0.5 * (g(i - 1, j, k) + g(i, j, k)); // 4) Calculate n on the cell faces. The sign of the // velocity determines which side is used. // X direction Stencil1D s; s.c = n(i, j, k); s.m = n(i - 1, j, k); s.mm = n(i - 2, j, k); s.p = n(i + 1, j, k); s.pp = n(i + 2, j, k); MC(s, coord->dx(i, j)); // Right side if ((i == mesh->xend) && (mesh->lastX())) { // At right boundary in X if (bndry_flux) { BoutReal flux; if (vR > 0.0) { // Flux to boundary flux = vR * s.R * gR; } else { // Flux in from boundary flux = vR * 0.5 * (n(i + 1, j, k) + n(i, j, k)) * gR; } result(i, j, k) += flux / (coord->dx(i, j) * coord->J(i, j)); result(i + 1, j, k) -= flux / (coord->dx(i + 1, j) * coord->J(i + 1, j)); } } else { // Not at a boundary if (vR > 0.0) { // Flux out into next cell BoutReal flux = vR * s.R * gR; result(i, j, k) += flux / (coord->dx(i, j) * coord->J(i, j)); result(i + 1, j, k) -= flux / (coord->dx(i + 1, j) * coord->J(i + 1, j)); } } // Left side if ((i == mesh->xstart) && (mesh->firstX())) { // At left boundary in X if (bndry_flux) { BoutReal flux; if (vL < 0.0) { // Flux to boundary flux = vL * s.L * gL; } else { // Flux in from boundary flux = vL * 0.5 * (n(i - 1, j, k) + n(i, j, k)) * gL; } result(i, j, k) -= flux / (coord->dx(i, j) * coord->J(i, j)); result(i - 1, j, k) += flux / (coord->dx(i - 1, j) * coord->J(i - 1, j)); } } else { // Not at a boundary if (vL < 0.0) { BoutReal flux = vL * s.L * gL; result(i, j, k) -= flux / (coord->dx(i, j) * coord->J(i, j)); result(i - 1, j, k) += flux / (coord->dx(i - 1, j) * coord->J(i - 1, j)); } } /// NOTE: Need to communicate fluxes // Z direction s.m = n(i, j, km); s.mm = n(i, j, kmm); s.p = n(i, j, kp); s.pp = n(i, j, kpp); MC(s, coord->dz(i, j)); if (vU > 0.0) { BoutReal flux = vU * s.R * gU/ (coord->J(i, j) * coord->dz(i, j)); result(i, j, k) += flux; result(i, j, kp) -= flux; } if (vD < 0.0) { BoutReal flux = vD * s.L * gD / (coord->J(i, j) * coord->dz(i, j)); result(i, j, k) -= flux; result(i, j, km) += flux; } } } } FV::communicateFluxes(result); return result; } const Field3D Div_par_K_Grad_par_mod(const Field3D& Kin, const Field3D& fin, Field3D& flow_ylow, bool bndry_flux) { TRACE("FV::Div_par_K_Grad_par_mod"); ASSERT2(Kin.getLocation() == fin.getLocation()); Mesh* mesh = Kin.getMesh(); bool use_parallel_slices = (Kin.hasParallelSlices() && fin.hasParallelSlices()); const auto& K = use_parallel_slices ? Kin : toFieldAligned(Kin, "RGN_NOX"); const auto& f = use_parallel_slices ? fin : toFieldAligned(fin, "RGN_NOX"); Field3D result{zeroFrom(f)}; flow_ylow = zeroFrom(f); // K and f fields in yup and ydown directions const auto& Kup = use_parallel_slices ? Kin.yup() : K; const auto& Kdown = use_parallel_slices ? Kin.ydown() : K; const auto& fup = use_parallel_slices ? fin.yup() : f; const auto& fdown = use_parallel_slices ? fin.ydown() : f; Coordinates* coord = fin.getCoordinates(); BOUT_FOR(i, result.getRegion("RGN_NOBNDRY")) { // Calculate flux at upper surface const auto iyp = i.yp(); const auto iym = i.ym(); if (bndry_flux || mesh->periodicY(i.x()) || !mesh->lastY(i.x()) || (i.y() != mesh->yend)) { BoutReal c = 0.5 * (K[i] + Kup[iyp]); // K at the upper boundary BoutReal J = 0.5 * (coord->J[i] + coord->J[iyp]); // Jacobian at boundary BoutReal g_22 = 0.5 * (coord->g_22[i] + coord->g_22[iyp]); BoutReal gradient = 2. * (fup[iyp] - f[i]) / (coord->dy[i] + coord->dy[iyp]); BoutReal flux = c * J * gradient / g_22; result[i] += flux / (coord->dy[i] * coord->J[i]); } // Calculate flux at lower surface if (bndry_flux || mesh->periodicY(i.x()) || !mesh->firstY(i.x()) || (i.y() != mesh->ystart)) { BoutReal c = 0.5 * (K[i] + Kdown[iym]); // K at the lower boundary BoutReal J = 0.5 * (coord->J[i] + coord->J[iym]); // Jacobian at boundary BoutReal g_22 = 0.5 * (coord->g_22[i] + coord->g_22[iym]); BoutReal gradient = 2. * (f[i] - fdown[iym]) / (coord->dy[i] + coord->dy[iym]); BoutReal flux = c * J * gradient / g_22; result[i] -= flux / (coord->dy[i] * coord->J[i]); flow_ylow[i] = - flux * coord->dx[i] * coord->dz[i]; } } if (!use_parallel_slices) { // Shifted to field aligned coordinates, so need to shift back result = fromFieldAligned(result, "RGN_NOBNDRY"); flow_ylow = fromFieldAligned(flow_ylow); } return result; }
43,065
C++
.cxx
1,075
31.082791
96
0.451097
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,214
loadmetric.cxx
bendudson_hermes-3/src/loadmetric.cxx
#include <bout/globals.hxx> #include <bout/output.hxx> #include <bout/utils.hxx> #include <bout/field2d.hxx> #include <bout/mesh.hxx> #include "../include/loadmetric.hxx" using bout::globals::mesh; void LoadMetric(BoutReal Lnorm, BoutReal Bnorm) { // Load metric coefficients from the mesh Field2D Rxy, Bpxy, Btxy, hthe, sinty; GRID_LOAD5(Rxy, Bpxy, Btxy, hthe, sinty); // Load metrics Coordinates *coord = mesh->getCoordinates(); // Checking for dpsi and qinty used in BOUT grids Field2D dx; if (!mesh->get(dx, "dpsi")) { output << "\tUsing dpsi as the x grid spacing\n"; coord->dx = dx; // Only use dpsi if found } else { // dx will have been read already from the grid output << "\tUsing dx as the x grid spacing\n"; } Rxy /= Lnorm; hthe /= Lnorm; sinty *= SQ(Lnorm) * Bnorm; coord->dx /= SQ(Lnorm) * Bnorm; Bpxy /= Bnorm; Btxy /= Bnorm; coord->Bxy /= Bnorm; // Calculate metric components if (Options::root()["mesh"]["paralleltransform"]["type"].as<std::string>() == "shifted") { sinty = 0.0; // I disappears from metric } BoutReal sbp = 1.0; // Sign of Bp if (min(Bpxy, true) < 0.0) { sbp = -1.0; } coord->g11 = SQ(Rxy * Bpxy); coord->g22 = 1.0 / SQ(hthe); coord->g33 = SQ(sinty) * coord->g11 + SQ(coord->Bxy) / coord->g11; coord->g12 = 0.0; coord->g13 = -sinty * coord->g11; coord->g23 = -sbp * Btxy / (hthe * Bpxy * Rxy); coord->J = hthe / Bpxy; coord->g_11 = 1.0 / coord->g11 + SQ(sinty * Rxy); coord->g_22 = SQ(coord->Bxy * hthe / Bpxy); coord->g_33 = Rxy * Rxy; coord->g_12 = sbp * Btxy * hthe * sinty * Rxy / Bpxy; coord->g_13 = sinty * Rxy * Rxy; coord->g_23 = sbp * Btxy * hthe * Rxy / Bpxy; coord->geometry(); }
1,737
C++
.cxx
51
30.882353
92
0.628965
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,215
neutral_mixed.cxx
bendudson_hermes-3/src/neutral_mixed.cxx
#include <bout/constants.hxx> #include <bout/fv_ops.hxx> #include <bout/derivs.hxx> #include <bout/difops.hxx> #include <bout/output_bout_types.hxx> #include "../include/div_ops.hxx" #include "../include/neutral_mixed.hxx" #include "../include/hermes_build_config.hxx" using bout::globals::mesh; NeutralMixed::NeutralMixed(const std::string& name, Options& alloptions, Solver* solver) : name(name) { AUTO_TRACE(); // Normalisations const Options& units = alloptions["units"]; const BoutReal meters = units["meters"]; const BoutReal seconds = units["seconds"]; const BoutReal Nnorm = units["inv_meters_cubed"]; const BoutReal Tnorm = units["eV"]; const BoutReal Omega_ci = 1. / units["seconds"].as<BoutReal>(); // Need to take derivatives in X for cross-field diffusion terms ASSERT0(mesh->xstart > 0); auto& options = alloptions[name]; // Evolving variables e.g name is "h" or "h+" solver->add(Nn, std::string("N") + name); solver->add(Pn, std::string("P") + name); evolve_momentum = options["evolve_momentum"] .doc("Evolve parallel neutral momentum?") .withDefault<bool>(true); if (evolve_momentum) { solver->add(NVn, std::string("NV") + name); } else { output_warn.write("WARNING: Not evolving neutral parallel momentum. NVn and Vn set to zero\n"); NVn = 0.0; Vn = 0.0; } sheath_ydown = options["sheath_ydown"] .doc("Enable wall boundary conditions at ydown") .withDefault<bool>(true); sheath_yup = options["sheath_yup"] .doc("Enable wall boundary conditions at yup") .withDefault<bool>(true); nn_floor = options["nn_floor"] .doc("A minimum density used when dividing NVn by Nn. " "Normalised units.") .withDefault(1e-5); precondition = options["precondition"] .doc("Enable preconditioning in neutral model?") .withDefault<bool>(true); flux_limit = options["flux_limit"] .doc("Limit diffusive fluxes to fraction of thermal speed. <0 means off.") .withDefault(0.2); diffusion_limit = options["diffusion_limit"] .doc("Upper limit on diffusion coefficient [m^2/s]. <0 means off") .withDefault(-1.0) / (meters * meters / seconds); // Normalise neutral_viscosity = options["neutral_viscosity"] .doc("Include neutral gas viscosity?") .withDefault<bool>(true); if (precondition) { inv = std::unique_ptr<Laplacian>(Laplacian::create(&options["precon_laplace"])); inv->setInnerBoundaryFlags(INVERT_DC_GRAD | INVERT_AC_GRAD); inv->setOuterBoundaryFlags(INVERT_DC_GRAD | INVERT_AC_GRAD); inv->setCoefA(1.0); } // Optionally output time derivatives output_ddt = options["output_ddt"].doc("Save derivatives to output?").withDefault<bool>(false); diagnose = options["diagnose"].doc("Save additional diagnostics?").withDefault<bool>(false); AA = options["AA"].doc("Particle atomic mass. Proton = 1").withDefault(1.0); // Try to read the density source from the mesh // Units of particles per cubic meter per second density_source = 0.0; mesh->get(density_source, std::string("N") + name + "_src"); // Allow the user to override the source density_source = alloptions[std::string("N") + name]["source"] .doc("Source term in ddt(N" + name + std::string("). Units [m^-3/s]")) .withDefault(density_source) / (Nnorm * Omega_ci); // Try to read the pressure source from the mesh // Units of Pascals per second pressure_source = 0.0; mesh->get(pressure_source, std::string("P") + name + "_src"); // Allow the user to override the source pressure_source = alloptions[std::string("P") + name]["source"] .doc(std::string("Source term in ddt(P") + name + std::string("). Units [N/m^2/s]")) .withDefault(pressure_source) / (SI::qe * Nnorm * Tnorm * Omega_ci); // Set boundary condition defaults: Neumann for all but the diffusivity. // The dirichlet on diffusivity ensures no radial flux. // NV and V are ignored as they are hardcoded in the parallel BC code. alloptions[std::string("Dnn") + name]["bndry_all"] = alloptions[std::string("Dnn") + name]["bndry_all"].withDefault("dirichlet"); alloptions[std::string("T") + name]["bndry_all"] = alloptions[std::string("T") + name]["bndry_all"].withDefault("neumann"); alloptions[std::string("P") + name]["bndry_all"] = alloptions[std::string("P") + name]["bndry_all"].withDefault("neumann"); alloptions[std::string("N") + name]["bndry_all"] = alloptions[std::string("N") + name]["bndry_all"].withDefault("neumann"); // Pick up BCs from input file Dnn.setBoundary(std::string("Dnn") + name); Tn.setBoundary(std::string("T") + name); Pn.setBoundary(std::string("P") + name); Nn.setBoundary(std::string("N") + name); // All floored versions of variables get the same boundary as the original Tnlim.setBoundary(std::string("T") + name); Pnlim.setBoundary(std::string("P") + name); logPnlim.setBoundary(std::string("P") + name); Nnlim.setBoundary(std::string("N") + name); // Product of Dnn and another parameter has same BC as Dnn - see eqns to see why this is necessary DnnNn.setBoundary(std::string("Dnn") + name); DnnPn.setBoundary(std::string("Dnn") + name); DnnTn.setBoundary(std::string("Dnn") + name); DnnNVn.setBoundary(std::string("Dnn") + name); } void NeutralMixed::transform(Options& state) { AUTO_TRACE(); mesh->communicate(Nn, Pn, NVn); Nn.clearParallelSlices(); Pn.clearParallelSlices(); NVn.clearParallelSlices(); Nn = floor(Nn, 0.0); Pn = floor(Pn, 0.0); // Nnlim Used where division by neutral density is needed Nnlim = floor(Nn, nn_floor); Tn = Pn / Nnlim; Tn.applyBoundary(); Vn = NVn / (AA * Nnlim); Vnlim = Vn; Vn.applyBoundary("neumann"); Vnlim.applyBoundary("neumann"); Pnlim = floor(Nnlim * Tn, 1e-8); Pnlim.applyBoundary(); ///////////////////////////////////////////////////// // Parallel boundary conditions TRACE("Neutral boundary conditions"); if (sheath_ydown) { for (RangeIterator r = mesh->iterateBndryLowerY(); !r.isDone(); r++) { for (int jz = 0; jz < mesh->LocalNz; jz++) { // Free boundary (constant gradient) density BoutReal nnwall = 0.5 * (3. * Nn(r.ind, mesh->ystart, jz) - Nn(r.ind, mesh->ystart + 1, jz)); if (nnwall < 0.0) nnwall = 0.0; BoutReal tnwall = Tn(r.ind, mesh->ystart, jz); Nn(r.ind, mesh->ystart - 1, jz) = 2 * nnwall - Nn(r.ind, mesh->ystart, jz); // Zero gradient temperature, heat flux added later Tn(r.ind, mesh->ystart - 1, jz) = tnwall; // Set pressure consistent at the boundary // Pn(r.ind, mesh->ystart - 1, jz) = // 2. * nnwall * tnwall - Pn(r.ind, mesh->ystart, jz); // Zero-gradient pressure Pn(r.ind, mesh->ystart - 1, jz) = Pn(r.ind, mesh->ystart, jz); Pnlim(r.ind, mesh->ystart - 1, jz) = Pnlim(r.ind, mesh->ystart, jz); // No flow into wall Vn(r.ind, mesh->ystart - 1, jz) = -Vn(r.ind, mesh->ystart, jz); Vnlim(r.ind, mesh->ystart - 1, jz) = -Vnlim(r.ind, mesh->ystart, jz); NVn(r.ind, mesh->ystart - 1, jz) = -NVn(r.ind, mesh->ystart, jz); } } } if (sheath_yup) { for (RangeIterator r = mesh->iterateBndryUpperY(); !r.isDone(); r++) { for (int jz = 0; jz < mesh->LocalNz; jz++) { // Free boundary (constant gradient) density BoutReal nnwall = 0.5 * (3. * Nn(r.ind, mesh->yend, jz) - Nn(r.ind, mesh->yend - 1, jz)); if (nnwall < 0.0) nnwall = 0.0; BoutReal tnwall = Tn(r.ind, mesh->yend, jz); Nn(r.ind, mesh->yend + 1, jz) = 2 * nnwall - Nn(r.ind, mesh->yend, jz); // Zero gradient temperature, heat flux added later Tn(r.ind, mesh->yend + 1, jz) = tnwall; // Zero-gradient pressure Pn(r.ind, mesh->yend + 1, jz) = Pn(r.ind, mesh->yend, jz); Pnlim(r.ind, mesh->yend + 1, jz) = Pnlim(r.ind, mesh->yend, jz); // No flow into wall Vn(r.ind, mesh->yend + 1, jz) = -Vn(r.ind, mesh->yend, jz); Vnlim(r.ind, mesh->yend + 1, jz) = -Vnlim(r.ind, mesh->yend, jz); NVn(r.ind, mesh->yend + 1, jz) = -NVn(r.ind, mesh->yend, jz); } } } // Set values in the state auto& localstate = state["species"][name]; set(localstate["density"], Nn); set(localstate["AA"], AA); // Atomic mass set(localstate["pressure"], Pn); set(localstate["momentum"], NVn); set(localstate["velocity"], Vn); set(localstate["temperature"], Tn); } void NeutralMixed::finally(const Options& state) { AUTO_TRACE(); auto& localstate = state["species"][name]; // Logarithms used to calculate perpendicular velocity // V_perp = -Dnn * ( Grad_perp(Nn)/Nn + Grad_perp(Tn)/Tn ) // // Grad(Pn) / Pn = Grad(Tn)/Tn + Grad(Nn)/Nn // = Grad(logTn + logNn) // Field3D logNn = log(Nn); // Field3D logTn = log(Tn); logPnlim = log(Pnlim); logPnlim.applyBoundary(); /////////////////////////////////////////////////////// // Calculate cross-field diffusion from collision frequency // // BoutReal neutral_lmax = 0.1 / get<BoutReal>(state["units"]["meters"]); // Normalised length Field3D Rnn = sqrt(Tn / AA) / neutral_lmax; // Neutral-neutral collisions [normalised frequency] if (localstate.isSet("collision_frequency")) { // Dnn = Vth^2 / sigma Dnn = (Tn / AA) / (get<Field3D>(localstate["collision_frequency"]) + Rnn); } else { Dnn = (Tn / AA) / Rnn; } if (flux_limit > 0.0) { // Apply flux limit to diffusion, // using the local thermal speed and pressure gradient magnitude Field3D Dmax = flux_limit * sqrt(Tn / AA) / (abs(Grad(logPnlim)) + 1. / neutral_lmax); BOUT_FOR(i, Dmax.getRegion("RGN_NOBNDRY")) { Dnn[i] = BOUTMIN(Dnn[i], Dmax[i]); } } if (diffusion_limit > 0.0) { // Impose an upper limit on the diffusion coefficient BOUT_FOR(i, Dnn.getRegion("RGN_NOBNDRY")) { Dnn[i] = BOUTMIN(Dnn[i], diffusion_limit); } } mesh->communicate(Dnn); Dnn.clearParallelSlices(); Dnn.applyBoundary(); // Neutral diffusion parameters have the same boundary condition as Dnn DnnPn = Dnn * Pn; DnnPn.applyBoundary(); DnnNn = Dnn * Nn; DnnNn.applyBoundary(); Field3D DnnNVn = Dnn * NVn; DnnNVn.applyBoundary(); if (sheath_ydown) { for (RangeIterator r = mesh->iterateBndryLowerY(); !r.isDone(); r++) { for (int jz = 0; jz < mesh->LocalNz; jz++) { Dnn(r.ind, mesh->ystart - 1, jz) = -Dnn(r.ind, mesh->ystart, jz); DnnPn(r.ind, mesh->ystart - 1, jz) = -DnnPn(r.ind, mesh->ystart, jz); DnnNn(r.ind, mesh->ystart - 1, jz) = -DnnNn(r.ind, mesh->ystart, jz); DnnNVn(r.ind, mesh->ystart - 1, jz) = -DnnNVn(r.ind, mesh->ystart, jz); } } } if (sheath_yup) { for (RangeIterator r = mesh->iterateBndryUpperY(); !r.isDone(); r++) { for (int jz = 0; jz < mesh->LocalNz; jz++) { Dnn(r.ind, mesh->yend + 1, jz) = -Dnn(r.ind, mesh->yend, jz); DnnPn(r.ind, mesh->yend + 1, jz) = -DnnPn(r.ind, mesh->yend, jz); DnnNn(r.ind, mesh->yend + 1, jz) = -DnnNn(r.ind, mesh->yend, jz); DnnNVn(r.ind, mesh->yend + 1, jz) = -DnnNVn(r.ind, mesh->yend, jz); } } } // Sound speed appearing in Lax flux for advection terms Field3D sound_speed = sqrt(Tn * (5. / 3) / AA); ///////////////////////////////////////////////////// // Neutral density TRACE("Neutral density"); ddt(Nn) = -FV::Div_par_mod<hermes::Limiter>(Nn, Vn, sound_speed, particle_flow_ylow) // Advection + FV::Div_a_Grad_perp(DnnNn, logPnlim) // Perpendicular diffusion ; Sn = density_source; // Save for possible output if (localstate.isSet("density_source")) { Sn += get<Field3D>(localstate["density_source"]); } ddt(Nn) += Sn; // Always add density_source if (evolve_momentum) { ///////////////////////////////////////////////////// // Neutral momentum TRACE("Neutral momentum"); ddt(NVn) = -AA * FV::Div_par_fvv<hermes::Limiter>(Nnlim, Vn, sound_speed) // Momentum flow - Grad_par(Pn) // Pressure gradient + FV::Div_a_Grad_perp(DnnNVn, logPnlim) // Perpendicular diffusion ; if (neutral_viscosity) { // NOTE: The following viscosity terms are are not (yet) balanced // by a viscous heating term // Relationship between heat conduction and viscosity for neutral // gas Chapman, Cowling "The Mathematical Theory of Non-Uniform // Gases", CUP 1952 Ferziger, Kaper "Mathematical Theory of // Transport Processes in Gases", 1972 // eta_n = (2. / 5) * kappa_n; // ddt(NVn) += AA * FV::Div_a_Grad_perp((2. / 5) * DnnNn, Vn) // Perpendicular viscosity + AA * FV::Div_par_K_Grad_par((2. / 5) * DnnNn, Vn) // Parallel viscosity ; } if (localstate.isSet("momentum_source")) { Snv = get<Field3D>(localstate["momentum_source"]); ddt(NVn) += Snv; } } else { ddt(NVn) = 0; Snv = 0; } ///////////////////////////////////////////////////// // Neutral pressure TRACE("Neutral pressure"); ddt(Pn) = -FV::Div_par_mod<hermes::Limiter>(Pn, Vn, sound_speed, energy_flow_ylow) // Advection - (2. / 3) * Pn * Div_par(Vn) // Compression + FV::Div_a_Grad_perp(DnnPn, logPnlim) // Perpendicular diffusion + FV::Div_a_Grad_perp(DnnNn, Tn) // Conduction + FV::Div_par_K_Grad_par(DnnNn, Tn) // Parallel conduction ; energy_flow_ylow *= 5./2; Sp = pressure_source; if (localstate.isSet("energy_source")) { Sp += (2. / 3) * get<Field3D>(localstate["energy_source"]); } ddt(Pn) += Sp; BOUT_FOR(i, Pn.getRegion("RGN_ALL")) { if ((Pn[i] < 1e-9) && (ddt(Pn)[i] < 0.0)) { ddt(Pn)[i] = 0.0; } if ((Nn[i] < 1e-7) && (ddt(Nn)[i] < 0.0)) { ddt(Nn)[i] = 0.0; } } // Scale time derivatives if (state.isSet("scale_timederivs")) { Field3D scale_timederivs = get<Field3D>(state["scale_timederivs"]); ddt(Nn) *= scale_timederivs; ddt(Pn) *= scale_timederivs; ddt(NVn) *= scale_timederivs; } #if CHECKLEVEL >= 1 for (auto& i : Nn.getRegion("RGN_NOBNDRY")) { if (!std::isfinite(ddt(Nn)[i])) { throw BoutException("ddt(N{}) non-finite at {}\n", name, i); } if (!std::isfinite(ddt(Pn)[i])) { throw BoutException("ddt(P{}) non-finite at {}\n", name, i); } if (!std::isfinite(ddt(NVn)[i])) { throw BoutException("ddt(NV{}) non-finite at {}\n", name, i); } } #endif } void NeutralMixed::outputVars(Options& state) { // Normalisations auto Nnorm = get<BoutReal>(state["Nnorm"]); auto Tnorm = get<BoutReal>(state["Tnorm"]); auto Omega_ci = get<BoutReal>(state["Omega_ci"]); auto Cs0 = get<BoutReal>(state["Cs0"]); const BoutReal Pnorm = SI::qe * Tnorm * Nnorm; state[std::string("N") + name].setAttributes({{"time_dimension", "t"}, {"units", "m^-3"}, {"conversion", Nnorm}, {"standard_name", "density"}, {"long_name", name + " number density"}, {"species", name}, {"source", "neutral_mixed"}}); state[std::string("P") + name].setAttributes({{"time_dimension", "t"}, {"units", "Pa"}, {"conversion", Pnorm}, {"standard_name", "pressure"}, {"long_name", name + " pressure"}, {"species", name}, {"source", "neutral_mixed"}}); state[std::string("NV") + name].setAttributes( {{"time_dimension", "t"}, {"units", "kg / m^2 / s"}, {"conversion", SI::Mp * Nnorm * Cs0}, {"standard_name", "momentum"}, {"long_name", name + " parallel momentum"}, {"species", name}, {"source", "neutral_mixed"}}); if (output_ddt) { set_with_attrs( state[std::string("ddt(N") + name + std::string(")")], ddt(Nn), {{"time_dimension", "t"}, {"units", "m^-3 s^-1"}, {"conversion", Nnorm * Omega_ci}, {"long_name", std::string("Rate of change of ") + name + " number density"}, {"source", "neutral_mixed"}}); set_with_attrs(state[std::string("ddt(P") + name + std::string(")")], ddt(Pn), {{"time_dimension", "t"}, {"units", "Pa s^-1"}, {"conversion", Pnorm * Omega_ci}, {"source", "neutral_mixed"}}); set_with_attrs(state[std::string("ddt(NV") + name + std::string(")")], ddt(NVn), {{"time_dimension", "t"}, {"units", "kg m^-2 s^-2"}, {"conversion", SI::Mp * Nnorm * Cs0 * Omega_ci}, {"source", "neutral_mixed"}}); } if (diagnose) { set_with_attrs(state[std::string("T") + name], Tn, {{"time_dimension", "t"}, {"units", "eV"}, {"conversion", Tnorm}, {"standard_name", "temperature"}, {"long_name", name + " temperature"}, {"source", "neutral_mixed"}}); set_with_attrs(state[std::string("Dnn") + name], Dnn, {{"time_dimension", "t"}, {"units", "m^2/s"}, {"conversion", Cs0 * Cs0 / Omega_ci}, {"standard_name", "diffusion coefficient"}, {"long_name", name + " diffusion coefficient"}, {"source", "neutral_mixed"}}); set_with_attrs(state[std::string("SN") + name], Sn, {{"time_dimension", "t"}, {"units", "m^-3 s^-1"}, {"conversion", Nnorm * Omega_ci}, {"standard_name", "density source"}, {"long_name", name + " number density source"}, {"source", "neutral_mixed"}}); set_with_attrs(state[std::string("SP") + name], Sp, {{"time_dimension", "t"}, {"units", "Pa s^-1"}, {"conversion", SI::qe * Tnorm * Nnorm * Omega_ci}, {"standard_name", "pressure source"}, {"long_name", name + " pressure source"}, {"source", "neutral_mixed"}}); set_with_attrs(state[std::string("SNV") + name], Snv, {{"time_dimension", "t"}, {"units", "kg m^-2 s^-2"}, {"conversion", SI::Mp * Nnorm * Cs0 * Omega_ci}, {"standard_name", "momentum source"}, {"long_name", name + " momentum source"}, {"source", "neutral_mixed"}}); set_with_attrs(state[std::string("S") + name + std::string("_src")], density_source, {{"time_dimension", "t"}, {"units", "m^-3 s^-1"}, {"conversion", Nnorm * Omega_ci}, {"standard_name", "density source"}, {"long_name", name + " number density source"}, {"species", name}, {"source", "neutral_mixed"}}); set_with_attrs(state[std::string("P") + name + std::string("_src")], pressure_source, {{"time_dimension", "t"}, {"units", "Pa s^-1"}, {"conversion", Pnorm * Omega_ci}, {"standard_name", "pressure source"}, {"long_name", name + " pressure source"}, {"species", name}, {"source", "neutral_mixed"}}); } } void NeutralMixed::precon(const Options& state, BoutReal gamma) { if (!precondition) { return; } // Neutral gas diffusion // Solve (1 - gamma*Dnn*Delp2)^{-1} Field3D coef = -gamma * Dnn; if (state.isSet("scale_timederivs")) { coef *= get<Field3D>(state["scale_timederivs"]); } inv->setCoefD(coef); ddt(Nn) = inv->solve(ddt(Nn)); if (evolve_momentum) { ddt(NVn) = inv->solve(ddt(NVn)); } ddt(Pn) = inv->solve(ddt(Pn)); }
20,718
C++
.cxx
465
36.184946
131
0.554056
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,216
sound_speed.cxx
bendudson_hermes-3/src/sound_speed.cxx
#include "../include/sound_speed.hxx" #include <bout/mesh.hxx> namespace { BoutReal floor(BoutReal value, BoutReal min) { if (value < min) return min; return value; } } // namespace void SoundSpeed::transform(Options &state) { Field3D total_pressure = 0.0; Field3D total_density = 0.0; Field3D fastest_wave = 0.0; for (auto& kv : state["species"].getChildren()) { const Options& species = kv.second; if (species.isSet("pressure")) { total_pressure += GET_NOBOUNDARY(Field3D, species["pressure"]); } if ((kv.first == "e") and !electron_dynamics) { // Exclude electron sound speed, but include electron pressure in // collective sound speed calculation (total_pressure). continue; } if (species.isSet("AA")) { auto AA = get<BoutReal>(species["AA"]); // Atomic mass number if (species.isSet("density")) { total_density += GET_NOBOUNDARY(Field3D, species["density"]) * get<BoutReal>(species["AA"]); } if (species.isSet("temperature")) { auto T = GET_NOBOUNDARY(Field3D, species["temperature"]); for (auto& i : fastest_wave.getRegion("RGN_NOBNDRY")) { BoutReal sound_speed = sqrt(floor(T[i], temperature_floor) / AA); fastest_wave[i] = BOUTMAX(fastest_wave[i], sound_speed); } } } } total_density = floor(total_density, 1e-10); Field3D sound_speed = sqrt(total_pressure / total_density); for (auto& i : fastest_wave.getRegion("RGN_NOBNDRY")) { fastest_wave[i] = BOUTMAX(fastest_wave[i], sound_speed[i]); } if (alfven_wave) { auto *coord = fastest_wave.getCoordinates(); for (auto& i : fastest_wave.getRegion("RGN_NOBNDRY")) { BoutReal alfven_speed = beta_norm * coord->Bxy[i] / sqrt(total_density[i]); fastest_wave[i] = BOUTMAX(fastest_wave[i], alfven_speed); } } set(state["sound_speed"], sound_speed); set(state["fastest_wave"], fastest_wave*fastest_wave_factor); }
1,972
C++
.cxx
52
32.903846
100
0.651809
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,217
binormal_stpm.cxx
bendudson_hermes-3/src/binormal_stpm.cxx
#include <bout/fv_ops.hxx> #include <bout/output_bout_types.hxx> #include "../include/binormal_stpm.hxx" #include "../include/hermes_utils.hxx" #include "../include/hermes_build_config.hxx" using bout::globals::mesh; BinormalSTPM::BinormalSTPM(std::string name, Options& alloptions, Solver* solver) : name(name) { AUTO_TRACE(); auto& options = alloptions[name]; const Options& units = alloptions["units"]; const BoutReal rho_s0 = units["meters"]; const BoutReal Omega_ci = 1. / units["seconds"].as<BoutReal>(); const BoutReal diffusion_norm = rho_s0 * rho_s0 * Omega_ci; // m^2/s Theta = options["Theta"] .doc("Field-line Pitch defined by Feng et al.") .withDefault(1e-3); chi = options["chi"] .doc("Anomalous heat diffusion.") .withDefault(3.) /diffusion_norm; D = options["D"] .doc("Anomalous density diffusion.") .withDefault(1.) /diffusion_norm; nu = options["nu"] .doc("Anomalous momentum diffusion.") .withDefault(1.) /diffusion_norm; chi_Theta = chi/Theta; D_Theta = D/Theta; nu_Theta = nu/Theta; Theta_inv = 1./Theta; diagnose = options["diagnose"] .doc("Output diagnostics?") .withDefault(false); } void BinormalSTPM::transform(Options& state) { AUTO_TRACE(); Options& allspecies = state["species"]; // Loop through all species for (auto& kv : allspecies.getChildren()) { const auto& species_name = kv.first; Options& species = allspecies[species_name]; auto AA = get<BoutReal>(species["AA"]); const Field3D N = species.isSet("density") ? GET_NOBOUNDARY(Field3D, species["density"]) : 0.0; const Field3D T = species.isSet("temperature") ? GET_NOBOUNDARY(Field3D, species["temperature"]) : 0.0; const Field3D NV = species.isSet("momentum") ? GET_NOBOUNDARY(Field3D, species["momentum"]) : 0.0; add(species["energy_source"], Theta_inv * FV::Div_par_K_Grad_par(chi_Theta*N, T, false)); add(species["momentum_source"], Theta_inv * FV::Div_par_K_Grad_par(AA*nu_Theta, NV, false)); add(species["density_source"], Theta_inv * FV::Div_par_K_Grad_par(D_Theta, N, false)); } } void BinormalSTPM::outputVars(Options& state) { AUTO_TRACE(); // Normalisations auto Omega_ci = get<BoutReal>(state["Omega_ci"]); auto rho_s0 = get<BoutReal>(state["rho_s0"]); if (diagnose) { AUTO_TRACE(); // Save particle, momentum and energy channels set_with_attrs(state[{std::string("D_") + name}], D, {{"time_dimension", "t"}, {"units", "m^2 s^-1"}, {"conversion", rho_s0 * rho_s0 * Omega_ci}, {"standard_name", "anomalous density diffusion"}, {"long_name", std::string("Binormal Stellarator 2pt model density diffusion of ") + name}, {"source", "binormal_stpm"}}); set_with_attrs(state[{std::string("chi_") + name}], chi, {{"time_dimension", "t"}, {"units", "m^2 s^-1"}, {"conversion", rho_s0 * rho_s0 * Omega_ci}, {"standard_name", "anomalous thermal diffusion"}, {"long_name", std::string("Binormal Stellarator 2pt model thermal diffusion of ") + name}, {"source", "binormal_stpm"}}); set_with_attrs(state[{std::string("nu_") + name}], nu, {{"time_dimension", "t"}, {"units", "m^2 s^-1"}, {"conversion", rho_s0 * rho_s0 * Omega_ci}, {"standard_name", "anomalous momentum diffusion"}, {"long_name", std::string("Binormal Stellarator 2pt model momentum diffusion of ") + name}, {"source", "binormal_stpm"}}); } }
3,839
C++
.cxx
93
33.354839
113
0.592613
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,218
amjuel_hyd_ionisation.cxx
bendudson_hermes-3/src/amjuel_hyd_ionisation.cxx
#include "../include/amjuel_hyd_ionisation.hxx" /// Coefficients to calculate the reaction rate <σv> /// Reaction 2.1.5, Amjuel page 135 /// E-index varies fastest, so coefficient is [T][n] static constexpr const BoutReal rate_coefs[9][9] = { {-32.4802533034, -0.05440669186583, 0.09048888225109, -0.04054078993576, 0.008976513750477, -0.001060334011186, 6.846238436472e-05, -2.242955329604e-06, 2.890437688072e-08}, {14.2533239151, -0.0359434716076, -0.02014729121556, 0.0103977361573, -0.001771792153042, 0.0001237467264294, -3.130184159149e-06, -3.051994601527e-08, 1.888148175469e-09}, {-6.632235026785, 0.09255558353174, -0.005580210154625, -0.005902218748238, 0.001295609806553, -0.0001056721622588, 4.646310029498e-06, -1.479612391848e-07, 2.85225125832e-09}, {2.059544135448, -0.07562462086943, 0.01519595967433, 0.0005803498098354, -0.0003527285012725, 3.201533740322e-05, -1.835196889733e-06, 9.474014343303e-08, -2.342505583774e-09}, {-0.442537033141, 0.02882634019199, -0.00728577148505, 0.0004643389885987, 1.145700685235e-06, 8.493662724988e-07, -1.001032516512e-08, -1.476839184318e-08, 6.047700368169e-10}, {0.06309381861496, -0.00578868653578, 0.00150738295525, -0.0001201550548662, 6.574487543511e-06, -9.678782818849e-07, 5.176265845225e-08, 1.29155167686e-09, -9.685157340473e-11}, {-0.005620091829261, 0.000632910556804, -0.0001527777697951, 8.270124691336e-06, 3.224101773605e-08, 4.377402649057e-08, -2.622921686955e-09, -2.259663431436e-10, 1.161438990709e-11}, {0.0002812016578355, -3.564132950345e-05, 7.222726811078e-06, 1.433018694347e-07, -1.097431215601e-07, 7.789031791949e-09, -4.197728680251e-10, 3.032260338723e-11, -8.911076930014e-13}, {-6.011143453374e-06, 8.089651265488e-07, -1.186212683668e-07, -2.381080756307e-08, 6.271173694534e-09, -5.48301024493e-10, 3.064611702159e-11, -1.355903284487e-12, 2.935080031599e-14}}; /// Coefficients to calculate the radiation energy loss /// Reaction 2.1.5, Amjuel page 280 /// E-index varies fastest, so coefficient is [T][n] static constexpr const BoutReal radiation_coefs[9][9] = { {-24.97580168306, 0.001081653961822, -0.0007358936044605, 0.0004122398646951, -0.0001408153300988, 2.46973083622e-05, -2.212823709798e-06, 9.648139704737e-08, -1.611904413846e-09}, {10.04448839974, -0.003189474633369, 0.002510128351932, -0.0007707040988954, 0.0001031309578578, -3.716939423005e-06, -4.249704742353e-07, 4.164960852522e-08, -9.893423877739e-10}, {-4.867952931298, -0.00585226785069, 0.002867458651322, -0.0008328668093987, 0.0002056134355492, -3.301570807523e-05, 2.831739755462e-06, -1.164969298033e-07, 1.78544027879e-09}, {1.689422238067, 0.007744372210287, -0.003087364236497, 0.000470767628842, -5.508611815406e-05, 7.305867762241e-06, -6.000115718138e-07, 2.045211951761e-08, -1.79031287169e-10}, {-0.41035323201, -0.003622291213236, 0.001327415215304, -0.0001424078519508, 3.307339563081e-06, 5.256679519499e-09, 7.597020291557e-10, 1.799505288362e-09, -9.280890205774e-11}, {0.06469718387357, 0.0008268567898126, -0.0002830939623802, 2.41184802496e-05, 5.7079848611e-07, -1.0169456933e-07, 3.517154874443e-09, -4.453195673947e-10, 2.002478264932e-11}, {-0.006215861314764, -9.836595524255e-05, 3.017296919092e-05, -1.474253805845e-06, -2.397868837417e-07, 1.518743025531e-08, 4.149084521319e-10, -6.803200444549e-12, -1.151855939531e-12}, {0.000328980989546, 5.845697922558e-06, -1.479323780613e-06, -4.633029022577e-08, 3.337390374041e-08, -1.770252084837e-09, -5.289806153651e-11, 3.86439477625e-12, -8.694978774411e-15}, {-7.335808238917e-06, -1.367574486885e-07, 2.423236476442e-08, 5.733871119707e-09, -1.512777532459e-09, 8.733801272834e-11, 7.196798841269e-13, -1.441033650378e-13, 1.734769090475e-15}}; void AmjuelHydIonisation::calculate_rates( Options& electron, Options& atom, Options& ion, Field3D &reaction_rate, Field3D &momentum_exchange, Field3D &energy_exchange, Field3D &energy_loss, BoutReal &rate_multiplier, BoutReal &radiation_multiplier) { electron_reaction(electron, atom, ion, rate_coefs, radiation_coefs, 0.0, // Note: Ionisation potential included in radiation_coefs reaction_rate, momentum_exchange, energy_exchange, energy_loss, rate_multiplier, radiation_multiplier ); }
4,494
C++
.cxx
72
57.166667
121
0.738176
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,540,219
evolve_pressure.cxx
bendudson_hermes-3/src/evolve_pressure.cxx
#include <bout/constants.hxx> #include <bout/fv_ops.hxx> #include <bout/field_factory.hxx> #include <bout/derivs.hxx> #include <bout/difops.hxx> #include <bout/output_bout_types.hxx> #include <bout/initialprofiles.hxx> #include <bout/invert_pardiv.hxx> #include "../include/div_ops.hxx" #include "../include/evolve_pressure.hxx" #include "../include/hermes_utils.hxx" #include "../include/hermes_build_config.hxx" using bout::globals::mesh; EvolvePressure::EvolvePressure(std::string name, Options& alloptions, Solver* solver) : name(name) { AUTO_TRACE(); auto& options = alloptions[name]; evolve_log = options["evolve_log"].doc("Evolve the logarithm of pressure?").withDefault<bool>(false); density_floor = options["density_floor"].doc("Minimum density floor").withDefault(1e-5); low_n_diffuse_perp = options["low_n_diffuse_perp"] .doc("Perpendicular diffusion at low density") .withDefault<bool>(false); temperature_floor = options["temperature_floor"].doc("Low temperature scale for low_T_diffuse_perp") .withDefault<BoutReal>(0.1) / get<BoutReal>(alloptions["units"]["eV"]); low_T_diffuse_perp = options["low_T_diffuse_perp"].doc("Add cross-field diffusion at low temperature?") .withDefault<bool>(false); pressure_floor = density_floor * (1./get<BoutReal>(alloptions["units"]["eV"])); low_p_diffuse_perp = options["low_p_diffuse_perp"] .doc("Perpendicular diffusion at low pressure") .withDefault<bool>(false); if (evolve_log) { // Evolve logarithm of pressure solver->add(logP, std::string("logP") + name); // Save the pressure to the restart file // so the simulation can be restarted evolving pressure //get_restart_datafile()->addOnce(P, std::string("P") + name); if (!alloptions["hermes"]["restarting"]) { // Set logN from N input options initial_profile(std::string("P") + name, P); logP = log(P); } else { // Ignore these settings Options::root()[std::string("P") + name].setConditionallyUsed(); } } else { // Evolve the pressure in time solver->add(P, std::string("P") + name); } bndry_flux = options["bndry_flux"] .doc("Allow flows through radial boundaries") .withDefault<bool>(true); poloidal_flows = options["poloidal_flows"].doc("Include poloidal ExB flow").withDefault<bool>(true); thermal_conduction = options["thermal_conduction"] .doc("Include parallel heat conduction?") .withDefault<bool>(true); kappa_coefficient = options["kappa_coefficient"] .doc("Numerical coefficient in parallel heat conduction. Default is 3.16 for electrons, 3.9 otherwise") .withDefault((name == "e") ? 3.16 : 3.9); kappa_limit_alpha = options["kappa_limit_alpha"] .doc("Flux limiter factor. < 0 means no limit. Typical is 0.2 for electrons, 1 for ions.") .withDefault(-1.0); p_div_v = options["p_div_v"] .doc("Use p*Div(v) form? Default, false => v * Grad(p) form") .withDefault<bool>(false); hyper_z = options["hyper_z"].doc("Hyper-diffusion in Z").withDefault(-1.0); hyper_z_T = options["hyper_z_T"] .doc("4th-order dissipation of temperature") .withDefault<BoutReal>(-1.0); diagnose = options["diagnose"] .doc("Save additional output diagnostics") .withDefault<bool>(false); enable_precon = options["precondition"] .doc("Enable preconditioner? (Note: solver may not use it)") .withDefault<bool>(true); const Options& units = alloptions["units"]; const BoutReal Nnorm = units["inv_meters_cubed"]; const BoutReal Tnorm = units["eV"]; const BoutReal Omega_ci = 1. / units["seconds"].as<BoutReal>(); auto& p_options = alloptions[std::string("P") + name]; source_normalisation = SI::qe * Nnorm * Tnorm * Omega_ci; // [Pa/s] or [W/m^3] if converted to energy time_normalisation = 1./Omega_ci; // [s] // Try to read the pressure source from the mesh // Units of Pascals per second source = 0.0; mesh->get(source, std::string("P") + name + "_src"); // Allow the user to override the source source = p_options["source"] .doc(std::string("Source term in ddt(P") + name + std::string("). Units [Pa/s], note P = 2/3 E")) .withDefault(source) / (source_normalisation); source_time_dependent = p_options["source_time_dependent"] .doc("Use a time-dependent source?") .withDefault<bool>(false); // If time dependent, parse the function with respect to time from the input file if (source_time_dependent) { auto str = p_options["source_prefactor"] .doc("Time-dependent function of multiplier on ddt(P" + name + std::string(") source.")) .as<std::string>(); source_prefactor_function = FieldFactory::get()->parse(str, &p_options); } if (p_options["source_only_in_core"] .doc("Zero the source outside the closed field-line region?") .withDefault<bool>(false)) { for (int x = mesh->xstart; x <= mesh->xend; x++) { if (!mesh->periodicY(x)) { // Not periodic, so not in core for (int y = mesh->ystart; y <= mesh->yend; y++) { for (int z = mesh->zstart; z <= mesh->zend; z++) { source(x, y, z) = 0.0; } } } } } neumann_boundary_average_z = p_options["neumann_boundary_average_z"] .doc("Apply neumann boundary with Z average?") .withDefault<bool>(false); numerical_viscous_heating = options["numerical_viscous_heating"] .doc("Include heating due to numerical viscosity?") .withDefault<bool>(false); if (numerical_viscous_heating) { fix_momentum_boundary_flux = options["fix_momentum_boundary_flux"] .doc("Fix Y boundary momentum flux to boundary midpoint value?") .withDefault<bool>(false); } } void EvolvePressure::transform(Options& state) { AUTO_TRACE(); if (evolve_log) { // Evolving logP, but most calculations use P P = exp(logP); } mesh->communicate(P); if (neumann_boundary_average_z) { // Take Z (usually toroidal) average and apply as X (radial) boundary condition if (mesh->firstX()) { for (int j = mesh->ystart; j <= mesh->yend; j++) { BoutReal Pavg = 0.0; // Average P in Z for (int k = 0; k < mesh->LocalNz; k++) { Pavg += P(mesh->xstart, j, k); } Pavg /= mesh->LocalNz; // Apply boundary condition for (int k = 0; k < mesh->LocalNz; k++) { P(mesh->xstart - 1, j, k) = 2. * Pavg - P(mesh->xstart, j, k); P(mesh->xstart - 2, j, k) = P(mesh->xstart - 1, j, k); } } } if (mesh->lastX()) { for (int j = mesh->ystart; j <= mesh->yend; j++) { BoutReal Pavg = 0.0; // Average P in Z for (int k = 0; k < mesh->LocalNz; k++) { Pavg += P(mesh->xend, j, k); } Pavg /= mesh->LocalNz; for (int k = 0; k < mesh->LocalNz; k++) { P(mesh->xend + 1, j, k) = 2. * Pavg - P(mesh->xend, j, k); P(mesh->xend + 2, j, k) = P(mesh->xend + 1, j, k); } } } } auto& species = state["species"][name]; // Calculate temperature // Not using density boundary condition N = getNoBoundary<Field3D>(species["density"]); Field3D Pfloor = floor(P, 0.0); T = Pfloor / floor(N, density_floor); Pfloor = N * T; // Ensure consistency set(species["pressure"], Pfloor); set(species["temperature"], T); } void EvolvePressure::finally(const Options& state) { AUTO_TRACE(); /// Get the section containing this species const auto& species = state["species"][name]; // Get updated pressure and temperature with boundary conditions // Note: Retain pressures which fall below zero P.clearParallelSlices(); P.setBoundaryTo(get<Field3D>(species["pressure"])); Field3D Pfloor = floor(P, 0.0); // Restricted to never go below zero T = get<Field3D>(species["temperature"]); N = get<Field3D>(species["density"]); if (species.isSet("charge") and (fabs(get<BoutReal>(species["charge"])) > 1e-5) and state.isSection("fields") and state["fields"].isSet("phi")) { // Electrostatic potential set and species is charged -> include ExB flow Field3D phi = get<Field3D>(state["fields"]["phi"]); ddt(P) = -Div_n_bxGrad_f_B_XPPM(P, phi, bndry_flux, poloidal_flows, true); } else { ddt(P) = 0.0; } if (species.isSet("velocity")) { Field3D V = get<Field3D>(species["velocity"]); // Typical wave speed used for numerical diffusion Field3D fastest_wave; if (state.isSet("fastest_wave")) { fastest_wave = get<Field3D>(state["fastest_wave"]); } else { BoutReal AA = get<BoutReal>(species["AA"]); fastest_wave = sqrt(T / AA); } if (p_div_v) { // Use the P * Div(V) form ddt(P) -= FV::Div_par_mod<hermes::Limiter>(P, V, fastest_wave, flow_ylow); // Work done. This balances energetically a term in the momentum equation ddt(P) -= (2. / 3) * Pfloor * Div_par(V); } else { // Use V * Grad(P) form // Note: A mixed form has been tried (on 1D neon example) // -(4/3)*FV::Div_par(P,V) + (1/3)*(V * Grad_par(P) - P * Div_par(V)) // Caused heating of charged species near sheath like p_div_v ddt(P) -= (5. / 3) * FV::Div_par_mod<hermes::Limiter>(P, V, fastest_wave, flow_ylow); ddt(P) += (2. / 3) * V * Grad_par(P); } flow_ylow *= 5. / 2; // Energy flow if (state.isSection("fields") and state["fields"].isSet("Apar_flutter")) { // Magnetic flutter term const Field3D Apar_flutter = get<Field3D>(state["fields"]["Apar_flutter"]); ddt(P) -= (5. / 3) * Div_n_g_bxGrad_f_B_XZ(P, V, -Apar_flutter); ddt(P) += (2. / 3) * V * bracket(P, Apar_flutter, BRACKET_ARAKAWA); } if (numerical_viscous_heating || diagnose) { // Viscous heating coming from numerical viscosity Field3D Nlim = floor(N, density_floor); const BoutReal AA = get<BoutReal>(species["AA"]); // Atomic mass Sp_nvh = (2. / 3) * AA * FV::Div_par_fvv_heating(Nlim, V, fastest_wave, flow_ylow_kinetic, fix_momentum_boundary_flux); flow_ylow_kinetic *= AA; flow_ylow += flow_ylow_kinetic; if (numerical_viscous_heating) { ddt(P) += Sp_nvh; } } } if (species.isSet("low_n_coeff")) { // Low density parallel diffusion Field3D low_n_coeff = get<Field3D>(species["low_n_coeff"]); ddt(P) += FV::Div_par_K_Grad_par(low_n_coeff * T, N) + FV::Div_par_K_Grad_par(low_n_coeff, P); } if (low_n_diffuse_perp) { ddt(P) += Div_Perp_Lap_FV_Index(density_floor / floor(N, 1e-3 * density_floor), P, true); } if (low_T_diffuse_perp) { ddt(P) += 1e-4 * Div_Perp_Lap_FV_Index(floor(temperature_floor / floor(T, 1e-3 * temperature_floor) - 1.0, 0.0), T, false); } if (low_p_diffuse_perp) { Field3D Plim = floor(P, 1e-3 * pressure_floor); ddt(P) += Div_Perp_Lap_FV_Index(pressure_floor / Plim, P, true); } // Parallel heat conduction if (thermal_conduction) { // Calculate ion collision times const Field3D tau = 1. / floor(get<Field3D>(species["collision_frequency"]), 1e-10); const BoutReal AA = get<BoutReal>(species["AA"]); // Atomic mass // Parallel heat conduction // Braginskii expression for parallel conduction // kappa ~ n * v_th^2 * tau // // Note: Coefficient is slightly different for electrons (3.16) and ions (3.9) kappa_par = kappa_coefficient * Pfloor * tau / AA; if (kappa_limit_alpha > 0.0) { /* * Flux limiter, as used in SOLPS. * * Calculate the heat flux from Spitzer-Harm and flux limit * * Typical value of alpha ~ 0.2 for electrons * * R.Schneider et al. Contrib. Plasma Phys. 46, No. 1-2, 3 – 191 (2006) * DOI 10.1002/ctpp.200610001 */ // Spitzer-Harm heat flux Field3D q_SH = kappa_par * Grad_par(T); // Free-streaming flux Field3D q_fl = kappa_limit_alpha * N * T * sqrt(T / AA); // This results in a harmonic average of the heat fluxes kappa_par = kappa_par / (1. + abs(q_SH / floor(q_fl, 1e-10))); // Values of kappa on cell boundaries are needed for fluxes mesh->communicate(kappa_par); } for (RangeIterator r = mesh->iterateBndryLowerY(); !r.isDone(); r++) { for (int jz = 0; jz < mesh->LocalNz; jz++) { auto i = indexAt(kappa_par, r.ind, mesh->ystart, jz); auto im = i.ym(); kappa_par[im] = kappa_par[i]; } } for (RangeIterator r = mesh->iterateBndryUpperY(); !r.isDone(); r++) { for (int jz = 0; jz < mesh->LocalNz; jz++) { auto i = indexAt(kappa_par, r.ind, mesh->yend, jz); auto ip = i.yp(); kappa_par[ip] = kappa_par[i]; } } // Note: Flux through boundary turned off, because sheath heat flux // is calculated and removed separately flow_ylow_conduction; ddt(P) += (2. / 3) * Div_par_K_Grad_par_mod(kappa_par, T, flow_ylow_conduction, false); flow_ylow += flow_ylow_conduction; if (state.isSection("fields") and state["fields"].isSet("Apar_flutter")) { // Magnetic flutter term. The operator splits into 4 pieces: // Div(k b b.Grad(T)) = Div(k b0 b0.Grad(T)) + Div(k d0 db.Grad(T)) // + Div(k db b0.Grad(T)) + Div(k db db.Grad(T)) // The first term is already calculated above. // Here we add the terms containing db const Field3D Apar_flutter = get<Field3D>(state["fields"]["Apar_flutter"]); Field3D db_dot_T = bracket(T, Apar_flutter, BRACKET_ARAKAWA); Field3D b0_dot_T = Grad_par(T); mesh->communicate(db_dot_T, b0_dot_T); ddt(P) += (2. / 3) * (Div_par(kappa_par * db_dot_T) - Div_n_g_bxGrad_f_B_XZ(kappa_par, db_dot_T + b0_dot_T, Apar_flutter)); } } if (hyper_z > 0.) { ddt(P) -= hyper_z * D4DZ4_Index(P); } if (hyper_z_T > 0.) { ddt(P) -= hyper_z_T * D4DZ4_Index(T); } ////////////////////// // Other sources if (source_time_dependent) { // Evaluate the source_prefactor function at the current time in seconds and scale source with it BoutReal time = get<BoutReal>(state["time"]); BoutReal source_prefactor = source_prefactor_function ->generate(bout::generator::Context().set("x",0,"y",0,"z",0,"t",time*time_normalisation)); final_source = source * source_prefactor; } else { final_source = source; } Sp = final_source; if (species.isSet("energy_source")) { Sp += (2. / 3) * get<Field3D>(species["energy_source"]); // For diagnostic output } #if CHECKLEVEL >= 1 if (species.isSet("pressure_source")) { throw BoutException("Components must evolve `energy_source` rather then `pressure_source`"); } #endif ddt(P) += Sp; // Term to force evolved P towards N * T // This is active when P < 0 or when N < density_floor ddt(P) += N * T - P; // Scale time derivatives if (state.isSet("scale_timederivs")) { ddt(P) *= get<Field3D>(state["scale_timederivs"]); } if (evolve_log) { ddt(logP) = ddt(P) / P; } #if CHECKLEVEL >= 1 for (auto& i : P.getRegion("RGN_NOBNDRY")) { if (!std::isfinite(ddt(P)[i])) { throw BoutException("ddt(P{}) non-finite at {}. Sp={}\n", name, i, Sp[i]); } } #endif if (diagnose) { // Save flows of energy if they are set if (species.isSet("energy_flow_xlow")) { flow_xlow = get<Field3D>(species["energy_flow_xlow"]); } if (species.isSet("energy_flow_ylow")) { flow_ylow += get<Field3D>(species["energy_flow_ylow"]); } } } void EvolvePressure::outputVars(Options& state) { AUTO_TRACE(); // Normalisations auto Nnorm = get<BoutReal>(state["Nnorm"]); auto Tnorm = get<BoutReal>(state["Tnorm"]); auto Omega_ci = get<BoutReal>(state["Omega_ci"]); auto rho_s0 = get<BoutReal>(state["rho_s0"]); BoutReal Pnorm = SI::qe * Tnorm * Nnorm; // Pressure normalisation if (evolve_log) { state[std::string("P") + name].force(P); } state[std::string("P") + name].setAttributes({{"time_dimension", "t"}, {"units", "Pa"}, {"conversion", Pnorm}, {"standard_name", "pressure"}, {"long_name", name + " pressure"}, {"species", name}, {"source", "evolve_pressure"}}); if (diagnose) { if (thermal_conduction) { set_with_attrs(state[std::string("kappa_par_") + name], kappa_par, {{"time_dimension", "t"}, {"units", "W / m / eV"}, {"conversion", (Pnorm * Omega_ci * SQ(rho_s0) )/ Tnorm}, {"long_name", name + " heat conduction coefficient"}, {"species", name}, {"source", "evolve_pressure"}}); } set_with_attrs(state[std::string("T") + name], T, {{"time_dimension", "t"}, {"units", "eV"}, {"conversion", Tnorm}, {"standard_name", "temperature"}, {"long_name", name + " temperature"}, {"species", name}, {"source", "evolve_pressure"}}); set_with_attrs(state[std::string("ddt(P") + name + std::string(")")], ddt(P), {{"time_dimension", "t"}, {"units", "Pa s^-1"}, {"conversion", Pnorm * Omega_ci}, {"long_name", std::string("Rate of change of ") + name + " pressure"}, {"species", name}, {"source", "evolve_pressure"}}); set_with_attrs(state[std::string("SP") + name], Sp, {{"time_dimension", "t"}, {"units", "Pa s^-1"}, {"conversion", Pnorm * Omega_ci}, {"standard_name", "pressure source"}, {"long_name", name + " pressure source"}, {"species", name}, {"source", "evolve_pressure"}}); set_with_attrs(state[std::string("P") + name + std::string("_src")], final_source, {{"time_dimension", "t"}, {"units", "Pa s^-1"}, {"conversion", Pnorm * Omega_ci}, {"standard_name", "pressure source"}, {"long_name", name + " pressure source"}, {"species", name}, {"source", "evolve_pressure"}}); if (flow_xlow.isAllocated()) { set_with_attrs(state[fmt::format("ef{}_tot_xlow", name)], flow_xlow, {{"time_dimension", "t"}, {"units", "W"}, {"conversion", rho_s0 * SQ(rho_s0) * Pnorm * Omega_ci}, {"standard_name", "power"}, {"long_name", name + " power through X cell face. Note: May be incomplete."}, {"species", name}, {"source", "evolve_pressure"}}); } if (flow_ylow.isAllocated()) { set_with_attrs(state[fmt::format("ef{}_tot_ylow", name)], flow_ylow, {{"time_dimension", "t"}, {"units", "W"}, {"conversion", rho_s0 * SQ(rho_s0) * Pnorm * Omega_ci}, {"standard_name", "power"}, {"long_name", name + " power through Y cell face. Note: May be incomplete."}, {"species", name}, {"source", "evolve_pressure"}}); set_with_attrs(state[fmt::format("ef{}_cond_ylow", name)], flow_ylow_conduction, {{"time_dimension", "t"}, {"units", "W"}, {"conversion", rho_s0 * SQ(rho_s0) * Pnorm * Omega_ci}, {"standard_name", "power"}, {"long_name", name + " conduction through Y cell face. Note: May be incomplete."}, {"species", name}, {"source", "evolve_pressure"}}); set_with_attrs(state[fmt::format("ef{}_kin_ylow", name)], flow_ylow_kinetic, {{"time_dimension", "t"}, {"units", "W"}, {"conversion", rho_s0 * SQ(rho_s0) * Pnorm * Omega_ci}, {"standard_name", "power"}, {"long_name", name + " kinetic energy flow through Y cell face. Note: May be incomplete."}, {"species", name}, {"source", "evolve_pressure"}}); } if (numerical_viscous_heating) { set_with_attrs(state[std::string("E") + name + std::string("_nvh")], Sp_nvh * 3/.2, {{"time_dimension", "t"}, {"units", "W"}, {"conversion", Pnorm * Omega_ci}, {"standard_name", "energy source"}, {"long_name", name + " energy source from numerical viscous heating"}, {"species", name}, {"source", "evolve_pressure"}}); } } } void EvolvePressure::precon(const Options &state, BoutReal gamma) { if (!(enable_precon and thermal_conduction)) { return; // Disabled } static std::unique_ptr<InvertParDiv> inv; if (!inv) { // Initialise parallel inversion class inv = InvertParDiv::create(); inv->setCoefA(1.0); } const auto& species = state["species"][name]; const Field3D N = get<Field3D>(species["density"]); // Set the coefficient in Div_par( B * Grad_par ) Field3D coef = -(2. / 3) * gamma * kappa_par / floor(N, density_floor); if (state.isSet("scale_timederivs")) { coef *= get<Field3D>(state["scale_timederivs"]); } inv->setCoefB(coef); Field3D dT = ddt(P); dT.applyBoundary("neumann"); ddt(P) = inv->solve(dT); }
22,158
C++
.cxx
498
36.044177
148
0.570924
bendudson/hermes-3
36
16
57
GPL-3.0
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false