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,015
|
main.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/test/test_math/main.cpp
|
#include <Arduino.h>
#include <unity.h>
#include "tests_crankmaths.h"
#include "tests_maths.h"
#define UNITY_EXCLUDE_DETAILS
void setup()
{
pinMode(LED_BUILTIN, OUTPUT);
// NOTE!!! Wait for >2 secs
// if board doesn't support software reset via Serial.DTR/RTS
delay(2000);
UNITY_BEGIN(); // IMPORTANT LINE!
testCrankMaths();
testMaths();
UNITY_END(); // stop unit testing
}
void loop()
{
// Blink to indicate end of test
digitalWrite(LED_BUILTIN, HIGH);
delay(250);
digitalWrite(LED_BUILTIN, LOW);
delay(250);
}
| 574
|
C++
|
.cpp
| 24
| 20.458333
| 65
| 0.675875
|
oelprinz-org/BlitzboxBL49sp
| 36
| 12
| 0
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,540,016
|
tests_crankmaths.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/test/test_math/tests_crankmaths.cpp
|
#include "globals.h"
#include "crankMaths.h"
#include "unity.h"
#include "decoders.h"
struct crankmaths_rev_testdata {
uint16_t rpm;
unsigned long revolutionTime;
uint16_t angle;
unsigned long expected;
} *crankmaths_rev_testdata_current;
struct crankmaths_tooth_testdata {
uint16_t rpm;
uint16_t triggerToothAngle;
unsigned long toothTime;
uint16_t angle;
unsigned long expected;
} *crankmaths_tooth_testdata_current;
void test_crankmaths_angletotime_revolution_execute() {
crankmaths_rev_testdata *testdata = crankmaths_rev_testdata_current;
revolutionTime = testdata->revolutionTime;
TEST_ASSERT_EQUAL(testdata->expected, angleToTime(testdata->angle, CRANKMATH_METHOD_INTERVAL_REV));
}
void test_crankmaths_angletotime_tooth_execute() {
crankmaths_tooth_testdata *testdata = crankmaths_tooth_testdata_current;
triggerToothAngle = testdata->triggerToothAngle;
toothLastToothTime = toothLastMinusOneToothTime + testdata->toothTime;
TEST_ASSERT_EQUAL(testdata->expected, angleToTime(testdata->angle, CRANKMATH_METHOD_INTERVAL_TOOTH));
}
void testCrankMaths()
{
const byte testNameLength = 200;
char testName[testNameLength];
const crankmaths_rev_testdata crankmaths_rev_testdatas[] = {
{ .rpm = 50, .revolutionTime = 1200000, .angle = 0, .expected = 0 },
{ .rpm = 50, .revolutionTime = 1200000, .angle = 25, .expected = 83333 }, // 83333,3333
{ .rpm = 50, .revolutionTime = 1200000, .angle = 720, .expected = 2400000 },
{ .rpm = 2500, .revolutionTime = 24000, .angle = 0, .expected = 0 },
{ .rpm = 2500, .revolutionTime = 24000, .angle = 25, .expected = 1666 }, // 1666,6666
{ .rpm = 2500, .revolutionTime = 24000, .angle = 720, .expected = 48000 },
{ .rpm = 20000, .revolutionTime = 3000, .angle = 0, .expected = 0 },
{ .rpm = 20000, .revolutionTime = 3000, .angle = 25, .expected = 208 }, // 208,3333
{ .rpm = 20000, .revolutionTime = 3000, .angle = 720, .expected = 6000 }
};
for (auto testdata : crankmaths_rev_testdatas) {
crankmaths_rev_testdata_current = &testdata;
snprintf(testName, testNameLength, "crankmaths/angletotime/revolution/%urpm/%uangle", testdata.rpm, testdata.angle);
UnityDefaultTestRun(test_crankmaths_angletotime_revolution_execute, testName, __LINE__);
}
const crankmaths_tooth_testdata crankmaths_tooth_testdatas[] = {
{ .rpm = 50, .triggerToothAngle = 3, .toothTime = 10000, .angle = 0, .expected = 0 },
{ .rpm = 50, .triggerToothAngle = 3, .toothTime = 10000, .angle = 25, .expected = 83333 }, // 83333,3333
{ .rpm = 50, .triggerToothAngle = 3, .toothTime = 10000, .angle = 720, .expected = 2400000 },
{ .rpm = 2500, .triggerToothAngle = 3, .toothTime = 200, .angle = 0, .expected = 0 },
{ .rpm = 2500, .triggerToothAngle = 3, .toothTime = 200, .angle = 25, .expected = 1666 }, // 1666,6666
{ .rpm = 2500, .triggerToothAngle = 3, .toothTime = 200, .angle = 720, .expected = 48000 },
{ .rpm = 20000, .triggerToothAngle = 3, .toothTime = 25, .angle = 0, .expected = 0 },
{ .rpm = 20000, .triggerToothAngle = 3, .toothTime = 25, .angle = 25, .expected = 208 }, // 208,3333
{ .rpm = 20000, .triggerToothAngle = 3, .toothTime = 25, .angle = 720, .expected = 6000 },
{ .rpm = 50, .triggerToothAngle = 180, .toothTime = 600000, .angle = 0, .expected = 0 },
{ .rpm = 50, .triggerToothAngle = 180, .toothTime = 600000, .angle = 25, .expected = 83333 }, // 83333,3333
{ .rpm = 50, .triggerToothAngle = 180, .toothTime = 600000, .angle = 720, .expected = 2400000 },
{ .rpm = 2500, .triggerToothAngle = 180, .toothTime = 12000, .angle = 0, .expected = 0 },
{ .rpm = 2500, .triggerToothAngle = 180, .toothTime = 12000, .angle = 25, .expected = 1666 }, // 1666,6666
{ .rpm = 2500, .triggerToothAngle = 180, .toothTime = 12000, .angle = 720, .expected = 48000 },
{ .rpm = 20000, .triggerToothAngle = 180, .toothTime = 1500, .angle = 0, .expected = 0 },
{ .rpm = 20000, .triggerToothAngle = 180, .toothTime = 1500, .angle = 25, .expected = 208 }, // 208,3333
{ .rpm = 20000, .triggerToothAngle = 180, .toothTime = 1500, .angle = 720, .expected = 6000 },
};
// The same for all tests
BIT_SET(decoderState, BIT_DECODER_TOOTH_ANG_CORRECT);
toothLastMinusOneToothTime = 200000;
for (auto testdata : crankmaths_tooth_testdatas) {
crankmaths_tooth_testdata_current = &testdata;
snprintf(testName, testNameLength, "crankmaths/angletotime/tooth/%urpm/%uangle/%utoothangle", testdata.rpm, testdata.angle, testdata.triggerToothAngle);
UnityDefaultTestRun(test_crankmaths_angletotime_tooth_execute, testName, __LINE__);
}
}
| 4,754
|
C++
|
.cpp
| 77
| 58.155844
| 156
| 0.667738
|
oelprinz-org/BlitzboxBL49sp
| 36
| 12
| 0
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,540,017
|
tests_maths.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/test/test_math/tests_maths.cpp
|
//#include <Arduino.h>
#include <string.h> // memcpy
#include <unity.h>
#include <stdio.h>
#include "tests_maths.h"
#include "maths.h"
void testMaths()
{
RUN_TEST(test_maths_percent_U8);
RUN_TEST(test_maths_percent_U16);
RUN_TEST(test_maths_percent_U32);
RUN_TEST(test_maths_halfpercent_U8);
RUN_TEST(test_maths_halfpercent_U16);
RUN_TEST(test_maths_halfpercent_U32);
RUN_TEST(test_maths_div100_U8);
RUN_TEST(test_maths_div100_U16);
RUN_TEST(test_maths_div100_U32);
RUN_TEST(test_maths_div100_S8);
RUN_TEST(test_maths_div100_S16);
RUN_TEST(test_maths_div100_S32);
}
void test_maths_percent_U8(void)
{
uint8_t percentOf = 200;
TEST_ASSERT_EQUAL(100, percentage(50, percentOf));
TEST_ASSERT_EQUAL(150, percentage(75, percentOf));
TEST_ASSERT_EQUAL(0, percentage(0, percentOf));
TEST_ASSERT_EQUAL(200, percentage(100, percentOf));
TEST_ASSERT_EQUAL(250, percentage(125, percentOf));
}
void test_maths_percent_U16(void)
{
uint16_t percentOf = 20000;
TEST_ASSERT_EQUAL(10000, percentage(50, percentOf));
TEST_ASSERT_EQUAL(15000, percentage(75, percentOf));
TEST_ASSERT_EQUAL(0, percentage(0, percentOf));
TEST_ASSERT_EQUAL(20000, percentage(100, percentOf));
TEST_ASSERT_EQUAL(25000, percentage(125, percentOf));
}
void test_maths_percent_U32(void)
{
uint32_t percentOf = 20000000UL;
TEST_ASSERT_EQUAL(10000000UL, percentage(50, percentOf));
TEST_ASSERT_EQUAL(15000000UL, percentage(75, percentOf));
TEST_ASSERT_EQUAL(0, percentage(0, percentOf));
TEST_ASSERT_EQUAL(20000000UL, percentage(100, percentOf));
TEST_ASSERT_EQUAL(25000000UL, percentage(125, percentOf));
}
void test_maths_halfpercent_U8(void)
{
uint8_t percentOf = 200;
TEST_ASSERT_EQUAL(50, halfPercentage(50, percentOf));
TEST_ASSERT_EQUAL(75, halfPercentage(75, percentOf));
TEST_ASSERT_EQUAL(0, halfPercentage(0, percentOf));
TEST_ASSERT_EQUAL(100, halfPercentage(100, percentOf));
TEST_ASSERT_EQUAL(125, halfPercentage(125, percentOf));
}
void test_maths_halfpercent_U16(void)
{
uint16_t percentOf = 20000;
TEST_ASSERT_EQUAL(5000, halfPercentage(50, percentOf));
TEST_ASSERT_EQUAL(7500, halfPercentage(75, percentOf));
TEST_ASSERT_EQUAL(0, halfPercentage(0, percentOf));
TEST_ASSERT_EQUAL(10000, halfPercentage(100, percentOf));
TEST_ASSERT_EQUAL(12500, halfPercentage(125, percentOf));
}
void test_maths_halfpercent_U32(void)
{
uint32_t percentOf = 20000000UL;
TEST_ASSERT_EQUAL(5000000UL, halfPercentage(50, percentOf));
TEST_ASSERT_EQUAL(7500000UL, halfPercentage(75, percentOf));
TEST_ASSERT_EQUAL(0, halfPercentage(0, percentOf));
TEST_ASSERT_EQUAL(10000000UL, halfPercentage(100, percentOf));
TEST_ASSERT_EQUAL(12500000UL, halfPercentage(125, percentOf));
}
void test_maths_div100_U8(void)
{
TEST_ASSERT_EQUAL_UINT8(1, div100((uint8_t)100U));
TEST_ASSERT_EQUAL_UINT8(2, div100((uint8_t)200U));
TEST_ASSERT_EQUAL_UINT8(0, div100((uint8_t)0U));
TEST_ASSERT_EQUAL_UINT8(0, div100((uint8_t)50U));
TEST_ASSERT_EQUAL_UINT8(2, div100((uint8_t)250U));
}
void test_maths_div100_U16(void)
{
TEST_ASSERT_EQUAL_UINT16(100, div100((uint16_t)10000U));
TEST_ASSERT_EQUAL_UINT16(400, div100((uint16_t)40000U));
}
void test_maths_div100_U32(void)
{
TEST_ASSERT_EQUAL_UINT32(1000000UL, div100(100000000UL));
TEST_ASSERT_EQUAL_UINT32(2000000UL, div100(200000000UL));
}
void test_maths_div100_S8(void)
{
//Check both the signed and unsigned results
TEST_ASSERT_EQUAL_INT8(1, div100((int8_t)100));
TEST_ASSERT_EQUAL_INT8(0, div100((int8_t)0));
TEST_ASSERT_EQUAL_INT8(0, div100((int8_t)50));
TEST_ASSERT_EQUAL_INT8(-1, div100((int8_t)-100));
TEST_ASSERT_EQUAL_INT8(0, div100((int8_t)-50));
TEST_ASSERT_EQUAL_INT8(-1, div100((int8_t)-120));
}
void test_maths_div100_S16(void)
{
//Check both the signed and unsigned results
TEST_ASSERT_EQUAL_INT16(100, div100((int16_t)10000));
TEST_ASSERT_EQUAL_INT16(0, div100((int16_t)0));
TEST_ASSERT_EQUAL_INT16(0, div100((int16_t)50));
TEST_ASSERT_EQUAL_INT16(-100, div100((int16_t)-10000));
TEST_ASSERT_EQUAL_INT16(0, div100((int16_t)-50));
TEST_ASSERT_EQUAL_INT16(-1, div100((int16_t)-120));
}
void test_maths_div100_S32(void)
{
//Check both the signed and unsigned results
#if defined(__arm__)
TEST_ASSERT_EQUAL_INT32(1000000L, div100((int)100000000L));
TEST_ASSERT_EQUAL_INT32(0, div100((int)0));
TEST_ASSERT_EQUAL_INT32(0, div100((int)50));
TEST_ASSERT_EQUAL_INT32(-1000000L, div100((int)-100000000L));
TEST_ASSERT_EQUAL_INT32(0, div100((int)-50));
TEST_ASSERT_EQUAL_INT32(-1, div100((int)-120));
#else
TEST_ASSERT_EQUAL_INT32(1000000L, div100((int32_t)100000000L));
TEST_ASSERT_EQUAL_INT32(0, div100((int32_t)0));
TEST_ASSERT_EQUAL_INT32(0, div100((int32_t)50));
TEST_ASSERT_EQUAL_INT32(-1000000L, div100((int32_t)-100000000L));
TEST_ASSERT_EQUAL_INT32(0, div100((int32_t)-50));
TEST_ASSERT_EQUAL_INT32(-1, div100((int32_t)-120));
#endif
}
| 4,925
|
C++
|
.cpp
| 132
| 34.886364
| 67
| 0.741253
|
oelprinz-org/BlitzboxBL49sp
| 36
| 12
| 0
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,540,018
|
test_decoders.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/test/test_decoders/test_decoders.cpp
|
#include <Arduino.h>
#include <globals.h>
#include <unity.h>
#include "missing_tooth/missing_tooth.h"
#include "dual_wheel/dual_wheel.h"
#include "renix/renix.h"
#include "Nissan360/Nissan360.h"
#include "FordST170/FordST170.h"
#include "NGC/test_ngc.h"
void setup()
{
pinMode(LED_BUILTIN, OUTPUT);
// NOTE!!! Wait for >2 secs
// if board doesn't support software reset via Serial.DTR/RTS
delay(2000);
UNITY_BEGIN(); // IMPORTANT LINE!
testMissingTooth();
testDualWheel();
testRenix();
testNissan360();
testFordST170();
testNGC();
UNITY_END(); // stop unit testing
}
void loop()
{
// Blink to indicate end of test
digitalWrite(LED_BUILTIN, HIGH);
delay(250);
digitalWrite(LED_BUILTIN, LOW);
delay(250);
}
| 783
|
C++
|
.cpp
| 32
| 21.125
| 65
| 0.685484
|
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,019
|
ForsdST170.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/test/test_decoders/FordST170/ForsdST170.cpp
|
#include <decoders.h>
#include <globals.h>
#include <unity.h>
#include "FordST170.h"
#include "scheduler.h"
#include "schedule_calcs.h"
extern uint16_t ignition1EndTooth;
extern uint16_t ignition2EndTooth;
extern uint16_t ignition3EndTooth;
extern uint16_t ignition4EndTooth;
void test_fordst170_newIgn_12_trig0_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 12/1
//Advance: 10
//triggerAngle=0
triggerSetup_FordST170();
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = 0; //No trigger offset
currentStatus.advance = 10;
calculateIgnitionAngle1(5);
triggerSetEndTeeth_FordST170();
TEST_ASSERT_EQUAL(34, ignition1EndTooth);
//Test again with 0 degrees advance
currentStatus.advance = 0;
calculateIgnitionAngle1(5);
triggerSetEndTeeth_FordST170();
TEST_ASSERT_EQUAL(35, ignition1EndTooth);
//Test again with 35 degrees advance
currentStatus.advance = 35;
calculateIgnitionAngle1(5);
triggerSetEndTeeth_FordST170();
TEST_ASSERT_EQUAL(31, ignition1EndTooth);
}
void test_fordst170_newIgn_12_trig90_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 12/1
//Advance: 10
//triggerAngle=90
triggerSetup_FordST170();
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = 90; //No trigger offset
currentStatus.advance = 35;
calculateIgnitionAngle1(5);
triggerSetEndTeeth_FordST170();
TEST_ASSERT_EQUAL(22, ignition1EndTooth);
}
void test_fordst170_newIgn_12_trig180_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=180
triggerSetup_FordST170();
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = 180; //No trigger offset
currentStatus.advance = 10;
calculateIgnitionAngle1(5);
triggerSetEndTeeth_FordST170();
TEST_ASSERT_EQUAL(16, ignition1EndTooth);
}
void test_fordst170_newIgn_12_trig270_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=270
triggerSetup_FordST170();
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = 270; //No trigger offset
currentStatus.advance = 10;
calculateIgnitionAngle1(5);
triggerSetEndTeeth_FordST170();
TEST_ASSERT_EQUAL(7, ignition1EndTooth);
}
void test_fordst170_newIgn_12_trig360_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=360
triggerSetup_FordST170();
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = 360; //No trigger offset
currentStatus.advance = 10;
calculateIgnitionAngle1(5);
triggerSetEndTeeth_FordST170();
TEST_ASSERT_EQUAL(34, ignition1EndTooth);
}
void test_fordst170_newIgn_12_trigNeg90_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=-90
triggerSetup_FordST170();
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = -90; //No trigger offset
currentStatus.advance = 10;
calculateIgnitionAngle1(5);
triggerSetEndTeeth_FordST170();
TEST_ASSERT_EQUAL(7, ignition1EndTooth);
}
void test_fordst170_newIgn_12_trigNeg180_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=-180
triggerSetup_FordST170();
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = -180; //No trigger offset
currentStatus.advance = 10;
calculateIgnitionAngle1(5);
triggerSetEndTeeth_FordST170();
TEST_ASSERT_EQUAL(16, ignition1EndTooth);
}
void test_fordst170_newIgn_12_trigNeg270_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=-270
triggerSetup_FordST170();
configPage4.sparkMode = IGN_MODE_WASTED;
currentStatus.advance = 10; //Set 10 degrees advance
configPage4.triggerAngle = -270; //No trigger offset
triggerSetEndTeeth_FordST170();
TEST_ASSERT_EQUAL(25, ignition1EndTooth);
}
void test_fordst170_newIgn_12_trigNeg360_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=-360
triggerSetup_FordST170();
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = -360; //No trigger offset
currentStatus.advance = 10;
calculateIgnitionAngle1(5);
triggerSetEndTeeth_FordST170();
TEST_ASSERT_EQUAL(34, ignition1EndTooth);
}
void testFordST170()
{
RUN_TEST(test_fordst170_newIgn_12_trig0_1);
RUN_TEST(test_fordst170_newIgn_12_trig90_1);
RUN_TEST(test_fordst170_newIgn_12_trig180_1);
RUN_TEST(test_fordst170_newIgn_12_trig270_1);
RUN_TEST(test_fordst170_newIgn_12_trig360_1);
RUN_TEST(test_fordst170_newIgn_12_trigNeg90_1);
RUN_TEST(test_fordst170_newIgn_12_trigNeg180_1);
RUN_TEST(test_fordst170_newIgn_12_trigNeg270_1);
RUN_TEST(test_fordst170_newIgn_12_trigNeg360_1);
}
| 5,100
|
C++
|
.cpp
| 157
| 28.152866
| 56
| 0.731139
|
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,020
|
Nissan360.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/test/test_decoders/Nissan360/Nissan360.cpp
|
#include <decoders.h>
#include <globals.h>
#include <unity.h>
#include "Nissan360.h"
#include "scheduler.h"
#include "schedule_calcs.h"
extern uint16_t ignition1EndTooth;
extern uint16_t ignition2EndTooth;
extern uint16_t ignition3EndTooth;
extern uint16_t ignition4EndTooth;
void test_nissan360_newIgn_12_trig0_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 12/1
//Advance: 10
//triggerAngle=0
triggerSetup_Nissan360();
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = 0; //No trigger offset
currentStatus.advance = 10; //Set 10deg advance
calculateIgnitionAngle1(5);
triggerSetEndTeeth_Nissan360();
TEST_ASSERT_EQUAL(171, ignition1EndTooth);
//Test again with 0 degrees advance
currentStatus.advance = 0; //Set 10deg advance
calculateIgnitionAngle1(5);
triggerSetEndTeeth_Nissan360();
TEST_ASSERT_EQUAL(176, ignition1EndTooth);
//Test again with 35 degrees advance
currentStatus.advance = 35; //Set 10deg advance
calculateIgnitionAngle1(5);
triggerSetEndTeeth_Nissan360();
TEST_ASSERT_EQUAL(158, ignition1EndTooth);
}
void test_nissan360_newIgn_12_trig90_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 12/1
//Advance: 10
//triggerAngle=90
triggerSetup_Nissan360();
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = 90; //No trigger offset
currentStatus.advance = 10; //Set 10deg advance
calculateIgnitionAngle1(0);
triggerSetEndTeeth_Nissan360();
TEST_ASSERT_EQUAL(126, ignition1EndTooth);
}
void test_nissan360_newIgn_12_trig180_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=180
triggerSetup_Nissan360();
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = 180; //No trigger offset
currentStatus.advance = 10; //Set 10deg advance
calculateIgnitionAngle1(0);
triggerSetEndTeeth_Nissan360();
TEST_ASSERT_EQUAL(81, ignition1EndTooth);
}
void test_nissan360_newIgn_12_trig270_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=270
triggerSetup_Nissan360();
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = 270; //No trigger offset
currentStatus.advance = 10; //Set 10deg advance
calculateIgnitionAngle1(0);
triggerSetEndTeeth_Nissan360();
TEST_ASSERT_EQUAL(36, ignition1EndTooth);
}
void test_nissan360_newIgn_12_trig360_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=360
triggerSetup_Nissan360();
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = 360; //No trigger offset
currentStatus.advance = 10; //Set 10deg advance
calculateIgnitionAngle1(0);
triggerSetEndTeeth_Nissan360();
TEST_ASSERT_EQUAL(351, ignition1EndTooth);
}
void test_nissan360_newIgn_12_trigNeg90_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=-90
triggerSetup_Nissan360();
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = -90; //No trigger offset
currentStatus.advance = 10; //Set 10deg advance
calculateIgnitionAngle1(0);
triggerSetEndTeeth_Nissan360();
TEST_ASSERT_EQUAL(216, ignition1EndTooth);
}
void test_nissan360_newIgn_12_trigNeg180_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=-180
triggerSetup_Nissan360();
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = -180; //No trigger offset
currentStatus.advance = 10; //Set 10deg advance
calculateIgnitionAngle1(0);
triggerSetEndTeeth_Nissan360();
TEST_ASSERT_EQUAL(261, ignition1EndTooth);
}
void test_nissan360_newIgn_12_trigNeg270_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=-270
triggerSetup_Nissan360();
configPage4.sparkMode = IGN_MODE_WASTED;
currentStatus.advance = 10; //Set 10 degrees advance
configPage4.triggerAngle = -270; //No trigger offset
triggerSetEndTeeth_Nissan360();
TEST_ASSERT_EQUAL(306, ignition1EndTooth);
}
void test_nissan360_newIgn_12_trigNeg360_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=-360
triggerSetup_Nissan360();
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = -360; //No trigger offset
currentStatus.advance = 10; //Set 10deg advance
calculateIgnitionAngle1(0);
triggerSetEndTeeth_Nissan360();
TEST_ASSERT_EQUAL(351, ignition1EndTooth);
}
void testNissan360()
{
RUN_TEST(test_nissan360_newIgn_12_trig0_1);
RUN_TEST(test_nissan360_newIgn_12_trig90_1);
RUN_TEST(test_nissan360_newIgn_12_trig180_1);
RUN_TEST(test_nissan360_newIgn_12_trig270_1);
RUN_TEST(test_nissan360_newIgn_12_trig360_1);
RUN_TEST(test_nissan360_newIgn_12_trigNeg90_1);
RUN_TEST(test_nissan360_newIgn_12_trigNeg180_1);
RUN_TEST(test_nissan360_newIgn_12_trigNeg270_1);
RUN_TEST(test_nissan360_newIgn_12_trigNeg360_1);
}
| 5,316
|
C++
|
.cpp
| 157
| 29.496815
| 56
| 0.731884
|
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,021
|
renix.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/test/test_decoders/renix/renix.cpp
|
#include <decoders.h>
#include <globals.h>
#include <unity.h>
#include "renix.h"
void test_setup_renix44()
{
//Setup a renix 44 tooth wheel
configPage4.TrigPattern = DECODER_RENIX;
configPage2.nCylinders = 4;
triggerSetup_Renix();
}
void test_setup_renix66()
{
//Setup a renix 66 tooth wheel
configPage4.TrigPattern = DECODER_RENIX;
configPage2.nCylinders = 6;
triggerSetup_Renix();
}
//************************************** Begin the new ignition setEndTooth tests **************************************
void test_Renix_newIgn_44_trig0_1()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=0
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 0; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(2, ignition1EndTooth);
}
void test_Renix_newIgn_44_trig90_1()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=90
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 90; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(1, ignition1EndTooth);
}
void test_Renix_newIgn_44_trig180_1()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=180
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 180; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(4, ignition1EndTooth);
}
void test_Renix_newIgn_44_trig270_1()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=270
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 270; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(3, ignition1EndTooth);
}
void test_Renix_newIgn_44_trig360_1()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=360
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 360; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(3, ignition1EndTooth);
}
void test_Renix_newIgn_44_trigNeg90_1()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=-90
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = -90; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(3, ignition1EndTooth);
}
void test_Renix_newIgn_44_trigNeg180_1()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=-180
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = -180; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(4, ignition1EndTooth);
}
void test_Renix_newIgn_44_trigNeg270_1()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=-270
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = -270; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(1, ignition1EndTooth);
}
void test_Renix_newIgn_44_trigNeg360_1()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=-360
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = -360; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(2, ignition1EndTooth);
}
// ******* CHannel 2 *******
void test_Renix_newIgn_44_trig0_2()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=0
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 0; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(4, ignition2EndTooth);
}
void test_Renix_newIgn_44_trig90_2()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=90
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 90; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(3, ignition2EndTooth);
}
void test_Renix_newIgn_44_trig180_2()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=180
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 180; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(3, ignition2EndTooth);
}
void test_Renix_newIgn_44_trig270_2()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=270
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 270; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(2, ignition2EndTooth);
}
void test_Renix_newIgn_44_trig366()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=360
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 360; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(1, ignition2EndTooth);
}
void test_Renix_newIgn_44_trigNeg90_2()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=-90
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = -90; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(1, ignition2EndTooth);
}
void test_Renix_newIgn_44_trigNeg180_2()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=-180
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = -180; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(2, ignition2EndTooth);
}
void test_Renix_newIgn_44_trigNeg270_2()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=-270
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = -270; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(3, ignition2EndTooth);
}
void test_Renix_newIgn_44_trigNeg366()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=-360
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = -360; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(4, ignition2EndTooth);
}
void test_Renix_newIgn_66_trig0_2()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=300
test_setup_renix66();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 0; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(1, ignition2EndTooth);
}
void test_Renix_newIgn_66_trig181_2()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=300
test_setup_renix66();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 181; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(5, ignition2EndTooth);
}
void testRenix()
{
RUN_TEST(test_Renix_newIgn_44_trig0_1);
RUN_TEST(test_Renix_newIgn_44_trig90_1);
RUN_TEST(test_Renix_newIgn_44_trig180_1);
RUN_TEST(test_Renix_newIgn_44_trig270_1);
RUN_TEST(test_Renix_newIgn_44_trig360_1);
RUN_TEST(test_Renix_newIgn_44_trigNeg90_1);
RUN_TEST(test_Renix_newIgn_44_trigNeg180_1);
RUN_TEST(test_Renix_newIgn_44_trigNeg270_1);
RUN_TEST(test_Renix_newIgn_44_trigNeg360_1);
RUN_TEST(test_Renix_newIgn_44_trig0_2);
RUN_TEST(test_Renix_newIgn_44_trig90_2);
RUN_TEST(test_Renix_newIgn_44_trig180_2);
RUN_TEST(test_Renix_newIgn_44_trig270_2);
RUN_TEST(test_Renix_newIgn_44_trig366);
RUN_TEST(test_Renix_newIgn_44_trigNeg90_2);
RUN_TEST(test_Renix_newIgn_44_trigNeg180_2);
RUN_TEST(test_Renix_newIgn_44_trigNeg270_2);
RUN_TEST(test_Renix_newIgn_44_trigNeg366);
RUN_TEST(test_Renix_newIgn_66_trig0_2);
RUN_TEST(test_Renix_newIgn_66_trig181_2);
}
| 9,570
|
C++
|
.cpp
| 283
| 29.508834
| 120
| 0.712052
|
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,022
|
test_ngc.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/test/test_decoders/NGC/test_ngc.cpp
|
#include <decoders.h>
#include <globals.h>
#include <unity.h>
#include "test_ngc.h"
#include "scheduler.h"
#include "schedule_calcs.h"
extern uint16_t ignition1EndTooth;
extern uint16_t ignition2EndTooth;
extern uint16_t ignition3EndTooth;
extern uint16_t ignition4EndTooth;
void test_ngc_newIgn_12_trig0_1()
{
triggerSetup_NGC();
CRANK_ANGLE_MAX_IGN = 360;
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = 0; //No trigger offset
currentStatus.advance = 10; //Set 10deg advance
calculateIgnitionAngle1(5);
triggerSetEndTeeth_NGC();
TEST_ASSERT_EQUAL(34, ignition1EndTooth);
//Test again with 0 degrees advance
currentStatus.advance = 0;
calculateIgnitionAngle1(5);
triggerSetEndTeeth_NGC();
TEST_ASSERT_EQUAL(34, ignition1EndTooth);
//Test again with 35 degrees advance
currentStatus.advance = 35;
calculateIgnitionAngle1(5);
triggerSetEndTeeth_NGC();
TEST_ASSERT_EQUAL(31, ignition1EndTooth);
}
void test_ngc_newIgn_12_trig90_1()
{
triggerSetup_NGC();
CRANK_ANGLE_MAX_IGN = 360;
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = 90;
currentStatus.advance = 10; //Set 10deg advance
calculateIgnitionAngle1(5);
triggerSetEndTeeth_NGC();
TEST_ASSERT_EQUAL(25, ignition1EndTooth);
}
void test_ngc_newIgn_12_trig180_1()
{
triggerSetup_NGC();
CRANK_ANGLE_MAX_IGN = 360;
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = 180;
currentStatus.advance = 10; //Set 10deg advance
calculateIgnitionAngle1(5);
triggerSetEndTeeth_NGC();
TEST_ASSERT_EQUAL(16, ignition1EndTooth);
}
void test_ngc_newIgn_12_trig270_1()
{
triggerSetup_NGC();
CRANK_ANGLE_MAX_IGN = 360;
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = 270;
currentStatus.advance = 10; //Set 10deg advance
calculateIgnitionAngle1(5);
triggerSetEndTeeth_NGC();
TEST_ASSERT_EQUAL(7, ignition1EndTooth);
}
void test_ngc_newIgn_12_trig360_1()
{
triggerSetup_NGC();
CRANK_ANGLE_MAX_IGN = 360;
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = 360;
currentStatus.advance = 10; //Set 10deg advance
calculateIgnitionAngle1(5);
triggerSetEndTeeth_NGC();
TEST_ASSERT_EQUAL(34, ignition1EndTooth);
}
void test_ngc_newIgn_12_trigNeg90_1()
{
triggerSetup_NGC();
CRANK_ANGLE_MAX_IGN = 360;
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = -90;
currentStatus.advance = 10; //Set 10deg advance
calculateIgnitionAngle1(5);
triggerSetEndTeeth_NGC();
TEST_ASSERT_EQUAL(7, ignition1EndTooth);
}
void test_ngc_newIgn_12_trigNeg180_1()
{
triggerSetup_NGC();
CRANK_ANGLE_MAX_IGN = 360;
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = -180;
currentStatus.advance = 10; //Set 10deg advance
calculateIgnitionAngle1(5);
triggerSetEndTeeth_NGC();
TEST_ASSERT_EQUAL(16, ignition1EndTooth);
}
void test_ngc_newIgn_12_trigNeg270_1()
{
triggerSetup_NGC();
CRANK_ANGLE_MAX_IGN = 360;
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = -270;
currentStatus.advance = 10; //Set 10deg advance
calculateIgnitionAngle1(5);
triggerSetEndTeeth_NGC();
TEST_ASSERT_EQUAL(25, ignition1EndTooth);
}
void test_ngc_newIgn_12_trigNeg360_1()
{
triggerSetup_NGC();
CRANK_ANGLE_MAX_IGN = 360;
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = -360;
currentStatus.advance = 10; //Set 10deg advance
calculateIgnitionAngle1(5);
triggerSetEndTeeth_NGC();
TEST_ASSERT_EQUAL(34, ignition1EndTooth);
}
void testNGC()
{
RUN_TEST(test_ngc_newIgn_12_trig0_1);
RUN_TEST(test_ngc_newIgn_12_trig90_1);
RUN_TEST(test_ngc_newIgn_12_trig180_1);
RUN_TEST(test_ngc_newIgn_12_trig270_1);
RUN_TEST(test_ngc_newIgn_12_trig360_1);
RUN_TEST(test_ngc_newIgn_12_trigNeg90_1);
RUN_TEST(test_ngc_newIgn_12_trigNeg180_1);
RUN_TEST(test_ngc_newIgn_12_trigNeg270_1);
RUN_TEST(test_ngc_newIgn_12_trigNeg360_1);
}
| 4,176
|
C++
|
.cpp
| 131
| 27.580153
| 53
| 0.728435
|
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,023
|
test_inj_calcs.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/test/test_schedule_calcs/test_inj_calcs.cpp
|
#include <Arduino.h>
#include <unity.h>
#include "test_calcs_common.h"
#include "schedule_calcs.h"
#include "crankMaths.h"
#define _countof(x) (sizeof(x) / sizeof (x[0]))
// void printFreeRam()
// {
// char msg[128];
// sprintf(msg, "freeRam: %u", freeRam());
// TEST_MESSAGE(msg);
// }
struct inj_test_parameters
{
uint16_t channelAngle; // deg
uint16_t pw; // uS
uint16_t crankAngle; // deg
uint32_t pending; // Expected delay when channel status is PENDING
uint32_t running; // Expected delay when channel status is RUNNING
};
static void test_calc_inj1_timeout(uint16_t pw, uint16_t crankAngle, uint32_t pending, uint32_t running)
{
uint16_t PWdivTimerPerDegree = div(pw, timePerDegree).quot;
memset(&fuelSchedule1, 0, sizeof(fuelSchedule1));
fuelSchedule1.Status = PENDING;
uint16_t startAngle = calculateInjectorStartAngle(PWdivTimerPerDegree, 0);
TEST_ASSERT_EQUAL(pending, calculateInjector1Timeout(startAngle, crankAngle));
fuelSchedule1.Status = RUNNING;
startAngle = calculateInjectorStartAngle( PWdivTimerPerDegree, 0);
TEST_ASSERT_EQUAL(running, calculateInjector1Timeout(startAngle, crankAngle));
}
static void test_calc_injN_timeout(const inj_test_parameters ¶meters)
{
char msg[150];
uint16_t PWdivTimerPerDegree = div(parameters.pw, timePerDegree).quot;
memset(&fuelSchedule2, 0, sizeof(fuelSchedule2));
fuelSchedule2.Status = PENDING;
uint16_t startAngle = calculateInjectorStartAngle(PWdivTimerPerDegree, parameters.channelAngle);
sprintf_P(msg, PSTR("PENDING channelAngle: % " PRIu16 ", pw: % " PRIu16 ", crankAngle: % " PRIu16 ", startAngle: % " PRIu16 ""), parameters.channelAngle, parameters.pw, parameters.crankAngle, startAngle);
TEST_ASSERT_EQUAL_MESSAGE(parameters.pending, calculateInjectorNTimeout(fuelSchedule2, parameters.channelAngle, startAngle, parameters.crankAngle), msg);
fuelSchedule2.Status = RUNNING;
startAngle = calculateInjectorStartAngle( PWdivTimerPerDegree, parameters.channelAngle);
sprintf_P(msg, PSTR("RUNNING channelAngle: % " PRIu16 ", pw: % " PRIu16 ", crankAngle: % " PRIu16 ", startAngle: % " PRIu16 ""), parameters.channelAngle, parameters.pw, parameters.crankAngle, startAngle);
TEST_ASSERT_EQUAL_MESSAGE(parameters.running, calculateInjectorNTimeout(fuelSchedule2, parameters.channelAngle, startAngle, parameters.crankAngle), msg);
}
static void test_calc_inj_timeout(const inj_test_parameters *pStart, const inj_test_parameters *pEnd)
{
inj_test_parameters local;
while (pStart!=pEnd)
{
memcpy_P(&local, pStart, sizeof(local));
test_calc_injN_timeout(local);
++pStart;
}
}
// Separate test for fuel 1 - different code path, same results!
static void test_calc_inj1_timeout()
{
setEngineSpeed(4000, 360);
currentStatus.injAngle = 355;
static const int16_t test_data[][4] PROGMEM = {
// ChannelAngle (deg), PW (uS), Crank (deg), Expected Pending, Expected Running
{ 3000, 0, 11562, 11562 },
{ 3000, 45, 9717, 9717 },
{ 3000, 90, 7872, 7872 },
{ 3000, 135, 6027, 6027 },
{ 3000, 180, 4182, 4182 },
{ 3000, 215, 2747, 2747 },
{ 3000, 270, 492, 492 },
{ 3000, 315, 0, 13407 },
{ 3000, 360, 0, 11562 },
{ 3000, 0, 11562, 11562 },
{ 3000, 45, 9717, 9717 },
{ 3000, 90, 7872, 7872 },
{ 3000, 135, 6027, 6027 },
{ 3000, 180, 4182, 4182 },
{ 3000, 215, 2747, 2747 },
{ 3000, 270, 492, 492 },
{ 3000, 315, 0, 13407 },
{ 3000, 360, 0, 11562 },
};
const int16_t (*pStart)[4] = &test_data[0];
const int16_t (*pEnd)[4] = &test_data[0]+_countof(test_data);
int16_t local[4];
while (pStart!=pEnd)
{
memcpy_P(local, pStart, sizeof(local));
test_calc_inj1_timeout(local[0], local[1], local[2], local[3]);
++pStart;
}
}
static void test_calc_injN_timeout_360()
{
setEngineSpeed(4000, 360);
currentStatus.injAngle = 355;
static const inj_test_parameters test_data[] PROGMEM = {
// ChannelAngle (deg), PW (uS), Crank (deg), Expected Pending (uS), Expected Running (uS)
{ 0, 3000, 0, 11562, 11562 },
{ 0, 3000, 45, 9717, 9717 },
{ 0, 3000, 90, 7872, 7872 },
{ 0, 3000, 135, 6027, 6027 },
{ 0, 3000, 180, 4182, 4182 },
{ 0, 3000, 215, 2747, 2747 },
{ 0, 3000, 270, 492, 492 },
{ 0, 3000, 315, 0, 13407 },
{ 0, 3000, 360, 0, 11562 },
{ 72, 3000, 0, 0, 14514 },
{ 72, 3000, 45, 0, 12669 },
{ 72, 3000, 90, 10824, 10824 },
{ 72, 3000, 135, 8979, 8979 },
{ 72, 3000, 180, 7134, 7134 },
{ 72, 3000, 215, 5699, 5699 },
{ 72, 3000, 270, 3444, 3444 },
{ 72, 3000, 315, 1599, 1599 },
{ 72, 3000, 360, 0, 14514 },
{ 80, 3000, 0, 82, 82 },
{ 80, 3000, 45, 0, 12997 },
{ 80, 3000, 90, 11152, 11152 },
{ 80, 3000, 135, 9307, 9307 },
{ 80, 3000, 180, 7462, 7462 },
{ 80, 3000, 215, 6027, 6027 },
{ 80, 3000, 270, 3772, 3772 },
{ 80, 3000, 315, 1927, 1927 },
{ 80, 3000, 360, 82, 82 },
{ 90, 3000, 0, 492, 492 },
{ 90, 3000, 45, 0, 13407 },
{ 90, 3000, 90, 11562, 11562 },
{ 90, 3000, 135, 9717, 9717 },
{ 90, 3000, 180, 7872, 7872 },
{ 90, 3000, 215, 6437, 6437 },
{ 90, 3000, 270, 4182, 4182 },
{ 90, 3000, 315, 2337, 2337 },
{ 90, 3000, 360, 492, 492 },
{ 144, 3000, 0, 2706, 2706 },
{ 144, 3000, 45, 861, 861 },
{ 144, 3000, 90, 0, 13776 },
{ 144, 3000, 135, 0, 11931 },
{ 144, 3000, 180, 10086, 10086 },
{ 144, 3000, 215, 8651, 8651 },
{ 144, 3000, 270, 6396, 6396 },
{ 144, 3000, 315, 4551, 4551 },
{ 144, 3000, 360, 2706, 2706 },
{ 180, 3000, 0, 4182, 4182 },
{ 180, 3000, 45, 2337, 2337 },
{ 180, 3000, 90, 492, 492 },
{ 180, 3000, 135, 0, 13407 },
{ 180, 3000, 180, 11562, 11562 },
{ 180, 3000, 215, 10127, 10127 },
{ 180, 3000, 270, 7872, 7872 },
{ 180, 3000, 315, 6027, 6027 },
{ 180, 3000, 360, 4182, 4182 },
{ 240, 3000, 0, 6642, 6642 },
{ 240, 3000, 45, 4797, 4797 },
{ 240, 3000, 90, 2952, 2952 },
{ 240, 3000, 135, 1107, 1107 },
{ 240, 3000, 180, 0, 14022 },
{ 240, 3000, 215, 0, 12587 },
{ 240, 3000, 270, 10332, 10332 },
{ 240, 3000, 315, 8487, 8487 },
{ 240, 3000, 360, 6642, 6642 },
{ 270, 3000, 0, 7872, 7872 },
{ 270, 3000, 45, 6027, 6027 },
{ 270, 3000, 90, 4182, 4182 },
{ 270, 3000, 135, 2337, 2337 },
{ 270, 3000, 180, 492, 492 },
{ 270, 3000, 215, 0, 13817 },
{ 270, 3000, 270, 11562, 11562 },
{ 270, 3000, 315, 9717, 9717 },
{ 270, 3000, 360, 7872, 7872 },
{ 360, 3000, 0, 11562, 11562 },
{ 360, 3000, 45, 9717, 9717 },
{ 360, 3000, 90, 7872, 7872 },
{ 360, 3000, 135, 6027, 6027 },
{ 360, 3000, 180, 4182, 4182 },
{ 360, 3000, 215, 2747, 2747 },
{ 360, 3000, 270, 492, 492 },
{ 360, 3000, 315, 0, 13407 },
{ 360, 3000, 360, 11562, 11562 },
};
test_calc_inj_timeout(&test_data[0], &test_data[0]+_countof(test_data));
}
static void test_calc_injN_timeout_720()
{
setEngineSpeed(4000, 720);
currentStatus.injAngle = 355;
static const inj_test_parameters test_data[] PROGMEM = {
// ChannelAngle (deg), PW (uS), Crank (deg), Expected Pending (uS), Expected Running (uS)
{ 0, 3000, 90, 7872, 7872 },
{ 0, 3000, 135, 6027, 6027 },
{ 0, 3000, 180, 4182, 4182 },
{ 0, 3000, 215, 2747, 2747 },
{ 0, 3000, 270, 492, 492 },
{ 0, 3000, 315, 0, 28167 },
{ 0, 3000, 360, 0, 26322 },
{ 72, 3000, 0, 0, 14514 },
{ 72, 3000, 45, 0, 12669 },
{ 72, 3000, 90, 10824, 10824 },
{ 72, 3000, 135, 8979, 8979 },
{ 72, 3000, 180, 7134, 7134 },
{ 72, 3000, 215, 5699, 5699 },
{ 72, 3000, 270, 3444, 3444 },
{ 72, 3000, 315, 1599, 1599 },
{ 72, 3000, 360, 0, 29274 },
{ 80, 3000, 0, 0, 14842 },
{ 80, 3000, 45, 0, 12997 },
{ 80, 3000, 90, 11152, 11152 },
{ 80, 3000, 135, 9307, 9307 },
{ 80, 3000, 180, 7462, 7462 },
{ 80, 3000, 215, 6027, 6027 },
{ 80, 3000, 270, 3772, 3772 },
{ 80, 3000, 315, 1927, 1927 },
{ 80, 3000, 360, 82, 82 },
{ 90, 3000, 0, 0, 15252 },
{ 90, 3000, 45, 0, 13407 },
{ 90, 3000, 90, 11562, 11562 },
{ 90, 3000, 135, 9717, 9717 },
{ 90, 3000, 180, 7872, 7872 },
{ 90, 3000, 215, 6437, 6437 },
{ 90, 3000, 270, 4182, 4182 },
{ 90, 3000, 315, 2337, 2337 },
{ 90, 3000, 360, 492, 492 },
{ 144, 3000, 0, 0, 17466 },
{ 144, 3000, 45, 0, 15621 },
{ 144, 3000, 90, 0, 13776 },
{ 144, 3000, 135, 0, 11931 },
{ 144, 3000, 180, 10086, 10086 },
{ 144, 3000, 215, 8651, 8651 },
{ 144, 3000, 270, 6396, 6396 },
{ 144, 3000, 315, 4551, 4551 },
{ 144, 3000, 360, 2706, 2706 },
{ 180, 3000, 0, 0, 18942 },
{ 180, 3000, 45, 0, 17097 },
{ 180, 3000, 90, 0, 15252 },
{ 180, 3000, 135, 0, 13407 },
{ 180, 3000, 180, 11562, 11562 },
{ 180, 3000, 215, 10127, 10127 },
{ 180, 3000, 270, 7872, 7872 },
{ 180, 3000, 315, 6027, 6027 },
{ 180, 3000, 360, 4182, 4182 },
{ 240, 3000, 0, 0, 21402 },
{ 240, 3000, 45, 0, 19557 },
{ 240, 3000, 90, 0, 17712 },
{ 240, 3000, 135, 0, 15867 },
{ 240, 3000, 180, 0, 14022 },
{ 240, 3000, 215, 0, 12587 },
{ 240, 3000, 270, 10332, 10332 },
{ 240, 3000, 315, 8487, 8487 },
{ 240, 3000, 360, 6642, 6642 },
{ 270, 3000, 0, 0, 22632 },
{ 270, 3000, 45, 0, 20787 },
{ 270, 3000, 90, 0, 18942 },
{ 270, 3000, 135, 0, 17097 },
{ 270, 3000, 180, 0, 15252 },
{ 270, 3000, 215, 0, 13817 },
{ 270, 3000, 270, 11562, 11562 },
{ 270, 3000, 315, 9717, 9717 },
{ 270, 3000, 360, 7872, 7872 },
{ 360, 3000, 0, 0, 26322 },
{ 360, 3000, 45, 0, 24477 },
{ 360, 3000, 90, 0, 22632 },
{ 360, 3000, 135, 0, 20787 },
{ 360, 3000, 180, 0, 18942 },
{ 360, 3000, 215, 0, 17507 },
{ 360, 3000, 270, 0, 15252 },
{ 360, 3000, 315, 0, 13407 },
{ 360, 3000, 360, 11562, 11562 },
{ 480, 3000, 0, 1722, 1722 },
{ 480, 3000, 45, 0, 29397 },
{ 480, 3000, 90, 0, 27552 },
{ 480, 3000, 135, 0, 25707 },
{ 480, 3000, 180, 0, 23862 },
{ 480, 3000, 215, 0, 22427 },
{ 480, 3000, 270, 0, 20172 },
{ 480, 3000, 315, 0, 18327 },
{ 480, 3000, 360, 0, 16482 },
{ 540, 3000, 0, 4182, 4182 },
{ 540, 3000, 45, 2337, 2337 },
{ 540, 3000, 90, 492, 492 },
{ 540, 3000, 135, 0, 28167 },
{ 540, 3000, 180, 0, 26322 },
{ 540, 3000, 215, 0, 24887 },
{ 540, 3000, 270, 0, 22632 },
{ 540, 3000, 315, 0, 20787 },
{ 540, 3000, 360, 0, 18942 },
{ 600, 3000, 0, 6642, 6642 },
{ 600, 3000, 45, 4797, 4797 },
{ 600, 3000, 90, 2952, 2952 },
{ 600, 3000, 135, 1107, 1107 },
{ 600, 3000, 180, 0, 28782 },
{ 600, 3000, 215, 0, 27347 },
{ 600, 3000, 270, 0, 25092 },
{ 600, 3000, 315, 0, 23247 },
{ 600, 3000, 360, 0, 21402 },
{ 630, 3000, 0, 7872, 7872 },
{ 630, 3000, 45, 6027, 6027 },
{ 630, 3000, 90, 4182, 4182 },
{ 630, 3000, 135, 2337, 2337 },
{ 630, 3000, 180, 492, 492 },
{ 630, 3000, 215, 0, 28577 },
{ 630, 3000, 270, 0, 26322 },
{ 630, 3000, 315, 0, 24477 },
{ 630, 3000, 360, 0, 22632 },
};
test_calc_inj_timeout(&test_data[0], &test_data[0]+_countof(test_data));
}
//
void test_calc_inj_timeout(void)
{
RUN_TEST(test_calc_inj1_timeout);
RUN_TEST(test_calc_injN_timeout_360);
RUN_TEST(test_calc_injN_timeout_720);
}
| 12,380
|
C++
|
.cpp
| 312
| 32.205128
| 208
| 0.530282
|
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,024
|
test_ign_calcs.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/test/test_schedule_calcs/test_ign_calcs.cpp
|
#include <Arduino.h>
#include <unity.h>
#include "test_calcs_common.h"
#include "schedule_calcs.h"
#include "crankMaths.h"
#define _countof(x) (sizeof(x) / sizeof (x[0]))
extern volatile uint16_t degreesPeruSx2048;
constexpr uint16_t DWELL_TIME_MS = 4;
uint16_t dwellAngle;
void setEngineSpeed(uint16_t rpm, int16_t max_crank) {
timePerDegreex16 = ldiv( 2666656L, rpm).quot; //The use of a x16 value gives accuracy down to 0.1 of a degree and can provide noticeably better timing results on low resolution triggers
timePerDegree = timePerDegreex16 / 16;
degreesPeruSx2048 = 2048 / timePerDegree;
degreesPeruSx32768 = 524288L / timePerDegreex16;
revolutionTime = (60L*1000000L) / rpm;
CRANK_ANGLE_MAX_IGN = max_crank;
CRANK_ANGLE_MAX_INJ = max_crank;
dwellAngle = timeToAngle(DWELL_TIME_MS*1000UL, CRANKMATH_METHOD_INTERVAL_REV);
}
struct ign_test_parameters
{
uint16_t channelAngle; // deg
int8_t advanceAngle; // deg
uint16_t crankAngle; // deg
uint32_t pending; // Expected delay when channel status is PENDING
uint32_t running; // Expected delay when channel status is RUNNING
int16_t expectedStartAngle; // Expected start angle
int16_t expectedEndAngle; // Expected end angle
};
void test_calc_ign1_timeout(const ign_test_parameters &test_params)
{
memset(&ignitionSchedule1, 0, sizeof(ignitionSchedule1));
ignitionSchedule1.Status = PENDING;
calculateIgnitionAngle1(dwellAngle);
TEST_ASSERT_EQUAL(test_params.expectedStartAngle, ignition1StartAngle);
TEST_ASSERT_EQUAL(test_params.expectedEndAngle, ignition1EndAngle);
TEST_ASSERT_EQUAL(test_params.pending, calculateIgnition1Timeout(test_params.crankAngle));
ignitionSchedule1.Status = RUNNING;
calculateIgnitionAngle1(dwellAngle);
TEST_ASSERT_EQUAL(test_params.running, calculateIgnition1Timeout(test_params.crankAngle));
}
void test_calc_ignN_timeout(Schedule &schedule, const ign_test_parameters &test_params, const int &startAngle, void (*pEndAngleCalc)(int), const int16_t &endAngle)
{
char msg[150];
memset(&schedule, 0, sizeof(schedule));
schedule.Status = PENDING;
pEndAngleCalc(dwellAngle);
TEST_ASSERT_EQUAL_MESSAGE(test_params.expectedStartAngle, startAngle, "startAngle");
TEST_ASSERT_EQUAL_MESSAGE(test_params.expectedEndAngle, endAngle, "endAngle");
sprintf_P(msg, PSTR("PENDING advanceAngle: %" PRIi8 ", channelAngle: % " PRIu16 ", crankAngle: %" PRIu16 ", endAngle: %" PRIi16), test_params.advanceAngle, test_params.channelAngle, test_params.crankAngle, endAngle);
TEST_ASSERT_EQUAL_MESSAGE(test_params.pending, calculateIgnitionNTimeout(schedule, startAngle, test_params.channelAngle, test_params.crankAngle), msg);
schedule.Status = RUNNING;
pEndAngleCalc(dwellAngle);
sprintf_P(msg, PSTR("RUNNING advanceAngle: %" PRIi8 ", channelAngle: % " PRIu16 ", crankAngle: %" PRIu16 ", endAngle: %" PRIi16), test_params.advanceAngle, test_params.channelAngle, test_params.crankAngle, endAngle);
TEST_ASSERT_EQUAL_MESSAGE(test_params.running, calculateIgnitionNTimeout(schedule, startAngle, test_params.channelAngle, test_params.crankAngle), msg);
}
//test_params.channelAngle, local.crankAngle, local.pending, local.running, local.endAngle
void test_calc_ign_timeout(const ign_test_parameters &test_params)
{
channel2IgnDegrees = test_params.channelAngle;
test_calc_ignN_timeout(ignitionSchedule2, test_params, ignition2StartAngle, &calculateIgnitionAngle2, ignition2EndAngle);
channel3IgnDegrees = test_params.channelAngle;
test_calc_ignN_timeout(ignitionSchedule3, test_params, ignition3StartAngle, &calculateIgnitionAngle3, ignition3EndAngle);
channel4IgnDegrees = test_params.channelAngle;
test_calc_ignN_timeout(ignitionSchedule4, test_params, ignition4StartAngle, &calculateIgnitionAngle4, ignition4EndAngle);
#if (IGN_CHANNELS >= 5)
channel5IgnDegrees = test_params.channelAngle;
test_calc_ignN_timeout(ignitionSchedule5, test_params, ignition5StartAngle, &calculateIgnitionAngle5, ignition5EndAngle);
#endif
#if (IGN_CHANNELS >= 6)
channel6IgnDegrees = test_params.channelAngle;
test_calc_ignN_timeout(ignitionSchedule6, test_params, ignition6StartAngle, &calculateIgnitionAngle6, ignition6EndAngle);
#endif
#if (IGN_CHANNELS >= 7)
channel7IgnDegrees = test_params.channelAngle;
test_calc_ignN_timeout(ignitionSchedule7, test_params, ignition7StartAngle, &calculateIgnitionAngle7, ignition7EndAngle);
#endif
#if (IGN_CHANNELS >= 8)
channel8IgnDegrees = test_params.channelAngle;
test_calc_ignN_timeout(ignitionSchedule8, test_params, ignition8StartAngle, &calculateIgnitionAngle8, ignition8EndAngle);
#endif
}
void test_calc_ign_timeout(const ign_test_parameters *pStart, const ign_test_parameters *pEnd)
{
ign_test_parameters local;
while (pStart!=pEnd)
{
memcpy_P(&local, pStart, sizeof(local));
currentStatus.advance = local.advanceAngle;
test_calc_ign_timeout(local);
++pStart;
}
}
// Separate test for ign 1 - different code path, same results!
void test_calc_ign1_timeout()
{
setEngineSpeed(4000, 360);
static const ign_test_parameters test_data[] PROGMEM = {
// ChannelAngle (deg), Advance, Crank, Expected Pending, Expected Running
{ 0, -40, 0, 12666, 12666, 304, 40 },
{ 0, -40, 45, 10791, 10791, 304, 40 },
{ 0, -40, 90, 8916, 8916, 304, 40 },
{ 0, -40, 135, 7041, 7041, 304, 40 },
{ 0, -40, 180, 5166, 5166, 304, 40 },
{ 0, -40, 215, 3708, 3708, 304, 40 },
{ 0, -40, 270, 1416, 1416, 304, 40 },
{ 0, -40, 315, 0, 14541, 304, 40 },
{ 0, -40, 360, 0, 12666, 304, 40 },
{ 0, 0, 0, 11000, 11000, 264, 360 },
{ 0, 0, 45, 9125, 9125, 264, 360 },
{ 0, 0, 90, 7250, 7250, 264, 360 },
{ 0, 0, 135, 5375, 5375, 264, 360 },
{ 0, 0, 180, 3500, 3500, 264, 360 },
{ 0, 0, 215, 2041, 2041, 264, 360 },
{ 0, 0, 270, 0, 14750, 264, 360 },
{ 0, 0, 315, 0, 12875, 264, 360 },
{ 0, 0, 360, 0, 11000, 264, 360 },
{ 0, 40, 0, 9333, 9333, 224, 320 },
{ 0, 40, 45, 7458, 7458, 224, 320 },
{ 0, 40, 90, 5583, 5583, 224, 320 },
{ 0, 40, 135, 3708, 3708, 224, 320 },
{ 0, 40, 180, 1833, 1833, 224, 320 },
{ 0, 40, 215, 375, 375, 224, 320 },
{ 0, 40, 270, 0, 13083, 224, 320 },
{ 0, 40, 315, 0, 11208, 224, 320 },
{ 0, 40, 360, 0, 9333, 224, 320 },
};
const ign_test_parameters *pStart = &test_data[0];
const ign_test_parameters *pEnd = pStart + +_countof(test_data);
ign_test_parameters local;
while (pStart!=pEnd)
{
memcpy_P(&local, pStart, sizeof(local));
currentStatus.advance = local.advanceAngle;
test_calc_ign1_timeout(local);
++pStart;
}
}
void test_calc_ign_timeout_360()
{
setEngineSpeed(4000, 360);
static const ign_test_parameters test_data[] PROGMEM = {
// ChannelAngle (deg), Advance, Crank, Expected Pending, Expected Running
{ 0, -40, 0, 12666, 12666, 304, 40 },
{ 0, -40, 45, 10791, 10791, 304, 40 },
{ 0, -40, 90, 8916, 8916, 304, 40 },
{ 0, -40, 135, 7041, 7041, 304, 40 },
{ 0, -40, 180, 5166, 5166, 304, 40 },
{ 0, -40, 215, 3708, 3708, 304, 40 },
{ 0, -40, 270, 1416, 1416, 304, 40 },
{ 0, -40, 315, 0, 14541, 304, 40 },
{ 0, -40, 360, 0, 12666, 304, 40 },
{ 0, 0, 0, 11000, 11000, 264, 0 },
{ 0, 0, 45, 9125, 9125, 264, 0 },
{ 0, 0, 90, 7250, 7250, 264, 0 },
{ 0, 0, 135, 5375, 5375, 264, 0 },
{ 0, 0, 180, 3500, 3500, 264, 0 },
{ 0, 0, 215, 2041, 2041, 264, 0 },
{ 0, 0, 270, 0, 14750, 264, 0 },
{ 0, 0, 315, 0, 12875, 264, 0 },
{ 0, 0, 360, 0, 11000, 264, 0 },
{ 0, 40, 0, 9333, 9333, 224, -40 },
{ 0, 40, 45, 7458, 7458, 224, -40 },
{ 0, 40, 90, 5583, 5583, 224, -40 },
{ 0, 40, 135, 3708, 3708, 224, -40 },
{ 0, 40, 180, 1833, 1833, 224, -40 },
{ 0, 40, 215, 375, 375, 224, -40 },
{ 0, 40, 270, 0, 13083, 224, -40 },
{ 0, 40, 315, 0, 11208, 224, -40 },
{ 0, 40, 360, 0, 9333, 224, -40 },
{ 72, -40, 0, 666, 666, 16, 112 },
{ 72, -40, 45, 0, 13791, 16, 112 },
{ 72, -40, 90, 11916, 11916, 16, 112 },
{ 72, -40, 135, 10041, 10041, 16, 112 },
{ 72, -40, 180, 8166, 8166, 16, 112 },
{ 72, -40, 215, 6708, 6708, 16, 112 },
{ 72, -40, 270, 4416, 4416, 16, 112 },
{ 72, -40, 315, 2541, 2541, 16, 112 },
{ 72, -40, 360, 666, 666, 16, 112 },
{ 72, 0, 0, 0, 14000, 336, 72 },
{ 72, 0, 45, 0, 12125, 336, 72 },
{ 72, 0, 90, 10250, 10250, 336, 72 },
{ 72, 0, 135, 8375, 8375, 336, 72 },
{ 72, 0, 180, 6500, 6500, 336, 72 },
{ 72, 0, 215, 5041, 5041, 336, 72 },
{ 72, 0, 270, 2750, 2750, 336, 72 },
{ 72, 0, 315, 875, 875, 336, 72 },
{ 72, 0, 360, 0, 14000, 336, 72 },
{ 72, 40, 0, 0, 12333, 296, 32 },
{ 72, 40, 45, 0, 10458, 296, 32 },
{ 72, 40, 90, 8583, 8583, 296, 32 },
{ 72, 40, 135, 6708, 6708, 296, 32 },
{ 72, 40, 180, 4833, 4833, 296, 32 },
{ 72, 40, 215, 3375, 3375, 296, 32 },
{ 72, 40, 270, 1083, 1083, 296, 32 },
{ 72, 40, 315, 0, 14208, 296, 32 },
{ 72, 40, 360, 0, 12333, 296, 32 },
{ 90, -40, 0, 1416, 1416, 34, 130 },
{ 90, -40, 45, 0, 14541, 34, 130 },
{ 90, -40, 90, 12666, 12666, 34, 130 },
{ 90, -40, 135, 10791, 10791, 34, 130 },
{ 90, -40, 180, 8916, 8916, 34, 130 },
{ 90, -40, 215, 7458, 7458, 34, 130 },
{ 90, -40, 270, 5166, 5166, 34, 130 },
{ 90, -40, 315, 3291, 3291, 34, 130 },
{ 90, -40, 360, 1416, 1416, 34, 130 },
{ 90, 0, 0, 0, 14750, 354, 90 },
{ 90, 0, 45, 0, 12875, 354, 90 },
{ 90, 0, 90, 11000, 11000, 354, 90 },
{ 90, 0, 135, 9125, 9125, 354, 90 },
{ 90, 0, 180, 7250, 7250, 354, 90 },
{ 90, 0, 215, 5791, 5791, 354, 90 },
{ 90, 0, 270, 3500, 3500, 354, 90 },
{ 90, 0, 315, 1625, 1625, 354, 90 },
{ 90, 0, 360, 0, 14750, 354, 90 },
{ 90, 40, 0, 0, 13083, 314, 50 },
{ 90, 40, 45, 0, 11208, 314, 50 },
{ 90, 40, 90, 9333, 9333, 314, 50 },
{ 90, 40, 135, 7458, 7458, 314, 50 },
{ 90, 40, 180, 5583, 5583, 314, 50 },
{ 90, 40, 215, 4125, 4125, 314, 50 },
{ 90, 40, 270, 1833, 1833, 314, 50 },
{ 90, 40, 315, 0, 14958, 314, 50 },
{ 90, 40, 360, 0, 13083, 314, 50 },
{ 144, -40, 0, 3666, 3666, 88, 184 },
{ 144, -40, 45, 1791, 1791, 88, 184 },
{ 144, -40, 90, 0, 14916, 88, 184 },
{ 144, -40, 135, 0, 13041, 88, 184 },
{ 144, -40, 180, 11166, 11166, 88, 184 },
{ 144, -40, 215, 9708, 9708, 88, 184 },
{ 144, -40, 270, 7416, 7416, 88, 184 },
{ 144, -40, 315, 5541, 5541, 88, 184 },
{ 144, -40, 360, 3666, 3666, 88, 184 },
{ 144, 0, 0, 2000, 2000, 48, 144 },
{ 144, 0, 45, 125, 125, 48, 144 },
{ 144, 0, 90, 0, 13250, 48, 144 },
{ 144, 0, 135, 0, 11375, 48, 144 },
{ 144, 0, 180, 9500, 9500, 48, 144 },
{ 144, 0, 215, 8041, 8041, 48, 144 },
{ 144, 0, 270, 5750, 5750, 48, 144 },
{ 144, 0, 315, 3875, 3875, 48, 144 },
{ 144, 0, 360, 2000, 2000, 48, 144 },
{ 144, 40, 0, 333, 333, 8, 104 },
{ 144, 40, 45, 0, 13458, 8, 104 },
{ 144, 40, 90, 0, 11583, 8, 104 },
{ 144, 40, 135, 0, 9708, 8, 104 },
{ 144, 40, 180, 7833, 7833, 8, 104 },
{ 144, 40, 215, 6375, 6375, 8, 104 },
{ 144, 40, 270, 4083, 4083, 8, 104 },
{ 144, 40, 315, 2208, 2208, 8, 104 },
{ 144, 40, 360, 333, 333, 8, 104 },
{ 180, -40, 0, 5166, 5166, 124, 220 },
{ 180, -40, 45, 3291, 3291, 124, 220 },
{ 180, -40, 90, 1416, 1416, 124, 220 },
{ 180, -40, 135, 0, 14541, 124, 220 },
{ 180, -40, 180, 12666, 12666, 124, 220 },
{ 180, -40, 215, 11208, 11208, 124, 220 },
{ 180, -40, 270, 8916, 8916, 124, 220 },
{ 180, -40, 315, 7041, 7041, 124, 220 },
{ 180, -40, 360, 5166, 5166, 124, 220 },
{ 180, 0, 0, 3500, 3500, 84, 180 },
{ 180, 0, 45, 1625, 1625, 84, 180 },
{ 180, 0, 90, 0, 14750, 84, 180 },
{ 180, 0, 135, 0, 12875, 84, 180 },
{ 180, 0, 180, 11000, 11000, 84, 180 },
{ 180, 0, 215, 9541, 9541, 84, 180 },
{ 180, 0, 270, 7250, 7250, 84, 180 },
{ 180, 0, 315, 5375, 5375, 84, 180 },
{ 180, 0, 360, 3500, 3500, 84, 180 },
{ 180, 40, 0, 1833, 1833, 44, 140 },
{ 180, 40, 45, 0, 14958, 44, 140 },
{ 180, 40, 90, 0, 13083, 44, 140 },
{ 180, 40, 135, 0, 11208, 44, 140 },
{ 180, 40, 180, 9333, 9333, 44, 140 },
{ 180, 40, 215, 7875, 7875, 44, 140 },
{ 180, 40, 270, 5583, 5583, 44, 140 },
{ 180, 40, 315, 3708, 3708, 44, 140 },
{ 180, 40, 360, 1833, 1833, 44, 140 },
{ 270, -40, 0, 8916, 8916, 214, 310 },
{ 270, -40, 45, 7041, 7041, 214, 310 },
{ 270, -40, 90, 5166, 5166, 214, 310 },
{ 270, -40, 135, 3291, 3291, 214, 310 },
{ 270, -40, 180, 1416, 1416, 214, 310 },
{ 270, -40, 215, 0, 14958, 214, 310 },
{ 270, -40, 270, 12666, 12666, 214, 310 },
{ 270, -40, 315, 10791, 10791, 214, 310 },
{ 270, -40, 360, 8916, 8916, 214, 310 },
{ 270, 0, 0, 7250, 7250, 174, 270 },
{ 270, 0, 45, 5375, 5375, 174, 270 },
{ 270, 0, 90, 3500, 3500, 174, 270 },
{ 270, 0, 135, 1625, 1625, 174, 270 },
{ 270, 0, 180, 0, 14750, 174, 270 },
{ 270, 0, 215, 0, 13291, 174, 270 },
{ 270, 0, 270, 11000, 11000, 174, 270 },
{ 270, 0, 315, 9125, 9125, 174, 270 },
{ 270, 0, 360, 7250, 7250, 174, 270 },
{ 270, 40, 0, 5583, 5583, 134, 230 },
{ 270, 40, 45, 3708, 3708, 134, 230 },
{ 270, 40, 90, 1833, 1833, 134, 230 },
{ 270, 40, 135, 0, 14958, 134, 230 },
{ 270, 40, 180, 0, 13083, 134, 230 },
{ 270, 40, 215, 0, 11625, 134, 230 },
{ 270, 40, 270, 9333, 9333, 134, 230 },
{ 270, 40, 315, 7458, 7458, 134, 230 },
{ 270, 40, 360, 5583, 5583, 134, 230 },
{ 360, -40, 0, 12666, 12666, 304, 40 },
{ 360, -40, 45, 10791, 10791, 304, 40 },
{ 360, -40, 90, 8916, 8916, 304, 40 },
{ 360, -40, 135, 7041, 7041, 304, 40 },
{ 360, -40, 180, 5166, 5166, 304, 40 },
{ 360, -40, 215, 3708, 3708, 304, 40 },
{ 360, -40, 270, 1416, 1416, 304, 40 },
{ 360, -40, 315, 0, 14541, 304, 40 },
{ 360, -40, 360, 12666, 12666, 304, 40 },
{ 360, 0, 0, 11000, 11000, 264, 360 },
{ 360, 0, 45, 9125, 9125, 264, 360 },
{ 360, 0, 90, 7250, 7250, 264, 360 },
{ 360, 0, 135, 5375, 5375, 264, 360 },
{ 360, 0, 180, 3500, 3500, 264, 360 },
{ 360, 0, 215, 2041, 2041, 264, 360 },
{ 360, 0, 270, 0, 14750, 264, 360 },
{ 360, 0, 315, 0, 12875, 264, 360 },
{ 360, 0, 360, 11000, 11000, 264, 360 },
{ 360, 40, 0, 9333, 9333, 224, 320 },
{ 360, 40, 45, 7458, 7458, 224, 320 },
{ 360, 40, 90, 5583, 5583, 224, 320 },
{ 360, 40, 135, 3708, 3708, 224, 320 },
{ 360, 40, 180, 1833, 1833, 224, 320 },
{ 360, 40, 215, 375, 375, 224, 320 },
{ 360, 40, 270, 0, 13083, 224, 320 },
{ 360, 40, 315, 0, 11208, 224, 320 },
{ 360, 40, 360, 9333, 9333, 224, 320 },
};
test_calc_ign_timeout(&test_data[0], &test_data[0]+_countof(test_data));
}
void test_calc_ign_timeout_720()
{
setEngineSpeed(4000, 720);
static const ign_test_parameters test_data[] PROGMEM = {
// ChannelAngle (deg), Advance, Crank, Expected Pending, Expected Running
{ 0, -40, 0, 27666, 27666, 664, 40 },
{ 0, -40, 45, 25791, 25791, 664, 40 },
{ 0, -40, 90, 23916, 23916, 664, 40 },
{ 0, -40, 135, 22041, 22041, 664, 40 },
{ 0, -40, 180, 20166, 20166, 664, 40 },
{ 0, -40, 215, 18708, 18708, 664, 40 },
{ 0, -40, 270, 16416, 16416, 664, 40 },
{ 0, -40, 315, 14541, 14541, 664, 40 },
{ 0, -40, 360, 12666, 12666, 664, 40 },
{ 0, 0, 0, 26000, 26000, 624, 0 },
{ 0, 0, 45, 24125, 24125, 624, 0 },
{ 0, 0, 90, 22250, 22250, 624, 0 },
{ 0, 0, 135, 20375, 20375, 624, 0 },
{ 0, 0, 180, 18500, 18500, 624, 0 },
{ 0, 0, 215, 17041, 17041, 624, 0 },
{ 0, 0, 270, 14750, 14750, 624, 0 },
{ 0, 0, 315, 12875, 12875, 624, 0 },
{ 0, 0, 360, 11000, 11000, 624, 0 },
{ 0, 40, 0, 24333, 24333, 584, -40 },
{ 0, 40, 45, 22458, 22458, 584, -40 },
{ 0, 40, 90, 20583, 20583, 584, -40 },
{ 0, 40, 135, 18708, 18708, 584, -40 },
{ 0, 40, 180, 16833, 16833, 584, -40 },
{ 0, 40, 215, 15375, 15375, 584, -40 },
{ 0, 40, 270, 13083, 13083, 584, -40 },
{ 0, 40, 315, 11208, 11208, 584, -40 },
{ 0, 40, 360, 9333, 9333, 584, -40 },
{ 72, -40, 0, 666, 666, 16, 112 },
{ 72, -40, 45, 0, 28791, 16, 112 },
{ 72, -40, 90, 26916, 26916, 16, 112 },
{ 72, -40, 135, 25041, 25041, 16, 112 },
{ 72, -40, 180, 23166, 23166, 16, 112 },
{ 72, -40, 215, 21708, 21708, 16, 112 },
{ 72, -40, 270, 19416, 19416, 16, 112 },
{ 72, -40, 315, 17541, 17541, 16, 112 },
{ 72, -40, 360, 15666, 15666, 16, 112 },
{ 72, 0, 0, 0, 29000, 696, 72 },
{ 72, 0, 45, 0, 27125, 696, 72 },
{ 72, 0, 90, 25250, 25250, 696, 72 },
{ 72, 0, 135, 23375, 23375, 696, 72 },
{ 72, 0, 180, 21500, 21500, 696, 72 },
{ 72, 0, 215, 20041, 20041, 696, 72 },
{ 72, 0, 270, 17750, 17750, 696, 72 },
{ 72, 0, 315, 15875, 15875, 696, 72 },
{ 72, 0, 360, 14000, 14000, 696, 72 },
{ 72, 40, 0, 0, 27333, 656, 32 },
{ 72, 40, 45, 0, 25458, 656, 32 },
{ 72, 40, 90, 23583, 23583, 656, 32 },
{ 72, 40, 135, 21708, 21708, 656, 32 },
{ 72, 40, 180, 19833, 19833, 656, 32 },
{ 72, 40, 215, 18375, 18375, 656, 32 },
{ 72, 40, 270, 16083, 16083, 656, 32 },
{ 72, 40, 315, 14208, 14208, 656, 32 },
{ 72, 40, 360, 12333, 12333, 656, 32 },
{ 90, -40, 0, 1416, 1416, 34, 130 },
{ 90, -40, 45, 0, 29541, 34, 130 },
{ 90, -40, 90, 27666, 27666, 34, 130 },
{ 90, -40, 135, 25791, 25791, 34, 130 },
{ 90, -40, 180, 23916, 23916, 34, 130 },
{ 90, -40, 215, 22458, 22458, 34, 130 },
{ 90, -40, 270, 20166, 20166, 34, 130 },
{ 90, -40, 315, 18291, 18291, 34, 130 },
{ 90, -40, 360, 16416, 16416, 34, 130 },
{ 90, 0, 0, 0, 29750, 714, 90 },
{ 90, 0, 45, 0, 27875, 714, 90 },
{ 90, 0, 90, 26000, 26000, 714, 90 },
{ 90, 0, 135, 24125, 24125, 714, 90 },
{ 90, 0, 180, 22250, 22250, 714, 90 },
{ 90, 0, 215, 20791, 20791, 714, 90 },
{ 90, 0, 270, 18500, 18500, 714, 90 },
{ 90, 0, 315, 16625, 16625, 714, 90 },
{ 90, 0, 360, 14750, 14750, 714, 90 },
{ 90, 40, 0, 0, 28083, 674, 50 },
{ 90, 40, 45, 0, 26208, 674, 50 },
{ 90, 40, 90, 24333, 24333, 674, 50 },
{ 90, 40, 135, 22458, 22458, 674, 50 },
{ 90, 40, 180, 20583, 20583, 674, 50 },
{ 90, 40, 215, 19125, 19125, 674, 50 },
{ 90, 40, 270, 16833, 16833, 674, 50 },
{ 90, 40, 315, 14958, 14958, 674, 50 },
{ 90, 40, 360, 13083, 13083, 674, 50 },
{ 144, -40, 0, 3666, 3666, 88, 184 },
{ 144, -40, 45, 1791, 1791, 88, 184 },
{ 144, -40, 90, 0, 29916, 88, 184 },
{ 144, -40, 135, 0, 28041, 88, 184 },
{ 144, -40, 180, 26166, 26166, 88, 184 },
{ 144, -40, 215, 24708, 24708, 88, 184 },
{ 144, -40, 270, 22416, 22416, 88, 184 },
{ 144, -40, 315, 20541, 20541, 88, 184 },
{ 144, -40, 360, 18666, 18666, 88, 184 },
{ 144, 0, 0, 2000, 2000, 48, 144 },
{ 144, 0, 45, 125, 125, 48, 144 },
{ 144, 0, 90, 0, 28250, 48, 144 },
{ 144, 0, 135, 0, 26375, 48, 144 },
{ 144, 0, 180, 24500, 24500, 48, 144 },
{ 144, 0, 215, 23041, 23041, 48, 144 },
{ 144, 0, 270, 20750, 20750, 48, 144 },
{ 144, 0, 315, 18875, 18875, 48, 144 },
{ 144, 0, 360, 17000, 17000, 48, 144 },
{ 144, 40, 0, 333, 333, 8, 104 },
{ 144, 40, 45, 0, 28458, 8, 104 },
{ 144, 40, 90, 0, 26583, 8, 104 },
{ 144, 40, 135, 0, 24708, 8, 104 },
{ 144, 40, 180, 22833, 22833, 8, 104 },
{ 144, 40, 215, 21375, 21375, 8, 104 },
{ 144, 40, 270, 19083, 19083, 8, 104 },
{ 144, 40, 315, 17208, 17208, 8, 104 },
{ 144, 40, 360, 15333, 15333, 8, 104 },
{ 180, -40, 0, 5166, 5166, 124, 220 },
{ 180, -40, 45, 3291, 3291, 124, 220 },
{ 180, -40, 90, 1416, 1416, 124, 220 },
{ 180, -40, 135, 0, 29541, 124, 220 },
{ 180, -40, 180, 27666, 27666, 124, 220 },
{ 180, -40, 215, 26208, 26208, 124, 220 },
{ 180, -40, 270, 23916, 23916, 124, 220 },
{ 180, -40, 315, 22041, 22041, 124, 220 },
{ 180, -40, 360, 20166, 20166, 124, 220 },
{ 180, 0, 0, 3500, 3500, 84, 180 },
{ 180, 0, 45, 1625, 1625, 84, 180 },
{ 180, 0, 90, 0, 29750, 84, 180 },
{ 180, 0, 135, 0, 27875, 84, 180 },
{ 180, 0, 180, 26000, 26000, 84, 180 },
{ 180, 0, 215, 24541, 24541, 84, 180 },
{ 180, 0, 270, 22250, 22250, 84, 180 },
{ 180, 0, 315, 20375, 20375, 84, 180 },
{ 180, 0, 360, 18500, 18500, 84, 180 },
{ 180, 40, 0, 1833, 1833, 44, 140 },
{ 180, 40, 45, 0, 29958, 44, 140 },
{ 180, 40, 90, 0, 28083, 44, 140 },
{ 180, 40, 135, 0, 26208, 44, 140 },
{ 180, 40, 180, 24333, 24333, 44, 140 },
{ 180, 40, 215, 22875, 22875, 44, 140 },
{ 180, 40, 270, 20583, 20583, 44, 140 },
{ 180, 40, 315, 18708, 18708, 44, 140 },
{ 180, 40, 360, 16833, 16833, 44, 140 },
{ 270, -40, 0, 8916, 8916, 214, 310 },
{ 270, -40, 45, 7041, 7041, 214, 310 },
{ 270, -40, 90, 5166, 5166, 214, 310 },
{ 270, -40, 135, 3291, 3291, 214, 310 },
{ 270, -40, 180, 1416, 1416, 214, 310 },
{ 270, -40, 215, 0, 29958, 214, 310 },
{ 270, -40, 270, 27666, 27666, 214, 310 },
{ 270, -40, 315, 25791, 25791, 214, 310 },
{ 270, -40, 360, 23916, 23916, 214, 310 },
{ 270, 0, 0, 7250, 7250, 174, 270 },
{ 270, 0, 45, 5375, 5375, 174, 270 },
{ 270, 0, 90, 3500, 3500, 174, 270 },
{ 270, 0, 135, 1625, 1625, 174, 270 },
{ 270, 0, 180, 0, 29750, 174, 270 },
{ 270, 0, 215, 0, 28291, 174, 270 },
{ 270, 0, 270, 26000, 26000, 174, 270 },
{ 270, 0, 315, 24125, 24125, 174, 270 },
{ 270, 0, 360, 22250, 22250, 174, 270 },
{ 270, 40, 0, 5583, 5583, 134, 230 },
{ 270, 40, 45, 3708, 3708, 134, 230 },
{ 270, 40, 90, 1833, 1833, 134, 230 },
{ 270, 40, 135, 0, 29958, 134, 230 },
{ 270, 40, 180, 0, 28083, 134, 230 },
{ 270, 40, 215, 0, 26625, 134, 230 },
{ 270, 40, 270, 24333, 24333, 134, 230 },
{ 270, 40, 315, 22458, 22458, 134, 230 },
{ 270, 40, 360, 20583, 20583, 134, 230 },
{ 360, -40, 0, 12666, 12666, 304, 400 },
{ 360, -40, 45, 10791, 10791, 304, 400 },
{ 360, -40, 90, 8916, 8916, 304, 400 },
{ 360, -40, 135, 7041, 7041, 304, 400 },
{ 360, -40, 180, 5166, 5166, 304, 400 },
{ 360, -40, 215, 3708, 3708, 304, 400 },
{ 360, -40, 270, 1416, 1416, 304, 400 },
{ 360, -40, 315, 0, 29541, 304, 400 },
{ 360, -40, 360, 27666, 27666, 304, 400 },
{ 360, 0, 0, 11000, 11000, 264, 360 },
{ 360, 0, 45, 9125, 9125, 264, 360 },
{ 360, 0, 90, 7250, 7250, 264, 360 },
{ 360, 0, 135, 5375, 5375, 264, 360 },
{ 360, 0, 180, 3500, 3500, 264, 360 },
{ 360, 0, 215, 2041, 2041, 264, 360 },
{ 360, 0, 270, 0, 29750, 264, 360 },
{ 360, 0, 315, 0, 27875, 264, 360 },
{ 360, 0, 360, 26000, 26000, 264, 360 },
{ 360, 40, 0, 9333, 9333, 224, 320 },
{ 360, 40, 45, 7458, 7458, 224, 320 },
{ 360, 40, 90, 5583, 5583, 224, 320 },
{ 360, 40, 135, 3708, 3708, 224, 320 },
{ 360, 40, 180, 1833, 1833, 224, 320 },
{ 360, 40, 215, 375, 375, 224, 320 },
{ 360, 40, 270, 0, 28083, 224, 320 },
{ 360, 40, 315, 0, 26208, 224, 320 },
{ 360, 40, 360, 24333, 24333, 224, 320 },
{ 432, -40, 0, 15666, 15666, 376, 472 },
{ 432, -40, 45, 13791, 13791, 376, 472 },
{ 432, -40, 90, 11916, 11916, 376, 472 },
{ 432, -40, 135, 10041, 10041, 376, 472 },
{ 432, -40, 180, 8166, 8166, 376, 472 },
{ 432, -40, 215, 6708, 6708, 376, 472 },
{ 432, -40, 270, 4416, 4416, 376, 472 },
{ 432, -40, 315, 2541, 2541, 376, 472 },
{ 432, -40, 360, 666, 666, 376, 472 },
{ 432, 0, 0, 14000, 14000, 336, 432 },
{ 432, 0, 45, 12125, 12125, 336, 432 },
{ 432, 0, 90, 10250, 10250, 336, 432 },
{ 432, 0, 135, 8375, 8375, 336, 432 },
{ 432, 0, 180, 6500, 6500, 336, 432 },
{ 432, 0, 215, 5041, 5041, 336, 432 },
{ 432, 0, 270, 2750, 2750, 336, 432 },
{ 432, 0, 315, 875, 875, 336, 432 },
{ 432, 0, 360, 0, 29000, 336, 432 },
{ 432, 40, 0, 12333, 12333, 296, 392 },
{ 432, 40, 45, 10458, 10458, 296, 392 },
{ 432, 40, 90, 8583, 8583, 296, 392 },
{ 432, 40, 135, 6708, 6708, 296, 392 },
{ 432, 40, 180, 4833, 4833, 296, 392 },
{ 432, 40, 215, 3375, 3375, 296, 392 },
{ 432, 40, 270, 1083, 1083, 296, 392 },
{ 432, 40, 315, 0, 29208, 296, 392 },
{ 432, 40, 360, 0, 27333, 296, 392 },
{ 576, -40, 0, 21666, 21666, 520, 616 },
{ 576, -40, 45, 19791, 19791, 520, 616 },
{ 576, -40, 90, 17916, 17916, 520, 616 },
{ 576, -40, 135, 16041, 16041, 520, 616 },
{ 576, -40, 180, 14166, 14166, 520, 616 },
{ 576, -40, 215, 12708, 12708, 520, 616 },
{ 576, -40, 270, 10416, 10416, 520, 616 },
{ 576, -40, 315, 8541, 8541, 520, 616 },
{ 576, -40, 360, 6666, 6666, 520, 616 },
{ 576, 0, 0, 20000, 20000, 480, 576 },
{ 576, 0, 45, 18125, 18125, 480, 576 },
{ 576, 0, 90, 16250, 16250, 480, 576 },
{ 576, 0, 135, 14375, 14375, 480, 576 },
{ 576, 0, 180, 12500, 12500, 480, 576 },
{ 576, 0, 215, 11041, 11041, 480, 576 },
{ 576, 0, 270, 8750, 8750, 480, 576 },
{ 576, 0, 315, 6875, 6875, 480, 576 },
{ 576, 0, 360, 5000, 5000, 480, 576 },
{ 576, 40, 0, 18333, 18333, 440, 536 },
{ 576, 40, 45, 16458, 16458, 440, 536 },
{ 576, 40, 90, 14583, 14583, 440, 536 },
{ 576, 40, 135, 12708, 12708, 440, 536 },
{ 576, 40, 180, 10833, 10833, 440, 536 },
{ 576, 40, 215, 9375, 9375, 440, 536 },
{ 576, 40, 270, 7083, 7083, 440, 536 },
{ 576, 40, 315, 5208, 5208, 440, 536 },
{ 576, 40, 360, 3333, 3333, 440, 536 },
{ 600, -40, 0, 22666, 22666, 544, 640 },
{ 600, -40, 45, 20791, 20791, 544, 640 },
{ 600, -40, 90, 18916, 18916, 544, 640 },
{ 600, -40, 135, 17041, 17041, 544, 640 },
{ 600, -40, 180, 15166, 15166, 544, 640 },
{ 600, -40, 215, 13708, 13708, 544, 640 },
{ 600, -40, 270, 11416, 11416, 544, 640 },
{ 600, -40, 315, 9541, 9541, 544, 640 },
{ 600, -40, 360, 7666, 7666, 544, 640 },
{ 600, 0, 0, 21000, 21000, 504, 600 },
{ 600, 0, 45, 19125, 19125, 504, 600 },
{ 600, 0, 90, 17250, 17250, 504, 600 },
{ 600, 0, 135, 15375, 15375, 504, 600 },
{ 600, 0, 180, 13500, 13500, 504, 600 },
{ 600, 0, 215, 12041, 12041, 504, 600 },
{ 600, 0, 270, 9750, 9750, 504, 600 },
{ 600, 0, 315, 7875, 7875, 504, 600 },
{ 600, 0, 360, 6000, 6000, 504, 600 },
{ 600, 40, 0, 19333, 19333, 464, 560 },
{ 600, 40, 45, 17458, 17458, 464, 560 },
{ 600, 40, 90, 15583, 15583, 464, 560 },
{ 600, 40, 135, 13708, 13708, 464, 560 },
{ 600, 40, 180, 11833, 11833, 464, 560 },
{ 600, 40, 215, 10375, 10375, 464, 560 },
{ 600, 40, 270, 8083, 8083, 464, 560 },
{ 600, 40, 315, 6208, 6208, 464, 560 },
{ 600, 40, 360, 4333, 4333, 464, 560 },
};
test_calc_ign_timeout(&test_data[0], &test_data[0]+_countof(test_data));
}
void test_rotary_channel3_calcs(void)
{
setEngineSpeed(4000, 360);
static const int16_t test_data[][5] PROGMEM = {
{ -40, 5, 0, -40, 315 },
{ -40, 95, 0, -40, 225 },
{ -40, 185, 0, -40, 135 },
{ -40, 275, 0, -40, 45 },
{ -40, 355, 0, -40, -35 },
{ -40, 5, 40, 0, 355 },
{ -40, 95, 40, 0, 265 },
{ -40, 185, 40, 0, 175 },
{ -40, 275, 40, 0, 85 },
{ -40, 355, 40, 0, 5 },
{ 0, 5, 0, 0, 355 },
{ 0, 95, 0, 0, 265 },
{ 0, 185, 0, 0, 175 },
{ 0, 275, 0, 0, 85 },
{ 0, 355, 0, 0, 5 },
{ 0, 5, 40, 40, 35 },
{ 0, 95, 40, 40, 305 },
{ 0, 185, 40, 40, 215 },
{ 0, 275, 40, 40, 125 },
{ 0, 355, 40, 40, 45 },
{ 40, 5, 0, 40, 35 },
{ 40, 95, 0, 40, 305 },
{ 40, 185, 0, 40, 215 },
{ 40, 275, 0, 40, 125 },
{ 40, 355, 0, 40, 45 },
{ 40, 5, 40, 80, 75 },
{ 40, 95, 40, 80, 345 },
{ 40, 185, 40, 80, 255 },
{ 40, 275, 40, 80, 165 },
{ 40, 355, 40, 80, 85 },
};
const int16_t (*pStart)[5] = &test_data[0];
const int16_t (*pEnd)[5] = &test_data[0]+_countof(test_data);
channel1IgnDegrees = 0;
int16_t local[5];
while (pStart!=pEnd)
{
memcpy_P(local, pStart, sizeof(local));
ignition1EndAngle = local[0];
calculateIgnitionAngle3(local[1], local[2]);
TEST_ASSERT_EQUAL(local[3], ignition3EndAngle);
TEST_ASSERT_EQUAL(local[4], ignition3StartAngle);
++pStart;
}
}
void test_rotary_channel4_calcs(void)
{
setEngineSpeed(4000, 360);
static const int16_t test_data[][5] PROGMEM = {
{ -40, 5, 0, -40, 315 },
{ -40, 95, 0, -40, 225 },
{ -40, 185, 0, -40, 135 },
{ -40, 275, 0, -40, 45 },
{ -40, 355, 0, -40, -35 },
{ -40, 5, 40, 0, 355 },
{ -40, 95, 40, 0, 265 },
{ -40, 185, 40, 0, 175 },
{ -40, 275, 40, 0, 85 },
{ -40, 355, 40, 0, 5 },
{ 0, 5, 0, 0, 355 },
{ 0, 95, 0, 0, 265 },
{ 0, 185, 0, 0, 175 },
{ 0, 275, 0, 0, 85 },
{ 0, 355, 0, 0, 5 },
{ 0, 5, 40, 40, 35 },
{ 0, 95, 40, 40, 305 },
{ 0, 185, 40, 40, 215 },
{ 0, 275, 40, 40, 125 },
{ 0, 355, 40, 40, 45 },
{ 40, 5, 0, 40, 35 },
{ 40, 95, 0, 40, 305 },
{ 40, 185, 0, 40, 215 },
{ 40, 275, 0, 40, 125 },
{ 40, 355, 0, 40, 45 },
{ 40, 5, 40, 80, 75 },
{ 40, 95, 40, 80, 345 },
{ 40, 185, 40, 80, 255 },
{ 40, 275, 40, 80, 165 },
{ 40, 355, 40, 80, 85 },
};
const int16_t (*pStart)[5] = &test_data[0];
const int16_t (*pEnd)[5] = &test_data[0]+_countof(test_data);
channel1IgnDegrees = 0;
int16_t local[5];
while (pStart!=pEnd)
{
memcpy_P(local, pStart, sizeof(local));
ignition2EndAngle = local[0];
calculateIgnitionAngle4(local[1], local[2]);
TEST_ASSERT_EQUAL(local[3], ignition4EndAngle);
TEST_ASSERT_EQUAL(local[4], ignition4StartAngle);
++pStart;
}
}
void test_calc_ign_timeout(void)
{
RUN_TEST(test_calc_ign1_timeout);
RUN_TEST(test_calc_ign_timeout_360);
RUN_TEST(test_calc_ign_timeout_720);
RUN_TEST(test_rotary_channel3_calcs);
RUN_TEST(test_rotary_channel4_calcs);
}
| 32,414
|
C++
|
.cpp
| 719
| 37.119611
| 220
| 0.504866
|
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,025
|
test_schedule_calcs.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/test/test_schedule_calcs/test_schedule_calcs.cpp
|
#include <Arduino.h>
#include <unity.h>
#include <init.h>
extern void test_calc_ign_timeout();
extern void test_calc_inj_timeout();
void setup()
{
pinMode(LED_BUILTIN, OUTPUT);
delay(2000);
UNITY_BEGIN(); // start unit testing
test_calc_ign_timeout();
test_calc_inj_timeout();
UNITY_END(); // stop unit testing
}
void loop()
{
digitalWrite(LED_BUILTIN, HIGH);
delay(250);
digitalWrite(LED_BUILTIN, LOW);
delay(250);
}
| 454
|
C++
|
.cpp
| 21
| 18.904762
| 38
| 0.698824
|
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,026
|
test_corrections.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/test/test_fuel/test_corrections.cpp
|
#include <globals.h>
#include <corrections.h>
#include <unity.h>
#include "test_corrections.h"
void testCorrections()
{
test_corrections_WUE();
test_corrections_dfco();
test_corrections_TAE(); //TPS based accel enrichment corrections
/*
RUN_TEST(test_corrections_cranking); //Not written yet
RUN_TEST(test_corrections_ASE); //Not written yet
RUN_TEST(test_corrections_floodclear); //Not written yet
RUN_TEST(test_corrections_closedloop); //Not written yet
RUN_TEST(test_corrections_flex); //Not written yet
RUN_TEST(test_corrections_bat); //Not written yet
RUN_TEST(test_corrections_iatdensity); //Not written yet
RUN_TEST(test_corrections_baro); //Not written yet
RUN_TEST(test_corrections_launch); //Not written yet
RUN_TEST(test_corrections_dfco); //Not written yet
*/
}
void test_corrections_WUE_active(void)
{
//Check for WUE being active
currentStatus.coolant = 0;
((uint8_t*)WUETable.axisX)[9] = 120 + CALIBRATION_TEMPERATURE_OFFSET; //Set a WUE end value of 120
correctionWUE();
TEST_ASSERT_BIT_HIGH(BIT_ENGINE_WARMUP, currentStatus.engine);
}
void test_corrections_WUE_inactive(void)
{
//Check for WUE being inactive due to the temp being too high
currentStatus.coolant = 200;
((uint8_t*)WUETable.axisX)[9] = 120 + CALIBRATION_TEMPERATURE_OFFSET; //Set a WUE end value of 120
correctionWUE();
TEST_ASSERT_BIT_LOW(BIT_ENGINE_WARMUP, currentStatus.engine);
}
void test_corrections_WUE_inactive_value(void)
{
//Check for WUE being set to the final row of the WUE curve if the coolant is above the max WUE temp
currentStatus.coolant = 200;
((uint8_t*)WUETable.axisX)[9] = 100;
((uint8_t*)WUETable.values)[9] = 123; //Use a value other than 100 here to ensure we are using the non-default value
//Force invalidate the cache
WUETable.cacheTime = currentStatus.secl - 1;
TEST_ASSERT_EQUAL(123, correctionWUE() );
}
void test_corrections_WUE_active_value(void)
{
//Check for WUE being made active and returning a correct interpolated value
currentStatus.coolant = 80;
//Set some fake values in the table axis. Target value will fall between points 6 and 7
((uint8_t*)WUETable.axisX)[0] = 0;
((uint8_t*)WUETable.axisX)[1] = 0;
((uint8_t*)WUETable.axisX)[2] = 0;
((uint8_t*)WUETable.axisX)[3] = 0;
((uint8_t*)WUETable.axisX)[4] = 0;
((uint8_t*)WUETable.axisX)[5] = 0;
((uint8_t*)WUETable.axisX)[6] = 70 + CALIBRATION_TEMPERATURE_OFFSET;
((uint8_t*)WUETable.axisX)[7] = 90 + CALIBRATION_TEMPERATURE_OFFSET;
((uint8_t*)WUETable.axisX)[8] = 100 + CALIBRATION_TEMPERATURE_OFFSET;
((uint8_t*)WUETable.axisX)[9] = 120 + CALIBRATION_TEMPERATURE_OFFSET;
((uint8_t*)WUETable.values)[6] = 120;
((uint8_t*)WUETable.values)[7] = 130;
//Force invalidate the cache
WUETable.cacheTime = currentStatus.secl - 1;
//Value should be midway between 120 and 130 = 125
TEST_ASSERT_EQUAL(125, correctionWUE() );
}
void test_corrections_WUE(void)
{
RUN_TEST(test_corrections_WUE_active);
RUN_TEST(test_corrections_WUE_inactive);
RUN_TEST(test_corrections_WUE_active_value);
RUN_TEST(test_corrections_WUE_inactive_value);
}
void test_corrections_cranking(void)
{
}
void test_corrections_ASE(void)
{
}
void test_corrections_floodclear(void)
{
}
void test_corrections_closedloop(void)
{
}
void test_corrections_flex(void)
{
}
void test_corrections_bat(void)
{
}
void test_corrections_iatdensity(void)
{
}
void test_corrections_baro(void)
{
}
void test_corrections_launch(void)
{
}
void setup_DFCO_on()
{
//Sets all the required conditions to have the DFCO be active
configPage2.dfcoEnabled = 1; //Ensure DFCO option is turned on
currentStatus.RPM = 4000; //Set the current simulated RPM to a level above the DFCO rpm threshold
currentStatus.TPS = 0; //Set the simulated TPS to 0
currentStatus.coolant = 80;
configPage4.dfcoRPM = 150; //DFCO enable RPM = 1500
configPage4.dfcoTPSThresh = 1;
configPage4.dfcoHyster = 50;
configPage2.dfcoMinCLT = 40; //Actually 0 with offset
configPage2.dfcoDelay = 10;
dfcoTaper = 1;
correctionDFCO();
dfcoTaper = 20;
}
//**********************************************************************************************************************
void test_corrections_dfco_on(void)
{
//Test under ideal conditions that DFCO goes active
setup_DFCO_on();
TEST_ASSERT_TRUE(correctionDFCO());
}
void test_corrections_dfco_off_RPM()
{
//Test that DFCO comes on and then goes off when the RPM drops below threshold
setup_DFCO_on();
TEST_ASSERT_TRUE(correctionDFCO()); //Make sure DFCO is on initially
currentStatus.RPM = 1000; //Set the current simulated RPM below the threshold + hyster
TEST_ASSERT_FALSE(correctionDFCO()); //Test DFCO is now off
}
void test_corrections_dfco_off_TPS()
{
//Test that DFCO comes on and then goes off when the TPS goes above the required threshold (ie not off throttle)
setup_DFCO_on();
TEST_ASSERT_TRUE(correctionDFCO()); //Make sure DFCO is on initially
currentStatus.TPS = 10; //Set the current simulated TPS to be above the threshold
TEST_ASSERT_FALSE(correctionDFCO()); //Test DFCO is now off
}
void test_corrections_dfco_off_delay()
{
//Test that DFCO comes will not activate if there has not been a long enough delay
//The steup function below simulates a 2 second delay
setup_DFCO_on();
//Set the threshold to be 2.5 seconds, above the simulated delay of 2s
configPage2.dfcoDelay = 250;
TEST_ASSERT_FALSE(correctionDFCO()); //Make sure DFCO does not come on
}
void test_corrections_dfco()
{
RUN_TEST(test_corrections_dfco_on);
RUN_TEST(test_corrections_dfco_off_RPM);
RUN_TEST(test_corrections_dfco_off_TPS);
RUN_TEST(test_corrections_dfco_off_delay);
}
//**********************************************************************************************************************
//Setup a basic TAE enrichment curve, threshold etc that are common to all tests. Specifica values maybe updated in each individual test
void test_corrections_TAE_setup()
{
configPage2.aeMode = AE_MODE_TPS; //Set AE to TPS
configPage4.taeValues[0] = 70;
configPage4.taeValues[1] = 103;
configPage4.taeValues[2] = 124;
configPage4.taeValues[3] = 136;
//Note: These values are divided by 10
configPage4.taeBins[0] = 0;
configPage4.taeBins[1] = 8;
configPage4.taeBins[2] = 22;
configPage4.taeBins[3] = 97;
configPage2.taeThresh = 0;
configPage2.taeMinChange = 0;
//Divided by 100
configPage2.aeTaperMin = 10; //1000
configPage2.aeTaperMax = 50; //5000
//Set the coolant to be above the warmup AE taper
configPage2.aeColdTaperMax = 60;
configPage2.aeColdTaperMin = 0;
currentStatus.coolant = (int)(configPage2.aeColdTaperMax - CALIBRATION_TEMPERATURE_OFFSET) + 1;
BIT_CLEAR(currentStatus.engine, BIT_ENGINE_ACC); //Make sure AE is turned off
BIT_CLEAR(currentStatus.engine, BIT_ENGINE_DCC); //Make sure AE is turned off
}
void test_corrections_TAE_no_rpm_taper()
{
//Disable the taper
currentStatus.RPM = 2000;
configPage2.aeTaperMin = 50; //5000
configPage2.aeTaperMax = 60; //6000
currentStatus.TPSlast = 0;
currentStatus.TPS = 50; //25% actual value
uint16_t accelValue = correctionAccel(); //Run the AE calcs
TEST_ASSERT_EQUAL(750, currentStatus.tpsDOT); //DOT is 750%/s (25 * 30)
TEST_ASSERT_EQUAL((100+132), accelValue);
TEST_ASSERT_TRUE(BIT_CHECK(currentStatus.engine, BIT_ENGINE_ACC)); //Confirm AE is flagged on
}
void test_corrections_TAE_50pc_rpm_taper()
{
//RPM is 50% of the way through the taper range
currentStatus.RPM = 3000;
configPage2.aeTaperMin = 10; //1000
configPage2.aeTaperMax = 50; //5000
currentStatus.TPSlast = 0;
currentStatus.TPS = 50; //25% actual value
uint16_t accelValue = correctionAccel(); //Run the AE calcs
TEST_ASSERT_EQUAL(750, currentStatus.tpsDOT); //DOT is 750%/s (25 * 30)
TEST_ASSERT_EQUAL((100+66), accelValue);
TEST_ASSERT_TRUE(BIT_CHECK(currentStatus.engine, BIT_ENGINE_ACC)); //Confirm AE is flagged on
}
void test_corrections_TAE_110pc_rpm_taper()
{
//RPM is 110% of the way through the taper range, which should result in no additional AE
currentStatus.RPM = 5400;
configPage2.aeTaperMin = 10; //1000
configPage2.aeTaperMax = 50; //5000
currentStatus.TPSlast = 0;
currentStatus.TPS = 50; //25% actual value
uint16_t accelValue = correctionAccel(); //Run the AE calcs
TEST_ASSERT_EQUAL(750, currentStatus.tpsDOT); //DOT is 750%/s (25 * 30)
TEST_ASSERT_EQUAL(100, accelValue); //Should be no AE as we're above the RPM taper end point
TEST_ASSERT_TRUE(BIT_CHECK(currentStatus.engine, BIT_ENGINE_ACC)); //Confirm AE is flagged on
}
void test_corrections_TAE_under_threshold()
{
//RPM is 50% of the way through the taper range, but TPS value will be below threshold
currentStatus.RPM = 3000;
configPage2.aeTaperMin = 10; //1000
configPage2.aeTaperMax = 50; //5000
currentStatus.TPSlast = 0;
currentStatus.TPS = 6; //3% actual value. TPSDot should be 90%/s
configPage2.taeThresh = 100; //Above the reading of 90%/s
uint16_t accelValue = correctionAccel(); //Run the AE calcs
TEST_ASSERT_EQUAL(90, currentStatus.tpsDOT); //DOT is 90%/s (3% * 30)
TEST_ASSERT_EQUAL(100, accelValue); //Should be no AE as we're above the RPM taper end point
TEST_ASSERT_FALSE(BIT_CHECK(currentStatus.engine, BIT_ENGINE_ACC)); //Confirm AE is flagged off
}
void test_corrections_TAE_50pc_warmup_taper()
{
//Disable the RPM taper
currentStatus.RPM = 2000;
configPage2.aeTaperMin = 50; //5000
configPage2.aeTaperMax = 60; //6000
currentStatus.TPSlast = 0;
currentStatus.TPS = 50; //25% actual value
//Set a cold % of 50% increase
configPage2.aeColdPct = 150;
configPage2.aeColdTaperMax = 60 + CALIBRATION_TEMPERATURE_OFFSET;
configPage2.aeColdTaperMin = 0 + CALIBRATION_TEMPERATURE_OFFSET;
//Set the coolant to be 50% of the way through the warmup range
currentStatus.coolant = 30;
uint16_t accelValue = correctionAccel(); //Run the AE calcs
TEST_ASSERT_EQUAL(750, currentStatus.tpsDOT); //DOT is 750%/s (25 * 30)
TEST_ASSERT_EQUAL((100+165), accelValue); //Total AE should be 132 + (50% * 50%) = 132 * 1.25 = 165
TEST_ASSERT_TRUE(BIT_CHECK(currentStatus.engine, BIT_ENGINE_ACC)); //Confirm AE is flagged on
}
void test_corrections_TAE()
{
test_corrections_TAE_setup();
RUN_TEST(test_corrections_TAE_no_rpm_taper);
BIT_CLEAR(currentStatus.engine, BIT_ENGINE_ACC); //Flag must be cleared between tests
RUN_TEST(test_corrections_TAE_50pc_rpm_taper);
BIT_CLEAR(currentStatus.engine, BIT_ENGINE_ACC); //Flag must be cleared between tests
RUN_TEST(test_corrections_TAE_110pc_rpm_taper);
BIT_CLEAR(currentStatus.engine, BIT_ENGINE_ACC); //Flag must be cleared between tests
RUN_TEST(test_corrections_TAE_under_threshold);
BIT_CLEAR(currentStatus.engine, BIT_ENGINE_ACC); //Flag must be cleared between tests
RUN_TEST(test_corrections_TAE_50pc_warmup_taper);
}
| 10,892
|
C++
|
.cpp
| 270
| 37.811111
| 136
| 0.730099
|
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,027
|
test_accuracy_duration.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/test/test_schedules/test_accuracy_duration.cpp
|
#include <Arduino.h>
#include <unity.h>
#include "scheduler.h"
#define TIMEOUT 1000
#define DURATION 1000
#define DELTA 20
static uint32_t start_time, end_time;
static void startCallback(void) { start_time = micros(); }
static void endCallback(void) { end_time = micros(); }
void test_accuracy_duration_inj1(void)
{
initialiseSchedulers();
setFuelSchedule1(TIMEOUT, DURATION);
while(fuelSchedule1.Status == PENDING) /*Wait*/ ;
start_time = micros();
while(fuelSchedule1.Status == RUNNING) /*Wait*/ ;
end_time = micros();
TEST_ASSERT_UINT32_WITHIN(DELTA, DURATION, end_time - start_time);
}
void test_accuracy_duration_inj2(void)
{
initialiseSchedulers();
setFuelSchedule2(TIMEOUT, DURATION);
while(fuelSchedule2.Status == PENDING) /*Wait*/ ;
start_time = micros();
while(fuelSchedule2.Status == RUNNING) /*Wait*/ ;
end_time = micros();
TEST_ASSERT_UINT32_WITHIN(DELTA, DURATION, end_time - start_time);
}
void test_accuracy_duration_inj3(void)
{
initialiseSchedulers();
setFuelSchedule3(TIMEOUT, DURATION);
while(fuelSchedule3.Status == PENDING) /*Wait*/ ;
start_time = micros();
while(fuelSchedule3.Status == RUNNING) /*Wait*/ ;
end_time = micros();
TEST_ASSERT_UINT32_WITHIN(DELTA, DURATION, end_time - start_time);
}
void test_accuracy_duration_inj4(void)
{
initialiseSchedulers();
setFuelSchedule4(TIMEOUT, DURATION);
while(fuelSchedule4.Status == PENDING) /*Wait*/ ;
start_time = micros();
while(fuelSchedule4.Status == RUNNING) /*Wait*/ ;
end_time = micros();
TEST_ASSERT_UINT32_WITHIN(DELTA, DURATION, end_time - start_time);
}
#if INJ_CHANNELS >= 5
void test_accuracy_duration_inj5(void)
{
initialiseSchedulers();
setFuelSchedule5(TIMEOUT, DURATION);
while(fuelSchedule5.Status == PENDING) /*Wait*/ ;
start_time = micros();
while(fuelSchedule5.Status == RUNNING) /*Wait*/ ;
end_time = micros();
TEST_ASSERT_UINT32_WITHIN(DELTA, DURATION, end_time - start_time);
}
#endif
#if INJ_CHANNELS >= 6
void test_accuracy_duration_inj6(void)
{
initialiseSchedulers();
setFuelSchedule6(TIMEOUT, DURATION);
while(fuelSchedule6.Status == PENDING) /*Wait*/ ;
start_time = micros();
while(fuelSchedule6.Status == RUNNING) /*Wait*/ ;
end_time = micros();
TEST_ASSERT_UINT32_WITHIN(DELTA, DURATION, end_time - start_time);
}
#endif
#if INJ_CHANNELS >= 7
void test_accuracy_duration_inj7(void)
{
initialiseSchedulers();
setFuelSchedule7(TIMEOUT, DURATION);
while(fuelSchedule7.Status == PENDING) /*Wait*/ ;
start_time = micros();
while(fuelSchedule7.Status == RUNNING) /*Wait*/ ;
end_time = micros();
TEST_ASSERT_UINT32_WITHIN(DELTA, DURATION, end_time - start_time);
}
#endif
#if INJ_CHANNELS >= 8
void test_accuracy_duration_inj8(void)
{
initialiseSchedulers();
setFuelSchedule8(TIMEOUT, DURATION);
while(fuelSchedule8.Status == PENDING) /*Wait*/ ;
start_time = micros();
while(fuelSchedule8.Status == RUNNING) /*Wait*/ ;
end_time = micros();
TEST_ASSERT_UINT32_WITHIN(DELTA, DURATION, end_time - start_time);
}
#endif
void test_accuracy_duration_ign1(void)
{
initialiseSchedulers();
setIgnitionSchedule1(startCallback, TIMEOUT, DURATION, endCallback);
while( (ignitionSchedule1.Status == PENDING) || (ignitionSchedule1.Status == RUNNING) ) /*Wait*/ ;
TEST_ASSERT_UINT32_WITHIN(DELTA, DURATION, end_time - start_time);
}
void test_accuracy_duration_ign2(void)
{
initialiseSchedulers();
setIgnitionSchedule2(startCallback, TIMEOUT, DURATION, endCallback);
while( (ignitionSchedule2.Status == PENDING) || (ignitionSchedule2.Status == RUNNING) ) /*Wait*/ ;
TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time);
}
void test_accuracy_duration_ign3(void)
{
initialiseSchedulers();
setIgnitionSchedule3(startCallback, TIMEOUT, DURATION, endCallback);
while( (ignitionSchedule3.Status == PENDING) || (ignitionSchedule3.Status == RUNNING) ) /*Wait*/ ;
TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time);
}
void test_accuracy_duration_ign4(void)
{
initialiseSchedulers();
setIgnitionSchedule4(startCallback, TIMEOUT, DURATION, endCallback);
while( (ignitionSchedule4.Status == PENDING) || (ignitionSchedule4.Status == RUNNING) ) /*Wait*/ ;
TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time);
}
void test_accuracy_duration_ign5(void)
{
#if IGN_CHANNELS >= 5
initialiseSchedulers();
setIgnitionSchedule5(startCallback, TIMEOUT, DURATION, endCallback);
while( (ignitionSchedule5.Status == PENDING) || (ignitionSchedule5.Status == RUNNING) ) /*Wait*/ ;
TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time);
#endif
}
#if INJ_CHANNELS >= 6
void test_accuracy_duration_ign6(void)
{
initialiseSchedulers();
setIgnitionSchedule6(startCallback, TIMEOUT, DURATION, endCallback);
while( (ignitionSchedule6.Status == PENDING) || (ignitionSchedule6.Status == RUNNING) ) /*Wait*/ ;
TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time);
}
#endif
#if INJ_CHANNELS >= 7
void test_accuracy_duration_ign7(void)
{
initialiseSchedulers();
setIgnitionSchedule7(startCallback, TIMEOUT, DURATION, endCallback);
while( (ignitionSchedule7.Status == PENDING) || (ignitionSchedule7.Status == RUNNING) ) /*Wait*/ ;
TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time);
}
#endif
#if INJ_CHANNELS >= 8
void test_accuracy_duration_ign8(void)
{
initialiseSchedulers();
setIgnitionSchedule8(startCallback, TIMEOUT, DURATION, endCallback);
while( (ignitionSchedule8.Status == PENDING) || (ignitionSchedule8.Status == RUNNING) ) /*Wait*/ ;
TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time);
}
#endif
void test_accuracy_duration(void)
{
RUN_TEST(test_accuracy_duration_inj1);
RUN_TEST(test_accuracy_duration_inj2);
RUN_TEST(test_accuracy_duration_inj3);
RUN_TEST(test_accuracy_duration_inj4);
#if INJ_CHANNELS >= 5
RUN_TEST(test_accuracy_duration_inj5);
#endif
#if INJ_CHANNELS >= 6
RUN_TEST(test_accuracy_duration_inj6);
#endif
#if INJ_CHANNELS >= 7
RUN_TEST(test_accuracy_duration_inj7);
#endif
#if INJ_CHANNELS >= 8
RUN_TEST(test_accuracy_duration_inj8);
#endif
RUN_TEST(test_accuracy_duration_ign1);
RUN_TEST(test_accuracy_duration_ign2);
RUN_TEST(test_accuracy_duration_ign3);
RUN_TEST(test_accuracy_duration_ign4);
#if INJ_CHANNELS >= 5
RUN_TEST(test_accuracy_duration_ign5);
#endif
#if INJ_CHANNELS >= 6
RUN_TEST(test_accuracy_duration_ign6);
#endif
#if INJ_CHANNELS >= 7
RUN_TEST(test_accuracy_duration_ign7);
#endif
#if INJ_CHANNELS >= 8
RUN_TEST(test_accuracy_duration_ign8);
#endif
}
| 6,769
|
C++
|
.cpp
| 196
| 31.295918
| 102
| 0.721679
|
oelprinz-org/BlitzboxBL49sp
| 36
| 12
| 0
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,540,028
|
test_accuracy_timeout.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/test/test_schedules/test_accuracy_timeout.cpp
|
#include <Arduino.h>
#include <unity.h>
#include "scheduler.h"
#include "scheduledIO.h"
#define TIMEOUT 1000
#define DURATION 1000
#define DELTA 24
static uint32_t start_time, end_time;
static void startCallback(void) { end_time = micros(); }
static void endCallback(void) { /*Empty*/ }
void test_accuracy_timeout_inj1(void)
{
initialiseSchedulers();
start_time = micros();
setFuelSchedule1(TIMEOUT, DURATION);
while(fuelSchedule1.Status == PENDING) /*Wait*/ ;
end_time = micros();
TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time);
}
void test_accuracy_timeout_inj2(void)
{
initialiseSchedulers();
start_time = micros();
setFuelSchedule2(TIMEOUT, DURATION);
while(fuelSchedule2.Status == PENDING) /*Wait*/ ;
end_time = micros();
TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time);
}
void test_accuracy_timeout_inj3(void)
{
initialiseSchedulers();
start_time = micros();
setFuelSchedule3(TIMEOUT, DURATION);
while(fuelSchedule3.Status == PENDING) /*Wait*/ ;
end_time = micros();
TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time);
}
void test_accuracy_timeout_inj4(void)
{
initialiseSchedulers();
start_time = micros();
setFuelSchedule4(TIMEOUT, DURATION);
while(fuelSchedule4.Status == PENDING) /*Wait*/ ;
end_time = micros();
TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time);
}
#if INJ_CHANNELS >= 5
void test_accuracy_timeout_inj5(void)
{
initialiseSchedulers();
start_time = micros();
setFuelSchedule5(TIMEOUT, DURATION);
while(fuelSchedule5.Status == PENDING) /*Wait*/ ;
end_time = micros();
TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time);
}
#endif
#if INJ_CHANNELS >= 6
void test_accuracy_timeout_inj6(void)
{
initialiseSchedulers();
start_time = micros();
setFuelSchedule6(TIMEOUT, DURATION);
while(fuelSchedule6.Status == PENDING) /*Wait*/ ;
end_time = micros();
TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time);
}
#endif
#if INJ_CHANNELS >= 7
void test_accuracy_timeout_inj7(void)
{
initialiseSchedulers();
start_time = micros();
setFuelSchedule7(TIMEOUT, DURATION);
while(fuelSchedule7.Status == PENDING) /*Wait*/ ;
end_time = micros();
TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time);
}
#endif
#if INJ_CHANNELS >= 8
void test_accuracy_timeout_inj8(void)
{
initialiseSchedulers();
start_time = micros();
setFuelSchedule8(TIMEOUT, DURATION);
while(fuelSchedule8.Status == PENDING) /*Wait*/ ;
end_time = micros();
TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time);
}
#endif
void test_accuracy_timeout_ign1(void)
{
initialiseSchedulers();
start_time = micros();
setIgnitionSchedule1(startCallback, TIMEOUT, DURATION, endCallback);
while(ignitionSchedule1.Status == PENDING) /*Wait*/ ;
TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time);
}
void test_accuracy_timeout_ign2(void)
{
initialiseSchedulers();
start_time = micros();
setIgnitionSchedule2(startCallback, TIMEOUT, DURATION, endCallback);
while(ignitionSchedule2.Status == PENDING) /*Wait*/ ;
TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time);
}
void test_accuracy_timeout_ign3(void)
{
initialiseSchedulers();
start_time = micros();
setIgnitionSchedule3(startCallback, TIMEOUT, DURATION, endCallback);
while(ignitionSchedule3.Status == PENDING) /*Wait*/ ;
TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time);
}
void test_accuracy_timeout_ign4(void)
{
initialiseSchedulers();
start_time = micros();
setIgnitionSchedule4(startCallback, TIMEOUT, DURATION, endCallback);
while(ignitionSchedule4.Status == PENDING) /*Wait*/ ;
TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time);
}
#if IGN_CHANNELS >= 5
void test_accuracy_timeout_ign5(void)
{
initialiseSchedulers();
start_time = micros();
setIgnitionSchedule5(startCallback, TIMEOUT, DURATION, endCallback);
while(ignitionSchedule5.Status == PENDING) /*Wait*/ ;
TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time);
}
#endif
#if IGN_CHANNELS >= 6
void test_accuracy_timeout_ign6(void)
{
initialiseSchedulers();
start_time = micros();
setIgnitionSchedule6(startCallback, TIMEOUT, DURATION, endCallback);
while(ignitionSchedule6.Status == PENDING) /*Wait*/ ;
TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time);
}
#endif
#if IGN_CHANNELS >= 7
void test_accuracy_timeout_ign7(void)
{
initialiseSchedulers();
start_time = micros();
setIgnitionSchedule7(startCallback, TIMEOUT, DURATION, endCallback);
while(ignitionSchedule7.Status == PENDING) /*Wait*/ ;
TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time);
}
#endif
#if IGN_CHANNELS >= 8
void test_accuracy_timeout_ign8(void)
{
initialiseSchedulers();
start_time = micros();
setIgnitionSchedule8(startCallback, TIMEOUT, DURATION, endCallback);
while(ignitionSchedule8.Status == PENDING) /*Wait*/ ;
TEST_ASSERT_UINT32_WITHIN(DELTA, TIMEOUT, end_time - start_time);
}
#endif
void test_accuracy_timeout(void)
{
RUN_TEST(test_accuracy_timeout_inj1);
RUN_TEST(test_accuracy_timeout_inj2);
RUN_TEST(test_accuracy_timeout_inj3);
RUN_TEST(test_accuracy_timeout_inj4);
#if INJ_CHANNELS >= 5
RUN_TEST(test_accuracy_timeout_inj5);
#endif
#if INJ_CHANNELS >= 6
RUN_TEST(test_accuracy_timeout_inj6);
#endif
#if INJ_CHANNELS >= 7
RUN_TEST(test_accuracy_timeout_inj7);
#endif
#if INJ_CHANNELS >= 8
RUN_TEST(test_accuracy_timeout_inj8);
#endif
RUN_TEST(test_accuracy_timeout_ign1);
RUN_TEST(test_accuracy_timeout_ign2);
RUN_TEST(test_accuracy_timeout_ign3);
RUN_TEST(test_accuracy_timeout_ign4);
#if IGN_CHANNELS >= 5
RUN_TEST(test_accuracy_timeout_ign5);
#endif
#if IGN_CHANNELS >= 6
RUN_TEST(test_accuracy_timeout_ign6);
#endif
#if IGN_CHANNELS >= 7
RUN_TEST(test_accuracy_timeout_ign7);
#endif
#if IGN_CHANNELS >= 8
RUN_TEST(test_accuracy_timeout_ign8);
#endif
}
| 6,163
|
C++
|
.cpp
| 197
| 28.055838
| 72
| 0.722531
|
oelprinz-org/BlitzboxBL49sp
| 36
| 12
| 0
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,540,029
|
test_status_off_to_pending.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/test/test_schedules/test_status_off_to_pending.cpp
|
#include <Arduino.h>
#include <unity.h>
#include "scheduler.h"
#define TIMEOUT 1000
#define DURATION 1000
static void emptyCallback(void) { }
void test_status_off_to_pending_inj1(void)
{
initialiseSchedulers();
setFuelSchedule1(TIMEOUT, DURATION);
TEST_ASSERT_EQUAL(PENDING, fuelSchedule1.Status);
}
void test_status_off_to_pending_inj2(void)
{
initialiseSchedulers();
setFuelSchedule2(TIMEOUT, DURATION);
TEST_ASSERT_EQUAL(PENDING, fuelSchedule2.Status);
}
void test_status_off_to_pending_inj3(void)
{
initialiseSchedulers();
setFuelSchedule3(TIMEOUT, DURATION);
TEST_ASSERT_EQUAL(PENDING, fuelSchedule3.Status);
}
void test_status_off_to_pending_inj4(void)
{
initialiseSchedulers();
setFuelSchedule4(TIMEOUT, DURATION);
TEST_ASSERT_EQUAL(PENDING, fuelSchedule4.Status);
}
#if INJ_CHANNELS >= 5
void test_status_off_to_pending_inj5(void)
{
initialiseSchedulers();
setFuelSchedule5(TIMEOUT, DURATION);
TEST_ASSERT_EQUAL(PENDING, fuelSchedule5.Status);
}
#endif
#if INJ_CHANNELS >= 6
void test_status_off_to_pending_inj6(void)
{
initialiseSchedulers();
setFuelSchedule6(TIMEOUT, DURATION);
TEST_ASSERT_EQUAL(PENDING, fuelSchedule6.Status);
}
#endif
#if INJ_CHANNELS >= 7
void test_status_off_to_pending_inj7(void)
{
initialiseSchedulers();
setFuelSchedule7(TIMEOUT, DURATION);
TEST_ASSERT_EQUAL(PENDING, fuelSchedule7.Status);
}
#endif
#if INJ_CHANNELS >= 8
void test_status_off_to_pending_inj8(void)
{
initialiseSchedulers();
setFuelSchedule8(TIMEOUT, DURATION);
TEST_ASSERT_EQUAL(PENDING, fuelSchedule8.Status);
}
#endif
void test_status_off_to_pending_ign1(void)
{
initialiseSchedulers();
setIgnitionSchedule1(emptyCallback, TIMEOUT, DURATION, emptyCallback);
TEST_ASSERT_EQUAL(PENDING, ignitionSchedule1.Status);
}
void test_status_off_to_pending_ign2(void)
{
initialiseSchedulers();
setIgnitionSchedule2(emptyCallback, TIMEOUT, DURATION, emptyCallback);
TEST_ASSERT_EQUAL(PENDING, ignitionSchedule2.Status);
}
void test_status_off_to_pending_ign3(void)
{
initialiseSchedulers();
setIgnitionSchedule3(emptyCallback, TIMEOUT, DURATION, emptyCallback);
TEST_ASSERT_EQUAL(PENDING, ignitionSchedule3.Status);
}
void test_status_off_to_pending_ign4(void)
{
initialiseSchedulers();
setIgnitionSchedule4(emptyCallback, TIMEOUT, DURATION, emptyCallback);
TEST_ASSERT_EQUAL(PENDING, ignitionSchedule4.Status);
}
#if IGN_CHANNELS >= 5
void test_status_off_to_pending_ign5(void)
{
initialiseSchedulers();
setIgnitionSchedule5(emptyCallback, TIMEOUT, DURATION, emptyCallback);
TEST_ASSERT_EQUAL(PENDING, ignitionSchedule5.Status);
}
#endif
#if IGN_CHANNELS >= 6
void test_status_off_to_pending_ign6(void)
{
initialiseSchedulers();
setIgnitionSchedule6(emptyCallback, TIMEOUT, DURATION, emptyCallback);
TEST_ASSERT_EQUAL(PENDING, ignitionSchedule6.Status);
}
#endif
#if IGN_CHANNELS >= 7
void test_status_off_to_pending_ign7(void)
{
initialiseSchedulers();
setIgnitionSchedule7(emptyCallback, TIMEOUT, DURATION, emptyCallback);
TEST_ASSERT_EQUAL(PENDING, ignitionSchedule7.Status);
}
#endif
#if IGN_CHANNELS >= 8
void test_status_off_to_pending_ign8(void)
{
initialiseSchedulers();
setIgnitionSchedule8(emptyCallback, TIMEOUT, DURATION, emptyCallback);
TEST_ASSERT_EQUAL(PENDING, ignitionSchedule8.Status);
}
#endif
void test_status_off_to_pending(void)
{
RUN_TEST(test_status_off_to_pending_inj1);
RUN_TEST(test_status_off_to_pending_inj2);
RUN_TEST(test_status_off_to_pending_inj3);
RUN_TEST(test_status_off_to_pending_inj4);
#if INJ_CHANNELS >= 5
RUN_TEST(test_status_off_to_pending_inj5);
#endif
#if INJ_CHANNELS >= 6
RUN_TEST(test_status_off_to_pending_inj6);
#endif
#if INJ_CHANNELS >= 7
RUN_TEST(test_status_off_to_pending_inj7);
#endif
#if INJ_CHANNELS >= 8
RUN_TEST(test_status_off_to_pending_inj8);
#endif
RUN_TEST(test_status_off_to_pending_ign1);
RUN_TEST(test_status_off_to_pending_ign2);
RUN_TEST(test_status_off_to_pending_ign3);
RUN_TEST(test_status_off_to_pending_ign4);
#if IGN_CHANNELS >= 5
RUN_TEST(test_status_off_to_pending_ign5);
#endif
#if IGN_CHANNELS >= 6
RUN_TEST(test_status_off_to_pending_ign6);
#endif
#if IGN_CHANNELS >= 7
RUN_TEST(test_status_off_to_pending_ign7);
#endif
#if IGN_CHANNELS >= 8
RUN_TEST(test_status_off_to_pending_ign8);
#endif
}
| 4,452
|
C++
|
.cpp
| 153
| 26.248366
| 74
| 0.761693
|
oelprinz-org/BlitzboxBL49sp
| 36
| 12
| 0
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,540,030
|
test_status_initial_off.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/test/test_schedules/test_status_initial_off.cpp
|
#include <Arduino.h>
#include <unity.h>
#include "scheduler.h"
void test_status_initial_off_inj1(void)
{
initialiseSchedulers();
TEST_ASSERT_EQUAL(OFF, fuelSchedule1.Status);
}
void test_status_initial_off_inj2(void)
{
initialiseSchedulers();
TEST_ASSERT_EQUAL(OFF, fuelSchedule2.Status);
}
void test_status_initial_off_inj3(void)
{
initialiseSchedulers();
TEST_ASSERT_EQUAL(OFF, fuelSchedule3.Status);
}
void test_status_initial_off_inj4(void)
{
initialiseSchedulers();
TEST_ASSERT_EQUAL(OFF, fuelSchedule4.Status);
}
#if INJ_CHANNELS >= 5
void test_status_initial_off_inj5(void)
{
initialiseSchedulers();
TEST_ASSERT_EQUAL(OFF, fuelSchedule5.Status);
}
#endif
#if INJ_CHANNELS >= 6
void test_status_initial_off_inj6(void)
{
initialiseSchedulers();
TEST_ASSERT_EQUAL(OFF, fuelSchedule6.Status);
}
#endif
#if INJ_CHANNELS >= 7
void test_status_initial_off_inj7(void)
{
initialiseSchedulers();
TEST_ASSERT_EQUAL(OFF, fuelSchedule7.Status);
}
#endif
#if INJ_CHANNELS >= 8
void test_status_initial_off_inj8(void)
{
initialiseSchedulers();
TEST_ASSERT_EQUAL(OFF, fuelSchedule8.Status);
}
#endif
void test_status_initial_off_ign1(void)
{
initialiseSchedulers();
TEST_ASSERT_EQUAL(OFF, ignitionSchedule1.Status);
}
void test_status_initial_off_ign2(void)
{
initialiseSchedulers();
TEST_ASSERT_EQUAL(OFF, ignitionSchedule2.Status);
}
void test_status_initial_off_ign3(void)
{
initialiseSchedulers();
TEST_ASSERT_EQUAL(OFF, ignitionSchedule3.Status);
}
void test_status_initial_off_ign4(void)
{
initialiseSchedulers();
TEST_ASSERT_EQUAL(OFF, ignitionSchedule4.Status);
}
#if IGN_CHANNELS >= 5
void test_status_initial_off_ign5(void)
{
initialiseSchedulers();
TEST_ASSERT_EQUAL(OFF, ignitionSchedule5.Status);
}
#endif
#if IGN_CHANNELS >= 6
void test_status_initial_off_ign6(void)
{
initialiseSchedulers();
TEST_ASSERT_EQUAL(OFF, ignitionSchedule6.Status);
}
#endif
#if IGN_CHANNELS >= 7
void test_status_initial_off_ign7(void)
{
initialiseSchedulers();
TEST_ASSERT_EQUAL(OFF, ignitionSchedule7.Status);
}
#endif
#if IGN_CHANNELS >= 8
void test_status_initial_off_ign8(void)
{
initialiseSchedulers();
TEST_ASSERT_EQUAL(OFF, ignitionSchedule8.Status);
}
#endif
void test_status_initial_off(void)
{
RUN_TEST(test_status_initial_off_inj1);
RUN_TEST(test_status_initial_off_inj2);
RUN_TEST(test_status_initial_off_inj3);
RUN_TEST(test_status_initial_off_inj4);
#if INJ_CHANNELS >= 5
RUN_TEST(test_status_initial_off_inj5);
#endif
#if INJ_CHANNELS >= 6
RUN_TEST(test_status_initial_off_inj6);
#endif
#if INJ_CHANNELS >= 7
RUN_TEST(test_status_initial_off_inj7);
#endif
#if INJ_CHANNELS >= 8
RUN_TEST(test_status_initial_off_inj8);
#endif
RUN_TEST(test_status_initial_off_ign1);
RUN_TEST(test_status_initial_off_ign2);
RUN_TEST(test_status_initial_off_ign3);
RUN_TEST(test_status_initial_off_ign4);
#if IGN_CHANNELS >= 5
RUN_TEST(test_status_initial_off_ign5);
#endif
#if IGN_CHANNELS >= 6
RUN_TEST(test_status_initial_off_ign6);
#endif
#if IGN_CHANNELS >= 7
RUN_TEST(test_status_initial_off_ign7);
#endif
#if IGN_CHANNELS >= 8
RUN_TEST(test_status_initial_off_ign8);
#endif
}
| 3,282
|
C++
|
.cpp
| 134
| 21.850746
| 53
| 0.744565
|
oelprinz-org/BlitzboxBL49sp
| 36
| 12
| 0
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,540,031
|
table3d_axis_io.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/table3d_axis_io.cpp
|
#include "table3d_axis_io.h"
constexpr int16_byte table3d_axis_io::converter_100;
constexpr int16_byte table3d_axis_io::converter_2;
constexpr int16_byte table3d_axis_io::converter_1;
| 184
|
C++
|
.cpp
| 4
| 45
| 52
| 0.811111
|
oelprinz-org/BlitzboxBL49sp
| 36
| 12
| 0
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
1,540,032
|
table3d_interpolate.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/table3d_interpolate.cpp
|
#include "table3d_interpolate.h"
// ============================= Axis Bin Searching =========================
static inline bool is_in_bin(const table3d_axis_t &testValue, const table3d_axis_t &min, const table3d_axis_t &max)
{
return testValue > min && testValue <= max;
}
// Find the axis index for the top of the bin that covers the test value.
// E.g. 4 in { 1, 3, 5, 7, 9 } would be 2
// We assume the axis is in order.
static inline table3d_dim_t find_bin_max(
table3d_axis_t &value, // Value to search for
const table3d_axis_t *pAxis, // The axis to search
table3d_dim_t minElement, // Axis index of the element with the lowest value (at one end of the array)
table3d_dim_t maxElement, // Axis index of the element with the highest value (at the other end of the array)
table3d_dim_t lastBinMax) // The last result from this call - used to speed up searches
{
// Direction to search (1 conventional, -1 to go backwards from pAxis)
int8_t stride = maxElement>minElement ? 1 : -1;
// It's quicker to increment/adjust this pointer than to repeatedly
// index the array - minimum 2%, often >5%
const table3d_axis_t *pMax = nullptr;
// minElement is at one end of the array, so the "lowest" bin
// is [minElement, minElement+stride]. Since we're working with the upper
// index of the bin pair, we can't go below minElement + stride.
table3d_dim_t minBinIndex = minElement + stride;
// Check the cached last bin and either side first - it's likely that this will give a hit under
// real world conditions
// Check if we're still in the same bin as last time
pMax = pAxis + lastBinMax;
if (is_in_bin(value, *(pMax - stride), *pMax))
{
return lastBinMax;
}
// Check the bin above the last one
pMax = pMax - stride;
if (lastBinMax!=minBinIndex && is_in_bin(value, *(pMax - stride), *pMax))
{
return lastBinMax-stride;
}
// Check the bin below the last one
pMax += stride*2;
if (lastBinMax!=maxElement && is_in_bin(value, *(pMax - stride), *pMax))
{
return lastBinMax+stride;
}
// Check if outside array limits - won't happen often in the real world
// so check after the cache check
// At or above maximum - clamp to final value
if (value>=pAxis[maxElement])
{
value = pAxis[maxElement];
return maxElement;
}
// At or below minimum - clamp to lowest value
if (value<=pAxis[minElement])
{
value = pAxis[minElement];
return minElement+stride;
}
// No hits above, so run a linear search.
// We start at the maximum & work down, rather than looping from [0] up to [max]
// This is because the important tables (fuel and injection) will have the highest
// RPM at the top of the X axis, so starting there will mean the best case occurs
// when the RPM is highest (and hence the CPU is needed most)
lastBinMax = maxElement;
pMax = pAxis + lastBinMax;
while (lastBinMax!=minBinIndex && !is_in_bin(value, *(pMax - stride), *pMax))
{
lastBinMax -= stride;
pMax -= stride;
}
return lastBinMax;
}
table3d_dim_t find_xbin(table3d_axis_t &value, const table3d_axis_t *pAxis, table3d_dim_t size, table3d_dim_t lastBin)
{
return find_bin_max(value, pAxis, size-1, 0, lastBin);
}
table3d_dim_t find_ybin(table3d_axis_t &value, const table3d_axis_t *pAxis, table3d_dim_t size, table3d_dim_t lastBin)
{
// Y axis is stored in reverse for performance purposes (not sure that's still valid).
// The minimum value is at the end & max at the start. So need to adjust for that.
return find_bin_max(value, pAxis, size-1, 0, lastBin);
}
// ========================= Fixed point math =========================
// An unsigned fixed point number type with 1 integer bit & 8 fractional bits.
// See https://en.wikipedia.org/wiki/Q_(number_format).
// This is specialised for the number range 0..1 - a generic fixed point
// class would miss some important optimisations. Specifically, we can avoid
// type promotion during multiplication.
typedef uint16_t QU1X8_t;
static constexpr uint8_t QU1X8_INTEGER_SHIFT = 8;
static constexpr QU1X8_t QU1X8_ONE = 1U << QU1X8_INTEGER_SHIFT;
static constexpr QU1X8_t QU1X8_HALF = 1U << (QU1X8_INTEGER_SHIFT-1);
inline QU1X8_t mulQU1X8(QU1X8_t a, QU1X8_t b)
{
// 1x1 == 1....but the real reason for this is to avoid 16-bit multiplication overflow.
//
// We are using uint16_t as our underlying fixed point type. If we follow the regular
// code path, we'd need to promote to uint32_t to avoid overflow.
//
// The overflow can only happen when *both* the X & Y inputs
// are at the edge of a bin.
//
// This is a rare condition, so most of the time we can use 16-bit multiplication and gain performance
if (a==QU1X8_ONE && b==QU1X8_ONE)
{
return QU1X8_ONE;
}
// Add the equivalent of 0.5 to the final calculation pre-rounding.
// This will have the effect of rounding to the nearest integer, rather
// than always rounding down.
return ((a * b) + QU1X8_HALF) >> QU1X8_INTEGER_SHIFT;
}
// ============================= Axis value to bin % =========================
static inline QU1X8_t compute_bin_position(table3d_axis_t value, const table3d_dim_t &bin, int8_t stride, const table3d_axis_t *pAxis)
{
table3d_axis_t binMinValue = pAxis[bin-stride];
if (value==binMinValue) { return 0; }
table3d_axis_t binMaxValue = pAxis[bin];
if (value==binMaxValue) { return QU1X8_ONE; }
table3d_axis_t binWidth = binMaxValue-binMinValue;
// Since we can have bins of any width, we need to use
// 24.8 fixed point to avoid overflow
uint32_t p = (uint32_t)(value - binMinValue) << QU1X8_INTEGER_SHIFT;
// But since we are computing the ratio (0 to 1), p is guaranteed to be
// less than binWidth and thus the division below will result in a value
// <=1. So we can reduce the data type from 24.8 (uint32_t) to 1.8 (uint16_t)
return p / binWidth;
}
// ============================= End internal support functions =========================
//This function pulls a value from a 3D table given a target for X and Y coordinates.
//It performs a 2D linear interpolation as described in: www.megamanual.com/v22manual/ve_tuner.pdf
table3d_value_t get3DTableValue(struct table3DGetValueCache *pValueCache,
table3d_dim_t axisSize,
const table3d_value_t *pValues,
const table3d_axis_t *pXAxis,
const table3d_axis_t *pYAxis,
table3d_axis_t Y_in, table3d_axis_t X_in)
{
//0th check is whether the same X and Y values are being sent as last time.
// If they are, this not only prevents a lookup of the axis, but prevents the
//interpolation calcs being performed
if( X_in == pValueCache->last_lookup.x &&
Y_in == pValueCache->last_lookup.y)
{
return pValueCache->lastOutput;
}
// Assign this here, as we might modify coords below.
pValueCache->last_lookup.x = X_in;
pValueCache->last_lookup.y = Y_in;
// Figure out where on the axes the incoming coord are
pValueCache->lastXBinMax = find_xbin(X_in, pXAxis, axisSize, pValueCache->lastXBinMax);
pValueCache->lastYBinMax = find_ybin(Y_in, pYAxis, axisSize, pValueCache->lastYBinMax);
/*
At this point we have the 4 corners of the map where the interpolated value will fall in
Eg: (yMax,xMin) (yMax,xMax)
(yMin,xMin) (yMin,xMax)
In the following calculation the table values are referred to by the following variables:
A B
C D
*/
table3d_dim_t rowMax = pValueCache->lastYBinMax * axisSize;
table3d_dim_t rowMin = rowMax + axisSize;
table3d_dim_t colMax = axisSize - pValueCache->lastXBinMax - 1;
table3d_dim_t colMin = colMax - 1;
table3d_value_t A = pValues[rowMax + colMin];
table3d_value_t B = pValues[rowMax + colMax];
table3d_value_t C = pValues[rowMin + colMin];
table3d_value_t D = pValues[rowMin + colMax];
//Check that all values aren't just the same (This regularly happens with things like the fuel trim maps)
if( (A == B) && (A == C) && (A == D) ) { pValueCache->lastOutput = A; }
else
{
//Create some normalised position values
//These are essentially percentages (between 0 and 1) of where the desired value falls between the nearest bins on each axis
const QU1X8_t p = compute_bin_position(X_in, pValueCache->lastXBinMax, -1, pXAxis);
const QU1X8_t q = compute_bin_position(Y_in, pValueCache->lastYBinMax, -1, pYAxis);
const QU1X8_t m = mulQU1X8(QU1X8_ONE-p, q);
const QU1X8_t n = mulQU1X8(p, q);
const QU1X8_t o = mulQU1X8(QU1X8_ONE-p, QU1X8_ONE-q);
const QU1X8_t r = mulQU1X8(p, QU1X8_ONE-q);
pValueCache->lastOutput = ( (A * m) + (B * n) + (C * o) + (D * r) ) >> QU1X8_INTEGER_SHIFT;
}
return pValueCache->lastOutput;
}
| 8,913
|
C++
|
.cpp
| 185
| 43.875676
| 134
| 0.672759
|
oelprinz-org/BlitzboxBL49sp
| 36
| 12
| 0
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,540,033
|
schedule_calcs.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/schedule_calcs.cpp
|
#include "schedule_calcs.h"
int ignition1StartAngle = 0;
int ignition2StartAngle = 0;
int ignition3StartAngle = 0;
int ignition4StartAngle = 0;
int ignition5StartAngle = 0;
int ignition6StartAngle = 0;
int ignition7StartAngle = 0;
int ignition8StartAngle = 0;
int channel1IgnDegrees = 0; /**< 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) */
int channel2IgnDegrees = 0; /**< The number of crank degrees until cylinder 2 (and 5/6/7/8) is at TDC */
int channel3IgnDegrees = 0; /**< The number of crank degrees until cylinder 3 (and 5/6/7/8) is at TDC */
int channel4IgnDegrees = 0; /**< The number of crank degrees until cylinder 4 (and 5/6/7/8) is at TDC */
int channel5IgnDegrees = 0; /**< The number of crank degrees until cylinder 5 is at TDC */
int channel6IgnDegrees = 0; /**< The number of crank degrees until cylinder 6 is at TDC */
int channel7IgnDegrees = 0; /**< The number of crank degrees until cylinder 7 is at TDC */
int channel8IgnDegrees = 0; /**< The number of crank degrees until cylinder 8 is at TDC */
int channel1InjDegrees = 0; /**< 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) */
int channel2InjDegrees = 0; /**< The number of crank degrees until cylinder 2 (and 5/6/7/8) is at TDC */
int channel3InjDegrees = 0; /**< The number of crank degrees until cylinder 3 (and 5/6/7/8) is at TDC */
int channel4InjDegrees = 0; /**< The number of crank degrees until cylinder 4 (and 5/6/7/8) is at TDC */
int channel5InjDegrees = 0; /**< The number of crank degrees until cylinder 5 is at TDC */
int channel6InjDegrees = 0; /**< The number of crank degrees until cylinder 6 is at TDC */
int channel7InjDegrees = 0; /**< The number of crank degrees until cylinder 7 is at TDC */
int channel8InjDegrees = 0; /**< The number of crank degrees until cylinder 8 is at TDC */
| 1,957
|
C++
|
.cpp
| 25
| 77.16
| 167
| 0.737688
|
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,034
|
table3d.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/table3d.cpp
|
#include <stdlib.h>
#include "table3d.h"
// =============================== Iterators =========================
table_value_iterator rows_begin(const void *pTable, table_type_t key)
{
#define CTA_GET_ROW_ITERATOR(size, xDomain, yDomain, pTable) \
return ((TABLE3D_TYPENAME_BASE(size, xDomain, yDomain)*)pTable)->values.begin();
CONCRETE_TABLE_ACTION(key, CTA_GET_ROW_ITERATOR, pTable);
}
/**
* Convert page iterator to table x axis iterator.
*/
table_axis_iterator x_begin(const void *pTable, table_type_t key)
{
#define CTA_GET_X_ITERATOR(size, xDomain, yDomain, pTable) \
return ((TABLE3D_TYPENAME_BASE(size, xDomain, yDomain)*)pTable)->axisX.begin();
CONCRETE_TABLE_ACTION(key, CTA_GET_X_ITERATOR, pTable);
}
table_axis_iterator x_rbegin(const void *pTable, table_type_t key)
{
#define CTA_GET_X_RITERATOR(size, xDomain, yDomain, pTable) \
return ((TABLE3D_TYPENAME_BASE(size, xDomain, yDomain)*)pTable)->axisX.rbegin();
CONCRETE_TABLE_ACTION(key, CTA_GET_X_RITERATOR, pTable);
}
/**
* Convert page iterator to table y axis iterator.
*/
table_axis_iterator y_begin(const void *pTable, table_type_t key)
{
#define CTA_GET_Y_ITERATOR(size, xDomain, yDomain, pTable) \
return ((TABLE3D_TYPENAME_BASE(size, xDomain, yDomain)*)pTable)->axisY.begin();
CONCRETE_TABLE_ACTION(key, CTA_GET_Y_ITERATOR, pTable);
}
table_axis_iterator y_rbegin(const void *pTable, table_type_t key)
{
#define CTA_GET_Y_RITERATOR(size, xDomain, yDomain, pTable) \
return ((TABLE3D_TYPENAME_BASE(size, xDomain, yDomain)*)pTable)->axisY.rbegin();
CONCRETE_TABLE_ACTION(key, CTA_GET_Y_RITERATOR, pTable);
}
| 1,638
|
C++
|
.cpp
| 39
| 39.461538
| 86
| 0.704959
|
oelprinz-org/BlitzboxBL49sp
| 36
| 12
| 0
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,540,035
|
comms.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/comms.cpp
|
/*
Speeduino - Simple engine management for the Arduino Mega 2560 platform
Copyright (C) Josh Stewart
A full copy of the license may be found in the projects root directory
*/
/** @file
* Process Incoming and outgoing serial communications.
*/
#include "globals.h"
#include "comms.h"
#include "cancomms.h"
#include "storage.h"
#include "maths.h"
#include "utilities.h"
#include "decoders.h"
#include "TS_CommandButtonHandler.h"
#include "errors.h"
#include "pages.h"
#include "page_crc.h"
#include "logger.h"
#include "comms_legacy.h"
#include "src/FastCRC/FastCRC.h"
#include <avr/pgmspace.h>
#ifdef RTC_ENABLED
#include "rtc_common.h"
#include "comms_sd.h"
#endif
#ifdef SD_LOGGING
#include "SD_logger.h"
#endif
// Forward declarations
/** @brief Processes a message once it has been fully recieved */
void processSerialCommand(void);
/** @brief Should be called when ::serialStatusFlag == SERIAL_TRANSMIT_TOOTH_INPROGRESS, */
void sendToothLog(void);
/** @brief Should be called when ::serialStatusFlag == LOG_SEND_COMPOSITE */
void sendCompositeLog(void);
#define SERIAL_RC_OK 0x00 //!< Success
#define SERIAL_RC_REALTIME 0x01 //!< Unused
#define SERIAL_RC_PAGE 0x02 //!< Unused
#define SERIAL_RC_BURN_OK 0x04 //!< EEPROM write succeeded
#define SERIAL_RC_TIMEOUT 0x80 //!< Timeout error
#define SERIAL_RC_CRC_ERR 0x82 //!< CRC mismatch
#define SERIAL_RC_UKWN_ERR 0x83 //!< Unknown command
#define SERIAL_RC_RANGE_ERR 0x84 //!< Incorrect range. TS will not retry command
#define SERIAL_RC_BUSY_ERR 0x85 //!< TS will wait and retry
#define SERIAL_LEN_SIZE 2U
#define SERIAL_TIMEOUT 3000 //ms
#define SEND_OUTPUT_CHANNELS 48U
//!@{
/** @brief Hard coded response for some TS messages.
* @attention Stored in flash (.text segment) and loaded on demand.
*/
constexpr byte serialVersion[] PROGMEM = {SERIAL_RC_OK, '0', '0', '2'};
constexpr byte canId[] PROGMEM = {SERIAL_RC_OK, 0};
//constexpr byte codeVersion[] PROGMEM = { SERIAL_RC_OK, 's','p','e','e','d','u','i','n','o',' ','2','0','2','2','1','0','-','d','e','v'} ; //Note no null terminator in array and statu variable at the start
//constexpr byte productString[] PROGMEM = { SERIAL_RC_OK, 'S', 'p', 'e', 'e', 'd', 'u', 'i', 'n', 'o', ' ', '2', '0', '2', '2', '.', '1', '0', '-', 'd', 'e', 'v'};
constexpr byte codeVersion[] PROGMEM = { SERIAL_RC_OK, 's','p','e','e','d','u','i','n','o',' ','2','0','2','3','0','5'} ; //Note no null terminator in array and statu variable at the start
constexpr byte productString[] PROGMEM = { SERIAL_RC_OK, 'S', 'p', 'e', 'e', 'd', 'u', 'i', 'n', 'o', ' ', '2', '0', '2', '3', '.', '0', '5'};
constexpr byte testCommsResponse[] PROGMEM = { SERIAL_RC_OK, 255 };
//!@}
/** @brief The number of bytes received or transmitted to date during nonblocking I/O.
*
* @attention We can share one variable between rx & tx because we only support simpex serial comms.
* I.e. we can only be receiving or transmitting at any one time.
*/
static uint16_t serialBytesRxTx = 0;
static uint32_t serialReceiveStartTime = 0; //!< The time at which the serial receive started. Used for calculating whether a timeout has occurred */
static FastCRC32 CRC32_serial; //!< Support accumulation of a CRC during non-blocking operations */
using crc_t = uint32_t;
#ifdef RTC_ENABLED
#undef SERIAL_BUFFER_SIZE
/** @brief Serial payload buffer must be significantly larger for boards that support SD logging.
*
* Large enough to contain 4 sectors + overhead
*/
#define SERIAL_BUFFER_SIZE (2048 + 3)
static uint16_t SDcurrentDirChunk;
static uint32_t SDreadStartSector;
static uint32_t SDreadNumSectors;
static uint32_t SDreadCompletedSectors = 0;
#endif
static uint8_t serialPayload[SERIAL_BUFFER_SIZE]; //!< Serial payload buffer. */
static uint16_t serialPayloadLength = 0; //!< How many bytes in serialPayload were received or sent */
#if defined(CORE_AVR)
#pragma GCC push_options
// These minimize RAM usage at no performance cost
#pragma GCC optimize ("Os")
#endif
static inline bool isTimeout(void) {
return (millis() - serialReceiveStartTime) > SERIAL_TIMEOUT;
}
// ====================================== Endianess Support =============================
/**
* @brief Flush all remaining bytes from the rx serial buffer
*/
void flushRXbuffer(void)
{
while (Serial.available() > 0) { Serial.read(); }
}
/** @brief Reverse the byte order of a uint32_t
*
* @attention noinline is needed to prevent enlarging callers stack frame, which in turn throws
* off free ram reporting.
* */
static __attribute__((noinline)) uint32_t reverse_bytes(uint32_t i)
{
return ((i>>24) & 0xffU) | // move byte 3 to byte 0
((i<<8 ) & 0xff0000U) | // move byte 1 to byte 2
((i>>8 ) & 0xff00U) | // move byte 2 to byte 1
((i<<24) & 0xff000000U);
}
// ====================================== Blocking IO Support ================================
void writeByteReliableBlocking(byte value) {
// Some platforms (I'm looking at you Teensy 3.5) do not mimic the Arduino 1.0
// contract and synchronously block.
// https://github.com/PaulStoffregen/cores/blob/master/teensy3/usb_serial.c#L215
while (!Serial.availableForWrite()) { /* Wait for the buffer to free up space */ }
Serial.write(value);
}
// ====================================== Multibyte Primitive IO Support =============================
/** @brief Read a uint32_t from Serial
*
* @attention noinline is needed to prevent enlarging callers stack frame, which in turn throws
* off free ram reporting.
* */
static __attribute__((noinline)) uint32_t readSerial32Timeout(void)
{
union {
char raw[sizeof(uint32_t)];
uint32_t value;
} buffer;
// Teensy 3.5: Serial.available() should only be used as a boolean test
// See https://www.pjrc.com/teensy/td_serial.html#singlebytepackets
size_t count=0;
while (count < sizeof(buffer.value)) {
if (Serial.available()!=0) {
buffer.raw[count++] =(byte)Serial.read();
} else if(isTimeout()) {
return 0;
} else { /* MISRA - no-op */ }
}
return reverse_bytes(buffer.value);
}
/** @brief Write a uint32_t to Serial
* @returns The value as transmitted on the wire
*/
static uint32_t serialWrite(uint32_t value)
{
value = reverse_bytes(value);
const byte *pBuffer = (const byte*)&value;
writeByteReliableBlocking(pBuffer[0]);
writeByteReliableBlocking(pBuffer[1]);
writeByteReliableBlocking(pBuffer[2]);
writeByteReliableBlocking(pBuffer[3]);
return value;
}
/** @brief Write a uint16_t to Serial */
static void serialWrite(uint16_t value)
{
writeByteReliableBlocking((value >> 8U) & 255U);
writeByteReliableBlocking(value & 255U);
}
// ====================================== Non-blocking IO Support =============================
/** @brief Send as much data as possible without blocking the caller
* @return Number of bytes sent
*/
static uint16_t writeNonBlocking(const byte *buffer, size_t length)
{
uint16_t bytesTransmitted = 0;
while (bytesTransmitted<length
&& Serial.availableForWrite() != 0
// Just in case
&& Serial.write(buffer[bytesTransmitted]) == 1)
{
bytesTransmitted++;
}
return bytesTransmitted;
// This doesn't work on Teensy.
// See https://github.com/PaulStoffregen/cores/issues/10#issuecomment-61514955
// size_t capacity = min((size_t)Serial.availableForWrite(), length);
// return Serial.write(buffer, capacity);
}
/** @brief Write a uint32_t to Serial without blocking the caller
* @return Number of bytes sent
*/
static size_t writeNonBlocking(size_t start, uint32_t value)
{
value = reverse_bytes(value);
const byte *pBuffer = (const byte*)&value;
return writeNonBlocking(pBuffer+start, sizeof(value)-start); //cppcheck-suppress misra-c2012-17.2
}
/** @brief Send the buffer, followed by it's CRC
*
* This is supposed to be called multiple times for the same buffer until
* it's all sent.
*
* @param start Index into the buffer to start sending at. [0, length)
* @param length Total size of the buffer
* @return Cumulative total number of bytes written . I.e. the next start value
*/
static uint16_t sendBufferAndCrcNonBlocking(const byte *buffer, size_t start, size_t length)
{
if (start<length)
{
start = start + writeNonBlocking(buffer+start, length-start);
}
if (start>=length && start<length+sizeof(crc_t))
{
start = start + writeNonBlocking(start-length, CRC32_serial.crc32(buffer, length));
}
return start;
}
/** @brief Start sending the shared serialPayload buffer.
*
* ::serialStatusFlag will be signal the result of the send:<br>
* ::serialStatusFlag == SERIAL_INACTIVE: send is complete <br>
* ::serialStatusFlag == SERIAL_TRANSMIT_INPROGRESS: partial send, subsequent calls to continueSerialTransmission
* will finish sending serialPayload
*
* @param payloadLength How many bytes to send [0, sizeof(serialPayload))
*/
static void sendSerialPayloadNonBlocking(uint16_t payloadLength)
{
//Start new transmission session
serialStatusFlag = SERIAL_TRANSMIT_INPROGRESS;
serialWrite(payloadLength);
serialPayloadLength = payloadLength;
serialBytesRxTx = sendBufferAndCrcNonBlocking(serialPayload, 0, payloadLength);
serialStatusFlag = serialBytesRxTx==payloadLength+sizeof(crc_t) ? SERIAL_INACTIVE : SERIAL_TRANSMIT_INPROGRESS;
}
// ====================================== TS Message Support =============================
/** @brief Send a message to TS containing only a return code.
*
* This is used when TS asks for an action to happen (E.g. start a logger) or
* to signal an error condition to TS
*
* @attention This is a blocking operation
*/
static void sendReturnCodeMsg(byte returnCode)
{
serialWrite((uint16_t)sizeof(returnCode));
writeByteReliableBlocking(returnCode);
serialWrite(CRC32_serial.crc32(&returnCode, sizeof(returnCode)));
}
// ====================================== Command/Action Support =============================
// The functions in this section are abstracted out to prevent enlarging callers stack frame,
// which in turn throws off free ram reporting.
/**
* @brief Update a pages contents from a buffer
*
* @param pageNum The index of the page to update
* @param offset Offset into the page
* @param buffer The buffer to read from
* @param length The buffer length
* @return true if page updated successfully
* @return false if page cannot be updated
*/
static bool updatePageValues(uint8_t pageNum, uint16_t offset, const byte *buffer, uint16_t length)
{
if ( (offset + length) <= getPageSize(pageNum) )
{
for(uint16_t i = 0; i < length; i++)
{
setPageValue(pageNum, (offset + i), buffer[i]);
}
deferEEPROMWritesUntil = micros() + EEPROM_DEFER_DELAY;
return true;
}
return false;
}
/**
* @brief Loads a pages contents into a buffer
*
* @param pageNum The index of the page to update
* @param offset Offset into the page
* @param buffer The buffer to read from
* @param length The buffer length
*/
static void loadPageValuesToBuffer(uint8_t pageNum, uint16_t offset, byte *buffer, uint16_t length)
{
for(uint16_t i = 0; i < length; i++)
{
buffer[i] = getPageValue(pageNum, offset + i);
}
}
/** @brief Send a status record back to tuning/logging SW.
* This will "live" information from @ref currentStatus struct.
* @param offset - Start field number
* @param packetLength - Length of actual message (after possible ack/confirm headers)
* E.g. tuning sw command 'A' (Send all values) will send data from field number 0, LOG_ENTRY_SIZE fields.
*/
static void generateLiveValues(uint16_t offset, uint16_t packetLength)
{
if(firstCommsRequest)
{
firstCommsRequest = false;
currentStatus.secl = 0;
}
currentStatus.spark ^= (-currentStatus.hasSync ^ currentStatus.spark) & (1U << BIT_SPARK_SYNC); //Set the sync bit of the Spark variable to match the hasSync variable
serialPayload[0] = SERIAL_RC_OK;
for(byte x=0; x<packetLength; x++)
{
serialPayload[x+1] = getTSLogEntry(offset+x);
}
// Reset any flags that are being used to trigger page refreshes
BIT_CLEAR(currentStatus.status3, BIT_STATUS3_VSS_REFRESH);
}
/**
* @brief Update the oxygen sensor table from serialPayload
*
* @param offset Offset into serialPayload and the table
* @param chunkSize Number of bytes available in serialPayload
*/
static void loadO2CalibrationChunk(uint16_t offset, uint16_t chunkSize)
{
using pCrcCalc = uint32_t (FastCRC32::*)(const uint8_t *, const uint16_t, bool);
// First pass through the loop, we need to INITIALIZE the CRC
pCrcCalc pCrcFun = offset==0U ? &FastCRC32::crc32 : &FastCRC32::crc32_upd;
uint32_t calibrationCRC = 0U;
//Check if this is the final chunk of calibration data
#ifdef CORE_STM32
//STM32 requires TS to send 16 x 64 bytes chunk rather than 4 x 256 bytes.
bool finalBlock = offset == (64U*15U);
#else
bool finalBlock = offset == (256U*3U);
#endif
//Read through the current chunk (Should be 256 bytes long)
// Note there are 2 loops here:
// [x, chunkSize)
// [offset, offset+chunkSize)
for(uint16_t x = 0; x < chunkSize; ++x, ++offset)
{
//TS sends a total of 1024 bytes of calibration data, broken up into 256 byte chunks
//As we're using an interpolated 2D table, we only need to store 32 values out of this 1024
if( (x % 32U) == 0U )
{
o2Calibration_values[offset/32U] = serialPayload[x+7U]; //O2 table stores 8 bit values
o2Calibration_bins[offset/32U] = offset;
}
//Update the CRC
calibrationCRC = (CRC32_serial.*pCrcFun)(&serialPayload[x+7U], 1, false);
// Subsequent passes through the loop, we need to UPDATE the CRC
pCrcFun = &FastCRC32::crc32_upd;
}
if(finalBlock)
{
storeCalibrationCRC32(O2_CALIBRATION_PAGE, ~calibrationCRC);
writeCalibrationPage(O2_CALIBRATION_PAGE);
}
}
/**
* @brief Convert 2 bytes into an offset temperature in degrees Celcius
* @attention Returned value will be offset CALIBRATION_TEMPERATURE_OFFSET
*/
static uint16_t toTemperature(byte lo, byte hi)
{
int16_t tempValue = (int16_t)(word(hi, lo)); //Combine the 2 bytes into a single, signed 16-bit value
tempValue = tempValue / 10; //TS sends values multiplied by 10 so divide back to whole degrees.
tempValue = ((tempValue - 32) * 5) / 9; //Convert from F to C
//Apply the temp offset and check that it results in all values being positive
return max( tempValue + CALIBRATION_TEMPERATURE_OFFSET, 0 );
}
/**
* @brief Update a temperature calibration table from serialPayload
*
* @param calibrationLength The chunk size received from TS
* @param calibrationPage Index of the table
* @param values The table values
* @param bins The table bin values
*/
static void processTemperatureCalibrationTableUpdate(uint16_t calibrationLength, uint8_t calibrationPage, uint16_t *values, uint16_t *bins)
{
//Temperature calibrations are sent as 32 16-bit values
if(calibrationLength == 64U)
{
for (uint16_t x = 0; x < 32U; x++)
{
values[x] = toTemperature(serialPayload[(2U * x) + 7U], serialPayload[(2U * x) + 8U]);
bins[x] = (x * 33U); // 0*33=0 to 31*33=1023
}
storeCalibrationCRC32(calibrationPage, CRC32_serial.crc32(&serialPayload[7], 64));
writeCalibrationPage(calibrationPage);
sendReturnCodeMsg(SERIAL_RC_OK);
}
else
{
sendReturnCodeMsg(SERIAL_RC_RANGE_ERR);
}
}
// ====================================== End Internal Functions =============================
/** Processes the incoming data on the serial buffer based on the command sent.
Can be either data for a new command or a continuation of data for command that is already in progress:
Comands are single byte (letter symbol) commands.
*/
void serialReceive(void)
{
//Check for an existing legacy command in progress
if(serialStatusFlag==SERIAL_COMMAND_INPROGRESS_LEGACY)
{
legacySerialCommand();
return;
}
if (Serial.available()!=0 && serialStatusFlag == SERIAL_INACTIVE)
{
//New command received
//Need at least 2 bytes to read the length of the command
byte highByte = (byte)Serial.peek();
//Check if the command is legacy using the call/response mechanism
if(highByte == 'F')
{
//F command is always allowed as it provides the initial serial protocol version.
legacySerialCommand();
return;
}
else if( (((highByte >= 'A') && (highByte <= 'z')) || (highByte == '?')) && (BIT_CHECK(currentStatus.status4, BIT_STATUS4_ALLOW_LEGACY_COMMS)) )
{
//Handle legacy cases here
legacySerialCommand();
return;
}
else
{
Serial.read();
while(Serial.available() == 0) { /* Wait for the 2nd byte to be received (This will almost never happen) */ }
serialPayloadLength = word(highByte, Serial.read());
serialBytesRxTx = 2;
serialStatusFlag = SERIAL_RECEIVE_INPROGRESS; //Flag the serial receive as being in progress
serialReceiveStartTime = millis();
}
}
//If there is a serial receive in progress, read as much from the buffer as possible or until we receive all bytes
while( (Serial.available() > 0) && (serialStatusFlag == SERIAL_RECEIVE_INPROGRESS) )
{
if (serialBytesRxTx < (serialPayloadLength + SERIAL_LEN_SIZE) )
{
serialPayload[serialBytesRxTx - SERIAL_LEN_SIZE] = (byte)Serial.read();
serialBytesRxTx++;
}
else
{
uint32_t incomingCrc = readSerial32Timeout();
serialStatusFlag = SERIAL_INACTIVE; //The serial receive is now complete
if (!isTimeout()) // CRC read can timeout also!
{
if (incomingCrc == CRC32_serial.crc32(serialPayload, serialPayloadLength))
{
//CRC is correct. Process the command
processSerialCommand();
BIT_CLEAR(currentStatus.status4, BIT_STATUS4_ALLOW_LEGACY_COMMS); //Lock out legacy commands until next power cycle
}
else {
//CRC Error. Need to send an error message
sendReturnCodeMsg(SERIAL_RC_CRC_ERR);
flushRXbuffer();
}
}
// else timeout - code below will kick in.
}
} //Data in serial buffer and serial receive in progress
//Check for a timeout
if( isTimeout() )
{
serialStatusFlag = SERIAL_INACTIVE; //Reset the serial receive
flushRXbuffer();
sendReturnCodeMsg(SERIAL_RC_TIMEOUT);
} //Timeout
}
void serialTransmit(void)
{
switch (serialStatusFlag)
{
case SERIAL_TRANSMIT_INPROGRESS_LEGACY:
sendValues(logItemsTransmitted, inProgressLength, SEND_OUTPUT_CHANNELS, 0);
break;
case SERIAL_TRANSMIT_TOOTH_INPROGRESS:
sendToothLog();
break;
case SERIAL_TRANSMIT_TOOTH_INPROGRESS_LEGACY:
sendToothLog_legacy(logItemsTransmitted);
break;
case SERIAL_TRANSMIT_COMPOSITE_INPROGRESS:
sendCompositeLog();
break;
case SERIAL_TRANSMIT_INPROGRESS:
serialBytesRxTx = sendBufferAndCrcNonBlocking(serialPayload, serialBytesRxTx, serialPayloadLength);
serialStatusFlag = serialBytesRxTx==serialPayloadLength+sizeof(crc_t) ? SERIAL_INACTIVE : SERIAL_TRANSMIT_INPROGRESS;
break;
default: // Nothing to do
break;
}
}
void processSerialCommand(void)
{
switch (serialPayload[0])
{
case 'A': // send x bytes of realtime values
generateLiveValues(0, LOG_ENTRY_SIZE);
break;
case 'b': // New EEPROM burn command to only burn a single page at a time
if( (micros() > deferEEPROMWritesUntil)) { writeConfig(serialPayload[2]); } //Read the table number and perform burn. Note that byte 1 in the array is unused
else { BIT_SET(currentStatus.status4, BIT_STATUS4_BURNPENDING); }
sendReturnCodeMsg(SERIAL_RC_BURN_OK);
break;
case 'B': // Same as above, but for the comms compat mode. Slows down the burn rate and increases the defer time
BIT_SET(currentStatus.status4, BIT_STATUS4_COMMS_COMPAT); //Force the compat mode
deferEEPROMWritesUntil += (EEPROM_DEFER_DELAY/4); //Add 25% more to the EEPROM defer time
if( (micros() > deferEEPROMWritesUntil)) { writeConfig(serialPayload[2]); } //Read the table number and perform burn. Note that byte 1 in the array is unused
else { BIT_SET(currentStatus.status4, BIT_STATUS4_BURNPENDING); }
sendReturnCodeMsg(SERIAL_RC_BURN_OK);
break;
case 'C': // test communications. This is used by Tunerstudio to see whether there is an ECU on a given serial port
(void)memcpy_P(serialPayload, testCommsResponse, sizeof(testCommsResponse) );
sendSerialPayloadNonBlocking(sizeof(testCommsResponse));
break;
case 'd': // Send a CRC32 hash of a given page
{
uint32_t CRC32_val = reverse_bytes(calculatePageCRC32( serialPayload[2] ));
serialPayload[0] = SERIAL_RC_OK;
(void)memcpy(&serialPayload[1], &CRC32_val, sizeof(CRC32_val));
sendSerialPayloadNonBlocking(5);
break;
}
case 'E': // receive command button commands
(void)TS_CommandButtonsHandler(word(serialPayload[1], serialPayload[2]));
sendReturnCodeMsg(SERIAL_RC_OK);
break;
case 'f': //Send serial capability details
serialPayload[0] = SERIAL_RC_OK;
serialPayload[1] = 2; //Serial protocol version
serialPayload[2] = highByte(BLOCKING_FACTOR);
serialPayload[3] = lowByte(BLOCKING_FACTOR);
serialPayload[4] = highByte(TABLE_BLOCKING_FACTOR);
serialPayload[5] = lowByte(TABLE_BLOCKING_FACTOR);
sendSerialPayloadNonBlocking(6);
break;
case 'F': // send serial protocol version
(void)memcpy_P(serialPayload, serialVersion, sizeof(serialVersion) );
sendSerialPayloadNonBlocking(sizeof(serialVersion));
break;
case 'H': //Start the tooth logger
startToothLogger();
sendReturnCodeMsg(SERIAL_RC_OK);
break;
case 'h': //Stop the tooth logger
stopToothLogger();
sendReturnCodeMsg(SERIAL_RC_OK);
break;
case 'I': // send CAN ID
(void)memcpy_P(serialPayload, canId, sizeof(canId) );
sendSerialPayloadNonBlocking(sizeof(serialVersion));
break;
case 'J': //Start the composite logger
startCompositeLogger();
sendReturnCodeMsg(SERIAL_RC_OK);
break;
case 'j': //Stop the composite logger
stopCompositeLogger();
sendReturnCodeMsg(SERIAL_RC_OK);
break;
case 'k': //Send CRC values for the calibration pages
{
uint32_t CRC32_val = reverse_bytes(readCalibrationCRC32(serialPayload[2])); //Get the CRC for the requested page
serialPayload[0] = SERIAL_RC_OK;
(void)memcpy(&serialPayload[1], &CRC32_val, sizeof(CRC32_val));
sendSerialPayloadNonBlocking(5);
break;
}
case 'M':
{
//New write command
//7 bytes required:
//2 - Page identifier
//2 - offset
//2 - Length
//1 - 1st New value
if (updatePageValues(serialPayload[2], word(serialPayload[4], serialPayload[3]), &serialPayload[7], word(serialPayload[6], serialPayload[5])))
{
sendReturnCodeMsg(SERIAL_RC_OK);
}
else
{
//This should never happen, but just in case
sendReturnCodeMsg(SERIAL_RC_RANGE_ERR);
}
break;
}
case 'O': //Start the composite logger 2nd cam (teritary)
startCompositeLoggerTertiary();
sendReturnCodeMsg(SERIAL_RC_OK);
break;
case 'o': //Stop the composite logger 2nd cam (tertiary)
stopCompositeLoggerTertiary();
sendReturnCodeMsg(SERIAL_RC_OK);
break;
case 'X': //Start the composite logger 2nd cam (teritary)
startCompositeLoggerCams();
sendReturnCodeMsg(SERIAL_RC_OK);
break;
case 'x': //Stop the composite logger 2nd cam (tertiary)
stopCompositeLoggerCams();
sendReturnCodeMsg(SERIAL_RC_OK);
break;
/*
* New method for sending page values (MS command equivalent is 'r')
*/
case 'p':
{
//6 bytes required:
//2 - Page identifier
//2 - offset
//2 - Length
uint16_t length = word(serialPayload[6], serialPayload[5]);
//Setup the transmit buffer
serialPayload[0] = SERIAL_RC_OK;
loadPageValuesToBuffer(serialPayload[2], word(serialPayload[4], serialPayload[3]), &serialPayload[1], length);
sendSerialPayloadNonBlocking(length + 1U);
break;
}
case 'Q': // send code version
(void)memcpy_P(serialPayload, codeVersion, sizeof(codeVersion) );
sendSerialPayloadNonBlocking(sizeof(codeVersion));
break;
case 'r': //New format for the optimised OutputChannels
{
uint8_t cmd = serialPayload[2];
uint16_t offset = word(serialPayload[4], serialPayload[3]);
uint16_t length = word(serialPayload[6], serialPayload[5]);
#ifdef RTC_ENABLED
uint16_t SD_arg1 = word(serialPayload[3], serialPayload[4]);
uint16_t SD_arg2 = word(serialPayload[5], serialPayload[6]);
#endif
if(cmd == SEND_OUTPUT_CHANNELS) //Send output channels command 0x30 is 48dec
{
generateLiveValues(offset, length);
sendSerialPayloadNonBlocking(length + 1U);
}
else if(cmd == 0x0f)
{
//Request for signature
(void)memcpy_P(serialPayload, codeVersion, sizeof(codeVersion) );
sendSerialPayloadNonBlocking(sizeof(codeVersion));
}
#ifdef RTC_ENABLED
else if(cmd == SD_RTC_PAGE) //Request to read SD card RTC
{
serialPayload[0] = SERIAL_RC_OK;
serialPayload[1] = rtc_getSecond(); //Seconds
serialPayload[2] = rtc_getMinute(); //Minutes
serialPayload[3] = rtc_getHour(); //Hours
serialPayload[4] = rtc_getDOW(); //Day of week
serialPayload[5] = rtc_getDay(); //Day of month
serialPayload[6] = rtc_getMonth(); //Month
serialPayload[7] = highByte(rtc_getYear()); //Year
serialPayload[8] = lowByte(rtc_getYear()); //Year
sendSerialPayloadNonBlocking(9);
}
else if(cmd == SD_READWRITE_PAGE) //Request SD card extended parameters
{
//SD read commands use the offset and length fields to indicate the request type
if((SD_arg1 == SD_READ_STAT_ARG1) && (SD_arg2 == SD_READ_STAT_ARG2))
{
//Read the status of the SD card
serialPayload[0] = SERIAL_RC_OK;
serialPayload[1] = currentStatus.TS_SD_Status;
serialPayload[2] = 0; //Error code
//Sector size = 512
serialPayload[3] = 2;
serialPayload[4] = 0;
//Max blocks (4 bytes)
uint32_t sectors = sectorCount();
serialPayload[5] = ((sectors >> 24) & 255);
serialPayload[6] = ((sectors >> 16) & 255);
serialPayload[7] = ((sectors >> 8) & 255);
serialPayload[8] = (sectors & 255);
/*
serialPayload[5] = 0;
serialPayload[6] = 0x20; //1gb dummy card
serialPayload[7] = 0;
serialPayload[8] = 0;
*/
//Max roots (Number of files)
uint16_t numLogFiles = getNextSDLogFileNumber() - 2; // -1 because this returns the NEXT file name not the current one and -1 because TS expects a 0 based index
serialPayload[9] = highByte(numLogFiles);
serialPayload[10] = lowByte(numLogFiles);
//Dir Start (4 bytes)
serialPayload[11] = 0;
serialPayload[12] = 0;
serialPayload[13] = 0;
serialPayload[14] = 0;
//Unknown purpose for last 2 bytes
serialPayload[15] = 0;
serialPayload[16] = 0;
sendSerialPayloadNonBlocking(17);
}
else if((SD_arg1 == SD_READ_DIR_ARG1) && (SD_arg2 == SD_READ_DIR_ARG2))
{
//Send file details
serialPayload[0] = SERIAL_RC_OK;
uint16_t logFileNumber = (SDcurrentDirChunk * 16) + 1;
uint8_t filesInCurrentChunk = 0;
uint16_t payloadIndex = 1;
while((filesInCurrentChunk < 16) && (getSDLogFileDetails(&serialPayload[payloadIndex], logFileNumber) == true))
{
logFileNumber++;
filesInCurrentChunk++;
payloadIndex += 32;
}
serialPayload[payloadIndex] = lowByte(SDcurrentDirChunk);
serialPayload[payloadIndex + 1] = highByte(SDcurrentDirChunk);
//Serial.print("Index:");
//Serial.print(payloadIndex);
sendSerialPayloadNonBlocking(payloadIndex + 2);
}
}
else if(cmd == SD_READFILE_PAGE)
{
//Fetch data from file
if(SD_arg2 == SD_READ_COMP_ARG2)
{
//arg1 is the block number to return
serialPayload[0] = SERIAL_RC_OK;
serialPayload[1] = highByte(SD_arg1);
serialPayload[2] = lowByte(SD_arg1);
uint32_t currentSector = SDreadStartSector + (SD_arg1 * 4);
int32_t numSectorsToSend = 0;
if(SDreadNumSectors > SDreadCompletedSectors)
{
numSectorsToSend = SDreadNumSectors - SDreadCompletedSectors;
if(numSectorsToSend > 4) //Maximum of 4 sectors at a time
{
numSectorsToSend = 4;
}
}
SDreadCompletedSectors += numSectorsToSend;
if(numSectorsToSend <= 0) { sendReturnCodeMsg(SERIAL_RC_OK); }
else
{
readSDSectors(&serialPayload[3], currentSector, numSectorsToSend);
sendSerialPayloadNonBlocking(numSectorsToSend * SD_SECTOR_SIZE + 3);
}
}
}
#endif
else
{
//No other r/ commands should be called
}
break;
}
case 'S': // send code version
(void)memcpy_P(serialPayload, productString, sizeof(productString) );
sendSerialPayloadNonBlocking(sizeof(productString));
currentStatus.secl = 0; //This is required in TS3 due to its stricter timings
break;
case 'T': //Send 256 tooth log entries to Tuner Studios tooth logger
logItemsTransmitted = 0;
if(currentStatus.toothLogEnabled == true) { sendToothLog(); } //Sends tooth log values as ints
else if (currentStatus.compositeTriggerUsed > 0) { sendCompositeLog(); }
else { /* MISRA no-op */ }
break;
case 't': // receive new Calibration info. Command structure: "t", <tble_idx> <data array>.
{
uint8_t cmd = serialPayload[2];
uint16_t offset = word(serialPayload[3], serialPayload[4]);
uint16_t calibrationLength = word(serialPayload[5], serialPayload[6]); // Should be 256
if(cmd == O2_CALIBRATION_PAGE)
{
loadO2CalibrationChunk(offset, calibrationLength);
sendReturnCodeMsg(SERIAL_RC_OK);
Serial.flush(); //This is safe because engine is assumed to not be running during calibration
}
else if(cmd == IAT_CALIBRATION_PAGE)
{
processTemperatureCalibrationTableUpdate(calibrationLength, IAT_CALIBRATION_PAGE, iatCalibration_values, iatCalibration_bins);
}
else if(cmd == CLT_CALIBRATION_PAGE)
{
processTemperatureCalibrationTableUpdate(calibrationLength, CLT_CALIBRATION_PAGE, cltCalibration_values, cltCalibration_bins);
}
else
{
sendReturnCodeMsg(SERIAL_RC_RANGE_ERR);
}
break;
}
case 'U': //User wants to reset the Arduino (probably for FW update)
if (resetControl != RESET_CONTROL_DISABLED)
{
#ifndef SMALL_FLASH_MODE
if (serialStatusFlag == SERIAL_INACTIVE) { Serial.println(F("Comms halted. Next byte will reset the Arduino.")); }
#endif
while (Serial.available() == 0) { }
digitalWrite(pinResetControl, LOW);
}
else
{
#ifndef SMALL_FLASH_MODE
if (serialStatusFlag == SERIAL_INACTIVE) { Serial.println(F("Reset control is currently disabled.")); }
#endif
}
break;
case 'w':
{
#ifdef RTC_ENABLED
uint8_t cmd = serialPayload[2];
uint16_t SD_arg1 = word(serialPayload[3], serialPayload[4]);
uint16_t SD_arg2 = word(serialPayload[5], serialPayload[6]);
if(cmd == SD_READWRITE_PAGE)
{
if((SD_arg1 == SD_WRITE_DO_ARG1) && (SD_arg2 == SD_WRITE_DO_ARG2))
{
/*
SD DO command. Single byte of data where the commands are:
0 Reset
1 Reset
2 Stop logging
3 Start logging
4 Load status variable
5 Init SD card
*/
uint8_t command = serialPayload[7];
if(command == 2) { endSDLogging(); manualLogActive = false; }
else if(command == 3) { beginSDLogging(); manualLogActive = true; }
else if(command == 4) { setTS_SD_status(); }
//else if(command == 5) { initSD(); }
sendReturnCodeMsg(SERIAL_RC_OK);
}
else if((SD_arg1 == SD_WRITE_DIR_ARG1) && (SD_arg2 == SD_WRITE_DIR_ARG2))
{
//Begin SD directory read. Value in payload represents the directory chunk to read
//Directory chunks are each 16 files long
SDcurrentDirChunk = word(serialPayload[7], serialPayload[8]);
sendReturnCodeMsg(SERIAL_RC_OK);
}
else if((SD_arg1 == SD_WRITE_SEC_ARG1) && (SD_arg2 == SD_WRITE_SEC_ARG2))
{
//SD write sector command
}
else if((SD_arg1 == SD_ERASEFILE_ARG1) && (SD_arg2 == SD_ERASEFILE_ARG2))
{
//Erase file command
//We just need the 4 ASCII characters of the file name
char log1 = serialPayload[7];
char log2 = serialPayload[8];
char log3 = serialPayload[9];
char log4 = serialPayload[10];
deleteLogFile(log1, log2, log3, log4);
sendReturnCodeMsg(SERIAL_RC_OK);
}
else if((SD_arg1 == SD_SPD_TEST_ARG1) && (SD_arg2 == SD_SPD_TEST_ARG2))
{
//Perform a speed test on the SD card
//First 4 bytes are the sector number to write to
uint32_t sector;
uint8_t sector1 = serialPayload[7];
uint8_t sector2 = serialPayload[8];
uint8_t sector3 = serialPayload[9];
uint8_t sector4 = serialPayload[10];
sector = (sector1 << 24) | (sector2 << 16) | (sector3 << 8) | sector4;
//Last 4 bytes are the number of sectors to test
uint32_t testSize;
uint8_t testSize1 = serialPayload[11];
uint8_t testSize2 = serialPayload[12];
uint8_t testSize3 = serialPayload[13];
uint8_t testSize4 = serialPayload[14];
testSize = (testSize1 << 24) | (testSize2 << 16) | (testSize3 << 8) | testSize4;
sendReturnCodeMsg(SERIAL_RC_OK);
}
else if((SD_arg1 == SD_WRITE_COMP_ARG1) && (SD_arg2 == SD_WRITE_COMP_ARG2))
{
//Prepare to read a 2024 byte chunk of data from the SD card
uint8_t sector1 = serialPayload[7];
uint8_t sector2 = serialPayload[8];
uint8_t sector3 = serialPayload[9];
uint8_t sector4 = serialPayload[10];
//SDreadStartSector = (sector1 << 24) | (sector2 << 16) | (sector3 << 8) | sector4;
SDreadStartSector = (sector4 << 24) | (sector3 << 16) | (sector2 << 8) | sector1;
//SDreadStartSector = sector4 | (sector3 << 8) | (sector2 << 16) | (sector1 << 24);
//Next 4 bytes are the number of sectors to write
uint8_t sectorCount1 = serialPayload[11];
uint8_t sectorCount2 = serialPayload[12];
uint8_t sectorCount3 = serialPayload[13];
uint8_t sectorCount4 = serialPayload[14];
SDreadNumSectors = (sectorCount1 << 24) | (sectorCount2 << 16) | (sectorCount3 << 8) | sectorCount4;
//Reset the sector counter
SDreadCompletedSectors = 0;
sendReturnCodeMsg(SERIAL_RC_OK);
}
}
else if(cmd == SD_RTC_PAGE)
{
//Used for setting RTC settings
if((SD_arg1 == SD_RTC_WRITE_ARG1) && (SD_arg2 == SD_RTC_WRITE_ARG2))
{
//Set the RTC date/time
byte second = serialPayload[7];
byte minute = serialPayload[8];
byte hour = serialPayload[9];
//byte dow = serialPayload[10]; //Not used
byte day = serialPayload[11];
byte month = serialPayload[12];
uint16_t year = word(serialPayload[13], serialPayload[14]);
rtc_setTime(second, minute, hour, day, month, year);
sendReturnCodeMsg(SERIAL_RC_OK);
}
}
#endif
break;
}
default:
//Unknown command
sendReturnCodeMsg(SERIAL_RC_UKWN_ERR);
break;
}
}
/**
*
*/
void sendToothLog(void)
{
//We need TOOTH_LOG_SIZE number of records to send to TunerStudio. If there aren't that many in the buffer then we just return and wait for the next call
if (BIT_CHECK(currentStatus.status1, BIT_STATUS1_TOOTHLOG1READY) == false)
{
//If the buffer is not yet full but TS has timed out, pad the rest of the buffer with 0s
while(toothHistoryIndex < TOOTH_LOG_SIZE)
{
toothHistory[toothHistoryIndex] = 0;
toothHistoryIndex++;
}
}
uint32_t CRC32_val = 0;
if(logItemsTransmitted == 0)
{
//Transmit the size of the packet
(void)serialWrite((uint16_t)(sizeof(toothHistory) + 1U)); //Size of the tooth log (uint32_t values) plus the return code
//Begin new CRC hash
const uint8_t returnCode = SERIAL_RC_OK;
CRC32_val = CRC32_serial.crc32(&returnCode, 1, false);
//Send the return code
writeByteReliableBlocking(returnCode);
}
for (; logItemsTransmitted < TOOTH_LOG_SIZE; logItemsTransmitted++)
{
//Check whether the tx buffer still has space
if(Serial.availableForWrite() < 4)
{
//tx buffer is full. Store the current state so it can be resumed later
serialStatusFlag = SERIAL_TRANSMIT_TOOTH_INPROGRESS;
return;
}
//Transmit the tooth time
uint32_t transmitted = serialWrite(toothHistory[logItemsTransmitted]);
CRC32_val = CRC32_serial.crc32_upd((const byte*)&transmitted, sizeof(transmitted), false);
}
BIT_CLEAR(currentStatus.status1, BIT_STATUS1_TOOTHLOG1READY);
serialStatusFlag = SERIAL_INACTIVE;
toothHistoryIndex = 0;
logItemsTransmitted = 0;
//Apply the CRC reflection
CRC32_val = ~CRC32_val;
//Send the CRC
(void)serialWrite(CRC32_val);
}
void sendCompositeLog(void)
{
if ( BIT_CHECK(currentStatus.status1, BIT_STATUS1_TOOTHLOG1READY) == false )
{
//If the buffer is not yet full but TS has timed out, pad the rest of the buffer with 0s
while(toothHistoryIndex < TOOTH_LOG_SIZE)
{
toothHistory[toothHistoryIndex] = toothHistory[toothHistoryIndex-1]; //Composite logger needs a realistic time value to display correctly. Copy the last value
compositeLogHistory[toothHistoryIndex] = 0;
toothHistoryIndex++;
}
}
uint32_t CRC32_val = 0;
if(logItemsTransmitted == 0)
{
//Transmit the size of the packet
(void)serialWrite((uint16_t)(sizeof(toothHistory) + sizeof(compositeLogHistory) + 1U)); //Size of the tooth log (uint32_t values) plus the return code
//Begin new CRC hash
const uint8_t returnCode = SERIAL_RC_OK;
CRC32_val = CRC32_serial.crc32(&returnCode, 1, false);
//Send the return code
writeByteReliableBlocking(returnCode);
}
for (; logItemsTransmitted < TOOTH_LOG_SIZE; logItemsTransmitted++)
{
//Check whether the tx buffer still has space
if((uint16_t)Serial.availableForWrite() < sizeof(toothHistory[logItemsTransmitted])+sizeof(compositeLogHistory[logItemsTransmitted]))
{
//tx buffer is full. Store the current state so it can be resumed later
serialStatusFlag = SERIAL_TRANSMIT_COMPOSITE_INPROGRESS;
return;
}
uint32_t transmitted = serialWrite(toothHistory[logItemsTransmitted]); //This combined runtime (in us) that the log was going for by this record
CRC32_serial.crc32_upd((const byte*)&transmitted, sizeof(transmitted), false);
//The status byte (Indicates the trigger edge, whether it was a pri/sec pulse, the sync status)
writeByteReliableBlocking(compositeLogHistory[logItemsTransmitted]);
CRC32_val = CRC32_serial.crc32_upd((const byte*)&compositeLogHistory[logItemsTransmitted], sizeof(compositeLogHistory[logItemsTransmitted]), false);
}
BIT_CLEAR(currentStatus.status1, BIT_STATUS1_TOOTHLOG1READY);
toothHistoryIndex = 0;
serialStatusFlag = SERIAL_INACTIVE;
logItemsTransmitted = 0;
//Apply the CRC reflection
CRC32_val = ~CRC32_val;
//Send the CRC
(void)serialWrite(CRC32_val);
}
#if defined(CORE_AVR)
#pragma GCC pop_options
#endif
| 40,867
|
C++
|
.cpp
| 1,014
| 34.5286
| 206
| 0.663698
|
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,036
|
pages.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/pages.cpp
|
#include "pages.h"
#include "globals.h"
#include "utilities.h"
#include "table3d_axis_io.h"
// Maps from virtual page "addresses" to addresses/bytes of real in memory entities
//
// For TunerStudio:
// 1. Each page has a numeric identifier (0 to N-1)
// 2. A single page is a contiguous block of data.
// So individual bytes are identified by a (page number, offset)
//
// The TS layout is not what is in memory. E.g.
//
// TS Page 2 |0123456789ABCD|0123456789ABCDEF|
// | |
// Arduino In Memory |--- Entity A ---| |--- Entity B -----|
//
// Further, the in memory entity may also not be contiguous or in the same
// order that TS expects
//
// So there is a 2 stage mapping:
// 1. Page # + Offset to entity
// 2. Offset to intra-entity byte
// Page sizes as defined in the .ini file
constexpr const uint16_t PROGMEM ini_page_sizes[] = { 0, 128, 288, 288, 128, 288, 128, 240, 384, 192, 192, 288, 192, 128, 288, 256 };
// ========================= Table size calculations =========================
// Note that these should be computed at compile time, assuming the correct
// calling context.
template <class table_t>
inline constexpr uint16_t get_table_value_end()
{
return table_t::xaxis_t::length*table_t::yaxis_t::length;
}
template <class table_t>
inline constexpr uint16_t get_table_axisx_end()
{
return get_table_value_end<table_t>()+table_t::xaxis_t::length;
}
template <class table_t>
inline constexpr uint16_t get_table_axisy_end(const table_t *)
{
return get_table_axisx_end<table_t>()+table_t::yaxis_t::length;
}
// ========================= Intra-table offset to byte class =========================
template<class table_t>
class offset_to_table
{
public:
// This class encapsulates mapping a linear offset to the various parts of a table
// and exposing the linear offset as an mutable byte.
//
// Tables do not map linearly to the TS page address space, so special
// handling is necessary (we do not use the normal array layout for
// performance reasons elsewhere)
//
// We take the offset & map it to a single value, x-axis or y-axis element
//
// Using a template here is a performance boost - we can call functions that
// are specialised per table type, which allows the compiler more optimisation
// opportunities. See get_table_value().
offset_to_table(table_t *pTable, uint16_t table_offset)
: _pTable(pTable),
_table_offset(table_offset)
{
}
// Getter
inline byte operator*() const
{
switch (get_table_location())
{
case table_location_values:
return get_value_value();
case table_location_xaxis:
return table3d_axis_io::to_byte(table_t::xaxis_t::domain, get_xaxis_value());
case table_location_yaxis:
default:
return table3d_axis_io::to_byte(table_t::yaxis_t::domain, get_yaxis_value());
}
}
// Setter
inline offset_to_table &operator=( byte new_value )
{
switch (get_table_location())
{
case table_location_values:
get_value_value() = new_value;
break;
case table_location_xaxis:
get_xaxis_value() = table3d_axis_io::from_byte(table_t::xaxis_t::domain, new_value);
break;
case table_location_yaxis:
default:
get_yaxis_value() = table3d_axis_io::from_byte(table_t::yaxis_t::domain, new_value);
}
invalidate_cache(&_pTable->get_value_cache);
return *this;
}
private:
inline byte& get_value_value() const
{
return _pTable->values.value_at((uint8_t)_table_offset);
}
inline table3d_axis_t& get_xaxis_value() const
{
return *(_pTable->axisX.begin().advance(_table_offset - get_table_value_end<table_t>()));
}
inline table3d_axis_t& get_yaxis_value() const
{
return *(_pTable->axisY.begin().advance(_table_offset - get_table_axisx_end<table_t>()));
}
enum table_location {
table_location_values, table_location_xaxis, table_location_yaxis
};
inline table_location get_table_location() const
{
if (_table_offset<get_table_value_end<table_t>())
{
return table_location_values;
}
if (_table_offset<get_table_axisx_end<table_t>())
{
return table_location_xaxis;
}
return table_location_yaxis;
}
table_t *_pTable;
uint16_t _table_offset;
};
// ========================= Offset to entity byte mapping =========================
inline byte& get_raw_location(page_iterator_t &entity, uint16_t offset)
{
return *((byte*)entity.pData + (offset-entity.start));
}
inline byte get_table_value(page_iterator_t &entity, uint16_t offset)
{
#define CTA_GET_TABLE_VALUE(size, xDomain, yDomain, pTable, offset) \
return *offset_to_table<TABLE3D_TYPENAME_BASE(size, xDomain, yDomain)>((TABLE3D_TYPENAME_BASE(size, xDomain, yDomain)*)pTable, offset);
CONCRETE_TABLE_ACTION(entity.table_key, CTA_GET_TABLE_VALUE, entity.pData, (offset-entity.start));
}
inline byte get_value(page_iterator_t &entity, uint16_t offset)
{
if (Raw==entity.type)
{
return get_raw_location(entity, offset);
}
if (Table==entity.type)
{
return get_table_value(entity, offset);
}
return 0U;
}
inline void set_table_value(page_iterator_t &entity, uint16_t offset, byte new_value)
{
#define CTA_SET_TABLE_VALUE(size, xDomain, yDomain, pTable, offset, new_value) \
offset_to_table<TABLE3D_TYPENAME_BASE(size, xDomain, yDomain)>((TABLE3D_TYPENAME_BASE(size, xDomain, yDomain)*)pTable, offset) = new_value; break;
CONCRETE_TABLE_ACTION(entity.table_key, CTA_SET_TABLE_VALUE, entity.pData, (offset-entity.start), new_value);
}
inline void set_value(page_iterator_t &entity, byte value, uint16_t offset)
{
if (Raw==entity.type)
{
get_raw_location(entity, offset) = value;
}
else if (Table==entity.type)
{
set_table_value(entity, offset, value);
}
}
// ========================= Static page size computation & checking ===================
// This will fail AND print the page number and required size
template <uint8_t pageNum, uint16_t min>
static inline void check_size() {
static_assert(ini_page_sizes[pageNum] >= min, "Size is off!");
}
// Since pages are a logical contiguous block, we can automatically compute the
// logical start address of every item: the first one starts at zero, following
// items must start at the end of the previous.
#define _ENTITY_START(entityNum) entity ## entityNum ## Start
#define ENTITY_START_VAR(entityNum) _ENTITY_START(entityNum)
// Compute the start address of the next entity. We need this to be a constexpr
// so we can static assert on it later. So we cannot increment an exiting var.
#define DECLARE_NEXT_ENTITY_START(entityIndex, entitySize) \
constexpr uint16_t ENTITY_START_VAR( PP_INC(entityIndex) ) = ENTITY_START_VAR(entityIndex)+entitySize;
// ========================= Logical page end processing ===================
// The members of all page_iterator_t instances are compile time constants and
// thus all page_iterator_t instances *could* be compile time constants.
//
// If we declare them inline as part of return statements, gcc recognises they
// are constants (even without constexpr). Constants need to be stored somewhere:
// gcc places them in the .data section, which is placed in SRAM :-(.
//
// So we would end up using several hundred bytes of SRAM.
//
// Instead we use this (and other) intermediate factory function(s) - it provides a barrier that
// forces GCC to construct the page_iterator_t instance at runtime.
inline const page_iterator_t create_end_iterator(uint8_t pageNum, uint16_t start)
{
return page_iterator_t {
.pData = nullptr,
.table_key = table_type_None,
.page = pageNum,
.start = start,
.size = start,
.type = End,
};
}
// Signal the end of a page
#define END_OF_PAGE(pageNum, entityNum) \
check_size<pageNum, ENTITY_START_VAR(entityNum)>(); \
return create_end_iterator(pageNum, ENTITY_START_VAR(entityNum)); \
// ========================= Table processing ===================
inline const page_iterator_t create_table_iterator(void *pTable, table_type_t key, uint8_t pageNum, uint16_t start, uint16_t size)
{
return page_iterator_t {
.pData = pTable,
.table_key = key,
.page = pageNum,
.start = start,
.size = size,
.type = Table,
};
}
// If the offset is in range, create a Table entity_t
#define CHECK_TABLE(pageNum, offset, pTable, entityNum) \
if (offset < ENTITY_START_VAR(entityNum)+get_table_axisy_end(pTable)) \
{ \
return create_table_iterator(pTable, (pTable)->type_key, \
pageNum, \
ENTITY_START_VAR(entityNum), get_table_axisy_end(pTable)); \
} \
DECLARE_NEXT_ENTITY_START(entityNum, get_table_axisy_end(pTable))
// ========================= Raw memory block processing ===================
inline const page_iterator_t create_raw_iterator(void *pBuffer, uint8_t pageNum, uint16_t start, uint16_t size)
{
return page_iterator_t {
.pData = pBuffer,
.table_key = table_type_None,
.page = pageNum,
.start = start,
.size = size,
.type = Raw,
};
}
// If the offset is in range, create a Raw entity_t
#define CHECK_RAW(pageNum, offset, pDataBlock, blockSize, entityNum) \
if (offset < ENTITY_START_VAR(entityNum)+blockSize) \
{ \
return create_raw_iterator(pDataBlock, pageNum, ENTITY_START_VAR(entityNum), blockSize);\
} \
DECLARE_NEXT_ENTITY_START(entityNum, blockSize)
// ===============================================================================
// Does the heavy lifting of mapping page+offset to an entity
//
// Alternative implementation would be to encode the mapping into data structures
// That uses flash memory, which is scarce. And it was too slow.
static inline __attribute__((always_inline)) // <-- this is critical for performance
page_iterator_t map_page_offset_to_entity(uint8_t pageNumber, uint16_t offset)
{
// The start address of the 1st entity in any page.
static constexpr uint16_t ENTITY_START_VAR(0) = 0U;
switch (pageNumber)
{
case 0:
END_OF_PAGE(0, 0)
case veMapPage:
{
CHECK_TABLE(veMapPage, offset, &fuelTable, 0)
END_OF_PAGE(veMapPage, 1)
}
case ignMapPage: //Ignition settings page (Page 2)
{
CHECK_TABLE(ignMapPage, offset, &ignitionTable, 0)
END_OF_PAGE(ignMapPage, 1)
}
case afrMapPage: //Air/Fuel ratio target settings page
{
CHECK_TABLE(afrMapPage, offset, &afrTable, 0)
END_OF_PAGE(afrMapPage, 1)
}
case boostvvtPage: //Boost, VVT and staging maps (all 8x8)
{
CHECK_TABLE(boostvvtPage, offset, &boostTable, 0)
CHECK_TABLE(boostvvtPage, offset, &vvtTable, 1)
CHECK_TABLE(boostvvtPage, offset, &stagingTable, 2)
END_OF_PAGE(boostvvtPage, 3)
}
case seqFuelPage:
{
CHECK_TABLE(seqFuelPage, offset, &trim1Table, 0)
CHECK_TABLE(seqFuelPage, offset, &trim2Table, 1)
CHECK_TABLE(seqFuelPage, offset, &trim3Table, 2)
CHECK_TABLE(seqFuelPage, offset, &trim4Table, 3)
CHECK_TABLE(seqFuelPage, offset, &trim5Table, 4)
CHECK_TABLE(seqFuelPage, offset, &trim6Table, 5)
CHECK_TABLE(seqFuelPage, offset, &trim7Table, 6)
CHECK_TABLE(seqFuelPage, offset, &trim8Table, 7)
END_OF_PAGE(seqFuelPage, 8)
}
case fuelMap2Page:
{
CHECK_TABLE(fuelMap2Page, offset, &fuelTable2, 0)
END_OF_PAGE(fuelMap2Page, 1)
}
case wmiMapPage:
{
CHECK_TABLE(wmiMapPage, offset, &wmiTable, 0)
CHECK_TABLE(wmiMapPage, offset, &vvt2Table, 1)
CHECK_TABLE(wmiMapPage, offset, &dwellTable, 2)
END_OF_PAGE(wmiMapPage, 3)
}
case ignMap2Page:
{
CHECK_TABLE(ignMap2Page, offset, &ignitionTable2, 0)
END_OF_PAGE(ignMap2Page, 1)
}
case veSetPage:
{
CHECK_RAW(veSetPage, offset, &configPage2, sizeof(configPage2), 0)
END_OF_PAGE(veSetPage, 1)
}
case ignSetPage:
{
CHECK_RAW(ignSetPage, offset, &configPage4, sizeof(configPage4), 0)
END_OF_PAGE(ignSetPage, 1)
}
case afrSetPage:
{
CHECK_RAW(afrSetPage, offset, &configPage6, sizeof(configPage6), 0)
END_OF_PAGE(afrSetPage, 1)
}
case canbusPage:
{
CHECK_RAW(canbusPage, offset, &configPage9, sizeof(configPage9), 0)
END_OF_PAGE(canbusPage, 1)
}
case warmupPage:
{
CHECK_RAW(warmupPage, offset, &configPage10, sizeof(configPage10), 0)
END_OF_PAGE(warmupPage, 1)
}
case progOutsPage:
{
CHECK_RAW(progOutsPage, offset, &configPage13, sizeof(configPage13), 0)
END_OF_PAGE(progOutsPage, 1)
}
case boostvvtPage2: //Boost, VVT and staging maps (all 8x8)
{
CHECK_TABLE(boostvvtPage2, offset, &boostTableLookupDuty, 0)
CHECK_RAW(boostvvtPage2, offset, &configPage15, sizeof(configPage15), 1)
END_OF_PAGE(boostvvtPage2, 2)
}
default:
abort(); // Unknown page number. Not a lot we can do.
break;
}
}
// ====================================== External functions ====================================
uint8_t getPageCount(void)
{
return _countof(ini_page_sizes);
}
uint16_t getPageSize(byte pageNum)
{
return pgm_read_word(&(ini_page_sizes[pageNum]));
}
void setPageValue(byte pageNum, uint16_t offset, byte value)
{
page_iterator_t entity = map_page_offset_to_entity(pageNum, offset);
set_value(entity, value, offset);
}
byte getPageValue(byte pageNum, uint16_t offset)
{
page_iterator_t entity = map_page_offset_to_entity(pageNum, offset);
return get_value(entity, offset);
}
// Support iteration over a pages entities.
// Check for entity.type==End
page_iterator_t page_begin(byte pageNum)
{
return map_page_offset_to_entity(pageNum, 0U);
}
page_iterator_t advance(const page_iterator_t &it)
{
return map_page_offset_to_entity(it.page, it.start+it.size);
}
/**
* Convert page iterator to table value iterator.
*/
table_value_iterator rows_begin(const page_iterator_t &it)
{
return rows_begin(it.pData, it.table_key);
}
/**
* Convert page iterator to table x axis iterator.
*/
table_axis_iterator x_begin(const page_iterator_t &it)
{
return x_begin(it.pData, it.table_key);
}
/**
* Convert page iterator to table x axis iterator.
*/
table_axis_iterator x_rbegin(const page_iterator_t &it)
{
return x_rbegin(it.pData, it.table_key);
}
/**
* Convert page iterator to table y axis iterator.
*/
table_axis_iterator y_begin(const page_iterator_t &it)
{
return y_begin(it.pData, it.table_key);
}
| 14,617
|
C++
|
.cpp
| 413
| 31.600484
| 152
| 0.67141
|
oelprinz-org/BlitzboxBL49sp
| 36
| 12
| 0
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,540,037
|
storage.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/storage.cpp
|
/*
Speeduino - Simple engine management for the Arduino Mega 2560 platform
Copyright (C) Josh Stewart
A full copy of the license may be found in the projects root directory
*/
/** @file
* Lower level ConfigPage*, Table2D, Table3D and EEPROM storage operations.
*/
#include "globals.h"
#include EEPROM_LIB_H //This is defined in the board .h files
#include "storage.h"
#include "pages.h"
#include "table3d_axis_io.h"
#define EEPROM_DATA_VERSION 0
// Calibration data is stored at the end of the EEPROM (This is in case any further calibration tables are needed as they are large blocks)
#define STORAGE_END 0xFFF // Should be E2END?
#define EEPROM_CALIBRATION_CLT_VALUES (STORAGE_END-sizeof(cltCalibration_values))
#define EEPROM_CALIBRATION_CLT_BINS (EEPROM_CALIBRATION_CLT_VALUES-sizeof(cltCalibration_bins))
#define EEPROM_CALIBRATION_IAT_VALUES (EEPROM_CALIBRATION_CLT_BINS-sizeof(iatCalibration_values))
#define EEPROM_CALIBRATION_IAT_BINS (EEPROM_CALIBRATION_IAT_VALUES-sizeof(iatCalibration_bins))
#define EEPROM_CALIBRATION_O2_VALUES (EEPROM_CALIBRATION_IAT_BINS-sizeof(o2Calibration_values))
#define EEPROM_CALIBRATION_O2_BINS (EEPROM_CALIBRATION_O2_VALUES-sizeof(o2Calibration_bins))
#define EEPROM_LAST_BARO (EEPROM_CALIBRATION_O2_BINS-1)
uint32_t deferEEPROMWritesUntil = 0;
bool isEepromWritePending(void)
{
return BIT_CHECK(currentStatus.status4, BIT_STATUS4_BURNPENDING);
}
/** Write all config pages to EEPROM.
*/
void writeAllConfig(void)
{
uint8_t pageCount = getPageCount();
uint8_t page = 1U;
writeConfig(page);
page = page + 1;
while (page<pageCount && !isEepromWritePending())
{
writeConfig(page);
page = page + 1;
}
}
// ================================= Internal write support ===============================
struct write_location {
eeprom_address_t address; // EEPROM address to write next
uint16_t counter; // Number of bytes written
uint8_t write_block_size; // Maximum number of bytes to write
/** Update byte to EEPROM by first comparing content and the need to write it.
We only ever write to the EEPROM where the new value is different from the currently stored byte
This is due to the limited write life of the EEPROM (Approximately 100,000 writes)
*/
void update(uint8_t value)
{
if (EEPROM.read(address)!=value)
{
EEPROM.write(address, value);
++counter;
}
}
/** Create a copy with a different write address.
* Allows chaining of instances.
*/
write_location changeWriteAddress(eeprom_address_t newAddress) const {
return { newAddress, counter, write_block_size };
}
write_location& operator++()
{
++address;
return *this;
}
bool can_write() const
{
bool canWrite = false;
if(currentStatus.RPM > 0) { canWrite = (counter <= write_block_size); }
else { canWrite = (counter <= (write_block_size * 8)); } //Write to EEPROM more aggressively if the engine is not running
return canWrite;
}
};
static inline write_location write_range(const byte *pStart, const byte *pEnd, write_location location)
{
while ( location.can_write() && pStart!=pEnd)
{
location.update(*pStart);
++pStart;
++location;
}
return location;
}
static inline write_location write(const table_row_iterator &row, write_location location)
{
return write_range(&*row, row.end(), location);
}
static inline write_location write(table_value_iterator it, write_location location)
{
while (location.can_write() && !it.at_end())
{
location = write(*it, location);
++it;
}
return location;
}
static inline write_location write(table_axis_iterator it, write_location location)
{
const int16_byte *pConverter = table3d_axis_io::get_converter(it.get_domain());
while (location.can_write() && !it.at_end())
{
location.update(pConverter->to_byte(*it));
++location;
++it;
}
return location;
}
static inline write_location writeTable(const void *pTable, table_type_t key, write_location location)
{
return write(y_rbegin(pTable, key),
write(x_begin(pTable, key),
write(rows_begin(pTable, key), location)));
}
//Simply an alias for EEPROM.update()
void EEPROMWriteRaw(uint16_t address, uint8_t data) { EEPROM.update(address, data); }
uint8_t EEPROMReadRaw(uint16_t address) { return EEPROM.read(address); }
// ================================= End write support ===============================
/** Write a table or map to EEPROM storage.
Takes the current configuration (config pages and maps)
and writes them to EEPROM as per the layout defined in storage.h.
*/
void writeConfig(uint8_t pageNum)
{
//The maximum number of write operations that will be performed in one go.
//If we try to write to the EEPROM too fast (Eg Each write takes ~3ms on the AVR) then
//the rest of the system can hang)
#if defined(USE_SPI_EEPROM)
//For use with common Winbond SPI EEPROMs Eg W25Q16JV
uint8_t EEPROM_MAX_WRITE_BLOCK = 20; //This needs tuning
#elif defined(CORE_STM32) || defined(CORE_TEENSY)
uint8_t EEPROM_MAX_WRITE_BLOCK = 64;
#else
uint8_t EEPROM_MAX_WRITE_BLOCK = 18;
if(BIT_CHECK(currentStatus.status4, BIT_STATUS4_COMMS_COMPAT)) { EEPROM_MAX_WRITE_BLOCK = 8; } //If comms compatibility mode is on, slow the burn rate down even further
#ifdef CORE_AVR
//In order to prevent missed pulses during EEPROM writes on AVR, scale the
//maximum write block size based on the RPM.
//This calculation is based on EEPROM writes taking approximately 4ms per byte
//(Actual value is 3.8ms, so 4ms has some safety margin)
if(currentStatus.RPM > 65) //Min RPM of 65 prevents overflow of uint8_t
{
EEPROM_MAX_WRITE_BLOCK = (uint8_t)(15000U / currentStatus.RPM);
EEPROM_MAX_WRITE_BLOCK = max(EEPROM_MAX_WRITE_BLOCK, 1);
EEPROM_MAX_WRITE_BLOCK = min(EEPROM_MAX_WRITE_BLOCK, 15); //Any higher than this will cause comms timeouts on AVR
}
#endif
#endif
write_location result = { 0, 0, EEPROM_MAX_WRITE_BLOCK };
switch(pageNum)
{
case veMapPage:
/*---------------------------------------------------
| Fuel table (See storage.h for data layout) - Page 1
| 16x16 table itself + the 16 values along each of the axis
-----------------------------------------------------*/
result = writeTable(&fuelTable, decltype(fuelTable)::type_key, result.changeWriteAddress(EEPROM_CONFIG1_MAP));
break;
case veSetPage:
/*---------------------------------------------------
| Config page 2 (See storage.h for data layout)
| 64 byte long config table
-----------------------------------------------------*/
result = write_range((byte *)&configPage2, (byte *)&configPage2+sizeof(configPage2), result.changeWriteAddress(EEPROM_CONFIG2_START));
break;
case ignMapPage:
/*---------------------------------------------------
| Ignition table (See storage.h for data layout) - Page 1
| 16x16 table itself + the 16 values along each of the axis
-----------------------------------------------------*/
result = writeTable(&ignitionTable, decltype(ignitionTable)::type_key, result.changeWriteAddress(EEPROM_CONFIG3_MAP));
break;
case ignSetPage:
/*---------------------------------------------------
| Config page 2 (See storage.h for data layout)
| 64 byte long config table
-----------------------------------------------------*/
result = write_range((byte *)&configPage4, (byte *)&configPage4+sizeof(configPage4), result.changeWriteAddress(EEPROM_CONFIG4_START));
break;
case afrMapPage:
/*---------------------------------------------------
| AFR table (See storage.h for data layout) - Page 5
| 16x16 table itself + the 16 values along each of the axis
-----------------------------------------------------*/
result = writeTable(&afrTable, decltype(afrTable)::type_key, result.changeWriteAddress(EEPROM_CONFIG5_MAP));
break;
case afrSetPage:
/*---------------------------------------------------
| Config page 3 (See storage.h for data layout)
| 64 byte long config table
-----------------------------------------------------*/
result = write_range((byte *)&configPage6, (byte *)&configPage6+sizeof(configPage6), result.changeWriteAddress(EEPROM_CONFIG6_START));
break;
case boostvvtPage:
/*---------------------------------------------------
| Boost and vvt tables (See storage.h for data layout) - Page 8
| 8x8 table itself + the 8 values along each of the axis
-----------------------------------------------------*/
result = writeTable(&boostTable, decltype(boostTable)::type_key, result.changeWriteAddress(EEPROM_CONFIG7_MAP1));
result = writeTable(&vvtTable, decltype(vvtTable)::type_key, result.changeWriteAddress(EEPROM_CONFIG7_MAP2));
result = writeTable(&stagingTable, decltype(stagingTable)::type_key, result.changeWriteAddress(EEPROM_CONFIG7_MAP3));
break;
case seqFuelPage:
/*---------------------------------------------------
| Fuel trim tables (See storage.h for data layout) - Page 9
| 6x6 tables itself + the 6 values along each of the axis
-----------------------------------------------------*/
result = writeTable(&trim1Table, decltype(trim1Table)::type_key, result.changeWriteAddress(EEPROM_CONFIG8_MAP1));
result = writeTable(&trim2Table, decltype(trim2Table)::type_key, result.changeWriteAddress(EEPROM_CONFIG8_MAP2));
result = writeTable(&trim3Table, decltype(trim3Table)::type_key, result.changeWriteAddress(EEPROM_CONFIG8_MAP3));
result = writeTable(&trim4Table, decltype(trim4Table)::type_key, result.changeWriteAddress(EEPROM_CONFIG8_MAP4));
result = writeTable(&trim5Table, decltype(trim5Table)::type_key, result.changeWriteAddress(EEPROM_CONFIG8_MAP5));
result = writeTable(&trim6Table, decltype(trim6Table)::type_key, result.changeWriteAddress(EEPROM_CONFIG8_MAP6));
result = writeTable(&trim7Table, decltype(trim7Table)::type_key, result.changeWriteAddress(EEPROM_CONFIG8_MAP7));
result = writeTable(&trim8Table, decltype(trim8Table)::type_key, result.changeWriteAddress(EEPROM_CONFIG8_MAP8));
break;
case canbusPage:
/*---------------------------------------------------
| Config page 10 (See storage.h for data layout)
| 192 byte long config table
-----------------------------------------------------*/
result = write_range((byte *)&configPage9, (byte *)&configPage9+sizeof(configPage9), result.changeWriteAddress(EEPROM_CONFIG9_START));
break;
case warmupPage:
/*---------------------------------------------------
| Config page 11 (See storage.h for data layout)
| 192 byte long config table
-----------------------------------------------------*/
result = write_range((byte *)&configPage10, (byte *)&configPage10+sizeof(configPage10), result.changeWriteAddress(EEPROM_CONFIG10_START));
break;
case fuelMap2Page:
/*---------------------------------------------------
| Fuel table 2 (See storage.h for data layout)
| 16x16 table itself + the 16 values along each of the axis
-----------------------------------------------------*/
result = writeTable(&fuelTable2, decltype(fuelTable2)::type_key, result.changeWriteAddress(EEPROM_CONFIG11_MAP));
break;
case wmiMapPage:
/*---------------------------------------------------
| WMI and Dwell tables (See storage.h for data layout) - Page 12
| 8x8 WMI table itself + the 8 values along each of the axis
| 8x8 VVT2 table + the 8 values along each of the axis
| 4x4 Dwell table itself + the 4 values along each of the axis
-----------------------------------------------------*/
result = writeTable(&wmiTable, decltype(wmiTable)::type_key, result.changeWriteAddress(EEPROM_CONFIG12_MAP));
result = writeTable(&vvt2Table, decltype(vvt2Table)::type_key, result.changeWriteAddress(EEPROM_CONFIG12_MAP2));
result = writeTable(&dwellTable, decltype(dwellTable)::type_key, result.changeWriteAddress(EEPROM_CONFIG12_MAP3));
break;
case progOutsPage:
/*---------------------------------------------------
| Config page 13 (See storage.h for data layout)
-----------------------------------------------------*/
result = write_range((byte *)&configPage13, (byte *)&configPage13+sizeof(configPage13), result.changeWriteAddress(EEPROM_CONFIG13_START));
break;
case ignMap2Page:
/*---------------------------------------------------
| Ignition table (See storage.h for data layout) - Page 1
| 16x16 table itself + the 16 values along each of the axis
-----------------------------------------------------*/
result = writeTable(&ignitionTable2, decltype(ignitionTable2)::type_key, result.changeWriteAddress(EEPROM_CONFIG14_MAP));
break;
case boostvvtPage2:
/*---------------------------------------------------
| Boost duty cycle lookuptable (See storage.h for data layout) - Page 15
| 8x8 table itself + the 8 values along each of the axis
-----------------------------------------------------*/
result = writeTable(&boostTableLookupDuty, decltype(boostTableLookupDuty)::type_key, result.changeWriteAddress(EEPROM_CONFIG15_MAP));
/*---------------------------------------------------
| Config page 15 (See storage.h for data layout)
-----------------------------------------------------*/
result = write_range((byte *)&configPage15, (byte *)&configPage15+sizeof(configPage15), result.changeWriteAddress(EEPROM_CONFIG15_START));
break;
default:
break;
}
BIT_WRITE(currentStatus.status4, BIT_STATUS4_BURNPENDING, !result.can_write());
}
/** Reset all configPage* structs (2,4,6,9,10,13) and write them full of null-bytes.
*/
void resetConfigPages(void)
{
for (uint8_t page=1; page<getPageCount(); ++page)
{
page_iterator_t entity = page_begin(page);
while (entity.type!=End)
{
if (entity.type==Raw)
{
memset(entity.pData, 0, entity.size);
}
entity = advance(entity);
}
}
}
// ================================= Internal read support ===============================
/** Load range of bytes form EEPROM offset to memory.
* @param address - start offset in EEPROM
* @param pFirst - Start memory address
* @param pLast - End memory address
*/
static inline eeprom_address_t load_range(eeprom_address_t address, byte *pFirst, const byte *pLast)
{
#if defined(CORE_AVR)
// The generic code in the #else branch works but this provides a 45% speed up on AVR
size_t size = pLast-pFirst;
eeprom_read_block(pFirst, (const void*)(size_t)address, size);
return address+size;
#else
for (; pFirst != pLast; ++address, (void)++pFirst)
{
*pFirst = EEPROM.read(address);
}
return address;
#endif
}
static inline eeprom_address_t load(table_row_iterator row, eeprom_address_t address)
{
return load_range(address, &*row, row.end());
}
static inline eeprom_address_t load(table_value_iterator it, eeprom_address_t address)
{
while (!it.at_end())
{
address = load(*it, address);
++it;
}
return address;
}
static inline eeprom_address_t load(table_axis_iterator it, eeprom_address_t address)
{
const int16_byte *pConverter = table3d_axis_io::get_converter(it.get_domain());
while (!it.at_end())
{
*it = pConverter->from_byte(EEPROM.read(address));
++address;
++it;
}
return address;
}
static inline eeprom_address_t loadTable(const void *pTable, table_type_t key, eeprom_address_t address)
{
return load(y_rbegin(pTable, key),
load(x_begin(pTable, key),
load(rows_begin(pTable, key), address)));
}
// ================================= End internal read support ===============================
/** Load all config tables from storage.
*/
void loadConfig(void)
{
loadTable(&fuelTable, decltype(fuelTable)::type_key, EEPROM_CONFIG1_MAP);
load_range(EEPROM_CONFIG2_START, (byte *)&configPage2, (byte *)&configPage2+sizeof(configPage2));
//*********************************************************************************************************************************************************************************
//IGNITION CONFIG PAGE (2)
loadTable(&ignitionTable, decltype(ignitionTable)::type_key, EEPROM_CONFIG3_MAP);
load_range(EEPROM_CONFIG4_START, (byte *)&configPage4, (byte *)&configPage4+sizeof(configPage4));
//*********************************************************************************************************************************************************************************
//AFR TARGET CONFIG PAGE (3)
loadTable(&afrTable, decltype(afrTable)::type_key, EEPROM_CONFIG5_MAP);
load_range(EEPROM_CONFIG6_START, (byte *)&configPage6, (byte *)&configPage6+sizeof(configPage6));
//*********************************************************************************************************************************************************************************
// Boost and vvt tables load
loadTable(&boostTable, decltype(boostTable)::type_key, EEPROM_CONFIG7_MAP1);
loadTable(&vvtTable, decltype(vvtTable)::type_key, EEPROM_CONFIG7_MAP2);
loadTable(&stagingTable, decltype(stagingTable)::type_key, EEPROM_CONFIG7_MAP3);
//*********************************************************************************************************************************************************************************
// Fuel trim tables load
loadTable(&trim1Table, decltype(trim1Table)::type_key, EEPROM_CONFIG8_MAP1);
loadTable(&trim2Table, decltype(trim2Table)::type_key, EEPROM_CONFIG8_MAP2);
loadTable(&trim3Table, decltype(trim3Table)::type_key, EEPROM_CONFIG8_MAP3);
loadTable(&trim4Table, decltype(trim4Table)::type_key, EEPROM_CONFIG8_MAP4);
loadTable(&trim5Table, decltype(trim5Table)::type_key, EEPROM_CONFIG8_MAP5);
loadTable(&trim6Table, decltype(trim6Table)::type_key, EEPROM_CONFIG8_MAP6);
loadTable(&trim7Table, decltype(trim7Table)::type_key, EEPROM_CONFIG8_MAP7);
loadTable(&trim8Table, decltype(trim8Table)::type_key, EEPROM_CONFIG8_MAP8);
//*********************************************************************************************************************************************************************************
//canbus control page load
load_range(EEPROM_CONFIG9_START, (byte *)&configPage9, (byte *)&configPage9+sizeof(configPage9));
//*********************************************************************************************************************************************************************************
//CONFIG PAGE (10)
load_range(EEPROM_CONFIG10_START, (byte *)&configPage10, (byte *)&configPage10+sizeof(configPage10));
//*********************************************************************************************************************************************************************************
//Fuel table 2 (See storage.h for data layout)
loadTable(&fuelTable2, decltype(fuelTable2)::type_key, EEPROM_CONFIG11_MAP);
//*********************************************************************************************************************************************************************************
// WMI, VVT2 and Dwell table load
loadTable(&wmiTable, decltype(wmiTable)::type_key, EEPROM_CONFIG12_MAP);
loadTable(&vvt2Table, decltype(vvt2Table)::type_key, EEPROM_CONFIG12_MAP2);
loadTable(&dwellTable, decltype(dwellTable)::type_key, EEPROM_CONFIG12_MAP3);
//*********************************************************************************************************************************************************************************
//CONFIG PAGE (13)
load_range(EEPROM_CONFIG13_START, (byte *)&configPage13, (byte *)&configPage13+sizeof(configPage13));
//*********************************************************************************************************************************************************************************
//SECOND IGNITION CONFIG PAGE (14)
loadTable(&ignitionTable2, decltype(ignitionTable2)::type_key, EEPROM_CONFIG14_MAP);
//*********************************************************************************************************************************************************************************
//CONFIG PAGE (15) + boost duty lookup table (LUT)
loadTable(&boostTableLookupDuty, decltype(boostTableLookupDuty)::type_key, EEPROM_CONFIG15_MAP);
load_range(EEPROM_CONFIG15_START, (byte *)&configPage15, (byte *)&configPage15+sizeof(configPage15));
//*********************************************************************************************************************************************************************************
}
/** Read the calibration information from EEPROM.
This is separate from the config load as the calibrations do not exist as pages within the ini file for Tuner Studio.
*/
void loadCalibration(void)
{
// If you modify this function be sure to also modify writeCalibration();
// it should be a mirror image of this function.
EEPROM.get(EEPROM_CALIBRATION_O2_BINS, o2Calibration_bins);
EEPROM.get(EEPROM_CALIBRATION_O2_VALUES, o2Calibration_values);
EEPROM.get(EEPROM_CALIBRATION_IAT_BINS, iatCalibration_bins);
EEPROM.get(EEPROM_CALIBRATION_IAT_VALUES, iatCalibration_values);
EEPROM.get(EEPROM_CALIBRATION_CLT_BINS, cltCalibration_bins);
EEPROM.get(EEPROM_CALIBRATION_CLT_VALUES, cltCalibration_values);
}
/** Write calibration tables to EEPROM.
This takes the values in the 3 calibration tables (Coolant, Inlet temp and O2)
and saves them to the EEPROM.
*/
void writeCalibration(void)
{
// If you modify this function be sure to also modify loadCalibration();
// it should be a mirror image of this function.
EEPROM.put(EEPROM_CALIBRATION_O2_BINS, o2Calibration_bins);
EEPROM.put(EEPROM_CALIBRATION_O2_VALUES, o2Calibration_values);
EEPROM.put(EEPROM_CALIBRATION_IAT_BINS, iatCalibration_bins);
EEPROM.put(EEPROM_CALIBRATION_IAT_VALUES, iatCalibration_values);
EEPROM.put(EEPROM_CALIBRATION_CLT_BINS, cltCalibration_bins);
EEPROM.put(EEPROM_CALIBRATION_CLT_VALUES, cltCalibration_values);
}
void writeCalibrationPage(uint8_t pageNum)
{
if(pageNum == O2_CALIBRATION_PAGE)
{
EEPROM.put(EEPROM_CALIBRATION_O2_BINS, o2Calibration_bins);
EEPROM.put(EEPROM_CALIBRATION_O2_VALUES, o2Calibration_values);
}
else if(pageNum == IAT_CALIBRATION_PAGE)
{
EEPROM.put(EEPROM_CALIBRATION_IAT_BINS, iatCalibration_bins);
EEPROM.put(EEPROM_CALIBRATION_IAT_VALUES, iatCalibration_values);
}
else if(pageNum == CLT_CALIBRATION_PAGE)
{
EEPROM.put(EEPROM_CALIBRATION_CLT_BINS, cltCalibration_bins);
EEPROM.put(EEPROM_CALIBRATION_CLT_VALUES, cltCalibration_values);
}
}
static eeprom_address_t compute_crc_address(uint8_t pageNum)
{
return EEPROM_LAST_BARO-((getPageCount() - pageNum)*sizeof(uint32_t));
}
/** Write CRC32 checksum to EEPROM.
Takes a page number and CRC32 value then stores it in the relevant place in EEPROM
@param pageNum - Config page number
@param crcValue - CRC32 checksum
*/
void storePageCRC32(uint8_t pageNum, uint32_t crcValue)
{
EEPROM.put(compute_crc_address(pageNum), crcValue);
}
/** Retrieves and returns the 4 byte CRC32 checksum for a given page from EEPROM.
@param pageNum - Config page number
*/
uint32_t readPageCRC32(uint8_t pageNum)
{
uint32_t crc32_val;
return EEPROM.get(compute_crc_address(pageNum), crc32_val);
}
/** Same as above, but writes the CRC32 for the calibration page rather than tune data
@param calibrationPageNum - Calibration page number
@param calibrationCRC - CRC32 checksum
*/
void storeCalibrationCRC32(uint8_t calibrationPageNum, uint32_t calibrationCRC)
{
uint16_t targetAddress;
switch(calibrationPageNum)
{
case O2_CALIBRATION_PAGE:
targetAddress = EEPROM_CALIBRATION_O2_CRC;
break;
case IAT_CALIBRATION_PAGE:
targetAddress = EEPROM_CALIBRATION_IAT_CRC;
break;
case CLT_CALIBRATION_PAGE:
targetAddress = EEPROM_CALIBRATION_CLT_CRC;
break;
default:
targetAddress = EEPROM_CALIBRATION_CLT_CRC; //Obviously should never happen
break;
}
EEPROM.put(targetAddress, calibrationCRC);
}
/** Retrieves and returns the 4 byte CRC32 checksum for a given calibration page from EEPROM.
@param calibrationPageNum - Config page number
*/
uint32_t readCalibrationCRC32(uint8_t calibrationPageNum)
{
uint32_t crc32_val;
uint16_t targetAddress;
switch(calibrationPageNum)
{
case O2_CALIBRATION_PAGE:
targetAddress = EEPROM_CALIBRATION_O2_CRC;
break;
case IAT_CALIBRATION_PAGE:
targetAddress = EEPROM_CALIBRATION_IAT_CRC;
break;
case CLT_CALIBRATION_PAGE:
targetAddress = EEPROM_CALIBRATION_CLT_CRC;
break;
default:
targetAddress = EEPROM_CALIBRATION_CLT_CRC; //Obviously should never happen
break;
}
EEPROM.get(targetAddress, crc32_val);
return crc32_val;
}
uint16_t getEEPROMSize(void)
{
return EEPROM.length();
}
// Utility functions.
// By having these in this file, it prevents other files from calling EEPROM functions directly. This is useful due to differences in the EEPROM libraries on different devces
/// Read last stored barometer reading from EEPROM.
byte readLastBaro(void) { return EEPROM.read(EEPROM_LAST_BARO); }
/// Write last acquired arometer reading to EEPROM.
void storeLastBaro(byte newValue) { EEPROM.update(EEPROM_LAST_BARO, newValue); }
/// Read EEPROM current data format version (from offset EEPROM_DATA_VERSION).
byte readEEPROMVersion(void) { return EEPROM.read(EEPROM_DATA_VERSION); }
/// Store EEPROM current data format version (to offset EEPROM_DATA_VERSION).
void storeEEPROMVersion(byte newVersion) { EEPROM.update(EEPROM_DATA_VERSION, newVersion); }
| 26,055
|
C++
|
.cpp
| 536
| 44.610075
| 181
| 0.61168
|
oelprinz-org/BlitzboxBL49sp
| 36
| 12
| 0
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,540,038
|
comms_legacy.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/comms_legacy.cpp
|
/*
Speeduino - Simple engine management for the Arduino Mega 2560 platform
Copyright (C) Josh Stewart
A full copy of the license may be found in the projects root directory
*/
/** @file
* Process Incoming and outgoing serial communications.
*/
#include "globals.h"
#include "comms_legacy.h"
#include "cancomms.h"
#include "storage.h"
#include "maths.h"
#include "utilities.h"
#include "decoders.h"
#include "TS_CommandButtonHandler.h"
#include "errors.h"
#include "pages.h"
#include "page_crc.h"
#include "logger.h"
#include "table3d_axis_io.h"
#ifdef RTC_ENABLED
#include "rtc_common.h"
#endif
static byte currentPage = 1;//Not the same as the speeduino config page numbers
bool firstCommsRequest = true; /**< 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 */
static byte currentCommand; /**< The serial command that is currently being processed. This is only useful when cmdPending=True */
static bool chunkPending = false; /**< Whether or not the current chunk write is complete or not */
static uint16_t chunkComplete = 0; /**< The number of bytes in a chunk write that have been written so far */
static uint16_t chunkSize = 0; /**< The complete size of the requested chunk write */
static int valueOffset; /**< The memory offset within a given page for a value to be read from or written to. Note that we cannot use 'offset' as a variable name, it is a reserved word for several teensy libraries */
byte logItemsTransmitted;
byte inProgressLength;
SerialStatus serialStatusFlag;
static bool isMap(void) {
// Detecting if the current page is a table/map
return (currentPage == veMapPage) || (currentPage == ignMapPage) || (currentPage == afrMapPage) || (currentPage == fuelMap2Page) || (currentPage == ignMap2Page);
}
/** Processes the incoming data on the serial buffer based on the command sent.
Can be either data for a new command or a continuation of data for command that is already in progress:
- cmdPending = If a command has started but is waiting on further data to complete
- chunkPending = Specifically for the new receive value method where TS will send a known number of contiguous bytes to be written to a table
Commands are single byte (letter symbol) commands.
*/
void legacySerialCommand(void)
{
if ( serialStatusFlag == SERIAL_INACTIVE ) { currentCommand = Serial.read(); }
switch (currentCommand)
{
case 'a':
serialStatusFlag = SERIAL_COMMAND_INPROGRESS_LEGACY;
if (Serial.available() >= 2)
{
Serial.read(); //Ignore the first value, it's always 0
Serial.read(); //Ignore the second value, it's always 6
sendValuesLegacy();
serialStatusFlag = SERIAL_INACTIVE;
}
break;
case 'A': // send x bytes of realtime values
sendValues(0, LOG_ENTRY_SIZE, 0x31, 0); //send values to serial0
break;
case 'b': // New EEPROM burn command to only burn a single page at a time
serialStatusFlag = SERIAL_COMMAND_INPROGRESS_LEGACY;
if (Serial.available() >= 2)
{
Serial.read(); //Ignore the first table value, it's always 0
writeConfig(Serial.read());
serialStatusFlag = SERIAL_INACTIVE;
}
break;
case 'B': // AS above but for the serial compatibility mode.
serialStatusFlag = SERIAL_COMMAND_INPROGRESS_LEGACY;
BIT_SET(currentStatus.status4, BIT_STATUS4_COMMS_COMPAT); //Force the compat mode
if (Serial.available() >= 2)
{
Serial.read(); //Ignore the first table value, it's always 0
writeConfig(Serial.read());
serialStatusFlag = SERIAL_INACTIVE;
}
break;
case 'C': // test communications. This is used by Tunerstudio to see whether there is an ECU on a given serial port
testComm();
break;
case 'c': //Send the current loops/sec value
Serial.write(lowByte(currentStatus.loopsPerSecond));
Serial.write(highByte(currentStatus.loopsPerSecond));
break;
case 'd': // Send a CRC32 hash of a given page
serialStatusFlag = SERIAL_COMMAND_INPROGRESS_LEGACY;
if (Serial.available() >= 2)
{
Serial.read(); //Ignore the first byte value, it's always 0
uint32_t CRC32_val = calculatePageCRC32( Serial.read() );
//Split the 4 bytes of the CRC32 value into individual bytes and send
Serial.write( ((CRC32_val >> 24) & 255) );
Serial.write( ((CRC32_val >> 16) & 255) );
Serial.write( ((CRC32_val >> 8) & 255) );
Serial.write( (CRC32_val & 255) );
serialStatusFlag = SERIAL_INACTIVE;
}
break;
case 'E': // receive command button commands
serialStatusFlag = SERIAL_COMMAND_INPROGRESS_LEGACY;
if(Serial.available() >= 2)
{
byte cmdGroup = (byte)Serial.read();
(void)TS_CommandButtonsHandler(word(cmdGroup, Serial.read()));
serialStatusFlag = SERIAL_INACTIVE;
}
break;
case 'F': // send serial protocol version
Serial.print(F("002"));
break;
//The G/g commands are used for bulk reading and writing to the EEPROM directly. This is typically a non-user feature but will be incorporated into SpeedyLoader for anyone programming many boards at once
case 'G': // Dumps the EEPROM values to serial
//The format is 2 bytes for the overall EEPROM size, a comma and then a raw dump of the EEPROM values
Serial.write(lowByte(getEEPROMSize()));
Serial.write(highByte(getEEPROMSize()));
Serial.print(',');
for(uint16_t x = 0; x < getEEPROMSize(); x++)
{
Serial.write(EEPROMReadRaw(x));
}
serialStatusFlag = SERIAL_INACTIVE;
break;
case 'g': // Receive a dump of raw EEPROM values from the user
{
//Format is similar to the above command. 2 bytes for the EEPROM size that is about to be transmitted, a comma and then a raw dump of the EEPROM values
while(Serial.available() < 3) { delay(1); }
uint16_t eepromSize = word(Serial.read(), Serial.read());
if(eepromSize != getEEPROMSize())
{
//Client is trying to send the wrong EEPROM size. Don't let it
Serial.println(F("ERR; Incorrect EEPROM size"));
break;
}
else
{
for(uint16_t x = 0; x < eepromSize; x++)
{
while(Serial.available() < 3) { delay(1); }
EEPROMWriteRaw(x, Serial.read());
}
}
serialStatusFlag = SERIAL_INACTIVE;
break;
}
case 'H': //Start the tooth logger
startToothLogger();
Serial.write(1); //TS needs an acknowledgement that this was received. I don't know if this is the correct response, but it seems to work
break;
case 'h': //Stop the tooth logger
stopToothLogger();
break;
case 'J': //Start the composite logger
startCompositeLogger();
Serial.write(1); //TS needs an acknowledgement that this was received. I don't know if this is the correct response, but it seems to work
break;
case 'j': //Stop the composite logger
stopCompositeLogger();
break;
case 'L': // List the contents of current page in human readable form
#ifndef SMALL_FLASH_MODE
sendPageASCII();
#endif
break;
case 'm': //Send the current free memory
currentStatus.freeRAM = freeRam();
Serial.write(lowByte(currentStatus.freeRAM));
Serial.write(highByte(currentStatus.freeRAM));
break;
case 'N': // Displays a new line. Like pushing enter in a text editor
Serial.println();
break;
case 'O': //Start the composite logger 2nd cam (teritary)
startCompositeLoggerTertiary();
Serial.write(1); //TS needs an acknowledgement that this was received. I don't know if this is the correct response, but it seems to work
break;
case 'o': //Stop the composite logger 2nd cam (tertiary)
stopCompositeLoggerTertiary();
break;
case 'X': //Start the composite logger 2nd cam (teritary)
startCompositeLoggerCams();
Serial.write(1); //TS needs an acknowledgement that this was received. I don't know if this is the correct response, but it seems to work
break;
case 'x': //Stop the composite logger 2nd cam (tertiary)
stopCompositeLoggerCams();
break;
case 'P': // set the current page
//This is a legacy function and is no longer used by TunerStudio. It is maintained for compatibility with other systems
//A 2nd byte of data is required after the 'P' specifying the new page number.
serialStatusFlag = SERIAL_COMMAND_INPROGRESS_LEGACY;
if (Serial.available() > 0)
{
currentPage = Serial.read();
//This converts the ASCII number char into binary. Note that this will break everything if there are ever more than 48 pages (48 = asci code for '0')
if ((currentPage >= '0') && (currentPage <= '9')) // 0 - 9
{
currentPage -= 48;
}
else if ((currentPage >= 'a') && (currentPage <= 'f')) // 10 - 15
{
currentPage -= 87;
}
else if ((currentPage >= 'A') && (currentPage <= 'F'))
{
currentPage -= 55;
}
serialStatusFlag = SERIAL_INACTIVE;
}
break;
/*
* New method for sending page values
*/
case 'p':
serialStatusFlag = SERIAL_COMMAND_INPROGRESS_LEGACY;
//6 bytes required:
//2 - Page identifier
//2 - offset
//2 - Length
if(Serial.available() >= 6)
{
byte offset1, offset2, length1, length2;
int length;
byte tempPage;
Serial.read(); // First byte of the page identifier can be ignored. It's always 0
tempPage = Serial.read();
//currentPage = 1;
offset1 = Serial.read();
offset2 = Serial.read();
valueOffset = word(offset2, offset1);
length1 = Serial.read();
length2 = Serial.read();
length = word(length2, length1);
for(int i = 0; i < length; i++)
{
Serial.write( getPageValue(tempPage, valueOffset + i) );
}
serialStatusFlag = SERIAL_INACTIVE;
}
break;
case 'Q': // send code version
Serial.print(F("speeduino 202305"));
//Serial.print(F("speeduino 202210-dev"));
break;
case 'r': //New format for the optimised OutputChannels
serialStatusFlag = SERIAL_COMMAND_INPROGRESS_LEGACY;
byte cmd;
if (Serial.available() >= 6)
{
Serial.read(); //Read the $tsCanId
cmd = Serial.read(); // read the command
uint16_t offset, length;
byte tmp;
tmp = Serial.read();
offset = word(Serial.read(), tmp);
tmp = Serial.read();
length = word(Serial.read(), tmp);
serialStatusFlag = SERIAL_INACTIVE;
if(cmd == 0x30) //Send output channels command 0x30 is 48dec
{
sendValues(offset, length, cmd, 0);
}
else
{
//No other r/ commands are supported in legacy mode
}
}
break;
case 'S': // send code version
Serial.print(F("Speeduino 2023.05"));
//Serial.print(F("Speeduino 2022.10-dev"));
currentStatus.secl = 0; //This is required in TS3 due to its stricter timings
break;
case 'T': //Send 256 tooth log entries to Tuner Studios tooth logger
//6 bytes required:
//2 - Page identifier
//2 - offset
//2 - Length
serialStatusFlag = SERIAL_COMMAND_INPROGRESS_LEGACY;
if(Serial.available() >= 6)
{
Serial.read(); // First byte of the page identifier can be ignored. It's always 0
Serial.read(); // First byte of the page identifier can be ignored. It's always 0
Serial.read(); // First byte of the page identifier can be ignored. It's always 0
Serial.read(); // First byte of the page identifier can be ignored. It's always 0
Serial.read(); // First byte of the page identifier can be ignored. It's always 0
Serial.read(); // First byte of the page identifier can be ignored. It's always 0
if(currentStatus.toothLogEnabled == true) { sendToothLog_legacy(0); } //Sends tooth log values as ints
else if (currentStatus.compositeTriggerUsed > 0) { sendCompositeLog_legacy(0); }
serialStatusFlag = SERIAL_INACTIVE;
}
break;
case 't': // receive new Calibration info. Command structure: "t", <tble_idx> <data array>.
byte tableID;
//byte canID;
//The first 2 bytes sent represent the canID and tableID
while (Serial.available() == 0) { }
tableID = Serial.read(); //Not currently used for anything
receiveCalibration(tableID); //Receive new values and store in memory
writeCalibration(); //Store received values in EEPROM
break;
case 'U': //User wants to reset the Arduino (probably for FW update)
if (resetControl != RESET_CONTROL_DISABLED)
{
#ifndef SMALL_FLASH_MODE
if (serialStatusFlag == SERIAL_INACTIVE) { Serial.println(F("Comms halted. Next byte will reset the Arduino.")); }
#endif
while (Serial.available() == 0) { }
digitalWrite(pinResetControl, LOW);
}
else
{
#ifndef SMALL_FLASH_MODE
if (serialStatusFlag == SERIAL_INACTIVE) { Serial.println(F("Reset control is currently disabled.")); }
#endif
}
break;
case 'V': // send VE table and constants in binary
sendPage();
break;
case 'W': // receive new VE obr constant at 'W'+<offset>+<newbyte>
serialStatusFlag = SERIAL_COMMAND_INPROGRESS_LEGACY;
if (isMap())
{
if(Serial.available() >= 3) // 1 additional byte is required on the MAP pages which are larger than 255 bytes
{
byte offset1, offset2;
offset1 = Serial.read();
offset2 = Serial.read();
valueOffset = word(offset2, offset1);
setPageValue(currentPage, valueOffset, Serial.read());
serialStatusFlag = SERIAL_INACTIVE;
}
}
else
{
if(Serial.available() >= 2)
{
valueOffset = Serial.read();
setPageValue(currentPage, valueOffset, Serial.read());
serialStatusFlag = SERIAL_INACTIVE;
}
}
break;
case 'M':
serialStatusFlag = SERIAL_COMMAND_INPROGRESS_LEGACY;
if(chunkPending == false)
{
//This means it's a new request
//7 bytes required:
//2 - Page identifier
//2 - offset
//2 - Length
//1 - 1st New value
if(Serial.available() >= 7)
{
byte offset1, offset2, length1, length2;
Serial.read(); // First byte of the page identifier can be ignored. It's always 0
currentPage = Serial.read();
//currentPage = 1;
offset1 = Serial.read();
offset2 = Serial.read();
valueOffset = word(offset2, offset1);
length1 = Serial.read();
length2 = Serial.read();
chunkSize = word(length2, length1);
//Regular page data
chunkPending = true;
chunkComplete = 0;
}
}
//This CANNOT be an else of the above if statement as chunkPending gets set to true above
if(chunkPending == true)
{
while( (Serial.available() > 0) && (chunkComplete < chunkSize) )
{
setPageValue(currentPage, (valueOffset + chunkComplete), Serial.read());
chunkComplete++;
}
if(chunkComplete >= chunkSize) { serialStatusFlag = SERIAL_INACTIVE; chunkPending = false; }
}
break;
case 'w':
//No w commands are supported in legacy mode. This should never be called
if(Serial.available() >= 7)
{
byte offset1, offset2, length1, length2;
Serial.read(); // First byte of the page identifier can be ignored. It's always 0
currentPage = Serial.read();
//currentPage = 1;
offset1 = Serial.read();
offset2 = Serial.read();
valueOffset = word(offset2, offset1);
length1 = Serial.read();
length2 = Serial.read();
chunkSize = word(length2, length1);
}
break;
case 'Z': //Totally non-standard testing function. Will be removed once calibration testing is completed. This function takes 1.5kb of program space! :S
#ifndef SMALL_FLASH_MODE
Serial.println(F("Coolant"));
for (int x = 0; x < 32; x++)
{
Serial.print(cltCalibration_bins[x]);
Serial.print(", ");
Serial.println(cltCalibration_values[x]);
}
Serial.println(F("Inlet temp"));
for (int x = 0; x < 32; x++)
{
Serial.print(iatCalibration_bins[x]);
Serial.print(", ");
Serial.println(iatCalibration_values[x]);
}
Serial.println(F("O2"));
for (int x = 0; x < 32; x++)
{
Serial.print(o2Calibration_bins[x]);
Serial.print(", ");
Serial.println(o2Calibration_values[x]);
}
Serial.println(F("WUE"));
for (int x = 0; x < 10; x++)
{
Serial.print(configPage4.wueBins[x]);
Serial.print(F(", "));
Serial.println(configPage2.wueValues[x]);
}
Serial.flush();
#endif
break;
case 'z': //Send 256 tooth log entries to a terminal emulator
sendToothLog_legacy(0); //Sends tooth log values as chars
break;
case '`': //Custom 16u2 firmware is making its presence known
serialStatusFlag = SERIAL_COMMAND_INPROGRESS_LEGACY;
if (Serial.available() >= 1) {
configPage4.bootloaderCaps = Serial.read();
serialStatusFlag = SERIAL_INACTIVE;
}
break;
case '?':
#ifndef SMALL_FLASH_MODE
Serial.println
(F(
"\n"
"===Command Help===\n\n"
"All commands are single character and are concatenated with their parameters \n"
"without spaces."
"Syntax: <command>+<parameter1>+<parameter2>+<parameterN>\n\n"
"===List of Commands===\n\n"
"A - Displays 31 bytes of currentStatus values in binary (live data)\n"
"B - Burn current map and configPage values to eeprom\n"
"C - Test COM port. Used by Tunerstudio to see whether an ECU is on a given serial \n"
" port. Returns a binary number.\n"
"N - Print new line.\n"
"P - Set current page. Syntax: P+<pageNumber>\n"
"R - Same as A command\n"
"S - Display signature number\n"
"Q - Same as S command\n"
"V - Display map or configPage values in binary\n"
"W - Set one byte in map or configPage. Expects binary parameters. \n"
" Syntax: W+<offset>+<newbyte>\n"
"t - Set calibration values. Expects binary parameters. Table index is either 0, \n"
" 1, or 2. Syntax: t+<tble_idx>+<newValue1>+<newValue2>+<newValueN>\n"
"Z - Display calibration values\n"
"T - Displays 256 tooth log entries in binary\n"
"r - Displays 256 tooth log entries\n"
"U - Prepare for firmware update. The next byte received will cause the Arduino to reset.\n"
"? - Displays this help page"
));
#endif
break;
default:
Serial.println(F("Err: Unknown cmd"));
serialStatusFlag = SERIAL_INACTIVE;
break;
}
}
/** Send a status record back to tuning/logging SW.
* This will "live" information from @ref currentStatus struct.
* @param offset - Start field number
* @param packetLength - Length of actual message (after possible ack/confirm headers)
* @param cmd - ??? - Will be used as some kind of ack on CANSerial
* @param portNum - Port number (0=Serial, 3=CANSerial)
* E.g. tuning sw command 'A' (Send all values) will send data from field number 0, LOG_ENTRY_SIZE fields.
* @return the current values of a fixed group of variables
*/
void sendValues(uint16_t offset, uint16_t packetLength, byte cmd, byte portNum)
{
serialStatusFlag = SERIAL_TRANSMIT_INPROGRESS_LEGACY;
if (portNum == 3)
{
//CAN serial
#if defined(USE_SERIAL3)
if (cmd == 30)
{
CANSerial.write("r"); //confirm cmd type
CANSerial.write(cmd);
}
else if (cmd == 31) { CANSerial.write("A"); } //confirm cmd type
#else
UNUSED(cmd);
#endif
}
else
{
if(firstCommsRequest)
{
firstCommsRequest = false;
currentStatus.secl = 0;
}
}
currentStatus.spark ^= (-currentStatus.hasSync ^ currentStatus.spark) & (1U << BIT_SPARK_SYNC); //Set the sync bit of the Spark variable to match the hasSync variable
for(byte x=0; x<packetLength; x++)
{
if (portNum == 0) { Serial.write(getTSLogEntry(offset+x)); }
#if defined(CANSerial_AVAILABLE)
else if (portNum == 3){ CANSerial.write(getTSLogEntry(offset+x)); }
#endif
//Check whether the tx buffer still has space
if(Serial.availableForWrite() < 1)
{
//tx buffer is full. Store the current state so it can be resumed later
logItemsTransmitted = offset + x + 1;
inProgressLength = packetLength - x - 1;
return;
}
}
serialStatusFlag = SERIAL_INACTIVE;
// Reset any flags that are being used to trigger page refreshes
BIT_CLEAR(currentStatus.status3, BIT_STATUS3_VSS_REFRESH);
}
void sendValuesLegacy(void)
{
uint16_t temp;
int bytestosend = 114;
bytestosend -= Serial.write(currentStatus.secl>>8);
bytestosend -= Serial.write(currentStatus.secl);
bytestosend -= Serial.write(currentStatus.PW1>>8);
bytestosend -= Serial.write(currentStatus.PW1);
bytestosend -= Serial.write(currentStatus.PW2>>8);
bytestosend -= Serial.write(currentStatus.PW2);
bytestosend -= Serial.write(currentStatus.RPM>>8);
bytestosend -= Serial.write(currentStatus.RPM);
temp = currentStatus.advance * 10;
bytestosend -= Serial.write(temp>>8);
bytestosend -= Serial.write(temp);
bytestosend -= Serial.write(currentStatus.nSquirts);
bytestosend -= Serial.write(currentStatus.engine);
bytestosend -= Serial.write(currentStatus.afrTarget);
bytestosend -= Serial.write(currentStatus.afrTarget); // send twice so afrtgt1 == afrtgt2
bytestosend -= Serial.write(99); // send dummy data as we don't have wbo2_en1
bytestosend -= Serial.write(99); // send dummy data as we don't have wbo2_en2
temp = currentStatus.baro * 10;
bytestosend -= Serial.write(temp>>8);
bytestosend -= Serial.write(temp);
temp = currentStatus.MAP * 10;
bytestosend -= Serial.write(temp>>8);
bytestosend -= Serial.write(temp);
temp = currentStatus.IAT * 10;
bytestosend -= Serial.write(temp>>8);
bytestosend -= Serial.write(temp);
temp = currentStatus.coolant * 10;
bytestosend -= Serial.write(temp>>8);
bytestosend -= Serial.write(temp);
temp = currentStatus.TPS * 10;
bytestosend -= Serial.write(temp>>8);
bytestosend -= Serial.write(temp);
bytestosend -= Serial.write(currentStatus.battery10>>8);
bytestosend -= Serial.write(currentStatus.battery10);
bytestosend -= Serial.write(currentStatus.O2>>8);
bytestosend -= Serial.write(currentStatus.O2);
bytestosend -= Serial.write(currentStatus.O2_2>>8);
bytestosend -= Serial.write(currentStatus.O2_2);
bytestosend -= Serial.write(99); // knock
bytestosend -= Serial.write(99); // knock
temp = currentStatus.egoCorrection * 10;
bytestosend -= Serial.write(temp>>8); // egocor1
bytestosend -= Serial.write(temp); // egocor1
bytestosend -= Serial.write(temp>>8); // egocor2
bytestosend -= Serial.write(temp); // egocor2
temp = currentStatus.iatCorrection * 10;
bytestosend -= Serial.write(temp>>8); // aircor
bytestosend -= Serial.write(temp); // aircor
temp = currentStatus.wueCorrection * 10;
bytestosend -= Serial.write(temp>>8); // warmcor
bytestosend -= Serial.write(temp); // warmcor
bytestosend -= Serial.write(99); // accelEnrich
bytestosend -= Serial.write(99); // accelEnrich
bytestosend -= Serial.write(99); // tpsFuelCut
bytestosend -= Serial.write(99); // tpsFuelCut
bytestosend -= Serial.write(99); // baroCorrection
bytestosend -= Serial.write(99); // baroCorrection
temp = currentStatus.corrections * 10;
bytestosend -= Serial.write(temp>>8); // gammaEnrich
bytestosend -= Serial.write(temp); // gammaEnrich
temp = currentStatus.VE * 10;
bytestosend -= Serial.write(temp>>8); // ve1
bytestosend -= Serial.write(temp); // ve1
temp = currentStatus.VE2 * 10;
bytestosend -= Serial.write(temp>>8); // ve2
bytestosend -= Serial.write(temp); // ve2
bytestosend -= Serial.write(99); // iacstep
bytestosend -= Serial.write(99); // iacstep
bytestosend -= Serial.write(99); // cold_adv_deg
bytestosend -= Serial.write(99); // cold_adv_deg
temp = currentStatus.tpsDOT;
bytestosend -= Serial.write(temp>>8); // TPSdot
bytestosend -= Serial.write(temp); // TPSdot
temp = currentStatus.mapDOT;
bytestosend -= Serial.write(temp >> 8); // MAPdot
bytestosend -= Serial.write(temp); // MAPdot
temp = currentStatus.dwell * 10;
bytestosend -= Serial.write(temp>>8); // dwell
bytestosend -= Serial.write(temp); // dwell
bytestosend -= Serial.write(99); // MAF
bytestosend -= Serial.write(99); // MAF
bytestosend -= Serial.write(currentStatus.fuelLoad*10); // fuelload
bytestosend -= Serial.write(99); // fuelcor
bytestosend -= Serial.write(99); // fuelcor
bytestosend -= Serial.write(99); // portStatus
temp = currentStatus.advance1 * 10;
bytestosend -= Serial.write(temp>>8);
bytestosend -= Serial.write(temp);
temp = currentStatus.advance2 * 10;
bytestosend -= Serial.write(temp>>8);
bytestosend -= Serial.write(temp);
for(int i = 0; i < bytestosend; i++)
{
// send dummy data to fill remote's buffer
Serial.write(99);
}
}
namespace {
void send_raw_entity(const page_iterator_t &entity)
{
Serial.write((byte *)entity.pData, entity.size);
}
inline void send_table_values(table_value_iterator it)
{
while (!it.at_end())
{
auto row = *it;
Serial.write(&*row, row.size());
++it;
}
}
inline void send_table_axis(table_axis_iterator it)
{
const int16_byte *pConverter = table3d_axis_io::get_converter(it.get_domain());
while (!it.at_end())
{
Serial.write(pConverter->to_byte(*it));
++it;
}
}
void send_table_entity(const page_iterator_t &entity)
{
send_table_values(rows_begin(entity));
send_table_axis(x_begin(entity));
send_table_axis(y_begin(entity));
}
void send_entity(const page_iterator_t &entity)
{
switch (entity.type)
{
case Raw:
return send_raw_entity(entity);
break;
case Table:
return send_table_entity(entity);
break;
case NoEntity:
// No-op
break;
default:
abort();
break;
}
}
}
/** Pack the data within the current page (As set with the 'P' command) into a buffer and send it.
*
* Creates a page iterator by @ref page_begin() (See: pages.cpp). Sends page given in @ref currentPage.
*
* Note that some translation of the data is required to lay it out in the way Megasquirt / TunerStudio expect it.
* Data is sent in binary format, as defined by in each page in the speeduino.ini.
*/
void sendPage(void)
{
page_iterator_t entity = page_begin(currentPage);
while (entity.type!=End)
{
send_entity(entity);
entity = advance(entity);
}
}
namespace {
/// Prints each element in the memory byte range (*first, *last).
void serial_println_range(const byte *first, const byte *last)
{
while (first!=last)
{
Serial.println(*first);
++first;
}
}
void serial_println_range(const uint16_t *first, const uint16_t *last)
{
while (first!=last)
{
Serial.println(*first);
++first;
}
}
void serial_print_space_delimited(const byte *first, const byte *last)
{
while (first!=last)
{
Serial.print(*first);// This displays the values horizontally on the screen
Serial.print(F(" "));
++first;
}
Serial.println();
}
#define serial_print_space_delimited_array(array) serial_print_space_delimited(array, _end_range_address(array))
void serial_print_prepadding(byte value)
{
if (value < 100)
{
Serial.print(F(" "));
if (value < 10)
{
Serial.print(F(" "));
}
}
}
void serial_print_prepadded_value(byte value)
{
serial_print_prepadding(value);
Serial.print(value);
Serial.print(F(" "));
}
void print_row(const table_axis_iterator &y_it, table_row_iterator row)
{
serial_print_prepadded_value(table3d_axis_io::to_byte(y_it.get_domain(), *y_it));
while (!row.at_end())
{
serial_print_prepadded_value(*row);
++row;
}
Serial.println();
}
void print_x_axis(const void *pTable, table_type_t key)
{
Serial.print(F(" "));
auto x_it = x_begin(pTable, key);
const int16_byte *pConverter = table3d_axis_io::get_converter(x_it.get_domain());
while(!x_it.at_end())
{
serial_print_prepadded_value(pConverter->to_byte(*x_it));
++x_it;
}
}
void serial_print_3dtable(const void *pTable, table_type_t key)
{
auto y_it = y_begin(pTable, key);
auto row_it = rows_begin(pTable, key);
while (!row_it.at_end())
{
print_row(y_it, *row_it);
++y_it;
++row_it;
}
print_x_axis(pTable, key);
Serial.println();
}
}
/** Send page as ASCII for debugging purposes.
* Similar to sendPage(), however data is sent in human readable format. Sends page given in @ref currentPage.
*
* This is used for testing only (Not used by TunerStudio) in order to see current map and config data without the need for TunerStudio.
*/
void sendPageASCII(void)
{
switch (currentPage)
{
case veMapPage:
Serial.println(F("\nVE Map"));
serial_print_3dtable(&fuelTable, fuelTable.type_key);
break;
case veSetPage:
Serial.println(F("\nPg 2 Cfg"));
// The following loop displays in human readable form of all byte values in config page 1 up to but not including the first array.
serial_println_range((byte *)&configPage2, configPage2.wueValues);
serial_print_space_delimited_array(configPage2.wueValues);
// This displays all the byte values between the last array up to but not including the first unsigned int on config page 1
serial_println_range(_end_range_byte_address(configPage2.wueValues), (byte*)&configPage2.injAng);
// The following loop displays four unsigned ints
serial_println_range(configPage2.injAng, configPage2.injAng + _countof(configPage2.injAng));
// Following loop displays byte values between the unsigned ints
serial_println_range(_end_range_byte_address(configPage2.injAng), (byte*)&configPage2.mapMax);
Serial.println(configPage2.mapMax);
// Following loop displays remaining byte values of the page
serial_println_range(&configPage2.fpPrime, (byte *)&configPage2 + sizeof(configPage2));
break;
case ignMapPage:
Serial.println(F("\nIgnition Map"));
serial_print_3dtable(&ignitionTable, ignitionTable.type_key);
break;
case ignSetPage:
Serial.println(F("\nPg 4 Cfg"));
Serial.println(configPage4.triggerAngle);// configPage4.triggerAngle is an int so just display it without complication
// Following loop displays byte values after that first int up to but not including the first array in config page 2
serial_println_range((byte*)&configPage4.FixAng, configPage4.taeBins);
serial_print_space_delimited_array(configPage4.taeBins);
serial_print_space_delimited_array(configPage4.taeValues);
serial_print_space_delimited_array(configPage4.wueBins);
Serial.println(configPage4.dwellLimit);// Little lonely byte stuck between two arrays. No complications just display it.
serial_print_space_delimited_array(configPage4.dwellCorrectionValues);
serial_println_range(_end_range_byte_address(configPage4.dwellCorrectionValues), (byte *)&configPage4 + sizeof(configPage4));
break;
case afrMapPage:
Serial.println(F("\nAFR Map"));
serial_print_3dtable(&afrTable, afrTable.type_key);
break;
case afrSetPage:
Serial.println(F("\nPg 6 Config"));
serial_println_range((byte *)&configPage6, configPage6.voltageCorrectionBins);
serial_print_space_delimited_array(configPage6.voltageCorrectionBins);
serial_print_space_delimited_array(configPage6.injVoltageCorrectionValues);
serial_print_space_delimited_array(configPage6.airDenBins);
serial_print_space_delimited_array(configPage6.airDenRates);
serial_println_range(_end_range_byte_address(configPage6.airDenRates), configPage6.iacCLValues);
serial_print_space_delimited_array(configPage6.iacCLValues);
serial_print_space_delimited_array(configPage6.iacOLStepVal);
serial_print_space_delimited_array(configPage6.iacOLPWMVal);
serial_print_space_delimited_array(configPage6.iacBins);
serial_print_space_delimited_array(configPage6.iacCrankSteps);
serial_print_space_delimited_array(configPage6.iacCrankDuty);
serial_print_space_delimited_array(configPage6.iacCrankBins);
// Following loop is for remaining byte value of page
serial_println_range(_end_range_byte_address(configPage6.iacCrankBins), (byte *)&configPage6 + sizeof(configPage6));
break;
case boostvvtPage:
Serial.println(F("\nBoost Map"));
serial_print_3dtable(&boostTable, boostTable.type_key);
Serial.println(F("\nVVT Map"));
serial_print_3dtable(&vvtTable, vvtTable.type_key);
break;
case seqFuelPage:
Serial.println(F("\nTrim 1 Table"));
serial_print_3dtable(&trim1Table, trim1Table.type_key);
break;
case canbusPage:
Serial.println(F("\nPage 9 Cfg"));
serial_println_range((byte *)&configPage9, (byte *)&configPage9 + sizeof(configPage9));
break;
case fuelMap2Page:
Serial.println(F("\n2nd Fuel Map"));
serial_print_3dtable(&fuelTable2, fuelTable2.type_key);
break;
case ignMap2Page:
Serial.println(F("\n2nd Ignition Map"));
serial_print_3dtable(&ignitionTable2, ignitionTable2.type_key);
break;
case boostvvtPage2:
Serial.println(F("\nBoost lookup table"));
serial_print_3dtable(&boostTableLookupDuty, boostTableLookupDuty.type_key);
break;
case warmupPage:
case progOutsPage:
default:
#ifndef SMALL_FLASH_MODE
Serial.println(F("\nPage has not been implemented yet"));
#endif
break;
}
}
/** Processes an incoming stream of calibration data (for CLT, IAT or O2) from TunerStudio.
* Result is store in EEPROM and memory.
*
* @param tableID - calibration table to process. 0 = Coolant Sensor. 1 = IAT Sensor. 2 = O2 Sensor.
*/
void receiveCalibration(byte tableID)
{
void* pnt_TargetTable_values; //Pointer that will be used to point to the required target table values
uint16_t* pnt_TargetTable_bins; //Pointer that will be used to point to the required target table bins
int OFFSET, DIVISION_FACTOR;
switch (tableID)
{
case 0:
//coolant table
pnt_TargetTable_values = (uint16_t *)&cltCalibration_values;
pnt_TargetTable_bins = (uint16_t *)&cltCalibration_bins;
OFFSET = CALIBRATION_TEMPERATURE_OFFSET; //
DIVISION_FACTOR = 10;
break;
case 1:
//Inlet air temp table
pnt_TargetTable_values = (uint16_t *)&iatCalibration_values;
pnt_TargetTable_bins = (uint16_t *)&iatCalibration_bins;
OFFSET = CALIBRATION_TEMPERATURE_OFFSET;
DIVISION_FACTOR = 10;
break;
case 2:
//O2 table
//pnt_TargetTable = (byte *)&o2CalibrationTable;
pnt_TargetTable_values = (uint8_t *)&o2Calibration_values;
pnt_TargetTable_bins = (uint16_t *)&o2Calibration_bins;
OFFSET = 0;
DIVISION_FACTOR = 1;
break;
default:
OFFSET = 0;
pnt_TargetTable_values = (uint16_t *)&iatCalibration_values;
pnt_TargetTable_bins = (uint16_t *)&iatCalibration_bins;
DIVISION_FACTOR = 10;
break; //Should never get here, but if we do, just fail back to main loop
}
int16_t tempValue;
byte tempBuffer[2];
if(tableID == 2)
{
//O2 calibration. Comes through as 1024 8-bit values of which we use every 32nd
for (int x = 0; x < 1024; x++)
{
while ( Serial.available() < 1 ) {}
tempValue = Serial.read();
if( (x % 32) == 0)
{
((uint8_t*)pnt_TargetTable_values)[(x/32)] = (byte)tempValue; //O2 table stores 8 bit values
pnt_TargetTable_bins[(x/32)] = (x);
}
}
}
else
{
//Temperature calibrations are sent as 32 16-bit values
for (uint16_t x = 0; x < 32; x++)
{
while ( Serial.available() < 2 ) {}
tempBuffer[0] = Serial.read();
tempBuffer[1] = Serial.read();
tempValue = (int16_t)(word(tempBuffer[1], tempBuffer[0])); //Combine the 2 bytes into a single, signed 16-bit value
tempValue = div(tempValue, DIVISION_FACTOR).quot; //TS sends values multiplied by 10 so divide back to whole degrees.
tempValue = ((tempValue - 32) * 5) / 9; //Convert from F to C
//Apply the temp offset and check that it results in all values being positive
tempValue = tempValue + OFFSET;
if (tempValue < 0) { tempValue = 0; }
((uint16_t*)pnt_TargetTable_values)[x] = tempValue; //Both temp tables have 16-bit values
pnt_TargetTable_bins[x] = (x * 32U);
writeCalibration();
}
}
writeCalibration();
}
/** Send 256 tooth log entries to serial.
* if useChar is true, the values are sent as chars to be printed out by a terminal emulator
* if useChar is false, the values are sent as a 2 byte integer which is readable by TunerStudios tooth logger
*/
void sendToothLog_legacy(byte startOffset) /* Blocking */
{
//We need TOOTH_LOG_SIZE number of records to send to TunerStudio. If there aren't that many in the buffer then we just return and wait for the next call
if (BIT_CHECK(currentStatus.status1, BIT_STATUS1_TOOTHLOG1READY)) //Sanity check. Flagging system means this should always be true
{
serialStatusFlag = SERIAL_TRANSMIT_TOOTH_INPROGRESS_LEGACY;
for (int x = startOffset; x < TOOTH_LOG_SIZE; x++)
{
Serial.write(toothHistory[x] >> 24);
Serial.write(toothHistory[x] >> 16);
Serial.write(toothHistory[x] >> 8);
Serial.write(toothHistory[x]);
}
BIT_CLEAR(currentStatus.status1, BIT_STATUS1_TOOTHLOG1READY);
serialStatusFlag = SERIAL_INACTIVE;
toothHistoryIndex = 0;
}
else
{
//TunerStudio has timed out, send a LOG of all 0s
for(int x = 0; x < (4*TOOTH_LOG_SIZE); x++)
{
Serial.write(static_cast<byte>(0x00)); //GCC9 fix
}
serialStatusFlag = SERIAL_INACTIVE;
}
}
void sendCompositeLog_legacy(byte startOffset) /* Non-blocking */
{
if (BIT_CHECK(currentStatus.status1, BIT_STATUS1_TOOTHLOG1READY)) //Sanity check. Flagging system means this should always be true
{
serialStatusFlag = SERIAL_TRANSMIT_COMPOSITE_INPROGRESS_LEGACY;
for (int x = startOffset; x < TOOTH_LOG_SIZE; x++)
{
//Check whether the tx buffer still has space
if(Serial.availableForWrite() < 4)
{
//tx buffer is full. Store the current state so it can be resumed later
logItemsTransmitted = x;
return;
}
uint32_t inProgressCompositeTime = toothHistory[x]; //This combined runtime (in us) that the log was going for by this record)
Serial.write(inProgressCompositeTime >> 24);
Serial.write(inProgressCompositeTime >> 16);
Serial.write(inProgressCompositeTime >> 8);
Serial.write(inProgressCompositeTime);
Serial.write(compositeLogHistory[x]); //The status byte (Indicates the trigger edge, whether it was a pri/sec pulse, the sync status)
}
BIT_CLEAR(currentStatus.status1, BIT_STATUS1_TOOTHLOG1READY);
toothHistoryIndex = 0;
serialStatusFlag = SERIAL_INACTIVE;
}
else
{
//TunerStudio has timed out, send a LOG of all 0s
for(int x = 0; x < (5*TOOTH_LOG_SIZE); x++)
{
Serial.write(static_cast<byte>(0x00)); //GCC9 fix
}
serialStatusFlag = SERIAL_INACTIVE;
}
}
void testComm(void)
{
Serial.write(1);
return;
}
| 40,660
|
C++
|
.cpp
| 1,031
| 33.316198
| 216
| 0.660755
|
oelprinz-org/BlitzboxBL49sp
| 36
| 12
| 0
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,540,039
|
page_crc.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/page_crc.cpp
|
#include "globals.h"
#include "page_crc.h"
#include "pages.h"
#include "table3d_axis_io.h"
using pCrcCalc = uint32_t (FastCRC32::*)(const uint8_t *, const uint16_t, bool);
static inline uint32_t compute_raw_crc(const page_iterator_t &entity, pCrcCalc calcFunc, FastCRC32 &crcCalc)
{
return (crcCalc.*calcFunc)((uint8_t*)entity.pData, entity.size, false);
}
static inline uint32_t compute_row_crc(const table_row_iterator &row, pCrcCalc calcFunc, FastCRC32 &crcCalc)
{
return (crcCalc.*calcFunc)(&*row, row.size(), false);
}
static inline uint32_t compute_tablevalues_crc(table_value_iterator it, pCrcCalc calcFunc, FastCRC32 &crcCalc)
{
uint32_t crc = compute_row_crc(*it, calcFunc, crcCalc);
++it;
while (!it.at_end())
{
crc = compute_row_crc(*it, &FastCRC32::crc32_upd, crcCalc);
++it;
}
return crc;
}
static inline uint32_t compute_tableaxis_crc(table_axis_iterator it, uint32_t crc, FastCRC32 &crcCalc)
{
const int16_byte *pConverter = table3d_axis_io::get_converter(it.get_domain());
byte values[32]; // Fingers crossed we don't have a table bigger than 32x32
byte *pValue = values;
while (!it.at_end())
{
*pValue++ = pConverter->to_byte(*it);
++it;
}
return pValue-values==0 ? crc : crcCalc.crc32_upd(values, pValue-values, false);
}
static inline uint32_t compute_table_crc(const page_iterator_t &entity, pCrcCalc calcFunc, FastCRC32 &crcCalc)
{
return compute_tableaxis_crc(y_begin(entity),
compute_tableaxis_crc(x_begin(entity),
compute_tablevalues_crc(rows_begin(entity), calcFunc, crcCalc),
crcCalc),
crcCalc);
}
static inline uint32_t pad_crc(uint16_t padding, uint32_t crc, FastCRC32 &crcCalc)
{
const uint8_t raw_value = 0u;
while (padding>0)
{
crc = crcCalc.crc32_upd(&raw_value, 1, false);
--padding;
}
return crc;
}
static inline uint32_t compute_crc(const page_iterator_t &entity, pCrcCalc calcFunc, FastCRC32 &crcCalc)
{
switch (entity.type)
{
case Raw:
return compute_raw_crc(entity, calcFunc, crcCalc);
break;
case Table:
return compute_table_crc(entity, calcFunc, crcCalc);
break;
case NoEntity:
return pad_crc(entity.size, 0U, crcCalc);
break;
default:
abort();
break;
}
}
uint32_t calculatePageCRC32(byte pageNum)
{
FastCRC32 crcCalc;
page_iterator_t entity = page_begin(pageNum);
// Initial CRC calc
uint32_t crc = compute_crc(entity, &FastCRC32::crc32, crcCalc);
entity = advance(entity);
while (entity.type!=End)
{
crc = compute_crc(entity, &FastCRC32::crc32_upd /* Note that we are *updating* */, crcCalc);
entity = advance(entity);
}
return ~pad_crc(getPageSize(pageNum) - entity.size, crc, crcCalc);
}
| 2,869
|
C++
|
.cpp
| 86
| 28.44186
| 110
| 0.671723
|
oelprinz-org/BlitzboxBL49sp
| 36
| 12
| 0
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,540,040
|
SPIAsEEPROM.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/src/SPIAsEEPROM/SPIAsEEPROM.cpp
|
/* Speeduino SPIAsEEPROM Library v.2.0.4
* Copyright (C) 2020 by Tjeerd Hoogendijk
* Created by Tjeerd Hoogendijk - 21/09/2019
* Updated by Tjeerd Hoogendijk - 19/04/2020
* Updated by Tjeerd Hoogendijk - 21/07/2020 no new version number
*
* This file is part of the Speeduino project. This library started out for
* Winbond SPI flash memory modules. As of version 2.0 it also works with internal
* flash memory of the STM32F407. In its current form it enables reading
* and writing individual bytes as if it where an AVR EEPROM. When the begin()
* fuction is called for the first time it will "format" the flash chip.
* !!!!THIS DISTROYS ANY EXISTING DATA ON THE FLASH!!!!
*
* This Library 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.
*
* This Library 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 v3.0
* along with the Speeduino SPIAsEEPROM Library. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include "SPIAsEEPROM.h"
FLASH_EEPROM_BaseClass::FLASH_EEPROM_BaseClass(EEPROM_Emulation_Config config)
{
//Class indicating if the emulated EEPROM flash is initialized
_EmulatedEEPROMAvailable=false;
//Class variable storing number of ones counted in adres translation block
_nrOfOnes = 0;
//Class variable storing what sector we are working in.
_sectorFlash = 0;
//Class variable storing what flash address we are working in.
_addressFLASH = 0;
//Class bool indicating if the flash is initialized and available for use
_FlashAvailable=false;
//save configuration
_config = config;
_Flash_Size_Used = _config.Flash_Sectors_Used*_config.Flash_Sector_Size;
_Flash_Size_Per_EEPROM_Byte = _config.Flash_Sector_Size/(_config.EEPROM_Bytes_Per_Sector +1);
_Addres_Translation_Size = _Flash_Size_Per_EEPROM_Byte/8;
_EEPROM_Emulation_Size = _config.Flash_Sectors_Used*_config.EEPROM_Bytes_Per_Sector;
}
int8_t FLASH_EEPROM_BaseClass::initialize(bool flashavailable)
{
bool formatted = false;
_FlashAvailable = flashavailable;
_EmulatedEEPROMAvailable = false;
if(_FlashAvailable)
{
formatted = checkForMagicNumbers();
//If not formatted format flash. This takes 10 seconds or more!
if(!formatted){
clear();
//check if format succeeded
formatted = checkForMagicNumbers();
}
if(formatted){_EmulatedEEPROMAvailable=true;}
}
return _EmulatedEEPROMAvailable;
}
byte FLASH_EEPROM_BaseClass::read(uint16_t addressEEPROM){
//version 0.1 does not check magic number
byte EEPROMbyte;
//Check if address is outside of the maximum. return zero if address is out of range.
if (addressEEPROM > _EEPROM_Emulation_Size){addressEEPROM = _EEPROM_Emulation_Size - 1; return 0;}
//Check at what flash sector the EEPROM byte information resides
_sectorFlash = addressEEPROM/_config.EEPROM_Bytes_Per_Sector;
//Check at what flash address the EEPROM byte information resides
_addressFLASH = (_sectorFlash*_config.Flash_Sector_Size) + ((addressEEPROM % _config.EEPROM_Bytes_Per_Sector) + 1) * _Flash_Size_Per_EEPROM_Byte;
//reset buffer to all 0xFF
for (uint32_t i = 0; i < _Flash_Size_Per_EEPROM_Byte; i++)
{
_ReadWriteBuffer[i] = 0xFF;
}
//read address translation part
readFlashBytes(_addressFLASH, _ReadWriteBuffer, _Addres_Translation_Size);
//calculate address of the valid data by couting the bits in the Address translation section
_nrOfOnes = count(_ReadWriteBuffer, _Addres_Translation_Size);
//Bring number of ones within specification of buffer size.
if(_nrOfOnes >=_Flash_Size_Per_EEPROM_Byte){_nrOfOnes =_Flash_Size_Per_EEPROM_Byte;}
//If it is the first read after clear (all ones still set), return 0xFF;
if (_nrOfOnes==_Flash_Size_Per_EEPROM_Byte){
EEPROMbyte = 0xFF;
}else{
byte tempBuf[1];
//read actual eeprom value of flash
readFlashBytes(_addressFLASH+_nrOfOnes, tempBuf, 1);
EEPROMbyte = tempBuf[0];
//make buffer correct, because write function expects a correct buffer.
_ReadWriteBuffer[_nrOfOnes] = EEPROMbyte;
}
return EEPROMbyte;
}
int8_t FLASH_EEPROM_BaseClass::write(uint16_t addressEEPROM, byte val){
//Check if address is outside of the maximum. limit to get inside maximum and return an error.
if (addressEEPROM > _EEPROM_Emulation_Size){addressEEPROM = _EEPROM_Emulation_Size - 1; return -1;}
//read the current value
uint8_t readValue = read(addressEEPROM);
//After reading the current byte all global variables containing information about the address are set correctly.
//only write if value is changed.
if (readValue != val){
//Check if section is full and an erase must be performed.
if (_nrOfOnes < _Addres_Translation_Size + 1){
//First read all the values in this sector that will get distroyed when erasing
byte tempBuf[_config.EEPROM_Bytes_Per_Sector];
for(uint16_t i = 0; i<_config.EEPROM_Bytes_Per_Sector; i++){
uint16_t TempEEPROMaddress = (_sectorFlash*_config.EEPROM_Bytes_Per_Sector) + i;
tempBuf[i] = read(TempEEPROMaddress);
}
//Now erase the sector
eraseFlashSector(_sectorFlash*_config.Flash_Sector_Size, _config.Flash_Sector_Size);
//Write the magic numbers
writeMagicNumbers(_sectorFlash);
//write all the values back
for(uint16_t i=0; i<_config.EEPROM_Bytes_Per_Sector; i++){
write((_sectorFlash*_config.EEPROM_Bytes_Per_Sector) + i, tempBuf[i]);
}
//Do not forget to write the new value!
write(addressEEPROM, val);
//Return we have writen a whole sector.
return 0xFF;
}
//determine the adress of the byte in the address translation section where one bit must be reset when writing new values
uint8_t AdressInAddressTranslation = (_nrOfOnes - 1)/8;
//write the new adress translation value at the new location in buffer
_ReadWriteBuffer[AdressInAddressTranslation] <<= 1;
//Write the new EEPROM value at the new location in the buffer.
_nrOfOnes--;
_ReadWriteBuffer[_nrOfOnes] = val;
//Write the buffer to the undelying flash storage.
// writeFlashBytes(_addressFLASH, _ReadWriteBuffer, _Flash_Size_Per_EEPROM_Byte);
//Write actual value part of the buffer to flash
byte tempBuffer[2];
_nrOfOnes &= ~(0x1); //align address with 2 byte (uint16_t) for write to flash for 32bit STM32 MCU
memcpy(&tempBuffer, &_ReadWriteBuffer[_nrOfOnes], sizeof(uint16_t));
writeFlashBytes(_addressFLASH +_nrOfOnes, tempBuffer, sizeof(uint16_t));
//Write address translation part of the buffer to flash
AdressInAddressTranslation &= ~(0x1); //align address with 2 byte for write to flash for 32bit STM32 MCU
memcpy(&tempBuffer, &_ReadWriteBuffer[AdressInAddressTranslation], sizeof(uint16_t));
writeFlashBytes(_addressFLASH+AdressInAddressTranslation, tempBuffer, sizeof(uint16_t));
return 1;
}
return 0;
}
int8_t FLASH_EEPROM_BaseClass::update(uint16_t addressEEPROM, uint8_t val){
return write(addressEEPROM, val);
}
int16_t FLASH_EEPROM_BaseClass::clear(){
uint32_t i;
for(i=0; i< _config.Flash_Sectors_Used; i++ ){
eraseFlashSector(i*_config.Flash_Sector_Size, _config.Flash_Sector_Size);
writeMagicNumbers(i);
}
return i;
}
uint16_t FLASH_EEPROM_BaseClass::length(){ return _EEPROM_Emulation_Size; }
bool FLASH_EEPROM_BaseClass::checkForMagicNumbers(){
bool magicnumbers = true;
for(uint32_t i=0; i< _config.Flash_Sectors_Used; i++ ){
readFlashBytes(i*_config.Flash_Sector_Size, _ReadWriteBuffer, _Flash_Size_Per_EEPROM_Byte);
if((_ReadWriteBuffer[0] != MAGICNUMBER1) | (_ReadWriteBuffer[1] != MAGICNUMBER2) | (_ReadWriteBuffer[2] != MAGICNUMBER3) | (_ReadWriteBuffer[3] != EEPROM_VERSION)){magicnumbers=false;}
}
return magicnumbers;
}
int8_t FLASH_EEPROM_BaseClass::writeMagicNumbers(uint32_t sector){
_ReadWriteBuffer[0] = MAGICNUMBER1;
_ReadWriteBuffer[1] = MAGICNUMBER2;
_ReadWriteBuffer[2] = MAGICNUMBER3;
_ReadWriteBuffer[3] = EEPROM_VERSION;
writeFlashBytes(sector*_config.Flash_Sector_Size, _ReadWriteBuffer, MAGICNUMBER_OFFSET);
return true;
}
uint16_t FLASH_EEPROM_BaseClass::count(byte* buffer, uint32_t length){
byte tempBuffer[length];
memcpy(&tempBuffer, buffer, length);
uint16_t count = _Flash_Size_Per_EEPROM_Byte; //It is faster to count the zeroes
for(int8_t j=(length-1); j >= 0; j--)
{
if (tempBuffer[j] == 0) { count -= 8; } //Skip 8 shifts
else if(tempBuffer[j] == 255) { break; }//Next bytes are 0xFF
else
{
while ((tempBuffer[j] & 0x01) == 0)
{
tempBuffer[j] >>= 1;
count--;
}
}
}
return count;
}
int8_t FLASH_EEPROM_BaseClass::readFlashBytes(uint32_t address __attribute__((__unused__)), byte* buffer __attribute__((__unused__)), uint32_t length __attribute__((__unused__))){return -1;}
int8_t FLASH_EEPROM_BaseClass::writeFlashBytes(uint32_t address __attribute__((__unused__)), byte* buffer __attribute__((__unused__)), uint32_t length __attribute__((__unused__))){return -1;}
int8_t FLASH_EEPROM_BaseClass::eraseFlashSector(uint32_t address __attribute__((__unused__)), uint32_t length __attribute__((__unused__))){return -1;}
#if defined(ARDUINO_ARCH_STM32)
SPI_EEPROM_Class::SPI_EEPROM_Class(EEPROM_Emulation_Config EmulationConfig, Flash_SPI_Config SPIConfig):FLASH_EEPROM_BaseClass(EmulationConfig)
{
_configSPI = SPIConfig;
}
byte SPI_EEPROM_Class::read(uint16_t addressEEPROM){
//Check if emulated EEPROM is available if not yet start it first.
if(!_EmulatedEEPROMAvailable){
SPISettings settings(22500000, MSBFIRST, SPI_MODE0); //22.5Mhz is highest it could get with this. But should be ~45Mhz :-(.
_configSPI.SPIport.beginTransaction(settings);
begin(_configSPI.SPIport, _configSPI.pinChipSelect);
}
return FLASH_EEPROM_BaseClass::read(addressEEPROM);
}
int8_t SPI_EEPROM_Class::begin(SPIClass &_spi, uint8_t pinSPIFlash_CS=6){
pinMode(pinSPIFlash_CS, OUTPUT);
bool flashavailable;
flashavailable = winbondSPIFlash.begin(_W25Q16,_spi, pinSPIFlash_CS);
return FLASH_EEPROM_BaseClass::initialize(flashavailable);
}
int8_t SPI_EEPROM_Class::readFlashBytes(uint32_t address, byte *buf, uint32_t length){
while(winbondSPIFlash.busy());
return winbondSPIFlash.read(address+_config.EEPROM_Flash_BaseAddress, buf, length);
}
int8_t SPI_EEPROM_Class::writeFlashBytes(uint32_t address, byte *buf, uint32_t length){
winbondSPIFlash.setWriteEnable(true);
winbondSPIFlash.writePage(address+_config.EEPROM_Flash_BaseAddress, buf, length);
while(winbondSPIFlash.busy());
return 0;
}
int8_t SPI_EEPROM_Class::eraseFlashSector(uint32_t address, uint32_t length){
winbondSPIFlash.setWriteEnable(true);
winbondSPIFlash.eraseSector(address+_config.EEPROM_Flash_BaseAddress);
while(winbondSPIFlash.busy());
return 0;
}
#endif
//THIS IS NOT WORKING! FOR STM32F103 YOU CAN ONLY WRITE IN JUST ERASED HALFWORDS(UINT16_T). THE PHILISOPHY IS FLAWWED THERE.
//#if defined(STM32F103xB)
// InternalSTM32F1_EEPROM_Class::InternalSTM32F1_EEPROM_Class(EEPROM_Emulation_Config config):FLASH_EEPROM_BaseClass(config)
// {
// }
// byte InternalSTM32F1_EEPROM_Class::read(uint16_t addressEEPROM){
// if(!_EmulatedEEPROMAvailable){
// FLASH_EEPROM_BaseClass::initialize(true);
// }
// return FLASH_EEPROM_BaseClass::read(addressEEPROM);
// }
// int8_t InternalSTM32F1_EEPROM_Class::readFlashBytes(uint32_t address, byte *buf, uint32_t length){
// memcpy(buf, (uint8_t *)(_config.EEPROM_Flash_BaseAddress + address), length);
// return 0;
// }
// int8_t InternalSTM32F1_EEPROM_Class::writeFlashBytes(uint32_t flashAddress, byte *buf, uint32_t length){
// {
// uint32_t translatedAddress = flashAddress+_config.EEPROM_Flash_BaseAddress;
// uint32_t data = 0;
// uint32_t countaddress = translatedAddress;
// HAL_FLASH_Unlock();
// while (countaddress < translatedAddress + length) {
// memcpy(&data, buf, sizeof(uint32_t));
// if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, countaddress, data) == HAL_OK) {
// countaddress += 4;
// offset += 4;
// } else {
// countaddress = translatedAddress + length + 1;
// }
// }
// }
// HAL_FLASH_Lock();
// return 0;
// }
// int8_t InternalSTM32F1_EEPROM_Class::eraseFlashSector(uint32_t address, uint32_t length){
// FLASH_EraseInitTypeDef EraseInitStruct;
// uint32_t pageError = 0;
// uint32_t realAddress = _config.EEPROM_Flash_BaseAddress+address;
// bool EraseSucceed=false;
// /* ERASING page */
// EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES;
// EraseInitStruct.Banks = 1;
// EraseInitStruct.PageAddress = realAddress;
// EraseInitStruct.NbPages = 1;
// HAL_FLASH_Unlock();
// if (HAL_FLASHEx_Erase(&EraseInitStruct, &pageError) == HAL_OK){EraseSucceed=true;}
// HAL_FLASH_Lock();
// return EraseSucceed;
// }
//#endif
#if defined(STM32F4)
//Look in the datasheet for more information about flash sectors and sizes
//This is the correct sector allocation for the STM32F407 all types
#define ADDR_FLASH_SECTOR_0 ((uint32_t)0x08000000) /* Base address of Sector 0, 16 Kbytes */
#define ADDR_FLASH_SECTOR_1 ((uint32_t)0x08004000) /* Base address of Sector 1, 16 Kbytes */
#define ADDR_FLASH_SECTOR_2 ((uint32_t)0x08008000) /* Base address of Sector 2, 16 Kbytes */
#define ADDR_FLASH_SECTOR_3 ((uint32_t)0x0800C000) /* Base address of Sector 3, 16 Kbytes */
#define ADDR_FLASH_SECTOR_4 ((uint32_t)0x08010000) /* Base address of Sector 4, 64 Kbytes */
#define ADDR_FLASH_SECTOR_5 ((uint32_t)0x08020000) /* Base address of Sector 5, 128 Kbytes */
#define ADDR_FLASH_SECTOR_6 ((uint32_t)0x08040000) /* Base address of Sector 6, 128 Kbytes */
#define ADDR_FLASH_SECTOR_7 ((uint32_t)0x08060000) /* Base address of Sector 7, 128 Kbytes */
#define ADDR_FLASH_SECTOR_8 ((uint32_t)0x08080000) /* Base address of Sector 8, 128 Kbytes */
#define ADDR_FLASH_SECTOR_9 ((uint32_t)0x080A0000) /* Base address of Sector 9, 128 Kbytes */
#define ADDR_FLASH_SECTOR_10 ((uint32_t)0x080C0000) /* Base address of Sector 10, 128 Kbytes */
#define ADDR_FLASH_SECTOR_11 ((uint32_t)0x080E0000) /* Base address of Sector 11, 128 Kbytes */
#define FLASH_END_ADDRESS ((uint32_t)0x08100000) /* END address of Sector 11, 128 Kbytes */
InternalSTM32F4_EEPROM_Class::InternalSTM32F4_EEPROM_Class(EEPROM_Emulation_Config config) : FLASH_EEPROM_BaseClass(config)
{
}
byte InternalSTM32F4_EEPROM_Class::read(uint16_t addressEEPROM){
if(!_EmulatedEEPROMAvailable){
FLASH_EEPROM_BaseClass::initialize(true);
}
return FLASH_EEPROM_BaseClass::read(addressEEPROM);
}
int8_t InternalSTM32F4_EEPROM_Class::readFlashBytes(uint32_t address, byte *buf, uint32_t length){
memcpy(buf, (uint8_t *)(_config.EEPROM_Flash_BaseAddress + address), length);
return 0;
}
int8_t InternalSTM32F4_EEPROM_Class::writeFlashBytes(uint32_t flashAddress, byte *buf, uint32_t length){
{
uint32_t translatedAddress = flashAddress+_config.EEPROM_Flash_BaseAddress;
uint16_t data = 0;
uint32_t offset = 0;
uint32_t countaddress = translatedAddress;
//Clear any flash errors before try writing to flash to prevent write failures.
if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR) != RESET) __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_WRPERR);
if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_PGAERR) != RESET) __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_PGAERR);
if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_PGPERR) != RESET) __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_PGPERR);
if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_PGSERR) != RESET) __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_PGSERR);
if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_OPERR ) != RESET) __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_OPERR);
HAL_FLASH_Unlock();
while (countaddress < translatedAddress + length) {
memcpy(&data, buf + offset, sizeof(uint16_t));
if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_HALFWORD, countaddress, data) == HAL_OK) {
countaddress += 2;
offset += 2;
} else {
countaddress = translatedAddress + length + 1;
}
}
}
HAL_FLASH_Lock();
return 0;
}
int8_t InternalSTM32F4_EEPROM_Class::eraseFlashSector(uint32_t address, uint32_t length){
FLASH_EraseInitTypeDef EraseInitStruct;
// uint32_t offset = 0;
uint32_t realAddress = _config.EEPROM_Flash_BaseAddress+address;
// uint32_t address_end = FLASH_BASE_ADDRESS + E2END;
bool EraseSucceed=false;
uint32_t SectorError = 0;
uint32_t _Sector = 11;
//Look in the datasheet for more information about flash sectors and sizes
//This is the correct sector allocation for the STM32F407 all types
if((realAddress < ADDR_FLASH_SECTOR_1) && (realAddress >= ADDR_FLASH_SECTOR_0)){_Sector = 0;}
if((realAddress < ADDR_FLASH_SECTOR_2) && (realAddress >= ADDR_FLASH_SECTOR_1)){_Sector = 1;}
if((realAddress < ADDR_FLASH_SECTOR_3) && (realAddress >= ADDR_FLASH_SECTOR_2)){_Sector = 2;}
if((realAddress < ADDR_FLASH_SECTOR_4) && (realAddress >= ADDR_FLASH_SECTOR_3)){_Sector = 3;}
if((realAddress < ADDR_FLASH_SECTOR_5) && (realAddress >= ADDR_FLASH_SECTOR_4)){_Sector = 4;}
if((realAddress < ADDR_FLASH_SECTOR_6) && (realAddress >= ADDR_FLASH_SECTOR_5)){_Sector = 5;}
if((realAddress < ADDR_FLASH_SECTOR_7) && (realAddress >= ADDR_FLASH_SECTOR_6)){_Sector = 6;}
if((realAddress < ADDR_FLASH_SECTOR_8) && (realAddress >= ADDR_FLASH_SECTOR_7)){_Sector = 7;}
if((realAddress < ADDR_FLASH_SECTOR_9) && (realAddress >= ADDR_FLASH_SECTOR_8)){_Sector = 8;}
if((realAddress < ADDR_FLASH_SECTOR_10) && (realAddress >= ADDR_FLASH_SECTOR_9)){_Sector = 9;}
if((realAddress < ADDR_FLASH_SECTOR_11) && (realAddress >= ADDR_FLASH_SECTOR_10)){_Sector = 10;}
if((realAddress < FLASH_END_ADDRESS) && (realAddress >= ADDR_FLASH_SECTOR_11)){_Sector = 11;}
EraseInitStruct.TypeErase = FLASH_TYPEERASE_SECTORS;
EraseInitStruct.VoltageRange = FLASH_VOLTAGE_RANGE_3;
EraseInitStruct.Sector = _Sector;
EraseInitStruct.NbSectors = 1;
HAL_FLASH_Unlock();
if (HAL_FLASHEx_Erase(&EraseInitStruct, &SectorError) == HAL_OK){EraseSucceed=true;}
HAL_FLASH_Lock();
return EraseSucceed;
}
#endif
#if defined(STM32F7xx)
#if defined(DUAL_BANK)
#define ADDR_FLASH_SECTOR_0 ((uint32_t)0x08000000) /* Base address of Sector 0, 16 Kbytes */
#define ADDR_FLASH_SECTOR_1 ((uint32_t)0x08004000) /* Base address of Sector 1, 16 Kbytes */
#define ADDR_FLASH_SECTOR_2 ((uint32_t)0x08008000) /* Base address of Sector 2, 16 Kbytes */
#define ADDR_FLASH_SECTOR_3 ((uint32_t)0x0800C000) /* Base address of Sector 3, 16 Kbytes */
#define ADDR_FLASH_SECTOR_4 ((uint32_t)0x08010000) /* Base address of Sector 4, 64 Kbytes */
#define ADDR_FLASH_SECTOR_5 ((uint32_t)0x08020000) /* Base address of Sector 5, 128 Kbytes */
#define ADDR_FLASH_SECTOR_6 ((uint32_t)0x08040000) /* Base address of Sector 6, 128 Kbytes */
#define ADDR_FLASH_SECTOR_7 ((uint32_t)0x08060000) /* Base address of Sector 7, 128 Kbytes */
#define ADDR_FLASH_SECTOR_8 ((uint32_t)0x08080000) /* Base address of Sector 8, 128 Kbytes */
#define ADDR_FLASH_SECTOR_9 ((uint32_t)0x080A0000) /* Base address of Sector 9, 128 Kbytes */
#define ADDR_FLASH_SECTOR_10 ((uint32_t)0x080C0000) /* Base address of Sector 10, 128 Kbytes */
#define ADDR_FLASH_SECTOR_11 ((uint32_t)0x080E0000) /* Base address of Sector 11, 128 Kbytes */
#define ADDR_FLASH_SECTOR_12 ((uint32_t)0x08100000) /* Base address of Sector 12, 16 Kbytes */
#define ADDR_FLASH_SECTOR_13 ((uint32_t)0x08104000) /* Base address of Sector 13, 16 Kbytes */
#define ADDR_FLASH_SECTOR_14 ((uint32_t)0x08108000) /* Base address of Sector 14, 16 Kbytes */
#define ADDR_FLASH_SECTOR_15 ((uint32_t)0x0810C000) /* Base address of Sector 15, 16 Kbytes */
#define ADDR_FLASH_SECTOR_16 ((uint32_t)0x08110000) /* Base address of Sector 16, 64 Kbytes */
#define ADDR_FLASH_SECTOR_17 ((uint32_t)0x08120000) /* Base address of Sector 17, 128 Kbytes */
#define ADDR_FLASH_SECTOR_18 ((uint32_t)0x08140000) /* Base address of Sector 18, 128 Kbytes */
#define ADDR_FLASH_SECTOR_19 ((uint32_t)0x08160000) /* Base address of Sector 19, 128 Kbytes */
#define ADDR_FLASH_SECTOR_20 ((uint32_t)0x08180000) /* Base address of Sector 20, 128 Kbytes */
#define ADDR_FLASH_SECTOR_21 ((uint32_t)0x081A0000) /* Base address of Sector 21, 128 Kbytes */
#define ADDR_FLASH_SECTOR_22 ((uint32_t)0x081C0000) /* Base address of Sector 22, 128 Kbytes */
#define ADDR_FLASH_SECTOR_23 ((uint32_t)0x081E0000) /* Base address of Sector 23, 128 Kbytes */
#else
#define ADDR_FLASH_SECTOR_0 ((uint32_t)0x08000000) /* Base address of Sector 0, 32 Kbytes */
#define ADDR_FLASH_SECTOR_1 ((uint32_t)0x08008000) /* Base address of Sector 1, 32 Kbytes */
#define ADDR_FLASH_SECTOR_2 ((uint32_t)0x08010000) /* Base address of Sector 2, 32 Kbytes */
#define ADDR_FLASH_SECTOR_3 ((uint32_t)0x08018000) /* Base address of Sector 3, 32 Kbytes */
#define ADDR_FLASH_SECTOR_4 ((uint32_t)0x08020000) /* Base address of Sector 4, 128 Kbytes */
#define ADDR_FLASH_SECTOR_5 ((uint32_t)0x08040000) /* Base address of Sector 5, 256 Kbytes */
#define ADDR_FLASH_SECTOR_6 ((uint32_t)0x08080000) /* Base address of Sector 6, 256 Kbytes */
#define ADDR_FLASH_SECTOR_7 ((uint32_t)0x080C0000) /* Base address of Sector 7, 256 Kbytes */
#define ADDR_FLASH_SECTOR_8 ((uint32_t)0x08100000) /* Base address of Sector 8, 256 Kbytes */
#define ADDR_FLASH_SECTOR_9 ((uint32_t)0x08140000) /* Base address of Sector 9, 256 Kbytes */
#define ADDR_FLASH_SECTOR_10 ((uint32_t)0x08180000) /* Base address of Sector 10, 256 Kbytes */
#define ADDR_FLASH_SECTOR_11 ((uint32_t)0x081C0000) /* Base address of Sector 11, 256 Kbytes */
#endif /* DUAL_BANK */
InternalSTM32F7_EEPROM_Class::InternalSTM32F7_EEPROM_Class(EEPROM_Emulation_Config config) : FLASH_EEPROM_BaseClass(config)
{
}
byte InternalSTM32F7_EEPROM_Class::read(uint16_t addressEEPROM){
if(!_EmulatedEEPROMAvailable){
FLASH_EEPROM_BaseClass::initialize(true);
}
return FLASH_EEPROM_BaseClass::read(addressEEPROM);
}
int8_t InternalSTM32F7_EEPROM_Class::readFlashBytes(uint32_t address, byte *buf, uint32_t length){
memcpy(buf, (uint8_t *)(_config.EEPROM_Flash_BaseAddress + address), length);
return 0;
}
int8_t InternalSTM32F7_EEPROM_Class::writeFlashBytes(uint32_t flashAddress, byte *buf, uint32_t length){
{
uint32_t translatedAddress = flashAddress+_config.EEPROM_Flash_BaseAddress;
uint32_t data = 0;
uint32_t offset = 0;
uint32_t countaddress = translatedAddress;
HAL_FLASH_Unlock();
while (countaddress < translatedAddress + length) {
memcpy(&data, buf + offset, sizeof(uint32_t));
if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, countaddress, data) == HAL_OK) {
countaddress += 4;
offset += 4;
} else {
countaddress = translatedAddress + length + 1;
}
}
}
HAL_FLASH_Lock();
return 0;
}
int8_t InternalSTM32F7_EEPROM_Class::eraseFlashSector(uint32_t address, uint32_t length){
FLASH_EraseInitTypeDef EraseInitStruct;
// uint32_t offset = 0;
uint32_t realAddress = _config.EEPROM_Flash_BaseAddress+address;
// uint32_t address_end = FLASH_BASE_ADDRESS + E2END;
bool EraseSucceed=false;
uint32_t SectorError = 0;
uint32_t _Sector = 11;
//Look in the datasheet for more information about flash sectors and sizes
//This is the correct sector allocation for the STM32F407 all types
if((realAddress < ADDR_FLASH_SECTOR_1) && (realAddress >= ADDR_FLASH_SECTOR_0)){_Sector = 0;}
if((realAddress < ADDR_FLASH_SECTOR_2) && (realAddress >= ADDR_FLASH_SECTOR_1)){_Sector = 1;}
if((realAddress < ADDR_FLASH_SECTOR_3) && (realAddress >= ADDR_FLASH_SECTOR_2)){_Sector = 2;}
if((realAddress < ADDR_FLASH_SECTOR_4) && (realAddress >= ADDR_FLASH_SECTOR_3)){_Sector = 3;}
if((realAddress < ADDR_FLASH_SECTOR_5) && (realAddress >= ADDR_FLASH_SECTOR_4)){_Sector = 4;}
if((realAddress < ADDR_FLASH_SECTOR_6) && (realAddress >= ADDR_FLASH_SECTOR_5)){_Sector = 5;}
if((realAddress < ADDR_FLASH_SECTOR_7) && (realAddress >= ADDR_FLASH_SECTOR_6)){_Sector = 6;}
if((realAddress < ADDR_FLASH_SECTOR_8) && (realAddress >= ADDR_FLASH_SECTOR_7)){_Sector = 7;}
if((realAddress < ADDR_FLASH_SECTOR_9) && (realAddress >= ADDR_FLASH_SECTOR_8)){_Sector = 8;}
if((realAddress < ADDR_FLASH_SECTOR_10) && (realAddress >= ADDR_FLASH_SECTOR_9)){_Sector = 9;}
if((realAddress < ADDR_FLASH_SECTOR_11) && (realAddress >= ADDR_FLASH_SECTOR_10)){_Sector = 10;}
else /* (Address < FLASH_END_ADDR) && (Address >= ADDR_FLASH_SECTOR_11) */
{
{_Sector = 11;}
}
#if defined(DUAL_BANK)
if((realAddress < ADDR_FLASH_SECTOR_13) && (realAddress >= ADDR_FLASH_SECTOR_12)){_Sector = 12;}
if((realAddress < ADDR_FLASH_SECTOR_14) && (realAddress >= ADDR_FLASH_SECTOR_13)){_Sector = 13;}
if((realAddress < ADDR_FLASH_SECTOR_15) && (realAddress >= ADDR_FLASH_SECTOR_14)){_Sector = 14;}
if((realAddress < ADDR_FLASH_SECTOR_16) && (realAddress >= ADDR_FLASH_SECTOR_15)){_Sector = 15;}
if((realAddress < ADDR_FLASH_SECTOR_17) && (realAddress >= ADDR_FLASH_SECTOR_16)){_Sector = 16;}
if((realAddress < ADDR_FLASH_SECTOR_18) && (realAddress >= ADDR_FLASH_SECTOR_17)){_Sector = 17;}
if((realAddress < ADDR_FLASH_SECTOR_19) && (realAddress >= ADDR_FLASH_SECTOR_18)){_Sector = 18;}
if((realAddress < ADDR_FLASH_SECTOR_20) && (realAddress >= ADDR_FLASH_SECTOR_19)){_Sector = 19;}
if((realAddress < ADDR_FLASH_SECTOR_21) && (realAddress >= ADDR_FLASH_SECTOR_20)){_Sector = 20;}
if((realAddress < ADDR_FLASH_SECTOR_22) && (realAddress >= ADDR_FLASH_SECTOR_21)){_Sector = 21;}
if((realAddress < ADDR_FLASH_SECTOR_23) && (realAddress >= ADDR_FLASH_SECTOR_22)){_Sector = 22;}
else /* (Address < FLASH_END_ADDR) && (Address >= ADDR_FLASH_SECTOR_23) */
{
{_Sector = 23;}
}
#endif /* DUAL_BANK */
EraseInitStruct.TypeErase = FLASH_TYPEERASE_SECTORS;
EraseInitStruct.VoltageRange = FLASH_VOLTAGE_RANGE_3;
EraseInitStruct.Sector = _Sector;
EraseInitStruct.NbSectors = 1;
HAL_FLASH_Unlock();
if (HAL_FLASHEx_Erase(&EraseInitStruct, &SectorError) == HAL_OK){EraseSucceed=true;}
HAL_FLASH_Lock();
return EraseSucceed;
}
#endif
| 27,042
|
C++
|
.cpp
| 498
| 50.273092
| 194
| 0.706644
|
oelprinz-org/BlitzboxBL49sp
| 36
| 12
| 0
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,540,041
|
PID_v1.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/src/PID_v1/PID_v1.cpp
|
/**********************************************************************************************
* Arduino PID Library - Version 1.0.1
* by Brett Beauregard <br3ttb@gmail.com> brettbeauregard.com
*
* This Library is licensed under a GPLv3 License
**********************************************************************************************/
#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include "PID_v1.h"
/*Constructor (...)*********************************************************
* The parameters specified here are those for for which we can't set up
* reliable defaults, so we need to have the user set them.
***************************************************************************/
PID::PID(long* Input, long* Output, long* Setpoint,
byte Kp, byte Ki, byte Kd, byte ControllerDirection)
{
myOutput = Output;
myInput = Input;
mySetpoint = Setpoint;
inAuto = false;
PID::SetOutputLimits(0, 255); //default output limit corresponds to
//the arduino pwm limits
SampleTime = 100; //default Controller Sample Time is 0.1 seconds
PID::SetControllerDirection(ControllerDirection);
PID::SetTunings(Kp, Ki, Kd);
lastTime = millis()-SampleTime;
}
/* Compute() **********************************************************************
* This, as they say, is where the magic happens. this function should be called
* every time "void loop()" executes. the function will decide for itself whether a new
* pid Output needs to be computed. returns true when the output is computed,
* false when nothing has been done.
**********************************************************************************/
bool PID::Compute()
{
if(!inAuto) return false;
unsigned long now = millis();
SampleTime = (now - lastTime);
//if(timeChange>=SampleTime)
{
/*Compute all the working error variables*/
long input = *myInput;
long error = *mySetpoint - input;
ITerm += (ki * error);
if(ITerm > outMax) ITerm= outMax;
else if(ITerm < outMin) ITerm = outMin;
long dInput = (input - lastInput);
/*Compute PID Output*/
long output = (kp * error) + ITerm- (kd * dInput);
if(output > outMax) { output = outMax; }
else if(output < outMin) { output = outMin; }
*myOutput = output/1000;
/*Remember some variables for next time*/
lastInput = input;
lastTime = now;
return true;
}
//else return false;
}
/* SetTunings(...)*************************************************************
* This function allows the controller's dynamic performance to be adjusted.
* it's called automatically from the constructor, but tunings can also
* be adjusted on the fly during normal operation
******************************************************************************/
void PID::SetTunings(byte Kp, byte Ki, byte Kd)
{
dispKp = Kp; dispKi = Ki; dispKd = Kd;
/*
double SampleTimeInSec = ((double)SampleTime)/1000;
kp = Kp;
ki = Ki * SampleTimeInSec;
kd = Kd / SampleTimeInSec;
*/
//long InverseSampleTimeInSec = 100;
kp = Kp;
ki = Ki;
kd = Kd * 10;
if(controllerDirection ==REVERSE)
{
kp = (0 - kp);
ki = (0 - ki);
kd = (0 - kd);
}
}
/* SetSampleTime(...) *********************************************************
* sets the period, in Milliseconds, at which the calculation is performed
******************************************************************************/
void PID::SetSampleTime(int NewSampleTime)
{
if (NewSampleTime > 0)
{
unsigned long ratioX1000 = (unsigned long)(NewSampleTime * 1000) / (unsigned long)SampleTime;
ki = (ki * ratioX1000) / 1000;
//kd /= ratio;
kd = (kd * 1000) / ratioX1000;
SampleTime = (unsigned long)NewSampleTime;
}
}
/* SetOutputLimits(...)****************************************************
* This function will be used far more often than SetInputLimits. while
* the input to the controller will generally be in the 0-1023 range (which is
* the default already,) the output will be a little different. maybe they'll
* be doing a time window and will need 0-8000 or something. or maybe they'll
* want to clamp it from 0-125. who knows. at any rate, that can all be done
* here.
**************************************************************************/
void PID::SetOutputLimits(long Min, long Max)
{
if(Min >= Max) return;
outMin = Min*1000;
outMax = Max*1000;
if(inAuto)
{
if(*myOutput > outMax) *myOutput = outMax;
else if(*myOutput < outMin) *myOutput = outMin;
if(ITerm > outMax) ITerm= outMax;
else if(ITerm < outMin) ITerm= outMin;
}
}
/* SetMode(...)****************************************************************
* Allows the controller Mode to be set to manual (0) or Automatic (non-zero)
* when the transition from manual to auto occurs, the controller is
* automatically initialized
******************************************************************************/
void PID::SetMode(int Mode)
{
bool newAuto = (Mode == AUTOMATIC);
if(newAuto == !inAuto)
{ /*we just went from manual to auto*/
PID::Initialize();
}
inAuto = newAuto;
}
/* Initialize()****************************************************************
* does all the things that need to happen to ensure a bumpless transfer
* from manual to automatic mode.
******************************************************************************/
void PID::Initialize()
{
ITerm = *myOutput;
lastInput = *myInput;
if(ITerm > outMax) ITerm = outMax;
else if(ITerm < outMin) ITerm = outMin;
}
/* SetControllerDirection(...)*************************************************
* The PID will either be connected to a DIRECT acting process (+Output leads
* to +Input) or a REVERSE acting process(+Output leads to -Input.) we need to
* know which one, because otherwise we may increase the output when we should
* be decreasing. This is called from the constructor.
******************************************************************************/
void PID::SetControllerDirection(byte Direction)
{
if(inAuto && Direction !=controllerDirection)
{
kp = (0 - kp);
ki = (0 - ki);
kd = (0 - kd);
}
controllerDirection = Direction;
}
/* Status Funcions*************************************************************
* Just because you set the Kp=-1 doesn't mean it actually happened. these
* functions query the internal state of the PID. they're here for display
* purposes. this are the functions the PID Front-end uses for example
******************************************************************************/
int16_t PID::GetKp(){ return dispKp; }
int16_t PID::GetKi(){ return dispKi;}
int16_t PID::GetKd(){ return dispKd;}
int PID::GetMode(){ return inAuto ? AUTOMATIC : MANUAL;}
int PID::GetDirection(){ return controllerDirection;}
/*Constructor (...)*********************************************************
* The parameters specified here are those for for which we can't set up
* reliable defaults, so we need to have the user set them.
***************************************************************************/
/**
* @brief A standard integer PID controller.
*
* @param Input Pointer to the variable holding the current value that is to be controlled. Eg In an idle control this would point to RPM
* @param Output The address in the page that should be returned. This is as per the page definition in the ini
*
* @return byte The current target advance value in degrees
*/
integerPID::integerPID(long* Input, long* Output, long* Setpoint,
int16_t Kp, int16_t Ki, int16_t Kd, byte ControllerDirection)
{
myOutput = Output;
myInput = Input;
mySetpoint = Setpoint;
inAuto = false;
integerPID::SetOutputLimits(0, 255); //default output limit corresponds to the arduino pwm limits
SampleTime = 250; //default Controller Sample Time is 0.25 seconds. This is the 4Hz control time for Idle and VVT
integerPID::SetControllerDirection(ControllerDirection);
integerPID::SetTunings(Kp, Ki, Kd);
lastTime = millis()-SampleTime;
}
/* Compute() **********************************************************************
* This, as they say, is where the magic happens. this function should be called
* every time "void loop()" executes. the function will decide for itself whether a new
* pid Output needs to be computed. returns true when the output is computed,
* false when nothing has been done.
**********************************************************************************/
bool integerPID::Compute(bool pOnE, long FeedForwardTerm)
{
if(!inAuto) return false;
unsigned long now = millis();
unsigned long timeChange = (now - lastTime);
if(timeChange >= SampleTime)
{
/*Compute all the working error variables*/
long input = *myInput;
if(input > 0) //Fail safe, should never be 0
{
long error = *mySetpoint - input;
long dInput = (input - lastInput);
FeedForwardTerm <<= PID_SHIFTS;
if (ki != 0)
{
outputSum += (ki * error); //integral += error × dt
if(outputSum > outMax-FeedForwardTerm) { outputSum = outMax-FeedForwardTerm; }
else if(outputSum < outMin-FeedForwardTerm) { outputSum = outMin-FeedForwardTerm; }
}
/*Compute PID Output*/
long output;
if(pOnE)
{
output = (kp * error);
if (ki != 0) { output += outputSum; }
}
else
{
outputSum -= (kp * dInput);
if(outputSum > outMax) { outputSum = outMax; }
else if(outputSum < outMin) { outputSum = outMin; }
output = outputSum;
}
if (kd != 0) { output -= (kd * dInput)>>2; }
output += FeedForwardTerm;
if(output > outMax) output = outMax;
else if(output < outMin) output = outMin;
*myOutput = output >> PID_SHIFTS;
/*Remember some variables for next time*/
lastInput = input;
lastTime = now;
return true;
}
}
return false;
}
bool integerPID::ComputeVVT(uint32_t Sample)
{
if(!inAuto) return false;
/*Compute all the working error variables*/
long pTerm, dTerm;
long input = *myInput;
long error = *mySetpoint - input;
long dInput = error - lastError;
long dTime = lastTime - Sample;
pTerm = kp * error;
if (ki != 0)
{
outputSum += (ki * error) * dTime; //integral += error × dt
if(outputSum > outMax*100) { outputSum = outMax*100; }
else if(outputSum < -outMax*100) { outputSum = -outMax*100; }
}
dTerm = dInput * kd * dTime;
/*Compute PID Output*/
long output = (pTerm + outputSum + dTerm) >> 5;
if(output > outMax) output = outMax;
else if(output < outMin) output = outMin;
*myOutput = output;
/*Remember some variables for next time*/
lastError = error;
lastTime = dTime;
return true;
}
bool integerPID::Compute2(int target, int input, bool pOnE)
{
if(!inAuto) return false;
unsigned long now = millis();
//SampleTime = (now - lastTime);
uint16_t timeChange = (now - lastTime);
if(timeChange >= SampleTime)
{
long Kp, Ki, Kd;
long PV;
long output;
long SP1;
long error;
long pid_deriv;
#define pid_divider 1024
#define pid_multiplier 100
//pid_divider = 128;
//pid_multiplier = 10;
//convert_unitless_percent(min, max, targ, raw_PV, &PV, &SP);
PV = (((long)input - outMin) * 10000L) / (outMax - outMin); //125
SP1 = (((long)target - outMin) * 10000L) / (outMax - outMin); //500
error = SP1 - PV; //375
pid_deriv = PV - (2 * lastInput) + lastMinusOneInput; //125
if(!pOnE)
{
Kp = ((long) ((PV - lastInput) * (long)kp)); //125 * kp
}
else
{
Kp = ((long) ((error - lastError) * (long)kp));
}
Ki = ((((long) error * timeChange) / (long)pid_divider) * (long)ki); //12*ki
Kd = ((long) pid_deriv * (((long) kd * pid_multiplier) / timeChange));
if(!pOnE)
{
output = Kp - Ki + Kd;
}
else
{
output = Kp + Ki - Kd;
}
if(output > outMax) output = outMax;
else if(output < outMin) output = outMin;
*myOutput = output;
/*Remember some variables for next time*/
lastMinusOneInput = lastInput;
lastInput = input;
lastError = error;
lastTime = now;
return true;
}
else return false;
}
/* SetTunings(...)*************************************************************
* This function allows the controller's dynamic performance to be adjusted.
* it's called automatically from the constructor, but tunings can also
* be adjusted on the fly during normal operation
******************************************************************************/
void integerPID::SetTunings(int16_t Kp, int16_t Ki, int16_t Kd, byte realTime)
{
if ( dispKp == Kp && dispKi == Ki && dispKd == Kd ) return; //Only do anything if one of the values has changed
dispKp = Kp; dispKi = Ki; dispKd = Kd;
/*
double SampleTimeInSec = ((double)SampleTime)/1000;
kp = Kp;
ki = Ki * SampleTimeInSec;
kd = Kd / SampleTimeInSec;
*/
if(realTime == 0)
{
long InverseSampleTimeInSec = 1000 / SampleTime;
//New resolution, 32x to improve ki here | kp 3.125% | ki 3.125% | kd 0.781%
kp = Kp * 32;
ki = (long)(Ki * 32) / InverseSampleTimeInSec;
kd = (long)(Kd * 32) * InverseSampleTimeInSec;
}
else
{
kp = Kp;
ki = Ki;
kd = Kd;
}
if(controllerDirection == REVERSE)
{
kp = (0 - kp);
ki = (0 - ki);
kd = (0 - kd);
}
}
/* SetSampleTime(...) *********************************************************
* sets the period, in Milliseconds, at which the calculation is performed
******************************************************************************/
void integerPID::SetSampleTime(uint16_t NewSampleTime)
{
if (SampleTime == (unsigned long)NewSampleTime) return; //If new value = old value, no action required.
SampleTime = NewSampleTime;
//This resets the tuning values with the appropriate new scaling
//The +1/-1 is there just so that this doesn't trip the check at the beginning of the SetTunings() function
SetTunings(dispKp+1, dispKi+1, dispKd+1);
SetTunings(dispKp-1, dispKi-1, dispKd-1);
}
/* SetOutputLimits(...)****************************************************
* This function will be used far more often than SetInputLimits. while
* the input to the controller will generally be in the 0-1023 range (which is
* the default already,) the output will be a little different. maybe they'll
* be doing a time window and will need 0-8000 or something. or maybe they'll
* want to clamp it from 0-125. who knows. at any rate, that can all be done
* here.
**************************************************************************/
void integerPID::SetOutputLimits(long Min, long Max)
{
if(Min >= Max) return;
outMin = Min << PID_SHIFTS;
outMax = Max << PID_SHIFTS;
if(inAuto)
{
if(*myOutput > Max) *myOutput = Max;
else if(*myOutput < Min) *myOutput = Min;
if(outputSum > outMax) { outputSum = outMax; }
else if(outputSum < outMin) { outputSum = outMin; }
}
}
/* SetMode(...)****************************************************************
* Allows the controller Mode to be set to manual (0) or Automatic (non-zero)
* when the transition from manual to auto occurs, the controller is
* automatically initialized
******************************************************************************/
void integerPID::SetMode(int Mode)
{
bool newAuto = (Mode == AUTOMATIC);
if(newAuto == !inAuto)
{ /*we just went from manual to auto*/
integerPID::Initialize();
}
inAuto = newAuto;
}
/* Initialize()****************************************************************
* does all the things that need to happen to ensure a bumpless transfer
* from manual to automatic mode.
******************************************************************************/
void integerPID::Initialize()
{
outputSum = *myOutput<<PID_SHIFTS;
lastInput = *myInput;
lastMinusOneInput = *myInput;
if(outputSum > outMax) { outputSum = outMax; }
else if(outputSum < outMin) { outputSum = outMin; }
}
/* SetControllerDirection(...)*************************************************
* The PID will either be connected to a DIRECT acting process (+Output leads
* to +Input) or a REVERSE acting process(+Output leads to -Input.) we need to
* know which one, because otherwise we may increase the output when we should
* be decreasing. This is called from the constructor.
******************************************************************************/
void integerPID::SetControllerDirection(byte Direction)
{
if(inAuto && Direction !=controllerDirection)
{
kp = (0 - kp);
ki = (0 - ki);
kd = (0 - kd);
}
controllerDirection = Direction;
}
/* Status Funcions*************************************************************
* Just because you set the Kp=-1 doesn't mean it actually happened. these
* functions query the internal state of the PID. they're here for display
* purposes. this are the functions the PID Front-end uses for example
******************************************************************************/
int integerPID::GetMode(){ return inAuto ? AUTOMATIC : MANUAL;}
int integerPID::GetDirection(){ return controllerDirection;}
void integerPID::ResetIntegeral() { outputSum=0;}
//************************************************************************************************************************
#define limitMultiplier 100 //How much outMin and OutMax must be multiplied by to get them in the same scale as the output
/*Constructor (...)*********************************************************
* The parameters specified here are those for for which we can't set up
* reliable defaults, so we need to have the user set them.
***************************************************************************/
integerPID_ideal::integerPID_ideal(long* Input, uint16_t* Output, uint16_t* Setpoint, uint16_t* Sensitivity, byte* SampleTime,
byte Kp, byte Ki, byte Kd, byte ControllerDirection)
{
myOutput = Output;
myInput = (long*)Input;
mySetpoint = Setpoint;
mySensitivity = Sensitivity;
mySampleTime = SampleTime;
integerPID_ideal::SetOutputLimits(20, 80); //default output limits
integerPID_ideal::SetControllerDirection(ControllerDirection);
integerPID_ideal::SetTunings(Kp, Ki, Kd);
lastTime = millis()- *mySampleTime;
lastError = 0;
}
/* Compute() **********************************************************************
* This, as they say, is where the magic happens. this function should be called
* every time "void loop()" executes. the function will decide for itself whether a new
* pid Output needs to be computed. returns true when the output is computed,
* false when nothing has been done.
**********************************************************************************/
bool integerPID_ideal::Compute()
{
//This is the orginal PID with 50% Base target DC
return Compute(50*limitMultiplier);
}
/* Compute() **********************************************************************
* This, as they say, is where the magic happens. this function should be called
* every time "void loop()" executes. the function will decide for itself whether a new
* pid Output needs to be computed. returns true when the output is computed,
* false when nothing has been done.
**********************************************************************************/
bool integerPID_ideal::Compute(uint16_t FeedForward)
{
unsigned long now = millis();
//SampleTime = (now - lastTime);
unsigned long timeChange = (now - lastTime);
if(timeChange >= *mySampleTime)
{
/*Compute all the working error variables*/
uint16_t sensitivity = 10001 - (*mySensitivity * 2);
long unitless_setpoint = (((long)*mySetpoint - 0) * 10000L) / (sensitivity - 0);
long unitless_input = (((long)*myInput - 0) * 10000L) / (sensitivity - 0);
long error = unitless_setpoint - unitless_input;
ITerm += error;
// uint16_t bias = 50; //Base target DC%
long output = 0;
if(ki != 0)
{
output = ((outMax * limitMultiplier * 100) - FeedForward) / (long)ki;
if (output < 0) { output = 0; }
}
if (ITerm > output) { ITerm = output; }
if(ki != 0)
{
output = (FeedForward - (-outMin * limitMultiplier * 100)) / (long)ki;
if (output < 0) { output = 0; }
}
else { output = 0; }
if (ITerm < -output) { ITerm = -output; }
/*Compute PID Output*/
output = (kp * error) + (ki * ITerm) + (kd * (error - lastError));
output = FeedForward + (output / 10); //output is % multipled by 1000. To get % with 2 decimal places, divide it by 10. Likewise, bias is % in whole numbers. Multiply it by 100 to get it with 2 places.
//if(output > (outMax * limitMultiplier)) { output = (outMax * limitMultiplier); }
//if(output < (outMin * limitMultiplier)) { output = (outMin * limitMultiplier); }
if(output > (outMax * limitMultiplier))
{
output = (outMax * limitMultiplier);
ITerm -= error; //Prevent the ITerm from growing indefinitely whilst the output is being limited (error was added to ITerm above, so this is simply setting it back to it's original value)
}
if(output < (outMin * limitMultiplier))
{
output = (outMin * limitMultiplier);
ITerm -= error; //Prevent the ITerm from growing indefinitely whilst the output is being limited (error was added to ITerm above, so this is simply setting it back to it's original value)
}
*myOutput = output;
/*Remember some variables for next time*/
lastTime = now;
lastError = error;
return true;
}
else return false;
}
/* SetTunings(...)*************************************************************
* This function allows the controller's dynamic performance to be adjusted.
* it's called automatically from the constructor, but tunings can also
* be adjusted on the fly during normal operation
******************************************************************************/
void integerPID_ideal::SetTunings(byte Kp, byte Ki, byte Kd)
{
if ( dispKp == Kp && dispKi == Ki && dispKd == Kd ) return; //Only do anything if one of the values has changed
dispKp = Kp; dispKi = Ki; dispKd = Kd;
kp = Kp;
ki = Ki;
kd = Kd;
if(controllerDirection == REVERSE)
{
kp = (0 - kp);
ki = (0 - ki);
kd = (0 - kd);
}
}
/* SetOutputLimits(...)****************************************************
* This function will be used far more often than SetInputLimits. while
* the input to the controller will generally be in the 0-1023 range (which is
* the default already,) the output will be a little different. maybe they'll
* be doing a time window and will need 0-8000 or something. or maybe they'll
* want to clamp it from 0-125. who knows. at any rate, that can all be done
* here.
**************************************************************************/
void integerPID_ideal::SetOutputLimits(long Min, long Max)
{
if(Min < Max)
{
outMin = Min;
outMax = Max;
}
}
/* Initialize()****************************************************************
* does all the things that need to happen to ensure a bumpless transfer
* from manual to automatic mode.
******************************************************************************/
void integerPID_ideal::Initialize()
{
ITerm = 0;
lastInput = *myInput;
lastError = 0;
}
/* SetControllerDirection(...)*************************************************
* The PID will either be connected to a DIRECT acting process (+Output leads
* to +Input) or a REVERSE acting process(+Output leads to -Input.) we need to
* know which one, because otherwise we may increase the output when we should
* be decreasing. This is called from the constructor.
******************************************************************************/
void integerPID_ideal::SetControllerDirection(byte Direction)
{
if(Direction != controllerDirection)
{
kp = (0 - kp);
ki = (0 - ki);
kd = (0 - kd);
}
controllerDirection = Direction;
}
/* Status Funcions*************************************************************
* Just because you set the Kp=-1 doesn't mean it actually happened. these
* functions query the internal state of the PID. they're here for display
* purposes. this are the functions the PID Front-end uses for example
******************************************************************************/
int integerPID_ideal::GetDirection(){ return controllerDirection;}
| 25,338
|
C++
|
.cpp
| 605
| 37.464463
| 207
| 0.556833
|
oelprinz-org/BlitzboxBL49sp
| 36
| 12
| 0
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,540,042
|
test_fuel_schedule_init.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202310/speeduino-202310/test/test_init/test_fuel_schedule_init.cpp
|
#include <Arduino.h>
#include <unity.h>
#include "globals.h"
#include "init.h"
#include "schedule_calcs.h"
#include "scheduledIO.h"
#include "utilities.h"
#include "../test_utils.h"
extern uint16_t req_fuel_uS;
static constexpr uint16_t reqFuel = 86; // ms * 10
static void __attribute__((noinline)) assert_fuel_channel(bool enabled, uint16_t angle, uint8_t cmdBit, int channelInjDegrees, voidVoidCallback startFunction, voidVoidCallback endFunction)
{
char msg[39];
sprintf_P(msg, PSTR("channel%" PRIu8 ".InjChannelIsEnabled. Max:%" PRIu8), cmdBit+1, maxInjOutputs);
TEST_ASSERT_TRUE_MESSAGE(!enabled || (cmdBit+1)<=maxInjOutputs, msg);
sprintf_P(msg, PSTR("channe%" PRIu8 ".InjDegrees"), cmdBit+1);
TEST_ASSERT_EQUAL_MESSAGE(angle, channelInjDegrees, msg);
sprintf_P(msg, PSTR("inj%" PRIu8 ".StartFunction"), cmdBit+1);
TEST_ASSERT_TRUE_MESSAGE(!enabled || (startFunction!=nullCallback), msg);
sprintf_P(msg, PSTR("inj%" PRIu8 ".EndFunction"), cmdBit+1);
TEST_ASSERT_TRUE_MESSAGE(!enabled || (endFunction!=nullCallback), msg);
}
static void __attribute__((noinline)) assert_fuel_schedules(uint16_t crankAngle, uint16_t reqFuel, const bool enabled[], const uint16_t angle[])
{
char msg[32];
strcpy_P(msg, PSTR("CRANK_ANGLE_MAX_INJ"));
TEST_ASSERT_EQUAL_INT16_MESSAGE(crankAngle, CRANK_ANGLE_MAX_INJ, msg);
strcpy_P(msg, PSTR("req_fuel_uS"));
TEST_ASSERT_EQUAL_UINT16_MESSAGE(reqFuel, req_fuel_uS, msg);
assert_fuel_channel(enabled[0], angle[0], INJ1_CMD_BIT, channel1InjDegrees, inj1StartFunction, inj1EndFunction);
assert_fuel_channel(enabled[1], angle[1], INJ2_CMD_BIT, channel2InjDegrees, inj2StartFunction, inj2EndFunction);
assert_fuel_channel(enabled[2], angle[2], INJ3_CMD_BIT, channel3InjDegrees, inj3StartFunction, inj3EndFunction);
assert_fuel_channel(enabled[3], angle[3], INJ4_CMD_BIT, channel4InjDegrees, inj4StartFunction, inj4EndFunction);
#if INJ_CHANNELS>=5
assert_fuel_channel(enabled[4], angle[4], INJ5_CMD_BIT, channel5InjDegrees, inj5StartFunction, inj5EndFunction);
#endif
#if INJ_CHANNELS>=6
assert_fuel_channel(enabled[5], angle[5], INJ6_CMD_BIT, channel6InjDegrees, inj6StartFunction, inj6EndFunction);
#endif
#if INJ_CHANNELS>=7
assert_fuel_channel(enabled[6], angle[6], INJ7_CMD_BIT, channel7InjDegrees, inj7StartFunction, inj7EndFunction);
#endif
#if INJ_CHANNELS>=8
assert_fuel_channel(enabled[7], angle[7], INJ8_CMD_BIT, channel8InjDegrees, inj8StartFunction, inj8EndFunction);
#endif
}
static void cylinder1_stroke4_seq_nostage(void)
{
configPage2.injLayout = INJ_SEQUENTIAL;
configPage2.injTiming = true;
configPage10.stagingEnabled = false;
initialiseAll(); //Run the main initialise function
const bool enabled[] = {true, false, false, false, false, false, false, false};
const uint16_t angle[] = {0,0,0,0,0,0,0,0};
assert_fuel_schedules(720U, reqFuel * 100U, enabled, angle);
}
static void cylinder1_stroke4_semiseq_nostage(void)
{
configPage2.injLayout = INJ_SEMISEQUENTIAL;
configPage2.injTiming = true;
configPage10.stagingEnabled = false;
initialiseAll(); //Run the main initialise function
const bool enabled[] = {true, false, false, false, false, false, false, false};
const uint16_t angle[] = {0,0,0,0,0,0,0,0};
assert_fuel_schedules(720U, reqFuel * 50U, enabled, angle);
}
static void cylinder1_stroke4_seq_staged(void)
{
configPage2.injLayout = INJ_SEQUENTIAL;
configPage2.injTiming = true;
configPage10.stagingEnabled = true;
initialiseAll(); //Run the main initialise function
const bool enabled[] = {true, true, false, false, false, false, false, false};
const uint16_t angle[] = {0,0,0,0,0,0,0,0};
assert_fuel_schedules(720U, reqFuel * 100U, enabled, angle);
}
static void cylinder1_stroke4_semiseq_staged(void)
{
configPage2.injLayout = INJ_SEMISEQUENTIAL;
configPage2.injTiming = true;
configPage10.stagingEnabled = true;
initialiseAll(); //Run the main initialise function
const bool enabled[] = {true, true, false, false, false, false, false, false};
const uint16_t angle[] = {0,0,0,0,0,0,0,0};
assert_fuel_schedules(720U, reqFuel * 50U, enabled, angle);
}
static void run_1_cylinder_4stroke_tests(void)
{
configPage2.nCylinders = 1;
configPage2.strokes = FOUR_STROKE;
configPage2.engineType = EVEN_FIRE;
configPage2.reqFuel = reqFuel;
configPage2.divider = 1;
RUN_TEST_P(cylinder1_stroke4_seq_nostage);
RUN_TEST_P(cylinder1_stroke4_semiseq_nostage);
RUN_TEST_P(cylinder1_stroke4_seq_staged);
RUN_TEST_P(cylinder1_stroke4_semiseq_staged);
}
static void cylinder1_stroke2_seq_nostage(void)
{
configPage2.injLayout = INJ_SEQUENTIAL;
configPage2.injTiming = true;
configPage10.stagingEnabled = false;
initialiseAll(); //Run the main initialise function
const bool enabled[] = {true, false, false, false, false, false, false, false};
const uint16_t angle[] = {0,0,0,0,0,0,0,0};
assert_fuel_schedules(360U, reqFuel * 100U, enabled, angle);
}
static void cylinder1_stroke2_semiseq_nostage(void)
{
configPage2.injLayout = INJ_SEMISEQUENTIAL;
configPage2.injTiming = true;
configPage10.stagingEnabled = false;
initialiseAll(); //Run the main initialise function
const bool enabled[] = {true, false, false, false, false, false, false, false};
const uint16_t angle[] = {0,0,0,0,0,0,0,0};
assert_fuel_schedules(360U, reqFuel * 100U, enabled, angle);
}
static void cylinder1_stroke2_seq_staged(void)
{
configPage2.injLayout = INJ_SEQUENTIAL;
configPage2.injTiming = true;
configPage10.stagingEnabled = true;
initialiseAll(); //Run the main initialise function
const bool enabled[] = {true, true, false, false, false, false, false, false};
const uint16_t angle[] = {0,0,0,0,0,0,0,0};
assert_fuel_schedules(360U, reqFuel * 100U, enabled, angle);
}
static void cylinder1_stroke2_semiseq_staged(void)
{
configPage2.injLayout = INJ_SEMISEQUENTIAL;
configPage2.injTiming = true;
configPage10.stagingEnabled = true;
initialiseAll(); //Run the main initialise function
const bool enabled[] = {true, true, false, false, false, false, false, false};
const uint16_t angle[] = {0,0,0,0,0,0,0,0};
assert_fuel_schedules(360U, reqFuel * 100U, enabled, angle);
}
static void run_1_cylinder_2stroke_tests(void)
{
configPage2.nCylinders = 1;
configPage2.strokes = TWO_STROKE;
configPage2.engineType = EVEN_FIRE;
configPage2.reqFuel = reqFuel;
configPage2.divider = 1;
RUN_TEST_P(cylinder1_stroke2_seq_nostage);
RUN_TEST_P(cylinder1_stroke2_semiseq_nostage);
RUN_TEST_P(cylinder1_stroke2_seq_staged);
RUN_TEST_P(cylinder1_stroke2_semiseq_staged);
}
static void cylinder2_stroke4_seq_nostage(void)
{
configPage2.injLayout = INJ_SEQUENTIAL;
configPage2.injTiming = true;
configPage10.stagingEnabled = false;
initialiseAll(); //Run the main initialise function
const bool enabled[] = {true, true, false, false, false, false, false, false};
const uint16_t angle[] = {0,180,0,0,0,0,0,0};
assert_fuel_schedules(720U, reqFuel * 100U, enabled, angle);
}
static void cylinder2_stroke4_semiseq_nostage(void)
{
configPage2.injLayout = INJ_SEMISEQUENTIAL;
configPage2.injTiming = true;
configPage10.stagingEnabled = false;
initialiseAll(); //Run the main initialise function
const bool enabled[] = {true, true, false, false, false, false, false, false};
const uint16_t angle[] = {0,180,0,0,0,0,0,0};
assert_fuel_schedules(360U, reqFuel * 50U, enabled, angle);
}
static void cylinder2_stroke4_seq_staged(void)
{
configPage2.injLayout = INJ_SEQUENTIAL;
configPage2.injTiming = true;
configPage10.stagingEnabled = true;
initialiseAll(); //Run the main initialise function
const bool enabled[] = {true, true, true, true, false, false, false, false};
const uint16_t angle[] = {0,180,0,180,0,0,0,0};
assert_fuel_schedules(720U, reqFuel * 100U, enabled, angle);
}
static void cylinder2_stroke4_semiseq_staged(void)
{
configPage2.injLayout = INJ_SEMISEQUENTIAL;
configPage2.injTiming = true;
configPage10.stagingEnabled = true;
initialiseAll(); //Run the main initialise function
const bool enabled[] = {true, true, true, true, false, false, false, false};
const uint16_t angle[] = {0,180,0,180,0,0,0,0};
assert_fuel_schedules(360U, reqFuel * 50U, enabled, angle);
}
static void run_2_cylinder_4stroke_tests(void)
{
configPage2.nCylinders = 2;
configPage2.strokes = FOUR_STROKE;
configPage2.engineType = EVEN_FIRE;
configPage2.reqFuel = reqFuel;
configPage2.divider = 1;
RUN_TEST_P(cylinder2_stroke4_seq_nostage);
RUN_TEST_P(cylinder2_stroke4_semiseq_nostage);
RUN_TEST_P(cylinder2_stroke4_seq_staged);
RUN_TEST_P(cylinder2_stroke4_semiseq_staged);
}
static void cylinder2_stroke2_seq_nostage(void)
{
configPage2.injLayout = INJ_SEQUENTIAL;
configPage2.injTiming = true;
configPage10.stagingEnabled = false;
initialiseAll(); //Run the main initialise function
const bool enabled[] = {true, true, false, false, false, false, false, false};
const uint16_t angle[] = {0,180,0,0,0,0,0,0};
assert_fuel_schedules(180U, reqFuel * 100U, enabled, angle);
}
static void cylinder2_stroke2_semiseq_nostage(void)
{
configPage2.injLayout = INJ_SEMISEQUENTIAL;
configPage2.injTiming = true;
configPage10.stagingEnabled = false;
initialiseAll(); //Run the main initialise function
const bool enabled[] = {true, true, false, false, false, false, false, false};
const uint16_t angle[] = {0,180,0,0,0,0,0,0};
assert_fuel_schedules(180U, reqFuel * 100U, enabled, angle);
}
static void cylinder2_stroke2_seq_staged(void)
{
configPage2.injLayout = INJ_SEQUENTIAL;
configPage2.injTiming = true;
configPage10.stagingEnabled = true;
initialiseAll(); //Run the main initialise function
const bool enabled[] = {true, true, true, true, false, false, false, false};
const uint16_t angle[] = {0,180,0,180,0,0,0,0};
assert_fuel_schedules(180U, reqFuel * 100U, enabled, angle);
}
static void cylinder2_stroke2_semiseq_staged(void)
{
configPage2.injLayout = INJ_SEMISEQUENTIAL;
configPage2.injTiming = true;
configPage10.stagingEnabled = true;
initialiseAll(); //Run the main initialise function
const bool enabled[] = {true, true, true, true, false, false, false, false};
const uint16_t angle[] = {0,180,0,180,0,0,0,0};
assert_fuel_schedules(180U, reqFuel * 100U, enabled, angle);
}
static void run_2_cylinder_2stroke_tests(void)
{
configPage2.nCylinders = 2;
configPage2.strokes = TWO_STROKE;
configPage2.engineType = EVEN_FIRE;
configPage2.reqFuel = reqFuel;
configPage2.divider = 1;
RUN_TEST_P(cylinder2_stroke2_seq_nostage);
RUN_TEST_P(cylinder2_stroke2_semiseq_nostage);
RUN_TEST_P(cylinder2_stroke2_seq_staged);
RUN_TEST_P(cylinder2_stroke2_semiseq_staged);
}
static void cylinder3_stroke4_seq_nostage(void)
{
configPage2.injLayout = INJ_SEQUENTIAL;
configPage2.injTiming = true;
configPage10.stagingEnabled = false;
initialiseAll(); //Run the main initialise function
const bool enabled[] = {true, true, true, false, false, false, false, false};
const uint16_t angle[] = {0,240,480,0,0,0,0,0};
assert_fuel_schedules(720U, reqFuel * 100U, enabled, angle);
}
static void cylinder3_stroke4_semiseq_nostage(void)
{
configPage2.injLayout = INJ_SEMISEQUENTIAL;
configPage2.injTiming = true;
configPage10.stagingEnabled = false;
initialiseAll(); //Run the main initialise function
const bool enabled[] = {true, true, true, false, false, false, false, false};
const uint16_t angle[] = {0,80,160,0,0,0,0,0};
//assert_fuel_schedules(240U, reqFuel * 50U, enabled, angle);
assert_fuel_schedules(720U, reqFuel * 50U, enabled, angle); //Special case as 3 squirts per cycle MUST be over 720 degrees
}
static void cylinder3_stroke4_seq_staged(void)
{
configPage2.injLayout = INJ_SEQUENTIAL;
configPage2.injTiming = true;
configPage10.stagingEnabled = true;
initialiseAll(); //Run the main initialise function
#if INJ_CHANNELS>=6
const bool enabled[] = {true, true, true, true, true, true, false, false};
const uint16_t angle[] = {0,240,480,0,240,480,0,0};
assert_fuel_schedules(720U, reqFuel * 100U, enabled, angle);
#else
const bool enabled[] = {true, true, true, true, false, false, false, false};
const uint16_t angle[] = {0,240,480,0,0,0,0,0};
assert_fuel_schedules(720U, reqFuel * 100U, enabled, angle);
#endif
}
static void cylinder3_stroke4_semiseq_staged(void)
{
configPage2.injLayout = INJ_SEMISEQUENTIAL;
configPage10.stagingEnabled = true;
initialiseAll(); //Run the main initialise function
#if INJ_CHANNELS>=6
const bool enabled[] = {true, true, true, true, true, true, false, false};
const uint16_t angle[] = {0,80,160,0,80,160,0,0};
assert_fuel_schedules(240U, reqFuel * 50U, enabled, angle);
#else
const bool enabled[] = {true, true, true, true, false, false, false, false};
const uint16_t angle[] = {0,80,160,0,0,0,0,0};
//assert_fuel_schedules(240U, reqFuel * 50U, enabled, angle);
assert_fuel_schedules(720U, reqFuel * 50U, enabled, angle); //Special case as 3 squirts per cycle MUST be over 720 degrees
#endif
}
static void run_3_cylinder_4stroke_tests(void)
{
configPage2.nCylinders = 3;
configPage2.strokes = FOUR_STROKE;
configPage2.engineType = EVEN_FIRE;
configPage2.reqFuel = reqFuel;
configPage2.divider = 1; //3 squirts per cycle for a 3 cylinder
RUN_TEST_P(cylinder3_stroke4_seq_nostage);
RUN_TEST_P(cylinder3_stroke4_semiseq_nostage);
RUN_TEST_P(cylinder3_stroke4_seq_staged);
RUN_TEST_P(cylinder3_stroke4_semiseq_staged);
}
static void cylinder3_stroke2_seq_nostage(void)
{
configPage2.injLayout = INJ_SEQUENTIAL;
configPage10.stagingEnabled = false;
initialiseAll(); //Run the main initialise function
const bool enabled[] = {true, true, true, false, false, false, false, false};
const uint16_t angle[] = {0,120,240,0,0,0,0,0};
assert_fuel_schedules(360U, reqFuel * 100U, enabled, angle);
}
static void cylinder3_stroke2_semiseq_nostage(void)
{
configPage2.injLayout = INJ_SEMISEQUENTIAL;
configPage10.stagingEnabled = false;
initialiseAll(); //Run the main initialise function
const bool enabled[] = {true, true, true, false, false, false, false, false};
const uint16_t angle[] = {0,80,160,0,0,0,0,0};
assert_fuel_schedules(120U, reqFuel * 100U, enabled, angle);
}
static void cylinder3_stroke2_seq_staged(void)
{
configPage2.injLayout = INJ_SEQUENTIAL;
configPage10.stagingEnabled = true;
initialiseAll(); //Run the main initialise function
#if INJ_CHANNELS>=6
const bool enabled[] = {true, true, true, true, true, true, false, false};
const uint16_t angle[] = {0,120,240,0,120,240,0,0};
assert_fuel_schedules(360U, reqFuel * 100U, enabled, angle);
#else
const bool enabled[] = {true, true, true, true, false, false, false, false};
const uint16_t angle[] = {0,120,240,0,0,0,0,0};
assert_fuel_schedules(360U, reqFuel * 100U, enabled, angle);
#endif
}
static void cylinder3_stroke2_semiseq_staged(void)
{
configPage2.injLayout = INJ_SEMISEQUENTIAL;
configPage10.stagingEnabled = true;
initialiseAll(); //Run the main initialise function
#if INJ_CHANNELS>=6
const bool enabled[] = {true, true, true, true, true, true, false, false};
const uint16_t angle[] = {0,80,160,0,80,160,0,0};
assert_fuel_schedules(120U, reqFuel * 100U, enabled, angle);
#else
const bool enabled[] = {true, true, true, true, false, false, false, false};
const uint16_t angle[] = {0,80,160,0,0,0,0,0};
assert_fuel_schedules(120U, reqFuel * 100U, enabled, angle);
#endif
}
static void run_3_cylinder_2stroke_tests(void)
{
configPage2.nCylinders = 3;
configPage2.strokes = TWO_STROKE;
configPage2.engineType = EVEN_FIRE;
configPage2.injTiming = true;
configPage2.reqFuel = reqFuel;
configPage2.divider = 1;
RUN_TEST_P(cylinder3_stroke2_seq_nostage);
RUN_TEST_P(cylinder3_stroke2_semiseq_nostage);
RUN_TEST_P(cylinder3_stroke2_seq_staged);
RUN_TEST_P(cylinder3_stroke2_semiseq_staged);
}
static void cylinder4_stroke4_seq_nostage(void)
{
configPage2.injLayout = INJ_SEQUENTIAL;
configPage10.stagingEnabled = false;
initialiseAll(); //Run the main initialise function
const bool enabled[] = {true, true, true, true, false, false, false, false};
const uint16_t angle[] = {0,180,360,540,0,0,0,0};
assert_fuel_schedules(720U, reqFuel * 100U, enabled, angle);
}
static void cylinder4_stroke4_semiseq_nostage(void)
{
configPage2.injLayout = INJ_SEMISEQUENTIAL;
configPage10.stagingEnabled = false;
initialiseAll(); //Run the main initialise function
const bool enabled[] = {true, true, false, false, false, false, false, false};
const uint16_t angle[] = {0,180,0,0,0,0,0,0};
assert_fuel_schedules(360U, reqFuel * 50U, enabled, angle);
}
static void cylinder4_stroke4_seq_staged(void)
{
configPage2.injLayout = INJ_SEQUENTIAL;
configPage10.stagingEnabled = true;
initialiseAll(); //Run the main initialise function
#if INJ_CHANNELS>=8
const bool enabled[] = {true, true, true, true, true, true, true, true};
const uint16_t angle[] = {0,180,360,540,0,180,36};
assert_fuel_schedules(720U, reqFuel * 100U, enabled, angle);
#elif INJ_CHANNELS >= 5
const bool enabled[] = {true, true, true, true, true, false, false, false};
const uint16_t angle[] = {0,180,360,540,0,0,0,0};
assert_fuel_schedules(720U, reqFuel * 100U, enabled, angle);
#else
const bool enabled[] = {true, true, true, true, false, false, false, false};
const uint16_t angle[] = {0,180,360,540,0,0,0,0};
assert_fuel_schedules(720U, reqFuel * 100U, enabled, angle);
#endif
}
static void cylinder4_stroke4_semiseq_staged(void)
{
configPage2.injLayout = INJ_PAIRED;
configPage10.stagingEnabled = true;
initialiseAll(); //Run the main initialise function
const bool enabled[] = {true, true, true, true, false, false, false, false};
const uint16_t angle[] = {0,180,0,180,0,0,0,0};
assert_fuel_schedules(360U, reqFuel * 50U, enabled, angle);
}
void run_4_cylinder_4stroke_tests(void)
{
configPage2.nCylinders = 4;
configPage2.strokes = FOUR_STROKE;
configPage2.engineType = EVEN_FIRE;
configPage2.injTiming = true;
configPage2.reqFuel = reqFuel;
configPage2.divider = 2;
RUN_TEST_P(cylinder4_stroke4_seq_nostage);
RUN_TEST_P(cylinder4_stroke4_semiseq_nostage);
RUN_TEST_P(cylinder4_stroke4_seq_staged);
RUN_TEST_P(cylinder4_stroke4_semiseq_staged);
}
static void cylinder4_stroke2_seq_nostage(void)
{
configPage2.injLayout = INJ_SEQUENTIAL;
configPage10.stagingEnabled = false;
initialiseAll(); //Run the main initialise function
const bool enabled[] = {true, true, false, false, false, false, false, false};
const uint16_t angle[] = {0,180,0,0,0,0,0,0};
assert_fuel_schedules(180U, reqFuel * 100U, enabled, angle);
}
static void cylinder4_stroke2_semiseq_nostage(void)
{
configPage2.injLayout = INJ_SEMISEQUENTIAL;
configPage10.stagingEnabled = false;
initialiseAll(); //Run the main initialise function
const bool enabled[] = {true, true, false, false, false, false, false, false};
const uint16_t angle[] = {0,180,0,0,0,0,0,0};
assert_fuel_schedules(180U, reqFuel * 100U, enabled, angle);
}
static void cylinder4_stroke2_seq_staged(void)
{
configPage2.injLayout = INJ_SEQUENTIAL;
configPage10.stagingEnabled = true;
initialiseAll(); //Run the main initialise function
#if INJ_CHANNELS>=8
const bool enabled[] = {true, true, true, true, true, true, true, true};
const uint16_t angle[] = {0,180,0,0,0,180,0,0};
assert_fuel_schedules(180U, reqFuel * 100U, enabled, angle);
#elif INJ_CHANNELS >= 5
const bool enabled[] = {true, true, true, true, true, false, false, false};
const uint16_t angle[] = {0,180,0,0,0,0,0,0};
assert_fuel_schedules(180U, reqFuel * 100U, enabled, angle);
#else
const bool enabled[] = {true, true, true, true, false, false, false, false};
const uint16_t angle[] = {0,180,0,0,0,0,0,0};
assert_fuel_schedules(180U, reqFuel * 100U, enabled, angle);
#endif
}
static void cylinder4_stroke2_semiseq_staged(void)
{
configPage2.injLayout = INJ_PAIRED;
configPage10.stagingEnabled = true;
initialiseAll(); //Run the main initialise function
const bool enabled[] = {true, true, true, true, false, false, false, false};
const uint16_t angle[] = {0,180,0,180,0,0,0,0};
assert_fuel_schedules(180U, reqFuel * 100U, enabled, angle);
}
void run_4_cylinder_2stroke_tests(void)
{
configPage2.nCylinders = 4;
configPage2.strokes = TWO_STROKE;
configPage2.engineType = EVEN_FIRE;
configPage2.injTiming = true;
configPage2.reqFuel = reqFuel;
configPage2.divider = 2;
RUN_TEST_P(cylinder4_stroke2_seq_nostage);
RUN_TEST_P(cylinder4_stroke2_semiseq_nostage);
RUN_TEST_P(cylinder4_stroke2_seq_staged);
RUN_TEST_P(cylinder4_stroke2_semiseq_staged);
}
static void cylinder5_stroke4_seq_nostage(void)
{
configPage2.injLayout = INJ_SEQUENTIAL;
configPage10.stagingEnabled = false;
initialiseAll(); //Run the main initialise function
#if INJ_CHANNELS >= 5
const bool enabled[] = {true, true, true, true, true, false, false, false};
const uint16_t angle[] = {0,144,288,432,576,0,0,0};
assert_fuel_schedules(720U, reqFuel * 100U, enabled, angle);
#else
const bool enabled[] = {true, true, true, true, false, false, false, false};
const uint16_t angle[] = {0,0,0,0,0,0,0,0};
assert_fuel_schedules(720U, reqFuel * 50U, enabled, angle);
#endif
}
static void cylinder5_stroke4_semiseq_nostage(void)
{
configPage2.injLayout = INJ_SEMISEQUENTIAL;
configPage10.stagingEnabled = false;
initialiseAll(); //Run the main initialise function
const bool enabled[] = {true, true, true, true, false, false, false, false};
const uint16_t angle[] = {0,72,144,216,288,0,0,0};
assert_fuel_schedules(720U, reqFuel * 50U, enabled, angle);
}
static void cylinder5_stroke4_seq_staged(void)
{
configPage2.injLayout = INJ_SEQUENTIAL;
configPage10.stagingEnabled = true;
initialiseAll(); //Run the main initialise function
#if INJ_CHANNELS >= 6
const bool enabled[] = {true, true, true, true, true, true, false, false};
const uint16_t angle[] = {0,144,288,432,576,0,0,0};
assert_fuel_schedules(720U, reqFuel * 100U, enabled, angle);
#else
const bool enabled[] = {true, true, true, true, false, false, false, false};
const uint16_t angle[] = {0,0,0,0,0,0,0,0};
assert_fuel_schedules(720U, reqFuel * 50U, enabled, angle);
#endif
}
static void cylinder5_stroke4_semiseq_staged(void)
{
configPage2.injLayout = INJ_PAIRED;
configPage10.stagingEnabled = true;
initialiseAll(); //Run the main initialise function
#if INJ_CHANNELS >= 5
const bool enabled[] = {true, true, true, true, true, false, false, false};
const uint16_t angle[] = {0,72,144,216,288,0,0,0};
assert_fuel_schedules(720U, reqFuel * 50U, enabled, angle);
#else
const bool enabled[] = {true, true, true, true, false, false, false, false};
const uint16_t angle[] = {0,72,144,216,288,0,0,0};
assert_fuel_schedules(720U, reqFuel * 50U, enabled, angle);
#endif
}
void run_5_cylinder_4stroke_tests(void)
{
configPage2.nCylinders = 5;
configPage2.strokes = FOUR_STROKE;
configPage2.engineType = EVEN_FIRE;
configPage2.injTiming = true;
configPage2.reqFuel = reqFuel;
configPage2.divider = 5;
RUN_TEST_P(cylinder5_stroke4_seq_nostage);
RUN_TEST_P(cylinder5_stroke4_semiseq_nostage);
RUN_TEST_P(cylinder5_stroke4_seq_staged);
RUN_TEST_P(cylinder5_stroke4_semiseq_staged);
}
static void cylinder6_stroke4_seq_nostage(void)
{
configPage2.injLayout = INJ_SEQUENTIAL;
configPage10.stagingEnabled = false;
initialiseAll(); //Run the main initialise function
#if INJ_CHANNELS >= 6
const bool enabled[] = {true, true, true, true, true, true, false, false};
const uint16_t angle[] = {0,120,240,360,480,600,0};
assert_fuel_schedules(720U, reqFuel * 100U, enabled, angle);
#else
const bool enabled[] = {true, true, true, false, false, false, false, false};
const uint16_t angle[] = {0,0,0,0,0,0,0,0};
assert_fuel_schedules(720U, reqFuel * 50U, enabled, angle);
#endif
}
static void cylinder6_stroke4_semiseq_nostage(void)
{
configPage2.injLayout = INJ_SEMISEQUENTIAL;
configPage10.stagingEnabled = false;
initialiseAll(); //Run the main initialise function
const bool enabled[] = {true, true, true, false, false, false, false, false};
const uint16_t angle[] = {0,120,240,0,0,0,0,0};
assert_fuel_schedules(720U, reqFuel * 50U, enabled, angle);
}
static void cylinder6_stroke4_seq_staged(void)
{
configPage2.injLayout = INJ_SEQUENTIAL;
configPage10.stagingEnabled = true;
initialiseAll(); //Run the main initialise function
#if INJ_CHANNELS >= 8
const bool enabled[] = {true, true, true, true, true, true, false, false};
const uint16_t angle[] = {0,120,240,360,480,600,0,0};
assert_fuel_schedules(720U, reqFuel * 100U, enabled, angle);
#else
const bool enabled[] = {true, true, true, false, false, false, false, false};
const uint16_t angle[] = {0,0,0,0,0,0,0,0};
assert_fuel_schedules(720U, reqFuel * 50U, enabled, angle);
#endif
}
static void cylinder6_stroke4_semiseq_staged(void)
{
configPage2.injLayout = INJ_SEMISEQUENTIAL;
configPage10.stagingEnabled = true;
initialiseAll(); //Run the main initialise function
#if INJ_CHANNELS >= 8
const bool enabled[] = {true, true, true, true, true, true, true, true};
const uint16_t angle[] = {0,120,240,0,0,120,240,0};
assert_fuel_schedules(720U, reqFuel * 50U, enabled, angle);
#else
const bool enabled[] = {true, true, true, false, false, false, false, false};
const uint16_t angle[] = {0,120,240,0,0,0,0,0};
assert_fuel_schedules(720U, reqFuel * 50U, enabled, angle);
#endif
}
void run_6_cylinder_4stroke_tests(void)
{
configPage2.nCylinders = 6;
configPage2.strokes = FOUR_STROKE;
configPage2.engineType = EVEN_FIRE;
configPage2.injTiming = true;
configPage2.reqFuel = reqFuel;
configPage2.divider = 6;
RUN_TEST_P(cylinder6_stroke4_seq_nostage);
RUN_TEST_P(cylinder6_stroke4_semiseq_nostage);
RUN_TEST_P(cylinder6_stroke4_seq_staged);
RUN_TEST_P(cylinder6_stroke4_semiseq_staged);
}
static void cylinder8_stroke4_seq_nostage(void)
{
configPage2.injLayout = INJ_SEQUENTIAL;
configPage10.stagingEnabled = false;
initialiseAll(); //Run the main initialise function
#if INJ_CHANNELS >= 8
const bool enabled[] = {true, true, true, true, true, true, true, true};
const uint16_t angle[] = {0,90,180,270,360,450,5};
assert_fuel_schedules(720U, reqFuel * 100U, enabled, angle);
#else
const bool enabled[] = {true, true, true, true, false, false, false, false};
const uint16_t angle[] = {0,0,0,0,0,0,0,0};
assert_fuel_schedules(720U, reqFuel * 50U, enabled, angle);
#endif
}
void run_8_cylinder_4stroke_tests(void)
{
configPage2.nCylinders = 8;
configPage2.strokes = FOUR_STROKE;
configPage2.engineType = EVEN_FIRE;
configPage2.injTiming = true;
configPage2.reqFuel = reqFuel;
configPage2.divider = 8;
// Staging not supported on 8 cylinders
RUN_TEST_P(cylinder8_stroke4_seq_nostage);
}
static constexpr uint16_t zeroAngles[] = {0,0,0,0,0,0,0,0};
static void cylinder_1_NoinjTiming_paired(void) {
configPage2.injLayout = INJ_PAIRED;
configPage2.nCylinders = 1;
configPage2.divider = 1;
initialiseAll(); //Run the main initialise function
const bool enabled[] = {true, false, false, false, false, false, false, false};
assert_fuel_schedules(720U, reqFuel * 50U, enabled, zeroAngles);
}
static void cylinder_2_NoinjTiming_paired(void) {
configPage2.injLayout = INJ_PAIRED;
configPage2.nCylinders = 2;
configPage2.divider = 2;
initialiseAll(); //Run the main initialise function
const bool enabled[] = {true, true, false, false, false, false, false, false};
assert_fuel_schedules(720U, reqFuel * 50U, enabled, zeroAngles);
}
static void cylinder_3_NoinjTiming_paired(void) {
configPage2.injLayout = INJ_PAIRED;
configPage2.nCylinders = 3;
configPage2.divider = 3;
initialiseAll(); //Run the main initialise function
const bool enabled[] = {true, true, true, false, false, false, false, false};
assert_fuel_schedules(720U, reqFuel * 50U, enabled, zeroAngles);
}
static void cylinder_4_NoinjTiming_paired(void) {
configPage2.injLayout = INJ_PAIRED;
configPage2.nCylinders = 4;
configPage2.divider = 4;
initialiseAll(); //Run the main initialise function
const bool enabled[] = {true, true, false, false, false, false, false, false};
assert_fuel_schedules(720U, reqFuel * 50U, enabled, zeroAngles);
}
static void cylinder_5_NoinjTiming_paired(void) {
configPage2.injLayout = INJ_PAIRED;
configPage2.nCylinders = 5;
configPage2.divider = 5;
initialiseAll(); //Run the main initialise function
#if INJ_CHANNELS>=5
const bool enabled[] = {true, true, true, true, true, false, false, false};
#else
const bool enabled[] = {true, true, true, true, false, false, false, false};
#endif
assert_fuel_schedules(720U, reqFuel * 50U, enabled, zeroAngles);
}
static void cylinder_6_NoinjTiming_paired(void) {
configPage2.injLayout = INJ_PAIRED;
configPage2.nCylinders = 6;
configPage2.divider = 6;
initialiseAll(); //Run the main initialise function
const bool enabled[] = {true, true, true, false, false, false, false, false};
assert_fuel_schedules(720U, reqFuel * 50U, enabled, zeroAngles);
}
static void cylinder_8_NoinjTiming_paired(void) {
configPage2.injLayout = INJ_PAIRED;
configPage2.nCylinders = 8;
configPage2.divider = 8;
initialiseAll(); //Run the main initialise function
#if INJ_CHANNELS>=8
const bool enabled[] = {true, true, true, true, true, true, true, true};
#else
const bool enabled[] = {true, true, true, true, false, false, false, false};
#endif
assert_fuel_schedules(720U, reqFuel * 50U, enabled, zeroAngles);
}
static void run_no_inj_timing_tests(void)
{
configPage2.strokes = FOUR_STROKE;
configPage2.engineType = EVEN_FIRE;
configPage2.injTiming = false;
configPage2.reqFuel = reqFuel;
configPage10.stagingEnabled = false;
RUN_TEST_P(cylinder_1_NoinjTiming_paired);
RUN_TEST_P(cylinder_2_NoinjTiming_paired);
RUN_TEST_P(cylinder_3_NoinjTiming_paired);
RUN_TEST_P(cylinder_4_NoinjTiming_paired);
RUN_TEST_P(cylinder_5_NoinjTiming_paired);
RUN_TEST_P(cylinder_6_NoinjTiming_paired);
RUN_TEST_P(cylinder_8_NoinjTiming_paired);
}
static void cylinder_2_oddfire(void)
{
configPage2.injLayout = INJ_PAIRED;
configPage2.nCylinders = 2;
configPage2.divider = 2;
initialiseAll(); //Run the main initialise function
const bool enabled[] = {true, true, false, false, false, false, false, false};
const uint16_t angle[] = {0,13,0,0,0,0,0,0};
Serial.println(configPage2.engineType);
assert_fuel_schedules(720U, reqFuel * 50U, enabled, angle);
}
static void run_oddfire_tests()
{
configPage2.strokes = FOUR_STROKE;
configPage2.engineType = ODD_FIRE;
configPage2.injTiming = true;
configPage2.reqFuel = reqFuel;
configPage10.stagingEnabled = false;
configPage2.oddfire2 = 13;
configPage2.oddfire3 = 111;
configPage2.oddfire4 = 217;
// Oddfire only affects 2 cylinder configurations
configPage2.nCylinders = 1;
configPage2.divider = 1;
RUN_TEST_P(cylinder1_stroke4_seq_nostage);
RUN_TEST_P(cylinder_2_oddfire);
configPage2.nCylinders = 3;
configPage2.divider = 1;
RUN_TEST_P(cylinder3_stroke4_seq_nostage);
configPage2.nCylinders = 4;
configPage2.divider = 2;
RUN_TEST_P(cylinder4_stroke4_seq_nostage);
configPage2.nCylinders = 5;
configPage2.divider = 5;
RUN_TEST_P(cylinder5_stroke4_seq_nostage);
configPage2.nCylinders = 6;
configPage2.divider = 6;
RUN_TEST_P(cylinder6_stroke4_seq_nostage);
configPage2.nCylinders = 8;
configPage2.divider = 8;
RUN_TEST_P(cylinder8_stroke4_seq_nostage);
}
void testFuelScheduleInit()
{
run_1_cylinder_4stroke_tests();
run_1_cylinder_2stroke_tests();
run_2_cylinder_4stroke_tests();
run_2_cylinder_2stroke_tests();
run_3_cylinder_4stroke_tests();
run_3_cylinder_2stroke_tests();
run_4_cylinder_4stroke_tests();
run_4_cylinder_2stroke_tests();
run_5_cylinder_4stroke_tests();
run_6_cylinder_4stroke_tests();
run_8_cylinder_4stroke_tests();
run_no_inj_timing_tests();
run_oddfire_tests();
}
| 32,029
|
C++
|
.cpp
| 796
| 37.780151
| 188
| 0.7413
|
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,043
|
ForsdST170.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202310/speeduino-202310/test/test_decoders/FordST170/ForsdST170.cpp
|
#include <decoders.h>
#include <globals.h>
#include <unity.h>
#include "FordST170.h"
#include "scheduler.h"
#include "schedule_calcs.h"
extern uint16_t ignition1EndTooth;
extern uint16_t ignition2EndTooth;
extern uint16_t ignition3EndTooth;
extern uint16_t ignition4EndTooth;
void test_fordst170_newIgn_12_trig0_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 12/1
//Advance: 10
//triggerAngle=0
triggerSetup_FordST170();
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = 0; //No trigger offset
calculateIgnitionAngle(5, 0, 10, &ignition1EndAngle, &ignition1StartAngle);
triggerSetEndTeeth_FordST170();
TEST_ASSERT_EQUAL(34, ignition1EndTooth);
//Test again with 0 degrees advance
calculateIgnitionAngle(5, 0, 0, &ignition1EndAngle, &ignition1StartAngle);
triggerSetEndTeeth_FordST170();
TEST_ASSERT_EQUAL(35, ignition1EndTooth);
//Test again with 35 degrees advance
calculateIgnitionAngle(5, 0, 35, &ignition1EndAngle, &ignition1StartAngle);
triggerSetEndTeeth_FordST170();
TEST_ASSERT_EQUAL(31, ignition1EndTooth);
}
void test_fordst170_newIgn_12_trig90_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 12/1
//Advance: 10
//triggerAngle=90
triggerSetup_FordST170();
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = 90; //No trigger offset
calculateIgnitionAngle(5, 0, 35, &ignition1EndAngle, &ignition1StartAngle);
triggerSetEndTeeth_FordST170();
TEST_ASSERT_EQUAL(22, ignition1EndTooth);
}
void test_fordst170_newIgn_12_trig180_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=180
triggerSetup_FordST170();
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = 180; //No trigger offset
calculateIgnitionAngle(5, 0, 10, &ignition1EndAngle, &ignition1StartAngle);
triggerSetEndTeeth_FordST170();
TEST_ASSERT_EQUAL(16, ignition1EndTooth);
}
void test_fordst170_newIgn_12_trig270_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=270
triggerSetup_FordST170();
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = 270; //No trigger offset
calculateIgnitionAngle(5, 0, 10, &ignition1EndAngle, &ignition1StartAngle);
triggerSetEndTeeth_FordST170();
TEST_ASSERT_EQUAL(7, ignition1EndTooth);
}
void test_fordst170_newIgn_12_trig360_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=360
triggerSetup_FordST170();
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = 360; //No trigger offset
calculateIgnitionAngle(5, 0, 10, &ignition1EndAngle, &ignition1StartAngle);
triggerSetEndTeeth_FordST170();
TEST_ASSERT_EQUAL(34, ignition1EndTooth);
}
void test_fordst170_newIgn_12_trigNeg90_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=-90
triggerSetup_FordST170();
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = -90; //No trigger offset
calculateIgnitionAngle(5, 0, 10, &ignition1EndAngle, &ignition1StartAngle);
triggerSetEndTeeth_FordST170();
TEST_ASSERT_EQUAL(7, ignition1EndTooth);
}
void test_fordst170_newIgn_12_trigNeg180_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=-180
triggerSetup_FordST170();
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = -180; //No trigger offset
calculateIgnitionAngle(5, 0, 10, &ignition1EndAngle, &ignition1StartAngle);
triggerSetEndTeeth_FordST170();
TEST_ASSERT_EQUAL(16, ignition1EndTooth);
}
void test_fordst170_newIgn_12_trigNeg270_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=-270
triggerSetup_FordST170();
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = -270; //No trigger offset
calculateIgnitionAngle(5, 0, 10, &ignition1EndAngle, &ignition1StartAngle);
triggerSetEndTeeth_FordST170();
TEST_ASSERT_EQUAL(25, ignition1EndTooth);
}
void test_fordst170_newIgn_12_trigNeg360_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=-360
triggerSetup_FordST170();
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = -360; //No trigger offset
calculateIgnitionAngle(5, 0, 10, &ignition1EndAngle, &ignition1StartAngle);
triggerSetEndTeeth_FordST170();
TEST_ASSERT_EQUAL(34, ignition1EndTooth);
}
void testFordST170()
{
RUN_TEST(test_fordst170_newIgn_12_trig0_1);
RUN_TEST(test_fordst170_newIgn_12_trig90_1);
RUN_TEST(test_fordst170_newIgn_12_trig180_1);
RUN_TEST(test_fordst170_newIgn_12_trig270_1);
RUN_TEST(test_fordst170_newIgn_12_trig360_1);
RUN_TEST(test_fordst170_newIgn_12_trigNeg90_1);
RUN_TEST(test_fordst170_newIgn_12_trigNeg180_1);
RUN_TEST(test_fordst170_newIgn_12_trigNeg270_1);
RUN_TEST(test_fordst170_newIgn_12_trigNeg360_1);
}
| 5,271
|
C++
|
.cpp
| 147
| 31.653061
| 80
| 0.737824
|
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,044
|
Nissan360.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202310/speeduino-202310/test/test_decoders/Nissan360/Nissan360.cpp
|
#include <decoders.h>
#include <globals.h>
#include <unity.h>
#include "Nissan360.h"
#include "scheduler.h"
#include "schedule_calcs.h"
extern uint16_t ignition1EndTooth;
extern uint16_t ignition2EndTooth;
extern uint16_t ignition3EndTooth;
extern uint16_t ignition4EndTooth;
void test_nissan360_newIgn_12_trig0_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 12/1
//Advance: 10
//triggerAngle=0
triggerSetup_Nissan360();
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = 0; //No trigger offset
calculateIgnitionAngle(5, 0, 10, &ignition1EndAngle, &ignition1StartAngle);
triggerSetEndTeeth_Nissan360();
TEST_ASSERT_EQUAL(171, ignition1EndTooth);
//Test again with 0 degrees advance
calculateIgnitionAngle(5, 0, 0, &ignition1EndAngle, &ignition1StartAngle);
triggerSetEndTeeth_Nissan360();
TEST_ASSERT_EQUAL(176, ignition1EndTooth);
//Test again with 35 degrees advance
calculateIgnitionAngle(5, 0, 35, &ignition1EndAngle, &ignition1StartAngle);
triggerSetEndTeeth_Nissan360();
TEST_ASSERT_EQUAL(158, ignition1EndTooth);
}
void test_nissan360_newIgn_12_trig90_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 12/1
//Advance: 10
//triggerAngle=90
triggerSetup_Nissan360();
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = 90; //No trigger offset
calculateIgnitionAngle(5, 0, 10, &ignition1EndAngle, &ignition1StartAngle);
triggerSetEndTeeth_Nissan360();
TEST_ASSERT_EQUAL(126, ignition1EndTooth);
}
void test_nissan360_newIgn_12_trig180_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=180
triggerSetup_Nissan360();
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = 180; //No trigger offset
calculateIgnitionAngle(5, 0, 10, &ignition1EndAngle, &ignition1StartAngle);
triggerSetEndTeeth_Nissan360();
TEST_ASSERT_EQUAL(81, ignition1EndTooth);
}
void test_nissan360_newIgn_12_trig270_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=270
triggerSetup_Nissan360();
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = 270; //No trigger offset
calculateIgnitionAngle(5, 0, 10, &ignition1EndAngle, &ignition1StartAngle);
triggerSetEndTeeth_Nissan360();
TEST_ASSERT_EQUAL(36, ignition1EndTooth);
}
void test_nissan360_newIgn_12_trig360_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=360
triggerSetup_Nissan360();
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = 360; //No trigger offset
calculateIgnitionAngle(5, 0, 10, &ignition1EndAngle, &ignition1StartAngle);
triggerSetEndTeeth_Nissan360();
TEST_ASSERT_EQUAL(351, ignition1EndTooth);
}
void test_nissan360_newIgn_12_trigNeg90_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=-90
triggerSetup_Nissan360();
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = -90; //No trigger offset
calculateIgnitionAngle(5, 0, 10, &ignition1EndAngle, &ignition1StartAngle);
triggerSetEndTeeth_Nissan360();
TEST_ASSERT_EQUAL(216, ignition1EndTooth);
}
void test_nissan360_newIgn_12_trigNeg180_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=-180
triggerSetup_Nissan360();
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = -180; //No trigger offset
calculateIgnitionAngle(5, 0, 10, &ignition1EndAngle, &ignition1StartAngle);
triggerSetEndTeeth_Nissan360();
TEST_ASSERT_EQUAL(261, ignition1EndTooth);
}
void test_nissan360_newIgn_12_trigNeg270_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=-270
triggerSetup_Nissan360();
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = -270; //No trigger offset
calculateIgnitionAngle(5, 0, 10, &ignition1EndAngle, &ignition1StartAngle);
triggerSetEndTeeth_Nissan360();
TEST_ASSERT_EQUAL(306, ignition1EndTooth);
}
void test_nissan360_newIgn_12_trigNeg360_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=-360
triggerSetup_Nissan360();
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = -360; //No trigger offset
calculateIgnitionAngle(5, 0, 10, &ignition1EndAngle, &ignition1StartAngle);
triggerSetEndTeeth_Nissan360();
TEST_ASSERT_EQUAL(351, ignition1EndTooth);
}
void testNissan360()
{
RUN_TEST(test_nissan360_newIgn_12_trig0_1);
RUN_TEST(test_nissan360_newIgn_12_trig90_1);
RUN_TEST(test_nissan360_newIgn_12_trig180_1);
RUN_TEST(test_nissan360_newIgn_12_trig270_1);
RUN_TEST(test_nissan360_newIgn_12_trig360_1);
RUN_TEST(test_nissan360_newIgn_12_trigNeg90_1);
RUN_TEST(test_nissan360_newIgn_12_trigNeg180_1);
RUN_TEST(test_nissan360_newIgn_12_trigNeg270_1);
RUN_TEST(test_nissan360_newIgn_12_trigNeg360_1);
}
| 5,285
|
C++
|
.cpp
| 147
| 31.727891
| 83
| 0.736945
|
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,045
|
missing_tooth.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202310/speeduino-202310/test/test_decoders/missing_tooth/missing_tooth.cpp
|
#include <decoders.h>
#include <globals.h>
#include <unity.h>
#include "missing_tooth.h"
#include "schedule_calcs.h"
void test_setup_36_1()
{
//Setup a 36-1 wheel
configPage4.triggerTeeth = 36;
configPage4.triggerMissingTeeth = 1;
configPage4.TrigSpeed = CRANK_SPEED;
configPage4.trigPatternSec = SEC_TRIGGER_SINGLE;
triggerSetup_missingTooth();
}
void test_setup_60_2()
{
//Setup a 60-2 wheel
configPage4.triggerTeeth = 60;
configPage4.triggerMissingTeeth = 2;
configPage4.TrigSpeed = CRANK_SPEED;
configPage4.trigPatternSec = SEC_TRIGGER_SINGLE;
triggerSetup_missingTooth();
}
//************************************** Begin the new ignition setEndTooth tests **************************************
void test_missingtooth_newIgn_36_1_trig0_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=0
test_setup_36_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 0; //No trigger offset
triggerSetEndTeeth_missingTooth();
TEST_ASSERT_EQUAL(34, ignition1EndTooth);
}
void test_missingtooth_newIgn_36_1_trig90_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=90
test_setup_36_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 90; //No trigger offset
triggerSetEndTeeth_missingTooth();
TEST_ASSERT_EQUAL(25, ignition1EndTooth);
}
void test_missingtooth_newIgn_36_1_trig180_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=180
test_setup_36_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 180; //No trigger offset
triggerSetEndTeeth_missingTooth();
TEST_ASSERT_EQUAL(16, ignition1EndTooth);
}
void test_missingtooth_newIgn_36_1_trig270_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=270
test_setup_36_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 270; //No trigger offset
triggerSetEndTeeth_missingTooth();
TEST_ASSERT_EQUAL(7, ignition1EndTooth);
}
void test_missingtooth_newIgn_36_1_trig360_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=360
test_setup_36_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 360; //No trigger offset
triggerSetEndTeeth_missingTooth();
TEST_ASSERT_EQUAL(34, ignition1EndTooth);
}
void test_missingtooth_newIgn_36_1_trigNeg90_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=-90
test_setup_36_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = -90; //No trigger offset
triggerSetEndTeeth_missingTooth();
TEST_ASSERT_EQUAL(7, ignition1EndTooth);
}
void test_missingtooth_newIgn_36_1_trigNeg180_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=-180
test_setup_36_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = -180; //No trigger offset
triggerSetEndTeeth_missingTooth();
TEST_ASSERT_EQUAL(16, ignition1EndTooth);
}
void test_missingtooth_newIgn_36_1_trigNeg270_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=-270
test_setup_36_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = -270; //No trigger offset
triggerSetEndTeeth_missingTooth();
TEST_ASSERT_EQUAL(25, ignition1EndTooth);
}
void test_missingtooth_newIgn_36_1_trigNeg360_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=-360
test_setup_36_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = -360; //No trigger offset
triggerSetEndTeeth_missingTooth();
TEST_ASSERT_EQUAL(34, ignition1EndTooth);
}
// ******* CHannel 2 *******
void test_missingtooth_newIgn_36_1_trig0_2()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=0
test_setup_36_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 0; //No trigger offset
triggerSetEndTeeth_missingTooth();
TEST_ASSERT_EQUAL(16, ignition2EndTooth);
}
void test_missingtooth_newIgn_36_1_trig90_2()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=90
test_setup_36_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 90; //No trigger offset
triggerSetEndTeeth_missingTooth();
TEST_ASSERT_EQUAL(7, ignition2EndTooth);
}
void test_missingtooth_newIgn_36_1_trig180_2()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=180
test_setup_36_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 180; //No trigger offset
triggerSetEndTeeth_missingTooth();
TEST_ASSERT_EQUAL(34, ignition2EndTooth);
}
void test_missingtooth_newIgn_36_1_trig270_2()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=270
test_setup_36_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 270; //No trigger offset
triggerSetEndTeeth_missingTooth();
TEST_ASSERT_EQUAL(25, ignition2EndTooth);
}
void test_missingtooth_newIgn_36_1_trig360_2()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=360
test_setup_36_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 360; //No trigger offset
triggerSetEndTeeth_missingTooth();
TEST_ASSERT_EQUAL(16, ignition2EndTooth);
}
void test_missingtooth_newIgn_36_1_trigNeg90_2()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=-90
test_setup_36_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = -90; //No trigger offset
triggerSetEndTeeth_missingTooth();
TEST_ASSERT_EQUAL(25, ignition2EndTooth);
}
void test_missingtooth_newIgn_36_1_trigNeg180_2()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=-180
test_setup_36_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = -180; //No trigger offset
triggerSetEndTeeth_missingTooth();
TEST_ASSERT_EQUAL(34, ignition2EndTooth);
}
void test_missingtooth_newIgn_36_1_trigNeg270_2()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=-270
test_setup_36_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = -270; //No trigger offset
triggerSetEndTeeth_missingTooth();
TEST_ASSERT_EQUAL(7, ignition2EndTooth);
}
void test_missingtooth_newIgn_36_1_trigNeg360_2()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=-360
test_setup_36_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = -360; //No trigger offset
triggerSetEndTeeth_missingTooth();
TEST_ASSERT_EQUAL(16, ignition2EndTooth);
}
void test_missingtooth_newIgn_60_2_trig0_2()
{
//Test the set end tooth function. Conditions:
//Trigger: 60-2
//Advance: 10
//triggerAngle=300
test_setup_60_2();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 0; //No trigger offset
triggerSetEndTeeth_missingTooth();
TEST_ASSERT_EQUAL(57, ignition2EndTooth);
}
void test_missingtooth_newIgn_60_2_trig181_2()
{
//Test the set end tooth function. Conditions:
//Trigger: 60-2
//Advance: 10
//triggerAngle=300
test_setup_60_2();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 181; //No trigger offset
triggerSetEndTeeth_missingTooth();
TEST_ASSERT_EQUAL(58, ignition2EndTooth);
}
void test_missingtooth_newIgn_2()
{
}
void test_missingtooth_newIgn_3()
{
}
void test_missingtooth_newIgn_4()
{
}
void testMissingTooth()
{
RUN_TEST(test_missingtooth_newIgn_36_1_trig0_1);
RUN_TEST(test_missingtooth_newIgn_36_1_trig90_1);
RUN_TEST(test_missingtooth_newIgn_36_1_trig180_1);
RUN_TEST(test_missingtooth_newIgn_36_1_trig270_1);
RUN_TEST(test_missingtooth_newIgn_36_1_trig360_1);
RUN_TEST(test_missingtooth_newIgn_36_1_trigNeg90_1);
RUN_TEST(test_missingtooth_newIgn_36_1_trigNeg180_1);
RUN_TEST(test_missingtooth_newIgn_36_1_trigNeg270_1);
RUN_TEST(test_missingtooth_newIgn_36_1_trigNeg360_1);
RUN_TEST(test_missingtooth_newIgn_36_1_trig0_2);
RUN_TEST(test_missingtooth_newIgn_36_1_trig90_2);
RUN_TEST(test_missingtooth_newIgn_36_1_trig180_2);
RUN_TEST(test_missingtooth_newIgn_36_1_trig270_2);
RUN_TEST(test_missingtooth_newIgn_36_1_trig360_2);
RUN_TEST(test_missingtooth_newIgn_36_1_trigNeg90_2);
RUN_TEST(test_missingtooth_newIgn_36_1_trigNeg180_2);
RUN_TEST(test_missingtooth_newIgn_36_1_trigNeg270_2);
RUN_TEST(test_missingtooth_newIgn_36_1_trigNeg360_2);
//RUN_TEST(test_missingtooth_newIgn_60_2_trig181_2);
//RUN_TEST(test_missingtooth_newIgn_60_2_trig182_2);
}
| 10,758
|
C++
|
.cpp
| 317
| 29.722397
| 120
| 0.713773
|
oelprinz-org/BlitzboxBL49sp
| 36
| 12
| 0
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,540,046
|
renix.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202310/speeduino-202310/test/test_decoders/renix/renix.cpp
|
#include <decoders.h>
#include <globals.h>
#include <unity.h>
#include "renix.h"
#include "schedule_calcs.h"
void test_setup_renix44()
{
//Setup a renix 44 tooth wheel
configPage4.TrigPattern = DECODER_RENIX;
configPage2.nCylinders = 4;
triggerSetup_Renix();
}
void test_setup_renix66()
{
//Setup a renix 66 tooth wheel
configPage4.TrigPattern = DECODER_RENIX;
configPage2.nCylinders = 6;
triggerSetup_Renix();
}
//************************************** Begin the new ignition setEndTooth tests **************************************
void test_Renix_newIgn_44_trig0_1()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=0
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 0; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(2, ignition1EndTooth);
}
void test_Renix_newIgn_44_trig90_1()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=90
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 90; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(1, ignition1EndTooth);
}
void test_Renix_newIgn_44_trig180_1()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=180
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 180; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(4, ignition1EndTooth);
}
void test_Renix_newIgn_44_trig270_1()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=270
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 270; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(3, ignition1EndTooth);
}
void test_Renix_newIgn_44_trig360_1()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=360
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 360; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(3, ignition1EndTooth);
}
void test_Renix_newIgn_44_trigNeg90_1()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=-90
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = -90; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(3, ignition1EndTooth);
}
void test_Renix_newIgn_44_trigNeg180_1()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=-180
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = -180; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(4, ignition1EndTooth);
}
void test_Renix_newIgn_44_trigNeg270_1()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=-270
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = -270; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(1, ignition1EndTooth);
}
void test_Renix_newIgn_44_trigNeg360_1()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=-360
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = -360; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(2, ignition1EndTooth);
}
// ******* CHannel 2 *******
void test_Renix_newIgn_44_trig0_2()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=0
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 0; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(4, ignition2EndTooth);
}
void test_Renix_newIgn_44_trig90_2()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=90
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 90; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(3, ignition2EndTooth);
}
void test_Renix_newIgn_44_trig180_2()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=180
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 180; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(3, ignition2EndTooth);
}
void test_Renix_newIgn_44_trig270_2()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=270
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 270; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(2, ignition2EndTooth);
}
void test_Renix_newIgn_44_trig366()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=360
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 360; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(1, ignition2EndTooth);
}
void test_Renix_newIgn_44_trigNeg90_2()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=-90
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = -90; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(1, ignition2EndTooth);
}
void test_Renix_newIgn_44_trigNeg180_2()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=-180
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = -180; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(2, ignition2EndTooth);
}
void test_Renix_newIgn_44_trigNeg270_2()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=-270
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = -270; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(3, ignition2EndTooth);
}
void test_Renix_newIgn_44_trigNeg366()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=-360
test_setup_renix44();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = -360; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(4, ignition2EndTooth);
}
void test_Renix_newIgn_66_trig0_2()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=300
test_setup_renix66();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 0; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(1, ignition2EndTooth);
}
void test_Renix_newIgn_66_trig181_2()
{
//Test the set end tooth function. Conditions:
//Advance: 10
//triggerAngle=300
test_setup_renix66();
configPage4.sparkMode = IGN_MODE_SINGLE;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 181; //No trigger offset
triggerSetEndTeeth_Renix();
TEST_ASSERT_EQUAL(5, ignition2EndTooth);
}
void testRenix()
{
RUN_TEST(test_Renix_newIgn_44_trig0_1);
RUN_TEST(test_Renix_newIgn_44_trig90_1);
RUN_TEST(test_Renix_newIgn_44_trig180_1);
RUN_TEST(test_Renix_newIgn_44_trig270_1);
RUN_TEST(test_Renix_newIgn_44_trig360_1);
RUN_TEST(test_Renix_newIgn_44_trigNeg90_1);
RUN_TEST(test_Renix_newIgn_44_trigNeg180_1);
RUN_TEST(test_Renix_newIgn_44_trigNeg270_1);
RUN_TEST(test_Renix_newIgn_44_trigNeg360_1);
RUN_TEST(test_Renix_newIgn_44_trig0_2);
RUN_TEST(test_Renix_newIgn_44_trig90_2);
RUN_TEST(test_Renix_newIgn_44_trig180_2);
RUN_TEST(test_Renix_newIgn_44_trig270_2);
RUN_TEST(test_Renix_newIgn_44_trig366);
RUN_TEST(test_Renix_newIgn_44_trigNeg90_2);
RUN_TEST(test_Renix_newIgn_44_trigNeg180_2);
RUN_TEST(test_Renix_newIgn_44_trigNeg270_2);
RUN_TEST(test_Renix_newIgn_44_trigNeg366);
RUN_TEST(test_Renix_newIgn_66_trig0_2);
RUN_TEST(test_Renix_newIgn_66_trig181_2);
}
| 9,597
|
C++
|
.cpp
| 284
| 29.5
| 120
| 0.712245
|
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,047
|
dual_wheel.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202310/speeduino-202310/test/test_decoders/dual_wheel/dual_wheel.cpp
|
#include <decoders.h>
#include <globals.h>
#include <unity.h>
#include "dual_wheel.h"
#include "schedule_calcs.h"
void test_setup_dualwheel_12_1()
{
//Setup a 36-1 wheel
configPage4.triggerTeeth = 12;
//configPage4.triggerMissingTeeth = 1;
configPage4.TrigSpeed = CRANK_SPEED;
configPage4.trigPatternSec = SEC_TRIGGER_SINGLE;
triggerSetup_missingTooth();
}
void test_setup_dualwheel_60_2()
{
//Setup a 60-2 wheel
configPage4.triggerTeeth = 60;
configPage4.triggerMissingTeeth = 2;
configPage4.TrigSpeed = CRANK_SPEED;
configPage4.trigPatternSec = SEC_TRIGGER_SINGLE;
triggerSetup_missingTooth();
}
//************************************** Begin the new ignition setEndTooth tests **************************************
void test_dualwheel_newIgn_12_1_trig0_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 12/1
//Advance: 10
//triggerAngle=0
test_setup_dualwheel_12_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 0; //No trigger offset
triggerSetEndTeeth_DualWheel();
TEST_ASSERT_EQUAL(11, ignition1EndTooth);
//Test again with 0 degrees advance
ignition1EndAngle = 360 - 0; //Set 0 degrees advance
triggerSetEndTeeth_DualWheel();
TEST_ASSERT_EQUAL(12, ignition1EndTooth);
//Test again with 35 degrees advance
ignition1EndAngle = 360 - 35; //Set 35 degrees advance
triggerSetEndTeeth_DualWheel();
TEST_ASSERT_EQUAL(10, ignition1EndTooth);
}
void test_dualwheel_newIgn_12_1_trig90_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 12/1
//Advance: 10
//triggerAngle=90
test_setup_dualwheel_12_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 90; //No trigger offset
triggerSetEndTeeth_DualWheel();
TEST_ASSERT_EQUAL(8, ignition1EndTooth);
}
void test_dualwheel_newIgn_12_1_trig180_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=180
test_setup_dualwheel_12_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 180; //No trigger offset
triggerSetEndTeeth_DualWheel();
TEST_ASSERT_EQUAL(5, ignition1EndTooth);
}
void test_dualwheel_newIgn_12_1_trig270_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=270
test_setup_dualwheel_12_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 270; //No trigger offset
triggerSetEndTeeth_DualWheel();
TEST_ASSERT_EQUAL(2, ignition1EndTooth);
}
void test_dualwheel_newIgn_12_1_trig360_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=360
test_setup_dualwheel_12_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 360; //No trigger offset
triggerSetEndTeeth_DualWheel();
TEST_ASSERT_EQUAL(12, ignition1EndTooth);
}
void test_dualwheel_newIgn_12_1_trigNeg90_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=-90
test_setup_dualwheel_12_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = -90; //No trigger offset
triggerSetEndTeeth_DualWheel();
TEST_ASSERT_EQUAL(2, ignition1EndTooth);
}
void test_dualwheel_newIgn_12_1_trigNeg180_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=-180
test_setup_dualwheel_12_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = -180; //No trigger offset
triggerSetEndTeeth_DualWheel();
TEST_ASSERT_EQUAL(5, ignition1EndTooth);
}
void test_dualwheel_newIgn_12_1_trigNeg270_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=-270
test_setup_dualwheel_12_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = -270; //No trigger offset
triggerSetEndTeeth_DualWheel();
TEST_ASSERT_EQUAL(8, ignition1EndTooth);
}
void test_dualwheel_newIgn_12_1_trigNeg360_1()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=-360
test_setup_dualwheel_12_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition1EndAngle = 360 - 10; //Set 10 degrees advance
configPage4.triggerAngle = -360; //No trigger offset
triggerSetEndTeeth_DualWheel();
TEST_ASSERT_EQUAL(11, ignition1EndTooth);
}
// ******* CHannel 2 *******
void test_dualwheel_newIgn_12_1_trig0_2()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=0
test_setup_dualwheel_12_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 0; //No trigger offset
triggerSetEndTeeth_DualWheel();
TEST_ASSERT_EQUAL(16, ignition2EndTooth);
}
void test_dualwheel_newIgn_12_1_trig90_2()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=90
test_setup_dualwheel_12_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 90; //No trigger offset
triggerSetEndTeeth_DualWheel();
TEST_ASSERT_EQUAL(7, ignition2EndTooth);
}
void test_dualwheel_newIgn_12_1_trig180_2()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=180
test_setup_dualwheel_12_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 180; //No trigger offset
triggerSetEndTeeth_DualWheel();
TEST_ASSERT_EQUAL(34, ignition2EndTooth);
}
void test_dualwheel_newIgn_12_1_trig270_2()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=270
test_setup_dualwheel_12_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 270; //No trigger offset
triggerSetEndTeeth_DualWheel();
TEST_ASSERT_EQUAL(25, ignition2EndTooth);
}
void test_dualwheel_newIgn_12_1_trig360_2()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=360
test_setup_dualwheel_12_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = 360; //No trigger offset
triggerSetEndTeeth_DualWheel();
TEST_ASSERT_EQUAL(16, ignition2EndTooth);
}
void test_dualwheel_newIgn_12_1_trigNeg90_2()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=-90
test_setup_dualwheel_12_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = -90; //No trigger offset
triggerSetEndTeeth_DualWheel();
TEST_ASSERT_EQUAL(25, ignition2EndTooth);
}
void test_dualwheel_newIgn_12_1_trigNeg180_2()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=-180
test_setup_dualwheel_12_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = -180; //No trigger offset
triggerSetEndTeeth_DualWheel();
TEST_ASSERT_EQUAL(34, ignition2EndTooth);
}
void test_dualwheel_newIgn_12_1_trigNeg270_2()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=-270
test_setup_dualwheel_12_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = -270; //No trigger offset
triggerSetEndTeeth_DualWheel();
TEST_ASSERT_EQUAL(7, ignition2EndTooth);
}
void test_dualwheel_newIgn_12_1_trigNeg360_2()
{
//Test the set end tooth function. Conditions:
//Trigger: 36-1
//Advance: 10
//triggerAngle=-360
test_setup_dualwheel_12_1();
configPage4.sparkMode = IGN_MODE_WASTED;
ignition2EndAngle = 180 - 10; //Set 10 degrees advance
configPage4.triggerAngle = -360; //No trigger offset
triggerSetEndTeeth_DualWheel();
TEST_ASSERT_EQUAL(16, ignition2EndTooth);
}
void test_dualwheel_newIgn_2()
{
}
void test_dualwheel_newIgn_3()
{
}
void test_dualwheel_newIgn_4()
{
}
void testDualWheel()
{
RUN_TEST(test_dualwheel_newIgn_12_1_trig0_1);
RUN_TEST(test_dualwheel_newIgn_12_1_trig90_1);
RUN_TEST(test_dualwheel_newIgn_12_1_trig180_1);
RUN_TEST(test_dualwheel_newIgn_12_1_trig270_1);
RUN_TEST(test_dualwheel_newIgn_12_1_trig360_1);
RUN_TEST(test_dualwheel_newIgn_12_1_trigNeg90_1);
RUN_TEST(test_dualwheel_newIgn_12_1_trigNeg180_1);
RUN_TEST(test_dualwheel_newIgn_12_1_trigNeg270_1);
RUN_TEST(test_dualwheel_newIgn_12_1_trigNeg360_1);
/*
RUN_TEST(test_dualwheel_newIgn_12_1_trig0_2);
RUN_TEST(test_dualwheel_newIgn_12_1_trig90_2);
RUN_TEST(test_dualwheel_newIgn_12_1_trig180_2);
RUN_TEST(test_dualwheel_newIgn_12_1_trig270_2);
RUN_TEST(test_dualwheel_newIgn_12_1_trig360_2);
RUN_TEST(test_dualwheel_newIgn_12_1_trigNeg90_2);
RUN_TEST(test_dualwheel_newIgn_12_1_trigNeg180_2);
RUN_TEST(test_dualwheel_newIgn_12_1_trigNeg270_2);
RUN_TEST(test_dualwheel_newIgn_12_1_trigNeg360_2);
*/
//RUN_TEST(test_dualwheel_newIgn_60_2_trig181_2);
//RUN_TEST(test_dualwheel_newIgn_60_2_trig182_2);
}
| 10,271
|
C++
|
.cpp
| 301
| 29.933555
| 120
| 0.712589
|
oelprinz-org/BlitzboxBL49sp
| 36
| 12
| 0
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,540,048
|
test_ngc.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202310/speeduino-202310/test/test_decoders/NGC/test_ngc.cpp
|
#include <decoders.h>
#include <globals.h>
#include <unity.h>
#include "test_ngc.h"
#include "scheduler.h"
#include "schedule_calcs.h"
extern uint16_t ignition1EndTooth;
extern uint16_t ignition2EndTooth;
extern uint16_t ignition3EndTooth;
extern uint16_t ignition4EndTooth;
void test_ngc_newIgn_12_trig0_1()
{
triggerSetup_NGC();
CRANK_ANGLE_MAX_IGN = 360;
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = 0; //No trigger offset
calculateIgnitionAngle(5, 0, 10, &ignition1EndAngle, &ignition1StartAngle);
triggerSetEndTeeth_NGC();
TEST_ASSERT_EQUAL(34, ignition1EndTooth);
//Test again with 0 degrees advance
calculateIgnitionAngle(5, 0, 0, &ignition1EndAngle, &ignition1StartAngle);
triggerSetEndTeeth_NGC();
TEST_ASSERT_EQUAL(34, ignition1EndTooth);
//Test again with 35 degrees advance
calculateIgnitionAngle(5, 0, 35, &ignition1EndAngle, &ignition1StartAngle);
triggerSetEndTeeth_NGC();
TEST_ASSERT_EQUAL(31, ignition1EndTooth);
}
void test_ngc_newIgn_12_trig90_1()
{
triggerSetup_NGC();
CRANK_ANGLE_MAX_IGN = 360;
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = 90;
calculateIgnitionAngle(5, 0, 10, &ignition1EndAngle, &ignition1StartAngle);
triggerSetEndTeeth_NGC();
TEST_ASSERT_EQUAL(25, ignition1EndTooth);
}
void test_ngc_newIgn_12_trig180_1()
{
triggerSetup_NGC();
CRANK_ANGLE_MAX_IGN = 360;
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = 180;
currentStatus.advance = 10; //Set 10deg advance
calculateIgnitionAngle(5, 0, 10, &ignition1EndAngle, &ignition1StartAngle);
triggerSetEndTeeth_NGC();
TEST_ASSERT_EQUAL(16, ignition1EndTooth);
}
void test_ngc_newIgn_12_trig270_1()
{
triggerSetup_NGC();
CRANK_ANGLE_MAX_IGN = 360;
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = 270;
calculateIgnitionAngle(5, 0, 10, &ignition1EndAngle, &ignition1StartAngle);
triggerSetEndTeeth_NGC();
TEST_ASSERT_EQUAL(7, ignition1EndTooth);
}
void test_ngc_newIgn_12_trig360_1()
{
triggerSetup_NGC();
CRANK_ANGLE_MAX_IGN = 360;
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = 360;
calculateIgnitionAngle(5, 0, 10, &ignition1EndAngle, &ignition1StartAngle);
triggerSetEndTeeth_NGC();
TEST_ASSERT_EQUAL(34, ignition1EndTooth);
}
void test_ngc_newIgn_12_trigNeg90_1()
{
triggerSetup_NGC();
CRANK_ANGLE_MAX_IGN = 360;
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = -90;
calculateIgnitionAngle(5, 0, 10, &ignition1EndAngle, &ignition1StartAngle);
triggerSetEndTeeth_NGC();
TEST_ASSERT_EQUAL(7, ignition1EndTooth);
}
void test_ngc_newIgn_12_trigNeg180_1()
{
triggerSetup_NGC();
CRANK_ANGLE_MAX_IGN = 360;
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = -180;
calculateIgnitionAngle(5, 0, 10, &ignition1EndAngle, &ignition1StartAngle);
triggerSetEndTeeth_NGC();
TEST_ASSERT_EQUAL(16, ignition1EndTooth);
}
void test_ngc_newIgn_12_trigNeg270_1()
{
triggerSetup_NGC();
CRANK_ANGLE_MAX_IGN = 360;
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = -270;
calculateIgnitionAngle(5, 0, 10, &ignition1EndAngle, &ignition1StartAngle);
triggerSetEndTeeth_NGC();
TEST_ASSERT_EQUAL(25, ignition1EndTooth);
}
void test_ngc_newIgn_12_trigNeg360_1()
{
triggerSetup_NGC();
CRANK_ANGLE_MAX_IGN = 360;
configPage4.sparkMode = IGN_MODE_WASTED;
configPage4.triggerAngle = -360;
calculateIgnitionAngle(5, 0, 10, &ignition1EndAngle, &ignition1StartAngle);
triggerSetEndTeeth_NGC();
TEST_ASSERT_EQUAL(34, ignition1EndTooth);
}
void testNGC()
{
RUN_TEST(test_ngc_newIgn_12_trig0_1);
RUN_TEST(test_ngc_newIgn_12_trig90_1);
RUN_TEST(test_ngc_newIgn_12_trig180_1);
RUN_TEST(test_ngc_newIgn_12_trig270_1);
RUN_TEST(test_ngc_newIgn_12_trig360_1);
RUN_TEST(test_ngc_newIgn_12_trigNeg90_1);
RUN_TEST(test_ngc_newIgn_12_trigNeg180_1);
RUN_TEST(test_ngc_newIgn_12_trigNeg270_1);
RUN_TEST(test_ngc_newIgn_12_trigNeg360_1);
}
| 4,224
|
C++
|
.cpp
| 121
| 30.669421
| 84
| 0.733284
|
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,049
|
test_inj_calcs.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202310/speeduino-202310/test/test_schedule_calcs/test_inj_calcs.cpp
|
#include <Arduino.h>
#include <unity.h>
#include "test_calcs_common.h"
#include "schedule_calcs.h"
#include "crankMaths.h"
#define _countof(x) (sizeof(x) / sizeof (x[0]))
// void printFreeRam()
// {
// char msg[128];
// sprintf(msg, "freeRam: %u", freeRam());
// TEST_MESSAGE(msg);
// }
struct inj_test_parameters
{
uint16_t channelAngle; // deg
uint16_t pw; // uS
uint16_t crankAngle; // deg
uint32_t pending; // Expected delay when channel status is PENDING
uint32_t running; // Expected delay when channel status is RUNNING
};
static void test_calc_inj_timeout(const inj_test_parameters ¶meters)
{
static constexpr uint16_t injAngle = 355;
char msg[150];
uint16_t PWdivTimerPerDegree = div(parameters.pw, timePerDegree).quot;
memset(&fuelSchedule2, 0, sizeof(fuelSchedule2));
fuelSchedule2.Status = PENDING;
uint16_t startAngle = calculateInjectorStartAngle(PWdivTimerPerDegree, parameters.channelAngle, injAngle);
sprintf_P(msg, PSTR("PENDING channelAngle: % " PRIu16 ", pw: % " PRIu16 ", crankAngle: % " PRIu16 ", startAngle: % " PRIu16 ""), parameters.channelAngle, parameters.pw, parameters.crankAngle, startAngle);
TEST_ASSERT_EQUAL_MESSAGE(parameters.pending, calculateInjectorTimeout(fuelSchedule2, parameters.channelAngle, startAngle, parameters.crankAngle), msg);
fuelSchedule2.Status = RUNNING;
startAngle = calculateInjectorStartAngle( PWdivTimerPerDegree, parameters.channelAngle, injAngle);
sprintf_P(msg, PSTR("RUNNING channelAngle: % " PRIu16 ", pw: % " PRIu16 ", crankAngle: % " PRIu16 ", startAngle: % " PRIu16 ""), parameters.channelAngle, parameters.pw, parameters.crankAngle, startAngle);
TEST_ASSERT_EQUAL_MESSAGE(parameters.running, calculateInjectorTimeout(fuelSchedule2, parameters.channelAngle, startAngle, parameters.crankAngle), msg);
}
static void test_calc_inj_timeout(const inj_test_parameters *pStart, const inj_test_parameters *pEnd)
{
inj_test_parameters local;
while (pStart!=pEnd)
{
memcpy_P(&local, pStart, sizeof(local));
test_calc_inj_timeout(local);
++pStart;
}
}
static void test_calc_inj_timeout_360()
{
setEngineSpeed(4000, 360);
static const inj_test_parameters test_data[] PROGMEM = {
// ChannelAngle (deg), PW (uS), Crank (deg), Expected Pending (uS), Expected Running (uS)
{ 0, 3000, 0, 11562, 11562 },
{ 0, 3000, 45, 9717, 9717 },
{ 0, 3000, 90, 7872, 7872 },
{ 0, 3000, 135, 6027, 6027 },
{ 0, 3000, 180, 4182, 4182 },
{ 0, 3000, 215, 2747, 2747 },
{ 0, 3000, 270, 492, 492 },
{ 0, 3000, 315, 0, 13407 },
{ 0, 3000, 360, 0, 11562 },
{ 72, 3000, 0, 0, 14514 },
{ 72, 3000, 45, 0, 12669 },
{ 72, 3000, 90, 10824, 10824 },
{ 72, 3000, 135, 8979, 8979 },
{ 72, 3000, 180, 7134, 7134 },
{ 72, 3000, 215, 5699, 5699 },
{ 72, 3000, 270, 3444, 3444 },
{ 72, 3000, 315, 1599, 1599 },
{ 72, 3000, 360, 0, 14514 },
{ 80, 3000, 0, 82, 82 },
{ 80, 3000, 45, 0, 12997 },
{ 80, 3000, 90, 11152, 11152 },
{ 80, 3000, 135, 9307, 9307 },
{ 80, 3000, 180, 7462, 7462 },
{ 80, 3000, 215, 6027, 6027 },
{ 80, 3000, 270, 3772, 3772 },
{ 80, 3000, 315, 1927, 1927 },
{ 80, 3000, 360, 82, 82 },
{ 90, 3000, 0, 492, 492 },
{ 90, 3000, 45, 0, 13407 },
{ 90, 3000, 90, 11562, 11562 },
{ 90, 3000, 135, 9717, 9717 },
{ 90, 3000, 180, 7872, 7872 },
{ 90, 3000, 215, 6437, 6437 },
{ 90, 3000, 270, 4182, 4182 },
{ 90, 3000, 315, 2337, 2337 },
{ 90, 3000, 360, 492, 492 },
{ 144, 3000, 0, 2706, 2706 },
{ 144, 3000, 45, 861, 861 },
{ 144, 3000, 90, 0, 13776 },
{ 144, 3000, 135, 0, 11931 },
{ 144, 3000, 180, 10086, 10086 },
{ 144, 3000, 215, 8651, 8651 },
{ 144, 3000, 270, 6396, 6396 },
{ 144, 3000, 315, 4551, 4551 },
{ 144, 3000, 360, 2706, 2706 },
{ 180, 3000, 0, 4182, 4182 },
{ 180, 3000, 45, 2337, 2337 },
{ 180, 3000, 90, 492, 492 },
{ 180, 3000, 135, 0, 13407 },
{ 180, 3000, 180, 11562, 11562 },
{ 180, 3000, 215, 10127, 10127 },
{ 180, 3000, 270, 7872, 7872 },
{ 180, 3000, 315, 6027, 6027 },
{ 180, 3000, 360, 4182, 4182 },
{ 240, 3000, 0, 6642, 6642 },
{ 240, 3000, 45, 4797, 4797 },
{ 240, 3000, 90, 2952, 2952 },
{ 240, 3000, 135, 1107, 1107 },
{ 240, 3000, 180, 0, 14022 },
{ 240, 3000, 215, 0, 12587 },
{ 240, 3000, 270, 10332, 10332 },
{ 240, 3000, 315, 8487, 8487 },
{ 240, 3000, 360, 6642, 6642 },
{ 270, 3000, 0, 7872, 7872 },
{ 270, 3000, 45, 6027, 6027 },
{ 270, 3000, 90, 4182, 4182 },
{ 270, 3000, 135, 2337, 2337 },
{ 270, 3000, 180, 492, 492 },
{ 270, 3000, 215, 0, 13817 },
{ 270, 3000, 270, 11562, 11562 },
{ 270, 3000, 315, 9717, 9717 },
{ 270, 3000, 360, 7872, 7872 },
{ 360, 3000, 0, 11562, 11562 },
{ 360, 3000, 45, 9717, 9717 },
{ 360, 3000, 90, 7872, 7872 },
{ 360, 3000, 135, 6027, 6027 },
{ 360, 3000, 180, 4182, 4182 },
{ 360, 3000, 215, 2747, 2747 },
{ 360, 3000, 270, 492, 492 },
{ 360, 3000, 315, 0, 13407 },
{ 360, 3000, 360, 11562, 11562 },
};
test_calc_inj_timeout(&test_data[0], &test_data[0]+_countof(test_data));
}
static void test_calc_inj_timeout_720()
{
setEngineSpeed(4000, 720);
static const inj_test_parameters test_data[] PROGMEM = {
// ChannelAngle (deg), PW (uS), Crank (deg), Expected Pending (uS), Expected Running (uS)
{ 0, 3000, 90, 7872, 7872 },
{ 0, 3000, 135, 6027, 6027 },
{ 0, 3000, 180, 4182, 4182 },
{ 0, 3000, 215, 2747, 2747 },
{ 0, 3000, 270, 492, 492 },
{ 0, 3000, 315, 0, 28167 },
{ 0, 3000, 360, 0, 26322 },
{ 72, 3000, 0, 0, 14514 },
{ 72, 3000, 45, 0, 12669 },
{ 72, 3000, 90, 10824, 10824 },
{ 72, 3000, 135, 8979, 8979 },
{ 72, 3000, 180, 7134, 7134 },
{ 72, 3000, 215, 5699, 5699 },
{ 72, 3000, 270, 3444, 3444 },
{ 72, 3000, 315, 1599, 1599 },
{ 72, 3000, 360, 0, 29274 },
{ 80, 3000, 0, 0, 14842 },
{ 80, 3000, 45, 0, 12997 },
{ 80, 3000, 90, 11152, 11152 },
{ 80, 3000, 135, 9307, 9307 },
{ 80, 3000, 180, 7462, 7462 },
{ 80, 3000, 215, 6027, 6027 },
{ 80, 3000, 270, 3772, 3772 },
{ 80, 3000, 315, 1927, 1927 },
{ 80, 3000, 360, 82, 82 },
{ 90, 3000, 0, 0, 15252 },
{ 90, 3000, 45, 0, 13407 },
{ 90, 3000, 90, 11562, 11562 },
{ 90, 3000, 135, 9717, 9717 },
{ 90, 3000, 180, 7872, 7872 },
{ 90, 3000, 215, 6437, 6437 },
{ 90, 3000, 270, 4182, 4182 },
{ 90, 3000, 315, 2337, 2337 },
{ 90, 3000, 360, 492, 492 },
{ 144, 3000, 0, 0, 17466 },
{ 144, 3000, 45, 0, 15621 },
{ 144, 3000, 90, 0, 13776 },
{ 144, 3000, 135, 0, 11931 },
{ 144, 3000, 180, 10086, 10086 },
{ 144, 3000, 215, 8651, 8651 },
{ 144, 3000, 270, 6396, 6396 },
{ 144, 3000, 315, 4551, 4551 },
{ 144, 3000, 360, 2706, 2706 },
{ 180, 3000, 0, 0, 18942 },
{ 180, 3000, 45, 0, 17097 },
{ 180, 3000, 90, 0, 15252 },
{ 180, 3000, 135, 0, 13407 },
{ 180, 3000, 180, 11562, 11562 },
{ 180, 3000, 215, 10127, 10127 },
{ 180, 3000, 270, 7872, 7872 },
{ 180, 3000, 315, 6027, 6027 },
{ 180, 3000, 360, 4182, 4182 },
{ 240, 3000, 0, 0, 21402 },
{ 240, 3000, 45, 0, 19557 },
{ 240, 3000, 90, 0, 17712 },
{ 240, 3000, 135, 0, 15867 },
{ 240, 3000, 180, 0, 14022 },
{ 240, 3000, 215, 0, 12587 },
{ 240, 3000, 270, 10332, 10332 },
{ 240, 3000, 315, 8487, 8487 },
{ 240, 3000, 360, 6642, 6642 },
{ 270, 3000, 0, 0, 22632 },
{ 270, 3000, 45, 0, 20787 },
{ 270, 3000, 90, 0, 18942 },
{ 270, 3000, 135, 0, 17097 },
{ 270, 3000, 180, 0, 15252 },
{ 270, 3000, 215, 0, 13817 },
{ 270, 3000, 270, 11562, 11562 },
{ 270, 3000, 315, 9717, 9717 },
{ 270, 3000, 360, 7872, 7872 },
{ 360, 3000, 0, 0, 26322 },
{ 360, 3000, 45, 0, 24477 },
{ 360, 3000, 90, 0, 22632 },
{ 360, 3000, 135, 0, 20787 },
{ 360, 3000, 180, 0, 18942 },
{ 360, 3000, 215, 0, 17507 },
{ 360, 3000, 270, 0, 15252 },
{ 360, 3000, 315, 0, 13407 },
{ 360, 3000, 360, 11562, 11562 },
{ 480, 3000, 0, 1722, 1722 },
{ 480, 3000, 45, 0, 29397 },
{ 480, 3000, 90, 0, 27552 },
{ 480, 3000, 135, 0, 25707 },
{ 480, 3000, 180, 0, 23862 },
{ 480, 3000, 215, 0, 22427 },
{ 480, 3000, 270, 0, 20172 },
{ 480, 3000, 315, 0, 18327 },
{ 480, 3000, 360, 0, 16482 },
{ 540, 3000, 0, 4182, 4182 },
{ 540, 3000, 45, 2337, 2337 },
{ 540, 3000, 90, 492, 492 },
{ 540, 3000, 135, 0, 28167 },
{ 540, 3000, 180, 0, 26322 },
{ 540, 3000, 215, 0, 24887 },
{ 540, 3000, 270, 0, 22632 },
{ 540, 3000, 315, 0, 20787 },
{ 540, 3000, 360, 0, 18942 },
{ 600, 3000, 0, 6642, 6642 },
{ 600, 3000, 45, 4797, 4797 },
{ 600, 3000, 90, 2952, 2952 },
{ 600, 3000, 135, 1107, 1107 },
{ 600, 3000, 180, 0, 28782 },
{ 600, 3000, 215, 0, 27347 },
{ 600, 3000, 270, 0, 25092 },
{ 600, 3000, 315, 0, 23247 },
{ 600, 3000, 360, 0, 21402 },
{ 630, 3000, 0, 7872, 7872 },
{ 630, 3000, 45, 6027, 6027 },
{ 630, 3000, 90, 4182, 4182 },
{ 630, 3000, 135, 2337, 2337 },
{ 630, 3000, 180, 492, 492 },
{ 630, 3000, 215, 0, 28577 },
{ 630, 3000, 270, 0, 26322 },
{ 630, 3000, 315, 0, 24477 },
{ 630, 3000, 360, 0, 22632 },
};
test_calc_inj_timeout(&test_data[0], &test_data[0]+_countof(test_data));
}
//
void test_calc_inj_timeout(void)
{
RUN_TEST(test_calc_inj_timeout_360);
RUN_TEST(test_calc_inj_timeout_720);
}
| 10,466
|
C++
|
.cpp
| 263
| 32.117871
| 208
| 0.514244
|
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,050
|
test_ign_calcs.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202310/speeduino-202310/test/test_schedule_calcs/test_ign_calcs.cpp
|
#include <Arduino.h>
#include <unity.h>
#include "test_calcs_common.h"
#include "schedule_calcs.h"
#include "crankMaths.h"
#define _countof(x) (sizeof(x) / sizeof (x[0]))
extern volatile uint16_t degreesPeruSx2048;
constexpr uint16_t DWELL_TIME_MS = 4;
uint16_t dwellAngle;
void setEngineSpeed(uint16_t rpm, int16_t max_crank) {
timePerDegreex16 = ldiv( 2666656L, rpm).quot; //The use of a x16 value gives accuracy down to 0.1 of a degree and can provide noticeably better timing results on low resolution triggers
timePerDegree = timePerDegreex16 / 16;
degreesPeruSx2048 = 2048 / timePerDegree;
degreesPeruSx32768 = 524288L / timePerDegreex16;
revolutionTime = (60L*1000000L) / rpm;
CRANK_ANGLE_MAX_IGN = max_crank;
CRANK_ANGLE_MAX_INJ = max_crank;
dwellAngle = timeToAngle(DWELL_TIME_MS*1000UL, CRANKMATH_METHOD_INTERVAL_REV);
}
struct ign_test_parameters
{
uint16_t channelAngle; // deg
int8_t advanceAngle; // deg
uint16_t crankAngle; // deg
uint32_t pending; // Expected delay when channel status is PENDING
uint32_t running; // Expected delay when channel status is RUNNING
int16_t expectedStartAngle; // Expected start angle
int16_t expectedEndAngle; // Expected end angle
};
void test_calc_ign_timeout(const ign_test_parameters &test_params)
{
char msg[150];
Schedule schedule;
memset(&schedule, 0, sizeof(schedule));
int startAngle;
int endAngle;
calculateIgnitionAngle(dwellAngle, test_params.channelAngle, test_params.advanceAngle, &endAngle, &startAngle);
TEST_ASSERT_EQUAL_MESSAGE(test_params.expectedStartAngle, startAngle, "startAngle");
TEST_ASSERT_EQUAL_MESSAGE(test_params.expectedEndAngle, endAngle, "endAngle");
sprintf_P(msg, PSTR("PENDING advanceAngle: %" PRIi8 ", channelAngle: % " PRIu16 ", crankAngle: %" PRIu16 ", endAngle: %" PRIi16), test_params.advanceAngle, test_params.channelAngle, test_params.crankAngle, endAngle);
schedule.Status = PENDING;
TEST_ASSERT_EQUAL_MESSAGE(test_params.pending, calculateIgnitionTimeout(schedule, startAngle, test_params.channelAngle, test_params.crankAngle), msg);
sprintf_P(msg, PSTR("RUNNING advanceAngle: %" PRIi8 ", channelAngle: % " PRIu16 ", crankAngle: %" PRIu16 ", endAngle: %" PRIi16), test_params.advanceAngle, test_params.channelAngle, test_params.crankAngle, endAngle);
schedule.Status = RUNNING;
TEST_ASSERT_EQUAL_MESSAGE(test_params.running, calculateIgnitionTimeout(schedule, startAngle, test_params.channelAngle, test_params.crankAngle), msg);
}
void test_calc_ign_timeout(const ign_test_parameters *pStart, const ign_test_parameters *pEnd)
{
ign_test_parameters local;
while (pStart!=pEnd)
{
memcpy_P(&local, pStart, sizeof(local));
test_calc_ign_timeout(local);
++pStart;
}
}
void test_calc_ign_timeout_360()
{
setEngineSpeed(4000, 360);
static const ign_test_parameters test_data[] PROGMEM = {
// ChannelAngle (deg), Advance, Crank, Expected Pending, Expected Running
{ 0, -40, 0, 12666, 12666, 304, 40 },
{ 0, -40, 45, 10791, 10791, 304, 40 },
{ 0, -40, 90, 8916, 8916, 304, 40 },
{ 0, -40, 135, 7041, 7041, 304, 40 },
{ 0, -40, 180, 5166, 5166, 304, 40 },
{ 0, -40, 215, 3708, 3708, 304, 40 },
{ 0, -40, 270, 1416, 1416, 304, 40 },
{ 0, -40, 315, 0, 14541, 304, 40 },
{ 0, -40, 360, 0, 12666, 304, 40 },
{ 0, 0, 0, 11000, 11000, 264, 360 },
{ 0, 0, 45, 9125, 9125, 264, 360 },
{ 0, 0, 90, 7250, 7250, 264, 360 },
{ 0, 0, 135, 5375, 5375, 264, 360 },
{ 0, 0, 180, 3500, 3500, 264, 360 },
{ 0, 0, 215, 2041, 2041, 264, 360 },
{ 0, 0, 270, 0, 14750, 264, 360 },
{ 0, 0, 315, 0, 12875, 264, 360 },
{ 0, 0, 360, 0, 11000, 264, 360 },
{ 0, 40, 0, 9333, 9333, 224, 320 },
{ 0, 40, 45, 7458, 7458, 224, 320 },
{ 0, 40, 90, 5583, 5583, 224, 320 },
{ 0, 40, 135, 3708, 3708, 224, 320 },
{ 0, 40, 180, 1833, 1833, 224, 320 },
{ 0, 40, 215, 375, 375, 224, 320 },
{ 0, 40, 270, 0, 13083, 224, 320 },
{ 0, 40, 315, 0, 11208, 224, 320 },
{ 0, 40, 360, 0, 9333, 224, 320 },
{ 72, -40, 0, 666, 666, 16, 112 },
{ 72, -40, 45, 0, 13791, 16, 112 },
{ 72, -40, 90, 11916, 11916, 16, 112 },
{ 72, -40, 135, 10041, 10041, 16, 112 },
{ 72, -40, 180, 8166, 8166, 16, 112 },
{ 72, -40, 215, 6708, 6708, 16, 112 },
{ 72, -40, 270, 4416, 4416, 16, 112 },
{ 72, -40, 315, 2541, 2541, 16, 112 },
{ 72, -40, 360, 666, 666, 16, 112 },
{ 72, 0, 0, 0, 14000, 336, 72 },
{ 72, 0, 45, 0, 12125, 336, 72 },
{ 72, 0, 90, 10250, 10250, 336, 72 },
{ 72, 0, 135, 8375, 8375, 336, 72 },
{ 72, 0, 180, 6500, 6500, 336, 72 },
{ 72, 0, 215, 5041, 5041, 336, 72 },
{ 72, 0, 270, 2750, 2750, 336, 72 },
{ 72, 0, 315, 875, 875, 336, 72 },
{ 72, 0, 360, 0, 14000, 336, 72 },
{ 72, 40, 0, 0, 12333, 296, 32 },
{ 72, 40, 45, 0, 10458, 296, 32 },
{ 72, 40, 90, 8583, 8583, 296, 32 },
{ 72, 40, 135, 6708, 6708, 296, 32 },
{ 72, 40, 180, 4833, 4833, 296, 32 },
{ 72, 40, 215, 3375, 3375, 296, 32 },
{ 72, 40, 270, 1083, 1083, 296, 32 },
{ 72, 40, 315, 0, 14208, 296, 32 },
{ 72, 40, 360, 0, 12333, 296, 32 },
{ 90, -40, 0, 1416, 1416, 34, 130 },
{ 90, -40, 45, 0, 14541, 34, 130 },
{ 90, -40, 90, 12666, 12666, 34, 130 },
{ 90, -40, 135, 10791, 10791, 34, 130 },
{ 90, -40, 180, 8916, 8916, 34, 130 },
{ 90, -40, 215, 7458, 7458, 34, 130 },
{ 90, -40, 270, 5166, 5166, 34, 130 },
{ 90, -40, 315, 3291, 3291, 34, 130 },
{ 90, -40, 360, 1416, 1416, 34, 130 },
{ 90, 0, 0, 0, 14750, 354, 90 },
{ 90, 0, 45, 0, 12875, 354, 90 },
{ 90, 0, 90, 11000, 11000, 354, 90 },
{ 90, 0, 135, 9125, 9125, 354, 90 },
{ 90, 0, 180, 7250, 7250, 354, 90 },
{ 90, 0, 215, 5791, 5791, 354, 90 },
{ 90, 0, 270, 3500, 3500, 354, 90 },
{ 90, 0, 315, 1625, 1625, 354, 90 },
{ 90, 0, 360, 0, 14750, 354, 90 },
{ 90, 40, 0, 0, 13083, 314, 50 },
{ 90, 40, 45, 0, 11208, 314, 50 },
{ 90, 40, 90, 9333, 9333, 314, 50 },
{ 90, 40, 135, 7458, 7458, 314, 50 },
{ 90, 40, 180, 5583, 5583, 314, 50 },
{ 90, 40, 215, 4125, 4125, 314, 50 },
{ 90, 40, 270, 1833, 1833, 314, 50 },
{ 90, 40, 315, 0, 14958, 314, 50 },
{ 90, 40, 360, 0, 13083, 314, 50 },
{ 144, -40, 0, 3666, 3666, 88, 184 },
{ 144, -40, 45, 1791, 1791, 88, 184 },
{ 144, -40, 90, 0, 14916, 88, 184 },
{ 144, -40, 135, 0, 13041, 88, 184 },
{ 144, -40, 180, 11166, 11166, 88, 184 },
{ 144, -40, 215, 9708, 9708, 88, 184 },
{ 144, -40, 270, 7416, 7416, 88, 184 },
{ 144, -40, 315, 5541, 5541, 88, 184 },
{ 144, -40, 360, 3666, 3666, 88, 184 },
{ 144, 0, 0, 2000, 2000, 48, 144 },
{ 144, 0, 45, 125, 125, 48, 144 },
{ 144, 0, 90, 0, 13250, 48, 144 },
{ 144, 0, 135, 0, 11375, 48, 144 },
{ 144, 0, 180, 9500, 9500, 48, 144 },
{ 144, 0, 215, 8041, 8041, 48, 144 },
{ 144, 0, 270, 5750, 5750, 48, 144 },
{ 144, 0, 315, 3875, 3875, 48, 144 },
{ 144, 0, 360, 2000, 2000, 48, 144 },
{ 144, 40, 0, 333, 333, 8, 104 },
{ 144, 40, 45, 0, 13458, 8, 104 },
{ 144, 40, 90, 0, 11583, 8, 104 },
{ 144, 40, 135, 0, 9708, 8, 104 },
{ 144, 40, 180, 7833, 7833, 8, 104 },
{ 144, 40, 215, 6375, 6375, 8, 104 },
{ 144, 40, 270, 4083, 4083, 8, 104 },
{ 144, 40, 315, 2208, 2208, 8, 104 },
{ 144, 40, 360, 333, 333, 8, 104 },
{ 180, -40, 0, 5166, 5166, 124, 220 },
{ 180, -40, 45, 3291, 3291, 124, 220 },
{ 180, -40, 90, 1416, 1416, 124, 220 },
{ 180, -40, 135, 0, 14541, 124, 220 },
{ 180, -40, 180, 12666, 12666, 124, 220 },
{ 180, -40, 215, 11208, 11208, 124, 220 },
{ 180, -40, 270, 8916, 8916, 124, 220 },
{ 180, -40, 315, 7041, 7041, 124, 220 },
{ 180, -40, 360, 5166, 5166, 124, 220 },
{ 180, 0, 0, 3500, 3500, 84, 180 },
{ 180, 0, 45, 1625, 1625, 84, 180 },
{ 180, 0, 90, 0, 14750, 84, 180 },
{ 180, 0, 135, 0, 12875, 84, 180 },
{ 180, 0, 180, 11000, 11000, 84, 180 },
{ 180, 0, 215, 9541, 9541, 84, 180 },
{ 180, 0, 270, 7250, 7250, 84, 180 },
{ 180, 0, 315, 5375, 5375, 84, 180 },
{ 180, 0, 360, 3500, 3500, 84, 180 },
{ 180, 40, 0, 1833, 1833, 44, 140 },
{ 180, 40, 45, 0, 14958, 44, 140 },
{ 180, 40, 90, 0, 13083, 44, 140 },
{ 180, 40, 135, 0, 11208, 44, 140 },
{ 180, 40, 180, 9333, 9333, 44, 140 },
{ 180, 40, 215, 7875, 7875, 44, 140 },
{ 180, 40, 270, 5583, 5583, 44, 140 },
{ 180, 40, 315, 3708, 3708, 44, 140 },
{ 180, 40, 360, 1833, 1833, 44, 140 },
{ 270, -40, 0, 8916, 8916, 214, 310 },
{ 270, -40, 45, 7041, 7041, 214, 310 },
{ 270, -40, 90, 5166, 5166, 214, 310 },
{ 270, -40, 135, 3291, 3291, 214, 310 },
{ 270, -40, 180, 1416, 1416, 214, 310 },
{ 270, -40, 215, 0, 14958, 214, 310 },
{ 270, -40, 270, 12666, 12666, 214, 310 },
{ 270, -40, 315, 10791, 10791, 214, 310 },
{ 270, -40, 360, 8916, 8916, 214, 310 },
{ 270, 0, 0, 7250, 7250, 174, 270 },
{ 270, 0, 45, 5375, 5375, 174, 270 },
{ 270, 0, 90, 3500, 3500, 174, 270 },
{ 270, 0, 135, 1625, 1625, 174, 270 },
{ 270, 0, 180, 0, 14750, 174, 270 },
{ 270, 0, 215, 0, 13291, 174, 270 },
{ 270, 0, 270, 11000, 11000, 174, 270 },
{ 270, 0, 315, 9125, 9125, 174, 270 },
{ 270, 0, 360, 7250, 7250, 174, 270 },
{ 270, 40, 0, 5583, 5583, 134, 230 },
{ 270, 40, 45, 3708, 3708, 134, 230 },
{ 270, 40, 90, 1833, 1833, 134, 230 },
{ 270, 40, 135, 0, 14958, 134, 230 },
{ 270, 40, 180, 0, 13083, 134, 230 },
{ 270, 40, 215, 0, 11625, 134, 230 },
{ 270, 40, 270, 9333, 9333, 134, 230 },
{ 270, 40, 315, 7458, 7458, 134, 230 },
{ 270, 40, 360, 5583, 5583, 134, 230 },
{ 360, -40, 0, 12666, 12666, 304, 40 },
{ 360, -40, 45, 10791, 10791, 304, 40 },
{ 360, -40, 90, 8916, 8916, 304, 40 },
{ 360, -40, 135, 7041, 7041, 304, 40 },
{ 360, -40, 180, 5166, 5166, 304, 40 },
{ 360, -40, 215, 3708, 3708, 304, 40 },
{ 360, -40, 270, 1416, 1416, 304, 40 },
{ 360, -40, 315, 0, 14541, 304, 40 },
{ 360, -40, 360, 12666, 12666, 304, 40 },
{ 360, 0, 0, 11000, 11000, 264, 360 },
{ 360, 0, 45, 9125, 9125, 264, 360 },
{ 360, 0, 90, 7250, 7250, 264, 360 },
{ 360, 0, 135, 5375, 5375, 264, 360 },
{ 360, 0, 180, 3500, 3500, 264, 360 },
{ 360, 0, 215, 2041, 2041, 264, 360 },
{ 360, 0, 270, 0, 14750, 264, 360 },
{ 360, 0, 315, 0, 12875, 264, 360 },
{ 360, 0, 360, 11000, 11000, 264, 360 },
{ 360, 40, 0, 9333, 9333, 224, 320 },
{ 360, 40, 45, 7458, 7458, 224, 320 },
{ 360, 40, 90, 5583, 5583, 224, 320 },
{ 360, 40, 135, 3708, 3708, 224, 320 },
{ 360, 40, 180, 1833, 1833, 224, 320 },
{ 360, 40, 215, 375, 375, 224, 320 },
{ 360, 40, 270, 0, 13083, 224, 320 },
{ 360, 40, 315, 0, 11208, 224, 320 },
{ 360, 40, 360, 9333, 9333, 224, 320 },
};
test_calc_ign_timeout(&test_data[0], &test_data[0]+_countof(test_data));
}
void test_calc_ign_timeout_720()
{
setEngineSpeed(4000, 720);
static const ign_test_parameters test_data[] PROGMEM = {
// ChannelAngle (deg), Advance, Crank, Expected Pending, Expected Running
{ 0, -40, 0, 27666, 27666, 664, 40 },
{ 0, -40, 45, 25791, 25791, 664, 40 },
{ 0, -40, 90, 23916, 23916, 664, 40 },
{ 0, -40, 135, 22041, 22041, 664, 40 },
{ 0, -40, 180, 20166, 20166, 664, 40 },
{ 0, -40, 215, 18708, 18708, 664, 40 },
{ 0, -40, 270, 16416, 16416, 664, 40 },
{ 0, -40, 315, 14541, 14541, 664, 40 },
{ 0, -40, 360, 12666, 12666, 664, 40 },
{ 0, 0, 0, 26000, 26000, 624, 720 },
{ 0, 0, 45, 24125, 24125, 624, 720 },
{ 0, 0, 90, 22250, 22250, 624, 720 },
{ 0, 0, 135, 20375, 20375, 624, 720 },
{ 0, 0, 180, 18500, 18500, 624, 720 },
{ 0, 0, 215, 17041, 17041, 624, 720 },
{ 0, 0, 270, 14750, 14750, 624, 720 },
{ 0, 0, 315, 12875, 12875, 624, 720 },
{ 0, 0, 360, 11000, 11000, 624, 720 },
{ 0, 40, 0, 24333, 24333, 584, 680 },
{ 0, 40, 45, 22458, 22458, 584, 680 },
{ 0, 40, 90, 20583, 20583, 584, 680 },
{ 0, 40, 135, 18708, 18708, 584, 680 },
{ 0, 40, 180, 16833, 16833, 584, 680 },
{ 0, 40, 215, 15375, 15375, 584, 680 },
{ 0, 40, 270, 13083, 13083, 584, 680 },
{ 0, 40, 315, 11208, 11208, 584, 680 },
{ 0, 40, 360, 9333, 9333, 584, 680 },
{ 72, -40, 0, 666, 666, 16, 112 },
{ 72, -40, 45, 0, 28791, 16, 112 },
{ 72, -40, 90, 26916, 26916, 16, 112 },
{ 72, -40, 135, 25041, 25041, 16, 112 },
{ 72, -40, 180, 23166, 23166, 16, 112 },
{ 72, -40, 215, 21708, 21708, 16, 112 },
{ 72, -40, 270, 19416, 19416, 16, 112 },
{ 72, -40, 315, 17541, 17541, 16, 112 },
{ 72, -40, 360, 15666, 15666, 16, 112 },
{ 72, 0, 0, 0, 29000, 696, 72 },
{ 72, 0, 45, 0, 27125, 696, 72 },
{ 72, 0, 90, 25250, 25250, 696, 72 },
{ 72, 0, 135, 23375, 23375, 696, 72 },
{ 72, 0, 180, 21500, 21500, 696, 72 },
{ 72, 0, 215, 20041, 20041, 696, 72 },
{ 72, 0, 270, 17750, 17750, 696, 72 },
{ 72, 0, 315, 15875, 15875, 696, 72 },
{ 72, 0, 360, 14000, 14000, 696, 72 },
{ 72, 40, 0, 0, 27333, 656, 32 },
{ 72, 40, 45, 0, 25458, 656, 32 },
{ 72, 40, 90, 23583, 23583, 656, 32 },
{ 72, 40, 135, 21708, 21708, 656, 32 },
{ 72, 40, 180, 19833, 19833, 656, 32 },
{ 72, 40, 215, 18375, 18375, 656, 32 },
{ 72, 40, 270, 16083, 16083, 656, 32 },
{ 72, 40, 315, 14208, 14208, 656, 32 },
{ 72, 40, 360, 12333, 12333, 656, 32 },
{ 90, -40, 0, 1416, 1416, 34, 130 },
{ 90, -40, 45, 0, 29541, 34, 130 },
{ 90, -40, 90, 27666, 27666, 34, 130 },
{ 90, -40, 135, 25791, 25791, 34, 130 },
{ 90, -40, 180, 23916, 23916, 34, 130 },
{ 90, -40, 215, 22458, 22458, 34, 130 },
{ 90, -40, 270, 20166, 20166, 34, 130 },
{ 90, -40, 315, 18291, 18291, 34, 130 },
{ 90, -40, 360, 16416, 16416, 34, 130 },
{ 90, 0, 0, 0, 29750, 714, 90 },
{ 90, 0, 45, 0, 27875, 714, 90 },
{ 90, 0, 90, 26000, 26000, 714, 90 },
{ 90, 0, 135, 24125, 24125, 714, 90 },
{ 90, 0, 180, 22250, 22250, 714, 90 },
{ 90, 0, 215, 20791, 20791, 714, 90 },
{ 90, 0, 270, 18500, 18500, 714, 90 },
{ 90, 0, 315, 16625, 16625, 714, 90 },
{ 90, 0, 360, 14750, 14750, 714, 90 },
{ 90, 40, 0, 0, 28083, 674, 50 },
{ 90, 40, 45, 0, 26208, 674, 50 },
{ 90, 40, 90, 24333, 24333, 674, 50 },
{ 90, 40, 135, 22458, 22458, 674, 50 },
{ 90, 40, 180, 20583, 20583, 674, 50 },
{ 90, 40, 215, 19125, 19125, 674, 50 },
{ 90, 40, 270, 16833, 16833, 674, 50 },
{ 90, 40, 315, 14958, 14958, 674, 50 },
{ 90, 40, 360, 13083, 13083, 674, 50 },
{ 144, -40, 0, 3666, 3666, 88, 184 },
{ 144, -40, 45, 1791, 1791, 88, 184 },
{ 144, -40, 90, 0, 29916, 88, 184 },
{ 144, -40, 135, 0, 28041, 88, 184 },
{ 144, -40, 180, 26166, 26166, 88, 184 },
{ 144, -40, 215, 24708, 24708, 88, 184 },
{ 144, -40, 270, 22416, 22416, 88, 184 },
{ 144, -40, 315, 20541, 20541, 88, 184 },
{ 144, -40, 360, 18666, 18666, 88, 184 },
{ 144, 0, 0, 2000, 2000, 48, 144 },
{ 144, 0, 45, 125, 125, 48, 144 },
{ 144, 0, 90, 0, 28250, 48, 144 },
{ 144, 0, 135, 0, 26375, 48, 144 },
{ 144, 0, 180, 24500, 24500, 48, 144 },
{ 144, 0, 215, 23041, 23041, 48, 144 },
{ 144, 0, 270, 20750, 20750, 48, 144 },
{ 144, 0, 315, 18875, 18875, 48, 144 },
{ 144, 0, 360, 17000, 17000, 48, 144 },
{ 144, 40, 0, 333, 333, 8, 104 },
{ 144, 40, 45, 0, 28458, 8, 104 },
{ 144, 40, 90, 0, 26583, 8, 104 },
{ 144, 40, 135, 0, 24708, 8, 104 },
{ 144, 40, 180, 22833, 22833, 8, 104 },
{ 144, 40, 215, 21375, 21375, 8, 104 },
{ 144, 40, 270, 19083, 19083, 8, 104 },
{ 144, 40, 315, 17208, 17208, 8, 104 },
{ 144, 40, 360, 15333, 15333, 8, 104 },
{ 180, -40, 0, 5166, 5166, 124, 220 },
{ 180, -40, 45, 3291, 3291, 124, 220 },
{ 180, -40, 90, 1416, 1416, 124, 220 },
{ 180, -40, 135, 0, 29541, 124, 220 },
{ 180, -40, 180, 27666, 27666, 124, 220 },
{ 180, -40, 215, 26208, 26208, 124, 220 },
{ 180, -40, 270, 23916, 23916, 124, 220 },
{ 180, -40, 315, 22041, 22041, 124, 220 },
{ 180, -40, 360, 20166, 20166, 124, 220 },
{ 180, 0, 0, 3500, 3500, 84, 180 },
{ 180, 0, 45, 1625, 1625, 84, 180 },
{ 180, 0, 90, 0, 29750, 84, 180 },
{ 180, 0, 135, 0, 27875, 84, 180 },
{ 180, 0, 180, 26000, 26000, 84, 180 },
{ 180, 0, 215, 24541, 24541, 84, 180 },
{ 180, 0, 270, 22250, 22250, 84, 180 },
{ 180, 0, 315, 20375, 20375, 84, 180 },
{ 180, 0, 360, 18500, 18500, 84, 180 },
{ 180, 40, 0, 1833, 1833, 44, 140 },
{ 180, 40, 45, 0, 29958, 44, 140 },
{ 180, 40, 90, 0, 28083, 44, 140 },
{ 180, 40, 135, 0, 26208, 44, 140 },
{ 180, 40, 180, 24333, 24333, 44, 140 },
{ 180, 40, 215, 22875, 22875, 44, 140 },
{ 180, 40, 270, 20583, 20583, 44, 140 },
{ 180, 40, 315, 18708, 18708, 44, 140 },
{ 180, 40, 360, 16833, 16833, 44, 140 },
{ 270, -40, 0, 8916, 8916, 214, 310 },
{ 270, -40, 45, 7041, 7041, 214, 310 },
{ 270, -40, 90, 5166, 5166, 214, 310 },
{ 270, -40, 135, 3291, 3291, 214, 310 },
{ 270, -40, 180, 1416, 1416, 214, 310 },
{ 270, -40, 215, 0, 29958, 214, 310 },
{ 270, -40, 270, 27666, 27666, 214, 310 },
{ 270, -40, 315, 25791, 25791, 214, 310 },
{ 270, -40, 360, 23916, 23916, 214, 310 },
{ 270, 0, 0, 7250, 7250, 174, 270 },
{ 270, 0, 45, 5375, 5375, 174, 270 },
{ 270, 0, 90, 3500, 3500, 174, 270 },
{ 270, 0, 135, 1625, 1625, 174, 270 },
{ 270, 0, 180, 0, 29750, 174, 270 },
{ 270, 0, 215, 0, 28291, 174, 270 },
{ 270, 0, 270, 26000, 26000, 174, 270 },
{ 270, 0, 315, 24125, 24125, 174, 270 },
{ 270, 0, 360, 22250, 22250, 174, 270 },
{ 270, 40, 0, 5583, 5583, 134, 230 },
{ 270, 40, 45, 3708, 3708, 134, 230 },
{ 270, 40, 90, 1833, 1833, 134, 230 },
{ 270, 40, 135, 0, 29958, 134, 230 },
{ 270, 40, 180, 0, 28083, 134, 230 },
{ 270, 40, 215, 0, 26625, 134, 230 },
{ 270, 40, 270, 24333, 24333, 134, 230 },
{ 270, 40, 315, 22458, 22458, 134, 230 },
{ 270, 40, 360, 20583, 20583, 134, 230 },
{ 360, -40, 0, 12666, 12666, 304, 400 },
{ 360, -40, 45, 10791, 10791, 304, 400 },
{ 360, -40, 90, 8916, 8916, 304, 400 },
{ 360, -40, 135, 7041, 7041, 304, 400 },
{ 360, -40, 180, 5166, 5166, 304, 400 },
{ 360, -40, 215, 3708, 3708, 304, 400 },
{ 360, -40, 270, 1416, 1416, 304, 400 },
{ 360, -40, 315, 0, 29541, 304, 400 },
{ 360, -40, 360, 27666, 27666, 304, 400 },
{ 360, 0, 0, 11000, 11000, 264, 360 },
{ 360, 0, 45, 9125, 9125, 264, 360 },
{ 360, 0, 90, 7250, 7250, 264, 360 },
{ 360, 0, 135, 5375, 5375, 264, 360 },
{ 360, 0, 180, 3500, 3500, 264, 360 },
{ 360, 0, 215, 2041, 2041, 264, 360 },
{ 360, 0, 270, 0, 29750, 264, 360 },
{ 360, 0, 315, 0, 27875, 264, 360 },
{ 360, 0, 360, 26000, 26000, 264, 360 },
{ 360, 40, 0, 9333, 9333, 224, 320 },
{ 360, 40, 45, 7458, 7458, 224, 320 },
{ 360, 40, 90, 5583, 5583, 224, 320 },
{ 360, 40, 135, 3708, 3708, 224, 320 },
{ 360, 40, 180, 1833, 1833, 224, 320 },
{ 360, 40, 215, 375, 375, 224, 320 },
{ 360, 40, 270, 0, 28083, 224, 320 },
{ 360, 40, 315, 0, 26208, 224, 320 },
{ 360, 40, 360, 24333, 24333, 224, 320 },
{ 432, -40, 0, 15666, 15666, 376, 472 },
{ 432, -40, 45, 13791, 13791, 376, 472 },
{ 432, -40, 90, 11916, 11916, 376, 472 },
{ 432, -40, 135, 10041, 10041, 376, 472 },
{ 432, -40, 180, 8166, 8166, 376, 472 },
{ 432, -40, 215, 6708, 6708, 376, 472 },
{ 432, -40, 270, 4416, 4416, 376, 472 },
{ 432, -40, 315, 2541, 2541, 376, 472 },
{ 432, -40, 360, 666, 666, 376, 472 },
{ 432, 0, 0, 14000, 14000, 336, 432 },
{ 432, 0, 45, 12125, 12125, 336, 432 },
{ 432, 0, 90, 10250, 10250, 336, 432 },
{ 432, 0, 135, 8375, 8375, 336, 432 },
{ 432, 0, 180, 6500, 6500, 336, 432 },
{ 432, 0, 215, 5041, 5041, 336, 432 },
{ 432, 0, 270, 2750, 2750, 336, 432 },
{ 432, 0, 315, 875, 875, 336, 432 },
{ 432, 0, 360, 0, 29000, 336, 432 },
{ 432, 40, 0, 12333, 12333, 296, 392 },
{ 432, 40, 45, 10458, 10458, 296, 392 },
{ 432, 40, 90, 8583, 8583, 296, 392 },
{ 432, 40, 135, 6708, 6708, 296, 392 },
{ 432, 40, 180, 4833, 4833, 296, 392 },
{ 432, 40, 215, 3375, 3375, 296, 392 },
{ 432, 40, 270, 1083, 1083, 296, 392 },
{ 432, 40, 315, 0, 29208, 296, 392 },
{ 432, 40, 360, 0, 27333, 296, 392 },
{ 576, -40, 0, 21666, 21666, 520, 616 },
{ 576, -40, 45, 19791, 19791, 520, 616 },
{ 576, -40, 90, 17916, 17916, 520, 616 },
{ 576, -40, 135, 16041, 16041, 520, 616 },
{ 576, -40, 180, 14166, 14166, 520, 616 },
{ 576, -40, 215, 12708, 12708, 520, 616 },
{ 576, -40, 270, 10416, 10416, 520, 616 },
{ 576, -40, 315, 8541, 8541, 520, 616 },
{ 576, -40, 360, 6666, 6666, 520, 616 },
{ 576, 0, 0, 20000, 20000, 480, 576 },
{ 576, 0, 45, 18125, 18125, 480, 576 },
{ 576, 0, 90, 16250, 16250, 480, 576 },
{ 576, 0, 135, 14375, 14375, 480, 576 },
{ 576, 0, 180, 12500, 12500, 480, 576 },
{ 576, 0, 215, 11041, 11041, 480, 576 },
{ 576, 0, 270, 8750, 8750, 480, 576 },
{ 576, 0, 315, 6875, 6875, 480, 576 },
{ 576, 0, 360, 5000, 5000, 480, 576 },
{ 576, 40, 0, 18333, 18333, 440, 536 },
{ 576, 40, 45, 16458, 16458, 440, 536 },
{ 576, 40, 90, 14583, 14583, 440, 536 },
{ 576, 40, 135, 12708, 12708, 440, 536 },
{ 576, 40, 180, 10833, 10833, 440, 536 },
{ 576, 40, 215, 9375, 9375, 440, 536 },
{ 576, 40, 270, 7083, 7083, 440, 536 },
{ 576, 40, 315, 5208, 5208, 440, 536 },
{ 576, 40, 360, 3333, 3333, 440, 536 },
{ 600, -40, 0, 22666, 22666, 544, 640 },
{ 600, -40, 45, 20791, 20791, 544, 640 },
{ 600, -40, 90, 18916, 18916, 544, 640 },
{ 600, -40, 135, 17041, 17041, 544, 640 },
{ 600, -40, 180, 15166, 15166, 544, 640 },
{ 600, -40, 215, 13708, 13708, 544, 640 },
{ 600, -40, 270, 11416, 11416, 544, 640 },
{ 600, -40, 315, 9541, 9541, 544, 640 },
{ 600, -40, 360, 7666, 7666, 544, 640 },
{ 600, 0, 0, 21000, 21000, 504, 600 },
{ 600, 0, 45, 19125, 19125, 504, 600 },
{ 600, 0, 90, 17250, 17250, 504, 600 },
{ 600, 0, 135, 15375, 15375, 504, 600 },
{ 600, 0, 180, 13500, 13500, 504, 600 },
{ 600, 0, 215, 12041, 12041, 504, 600 },
{ 600, 0, 270, 9750, 9750, 504, 600 },
{ 600, 0, 315, 7875, 7875, 504, 600 },
{ 600, 0, 360, 6000, 6000, 504, 600 },
{ 600, 40, 0, 19333, 19333, 464, 560 },
{ 600, 40, 45, 17458, 17458, 464, 560 },
{ 600, 40, 90, 15583, 15583, 464, 560 },
{ 600, 40, 135, 13708, 13708, 464, 560 },
{ 600, 40, 180, 11833, 11833, 464, 560 },
{ 600, 40, 215, 10375, 10375, 464, 560 },
{ 600, 40, 270, 8083, 8083, 464, 560 },
{ 600, 40, 315, 6208, 6208, 464, 560 },
{ 600, 40, 360, 4333, 4333, 464, 560 },
};
test_calc_ign_timeout(&test_data[0], &test_data[0]+_countof(test_data));
}
void test_rotary_channel_calcs(void)
{
setEngineSpeed(4000, 360);
static const int16_t test_data[][5] PROGMEM = {
// End Angle (deg), Dwell Angle, rotary split degrees, expected start angle, expected end angle
{ -40, 5, 0, -40, 315 },
{ -40, 95, 0, -40, 225 },
{ -40, 185, 0, -40, 135 },
{ -40, 275, 0, -40, 45 },
{ -40, 355, 0, -40, -35 },
{ -40, 5, 40, 0, 355 },
{ -40, 95, 40, 0, 265 },
{ -40, 185, 40, 0, 175 },
{ -40, 275, 40, 0, 85 },
{ -40, 355, 40, 0, 5 },
{ 0, 5, 0, 0, 355 },
{ 0, 95, 0, 0, 265 },
{ 0, 185, 0, 0, 175 },
{ 0, 275, 0, 0, 85 },
{ 0, 355, 0, 0, 5 },
{ 0, 5, 40, 40, 35 },
{ 0, 95, 40, 40, 305 },
{ 0, 185, 40, 40, 215 },
{ 0, 275, 40, 40, 125 },
{ 0, 355, 40, 40, 45 },
{ 40, 5, 0, 40, 35 },
{ 40, 95, 0, 40, 305 },
{ 40, 185, 0, 40, 215 },
{ 40, 275, 0, 40, 125 },
{ 40, 355, 0, 40, 45 },
{ 40, 5, 40, 80, 75 },
{ 40, 95, 40, 80, 345 },
{ 40, 185, 40, 80, 255 },
{ 40, 275, 40, 80, 165 },
{ 40, 355, 40, 80, 85 },
};
const int16_t (*pStart)[5] = &test_data[0];
const int16_t (*pEnd)[5] = &test_data[0]+_countof(test_data);
int16_t endAngle, startAngle;
int16_t local[5];
while (pStart!=pEnd)
{
memcpy_P(local, pStart, sizeof(local));
ignition2EndAngle = local[0];
calculateIgnitionTrailingRotary(local[1], local[2], local[0], &endAngle, &startAngle);
TEST_ASSERT_EQUAL(local[3], endAngle);
TEST_ASSERT_EQUAL(local[4], startAngle);
++pStart;
}
}
void test_calc_ign_timeout(void)
{
RUN_TEST(test_calc_ign_timeout_360);
RUN_TEST(test_calc_ign_timeout_720);
RUN_TEST(test_rotary_channel_calcs);
}
| 26,871
|
C++
|
.cpp
| 587
| 37.505963
| 220
| 0.485772
|
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,051
|
test_corrections.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202310/speeduino-202310/test/test_fuel/test_corrections.cpp
|
#include <globals.h>
#include <corrections.h>
#include <unity.h>
#include "test_corrections.h"
void testCorrections()
{
test_corrections_WUE();
test_corrections_dfco();
test_corrections_TAE(); //TPS based accel enrichment corrections
/*
RUN_TEST(test_corrections_cranking); //Not written yet
RUN_TEST(test_corrections_ASE); //Not written yet
RUN_TEST(test_corrections_floodclear); //Not written yet
RUN_TEST(test_corrections_closedloop); //Not written yet
RUN_TEST(test_corrections_flex); //Not written yet
RUN_TEST(test_corrections_bat); //Not written yet
RUN_TEST(test_corrections_iatdensity); //Not written yet
RUN_TEST(test_corrections_baro); //Not written yet
RUN_TEST(test_corrections_launch); //Not written yet
RUN_TEST(test_corrections_dfco); //Not written yet
*/
}
void test_corrections_WUE_active(void)
{
//Check for WUE being active
currentStatus.coolant = 0;
((uint8_t*)WUETable.axisX)[9] = 120 + CALIBRATION_TEMPERATURE_OFFSET; //Set a WUE end value of 120
correctionWUE();
TEST_ASSERT_BIT_HIGH(BIT_ENGINE_WARMUP, currentStatus.engine);
}
void test_corrections_WUE_inactive(void)
{
//Check for WUE being inactive due to the temp being too high
currentStatus.coolant = 200;
((uint8_t*)WUETable.axisX)[9] = 120 + CALIBRATION_TEMPERATURE_OFFSET; //Set a WUE end value of 120
correctionWUE();
TEST_ASSERT_BIT_LOW(BIT_ENGINE_WARMUP, currentStatus.engine);
}
void test_corrections_WUE_inactive_value(void)
{
//Check for WUE being set to the final row of the WUE curve if the coolant is above the max WUE temp
currentStatus.coolant = 200;
((uint8_t*)WUETable.axisX)[9] = 100;
((uint8_t*)WUETable.values)[9] = 123; //Use a value other than 100 here to ensure we are using the non-default value
//Force invalidate the cache
WUETable.cacheTime = currentStatus.secl - 1;
TEST_ASSERT_EQUAL(123, correctionWUE() );
}
void test_corrections_WUE_active_value(void)
{
//Check for WUE being made active and returning a correct interpolated value
currentStatus.coolant = 80;
//Set some fake values in the table axis. Target value will fall between points 6 and 7
((uint8_t*)WUETable.axisX)[0] = 0;
((uint8_t*)WUETable.axisX)[1] = 0;
((uint8_t*)WUETable.axisX)[2] = 0;
((uint8_t*)WUETable.axisX)[3] = 0;
((uint8_t*)WUETable.axisX)[4] = 0;
((uint8_t*)WUETable.axisX)[5] = 0;
((uint8_t*)WUETable.axisX)[6] = 70 + CALIBRATION_TEMPERATURE_OFFSET;
((uint8_t*)WUETable.axisX)[7] = 90 + CALIBRATION_TEMPERATURE_OFFSET;
((uint8_t*)WUETable.axisX)[8] = 100 + CALIBRATION_TEMPERATURE_OFFSET;
((uint8_t*)WUETable.axisX)[9] = 120 + CALIBRATION_TEMPERATURE_OFFSET;
((uint8_t*)WUETable.values)[6] = 120;
((uint8_t*)WUETable.values)[7] = 130;
//Force invalidate the cache
WUETable.cacheTime = currentStatus.secl - 1;
//Value should be midway between 120 and 130 = 125
TEST_ASSERT_EQUAL(125, correctionWUE() );
}
void test_corrections_WUE(void)
{
RUN_TEST(test_corrections_WUE_active);
RUN_TEST(test_corrections_WUE_inactive);
RUN_TEST(test_corrections_WUE_active_value);
RUN_TEST(test_corrections_WUE_inactive_value);
}
void test_corrections_cranking(void)
{
}
void test_corrections_ASE(void)
{
}
void test_corrections_floodclear(void)
{
}
void test_corrections_closedloop(void)
{
}
void test_corrections_flex(void)
{
}
void test_corrections_bat(void)
{
}
void test_corrections_iatdensity(void)
{
}
void test_corrections_baro(void)
{
}
void test_corrections_launch(void)
{
}
void setup_DFCO_on()
{
//Sets all the required conditions to have the DFCO be active
configPage2.dfcoEnabled = 1; //Ensure DFCO option is turned on
currentStatus.RPM = 4000; //Set the current simulated RPM to a level above the DFCO rpm threshold
currentStatus.TPS = 0; //Set the simulated TPS to 0
currentStatus.coolant = 80;
configPage4.dfcoRPM = 150; //DFCO enable RPM = 1500
configPage4.dfcoTPSThresh = 1;
configPage4.dfcoHyster = 25;
configPage2.dfcoMinCLT = 40; //Actually 0 with offset
configPage2.dfcoDelay = 10;
dfcoTaper = 1;
correctionDFCO();
dfcoTaper = 20;
}
//**********************************************************************************************************************
void test_corrections_dfco_on(void)
{
//Test under ideal conditions that DFCO goes active
setup_DFCO_on();
TEST_ASSERT_TRUE(correctionDFCO());
}
void test_corrections_dfco_off_RPM()
{
//Test that DFCO comes on and then goes off when the RPM drops below threshold
setup_DFCO_on();
TEST_ASSERT_TRUE(correctionDFCO()); //Make sure DFCO is on initially
currentStatus.RPM = 1000; //Set the current simulated RPM below the threshold + hyster
TEST_ASSERT_FALSE(correctionDFCO()); //Test DFCO is now off
}
void test_corrections_dfco_off_TPS()
{
//Test that DFCO comes on and then goes off when the TPS goes above the required threshold (ie not off throttle)
setup_DFCO_on();
TEST_ASSERT_TRUE(correctionDFCO()); //Make sure DFCO is on initially
currentStatus.TPS = 10; //Set the current simulated TPS to be above the threshold
TEST_ASSERT_FALSE(correctionDFCO()); //Test DFCO is now off
}
void test_corrections_dfco_off_delay()
{
//Test that DFCO comes will not activate if there has not been a long enough delay
//The steup function below simulates a 2 second delay
setup_DFCO_on();
//Set the threshold to be 2.5 seconds, above the simulated delay of 2s
configPage2.dfcoDelay = 250;
TEST_ASSERT_FALSE(correctionDFCO()); //Make sure DFCO does not come on
}
void test_corrections_dfco()
{
RUN_TEST(test_corrections_dfco_on);
RUN_TEST(test_corrections_dfco_off_RPM);
RUN_TEST(test_corrections_dfco_off_TPS);
RUN_TEST(test_corrections_dfco_off_delay);
}
//**********************************************************************************************************************
//Setup a basic TAE enrichment curve, threshold etc that are common to all tests. Specifica values maybe updated in each individual test
void test_corrections_TAE_setup()
{
configPage2.aeMode = AE_MODE_TPS; //Set AE to TPS
configPage4.taeValues[0] = 70;
configPage4.taeValues[1] = 103;
configPage4.taeValues[2] = 124;
configPage4.taeValues[3] = 136;
//Note: These values are divided by 10
configPage4.taeBins[0] = 0;
configPage4.taeBins[1] = 8;
configPage4.taeBins[2] = 22;
configPage4.taeBins[3] = 97;
configPage2.taeThresh = 0;
configPage2.taeMinChange = 0;
//Divided by 100
configPage2.aeTaperMin = 10; //1000
configPage2.aeTaperMax = 50; //5000
//Set the coolant to be above the warmup AE taper
configPage2.aeColdTaperMax = 60;
configPage2.aeColdTaperMin = 0;
currentStatus.coolant = (int)(configPage2.aeColdTaperMax - CALIBRATION_TEMPERATURE_OFFSET) + 1;
BIT_CLEAR(currentStatus.engine, BIT_ENGINE_ACC); //Make sure AE is turned off
BIT_CLEAR(currentStatus.engine, BIT_ENGINE_DCC); //Make sure AE is turned off
}
void test_corrections_TAE_no_rpm_taper()
{
//Disable the taper
currentStatus.RPM = 2000;
configPage2.aeTaperMin = 50; //5000
configPage2.aeTaperMax = 60; //6000
currentStatus.TPSlast = 0;
currentStatus.TPS = 50; //25% actual value
uint16_t accelValue = correctionAccel(); //Run the AE calcs
TEST_ASSERT_EQUAL(750, currentStatus.tpsDOT); //DOT is 750%/s (25 * 30)
TEST_ASSERT_EQUAL((100+132), accelValue);
TEST_ASSERT_TRUE(BIT_CHECK(currentStatus.engine, BIT_ENGINE_ACC)); //Confirm AE is flagged on
}
void test_corrections_TAE_50pc_rpm_taper()
{
//RPM is 50% of the way through the taper range
currentStatus.RPM = 3000;
configPage2.aeTaperMin = 10; //1000
configPage2.aeTaperMax = 50; //5000
currentStatus.TPSlast = 0;
currentStatus.TPS = 50; //25% actual value
uint16_t accelValue = correctionAccel(); //Run the AE calcs
TEST_ASSERT_EQUAL(750, currentStatus.tpsDOT); //DOT is 750%/s (25 * 30)
TEST_ASSERT_EQUAL((100+66), accelValue);
TEST_ASSERT_TRUE(BIT_CHECK(currentStatus.engine, BIT_ENGINE_ACC)); //Confirm AE is flagged on
}
void test_corrections_TAE_110pc_rpm_taper()
{
//RPM is 110% of the way through the taper range, which should result in no additional AE
currentStatus.RPM = 5400;
configPage2.aeTaperMin = 10; //1000
configPage2.aeTaperMax = 50; //5000
currentStatus.TPSlast = 0;
currentStatus.TPS = 50; //25% actual value
uint16_t accelValue = correctionAccel(); //Run the AE calcs
TEST_ASSERT_EQUAL(750, currentStatus.tpsDOT); //DOT is 750%/s (25 * 30)
TEST_ASSERT_EQUAL(100, accelValue); //Should be no AE as we're above the RPM taper end point
TEST_ASSERT_TRUE(BIT_CHECK(currentStatus.engine, BIT_ENGINE_ACC)); //Confirm AE is flagged on
}
void test_corrections_TAE_under_threshold()
{
//RPM is 50% of the way through the taper range, but TPS value will be below threshold
currentStatus.RPM = 3000;
configPage2.aeTaperMin = 10; //1000
configPage2.aeTaperMax = 50; //5000
currentStatus.TPSlast = 0;
currentStatus.TPS = 6; //3% actual value. TPSDot should be 90%/s
configPage2.taeThresh = 100; //Above the reading of 90%/s
uint16_t accelValue = correctionAccel(); //Run the AE calcs
TEST_ASSERT_EQUAL(90, currentStatus.tpsDOT); //DOT is 90%/s (3% * 30)
TEST_ASSERT_EQUAL(100, accelValue); //Should be no AE as we're above the RPM taper end point
TEST_ASSERT_FALSE(BIT_CHECK(currentStatus.engine, BIT_ENGINE_ACC)); //Confirm AE is flagged off
}
void test_corrections_TAE_50pc_warmup_taper()
{
//Disable the RPM taper
currentStatus.RPM = 2000;
configPage2.aeTaperMin = 50; //5000
configPage2.aeTaperMax = 60; //6000
currentStatus.TPSlast = 0;
currentStatus.TPS = 50; //25% actual value
//Set a cold % of 50% increase
configPage2.aeColdPct = 150;
configPage2.aeColdTaperMax = 60 + CALIBRATION_TEMPERATURE_OFFSET;
configPage2.aeColdTaperMin = 0 + CALIBRATION_TEMPERATURE_OFFSET;
//Set the coolant to be 50% of the way through the warmup range
currentStatus.coolant = 30;
uint16_t accelValue = correctionAccel(); //Run the AE calcs
TEST_ASSERT_EQUAL(750, currentStatus.tpsDOT); //DOT is 750%/s (25 * 30)
TEST_ASSERT_EQUAL((100+165), accelValue); //Total AE should be 132 + (50% * 50%) = 132 * 1.25 = 165
TEST_ASSERT_TRUE(BIT_CHECK(currentStatus.engine, BIT_ENGINE_ACC)); //Confirm AE is flagged on
}
void test_corrections_TAE()
{
test_corrections_TAE_setup();
RUN_TEST(test_corrections_TAE_no_rpm_taper);
BIT_CLEAR(currentStatus.engine, BIT_ENGINE_ACC); //Flag must be cleared between tests
RUN_TEST(test_corrections_TAE_50pc_rpm_taper);
BIT_CLEAR(currentStatus.engine, BIT_ENGINE_ACC); //Flag must be cleared between tests
RUN_TEST(test_corrections_TAE_110pc_rpm_taper);
BIT_CLEAR(currentStatus.engine, BIT_ENGINE_ACC); //Flag must be cleared between tests
RUN_TEST(test_corrections_TAE_under_threshold);
BIT_CLEAR(currentStatus.engine, BIT_ENGINE_ACC); //Flag must be cleared between tests
RUN_TEST(test_corrections_TAE_50pc_warmup_taper);
}
| 10,892
|
C++
|
.cpp
| 270
| 37.811111
| 136
| 0.730099
|
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,052
|
test_staging.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202310/speeduino-202310/test/test_fuel/test_staging.cpp
|
#include <globals.h>
#include <speeduino.h>
#include <unity.h>
#include "test_staging.h"
void testStaging(void)
{
RUN_TEST(test_Staging_Off);
RUN_TEST(test_Staging_4cyl_Auto_Inactive);
RUN_TEST(test_Staging_4cyl_Table_Inactive);
RUN_TEST(test_Staging_4cyl_Auto_50pct);
RUN_TEST(test_Staging_4cyl_Auto_33pct);
RUN_TEST(test_Staging_4cyl_Table_50pct);
}
void test_Staging_setCommon()
{
configPage2.nCylinders = 4;
currentStatus.RPM = 3000;
currentStatus.fuelLoad = 50;
inj_opentime_uS = 1000; //1ms inj open time
/*
These values are a percentage of the 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
*/
configPage10.stagedInjSizePri = 250;
configPage10.stagedInjSizeSec = 500;
uint32_t totalInjector = configPage10.stagedInjSizePri + configPage10.stagedInjSizeSec;
staged_req_fuel_mult_pri = (100 * totalInjector) / configPage10.stagedInjSizePri;
staged_req_fuel_mult_sec = (100 * totalInjector) / configPage10.stagedInjSizeSec;
}
void test_Staging_Off(void)
{
test_Staging_setCommon();
BIT_SET(currentStatus.status4, BIT_STATUS4_STAGING_ACTIVE);
configPage10.stagingEnabled = false;
uint32_t pwLimit = 9000; //90% duty cycle at 6000rpm
calculateStaging(pwLimit);
TEST_ASSERT_FALSE(BIT_CHECK(currentStatus.status4, BIT_STATUS4_STAGING_ACTIVE));
}
void test_Staging_4cyl_Auto_Inactive(void)
{
test_Staging_setCommon();
uint16_t testPW = 3000;
BIT_SET(currentStatus.status4, BIT_STATUS4_STAGING_ACTIVE);
configPage2.injLayout = INJ_PAIRED;
configPage10.stagingEnabled = true;
configPage10.stagingMode = STAGING_MODE_AUTO;
currentStatus.PW1 = testPW; //Over open time but below the pwLimit set below
uint32_t pwLimit = 9000; //90% duty cycle at 6000rpm
calculateStaging(pwLimit);
//PW 1 and 2 should be normal, 3 and 4 should be 0 as that testPW is below the pwLimit
//PW1/2 should be (PW - openTime) * staged_req_fuel_mult_pri = (3000 - 1000) * 3.0 = 6000
TEST_ASSERT_EQUAL(6000, currentStatus.PW1);
TEST_ASSERT_EQUAL(6000, currentStatus.PW2);
TEST_ASSERT_EQUAL(0, currentStatus.PW3);
TEST_ASSERT_EQUAL(0, currentStatus.PW4);
TEST_ASSERT_FALSE(BIT_CHECK(currentStatus.status4, BIT_STATUS4_STAGING_ACTIVE));
}
void test_Staging_4cyl_Table_Inactive(void)
{
test_Staging_setCommon();
uint16_t testPW = 3000;
BIT_SET(currentStatus.status4, BIT_STATUS4_STAGING_ACTIVE);
configPage2.injLayout = INJ_PAIRED;
configPage10.stagingEnabled = true;
configPage10.stagingMode = STAGING_MODE_TABLE;
currentStatus.PW1 = testPW; //Over open time but below the pwLimit set below
//Load the staging table with all 0
//For this test it doesn't matter what the X and Y axis are, as the table is all 0 values
for(byte x=0; x<64; x++) { stagingTable.values.values[x] = 0; }
uint32_t pwLimit = 9000; //90% duty cycle at 6000rpm
calculateStaging(pwLimit);
//PW 1 and 2 should be normal, 3 and 4 should be 0 as that testPW is below the pwLimit
//PW1/2 should be (PW - openTime) * staged_req_fuel_mult_pri = (3000 - 1000) * 3.0 = 6000
TEST_ASSERT_EQUAL(7000, currentStatus.PW1);
TEST_ASSERT_EQUAL(7000, currentStatus.PW2);
TEST_ASSERT_EQUAL(0, currentStatus.PW3);
TEST_ASSERT_EQUAL(0, currentStatus.PW4);
TEST_ASSERT_FALSE(BIT_CHECK(currentStatus.status4, BIT_STATUS4_STAGING_ACTIVE));
}
void test_Staging_4cyl_Auto_50pct(void)
{
test_Staging_setCommon();
uint16_t testPW = 9000;
BIT_CLEAR(currentStatus.status4, BIT_STATUS4_STAGING_ACTIVE);
configPage2.injLayout = INJ_PAIRED;
configPage10.stagingEnabled = true;
configPage10.stagingMode = STAGING_MODE_AUTO;
currentStatus.PW1 = testPW; //Over open time but below the pwLimit set below
uint32_t pwLimit = 9000; //90% duty cycle at 6000rpm
calculateStaging(pwLimit);
//PW 1 and 2 should be maxed out at the pwLimit, 3 and 4 should be based on their relative size
TEST_ASSERT_EQUAL(pwLimit, currentStatus.PW1); //PW1/2 run at maximum available limit
TEST_ASSERT_EQUAL(pwLimit, currentStatus.PW2);
TEST_ASSERT_EQUAL(9000, currentStatus.PW3);
TEST_ASSERT_EQUAL(9000, currentStatus.PW4);
TEST_ASSERT_TRUE(BIT_CHECK(currentStatus.status4, BIT_STATUS4_STAGING_ACTIVE));
}
void test_Staging_4cyl_Auto_33pct(void)
{
test_Staging_setCommon();
uint16_t testPW = 7000;
BIT_CLEAR(currentStatus.status4, BIT_STATUS4_STAGING_ACTIVE);
configPage2.injLayout = INJ_PAIRED;
configPage10.stagingEnabled = true;
configPage10.stagingMode = STAGING_MODE_AUTO;
currentStatus.PW1 = testPW; //Over open time but below the pwLimit set below
uint32_t pwLimit = 9000; //90% duty cycle at 6000rpm
calculateStaging(pwLimit);
//PW 1 and 2 should be maxed out at the pwLimit, 3 and 4 should be based on their relative size
TEST_ASSERT_EQUAL(pwLimit, currentStatus.PW1); //PW1/2 run at maximum available limit
TEST_ASSERT_EQUAL(pwLimit, currentStatus.PW2);
TEST_ASSERT_EQUAL(6000, currentStatus.PW3);
TEST_ASSERT_EQUAL(6000, currentStatus.PW4);
TEST_ASSERT_TRUE(BIT_CHECK(currentStatus.status4, BIT_STATUS4_STAGING_ACTIVE));
}
void test_Staging_4cyl_Table_50pct(void)
{
test_Staging_setCommon();
uint16_t testPW = 3000;
BIT_CLEAR(currentStatus.status4, BIT_STATUS4_STAGING_ACTIVE);
configPage2.injLayout = INJ_PAIRED;
configPage10.stagingEnabled = true;
configPage10.stagingMode = STAGING_MODE_TABLE;
currentStatus.PW1 = testPW; //Over open time but below the pwLimit set below
//Load the staging table with all 0
//For this test it doesn't matter what the X and Y axis are, as the table is all 50 values
for(byte x=0; x<64; x++) { stagingTable.values.values[x] = 50; }
uint32_t pwLimit = 9000; //90% duty cycle at 6000rpm
//Need to change the lookup values so we don't get a cached value
currentStatus.RPM += 1;
currentStatus.fuelLoad += 1;
calculateStaging(pwLimit);
TEST_ASSERT_EQUAL(4000, currentStatus.PW1);
TEST_ASSERT_EQUAL(4000, currentStatus.PW2);
TEST_ASSERT_EQUAL(2500, currentStatus.PW3);
TEST_ASSERT_EQUAL(2500, currentStatus.PW4);
TEST_ASSERT_TRUE(BIT_CHECK(currentStatus.status4, BIT_STATUS4_STAGING_ACTIVE));
}
| 6,530
|
C++
|
.cpp
| 143
| 42.643357
| 157
| 0.760069
|
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,053
|
test_PW.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202310/speeduino-202310/test/test_fuel/test_PW.cpp
|
#include <globals.h>
#include <speeduino.h>
#include <unity.h>
#include "test_PW.h"
#define PW_ALLOWED_ERROR 30
void testPW(void)
{
RUN_TEST(test_PW_No_Multiply);
RUN_TEST(test_PW_MAP_Multiply);
RUN_TEST(test_PW_MAP_Multiply_Compatibility);
RUN_TEST(test_PW_AFR_Multiply);
RUN_TEST(test_PW_Large_Correction);
RUN_TEST(test_PW_Very_Large_Correction);
RUN_TEST(test_PW_4Cyl_PW0);
}
int16_t REQ_FUEL;
byte VE;
long MAP;
uint16_t corrections;
int injOpen;
void test_PW_setCommon()
{
REQ_FUEL = 1060;
VE = 130;
MAP = 94;
corrections = 113;
injOpen = 1000;
}
void test_PW_No_Multiply()
{
test_PW_setCommon();
configPage2.multiplyMAP = 0;
configPage2.includeAFR = 0;
configPage2.incorporateAFR = 0;
configPage2.aeApplyMode = 0;
uint16_t result = PW(REQ_FUEL, VE, MAP, corrections, injOpen);
TEST_ASSERT_UINT16_WITHIN(PW_ALLOWED_ERROR, 2557, result);
}
void test_PW_MAP_Multiply()
{
test_PW_setCommon();
configPage2.multiplyMAP = 1;
currentStatus.baro = 103;
configPage2.includeAFR = 0;
configPage2.incorporateAFR = 0;
configPage2.aeApplyMode = 0;
uint16_t result = PW(REQ_FUEL, VE, MAP, corrections, injOpen);
TEST_ASSERT_UINT16_WITHIN(PW_ALLOWED_ERROR, 2400, result);
}
void test_PW_MAP_Multiply_Compatibility()
{
test_PW_setCommon();
configPage2.multiplyMAP = 2; //Divide MAP reading by 100 rather than by Baro reading
currentStatus.baro = 103;
configPage2.includeAFR = 0;
configPage2.incorporateAFR = 0;
configPage2.aeApplyMode = 0;
uint16_t result = PW(REQ_FUEL, VE, MAP, corrections, injOpen);
TEST_ASSERT_UINT16_WITHIN(PW_ALLOWED_ERROR, 2449, result);
}
void test_PW_AFR_Multiply()
{
test_PW_setCommon();
configPage2.multiplyMAP = 0;
currentStatus.baro = 100;
configPage2.includeAFR = 1;
configPage2.incorporateAFR = 0;
configPage2.aeApplyMode = 0;
configPage6.egoType = 2; //Set O2 sensor type to wideband
currentStatus.runSecs = 20; configPage6.ego_sdelay = 10; //Ensure that the run time is longer than the O2 warmup time
currentStatus.O2 = 150;
currentStatus.afrTarget = 147;
uint16_t result = PW(REQ_FUEL, VE, MAP, corrections, injOpen);
TEST_ASSERT_UINT16_WITHIN(PW_ALLOWED_ERROR, 2588, result);
}
/*
To avoid overflow errors, the PW() function reduces accuracy slightly when the corrections figure becomes large.
There are 3 levels of this:
1) Corrections below 511 - No change in accuracy
2) Corrections between 512 and 1023 - Minor reduction to accuracy
3) Corrections above 1023 - Further reduction to accuracy
*/
void test_PW_Large_Correction()
{
//This is the same as the test_PW_No_Multiply, but with correction changed to 600
test_PW_setCommon();
corrections = 600;
configPage2.multiplyMAP = 0;
configPage2.includeAFR = 0;
configPage2.incorporateAFR = 0;
configPage2.aeApplyMode = 0;
uint16_t result = PW(REQ_FUEL, VE, MAP, corrections, injOpen);
TEST_ASSERT_UINT16_WITHIN(PW_ALLOWED_ERROR, 9268, result);
}
void test_PW_Very_Large_Correction()
{
//This is the same as the test_PW_No_Multiply, but with correction changed to 1500
test_PW_setCommon();
corrections = 1500;
configPage2.multiplyMAP = 0;
configPage2.includeAFR = 0;
configPage2.incorporateAFR = 0;
configPage2.aeApplyMode = 0;
uint16_t result = PW(REQ_FUEL, VE, MAP, corrections, injOpen);
TEST_ASSERT_UINT16_WITHIN(PW_ALLOWED_ERROR+30, 21670, result); //Additional allowed error here
}
//Test that unused pulse width values are set to 0
//This test is for a 4 cylinder using paired injection where only INJ 1 and 2 should have PW > 0
void test_PW_4Cyl_PW0(void)
{
test_PW_setCommon();
configPage2.nCylinders = 4;
configPage2.injLayout = INJ_PAIRED;
configPage10.stagingEnabled = false; //Staging must be off or channels 3 and 4 will be used
loop();
TEST_ASSERT_EQUAL(0, currentStatus.PW3);
TEST_ASSERT_EQUAL(0, currentStatus.PW4);
}
| 3,890
|
C++
|
.cpp
| 118
| 30.440678
| 119
| 0.749933
|
oelprinz-org/BlitzboxBL49sp
| 36
| 12
| 0
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,540,054
|
test_fuel.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202310/speeduino-202310/test/test_fuel/test_fuel.cpp
|
#include <globals.h>
#include <init.h>
#include <Arduino.h>
#include <unity.h>
#include "test_corrections.h"
#include "test_PW.h"
#include "test_staging.h"
#define UNITY_EXCLUDE_DETAILS
void setup()
{
pinMode(LED_BUILTIN, OUTPUT);
// NOTE!!! Wait for >2 secs
// if board doesn't support software reset via Serial.DTR/RTS
delay(2000);
UNITY_BEGIN(); // IMPORTANT LINE!
initialiseAll(); //Run the main initialise function
testCorrections();
testPW();
testStaging();
UNITY_END(); // stop unit testing
}
void loop()
{
// Blink to indicate end of test
digitalWrite(LED_BUILTIN, HIGH);
delay(250);
digitalWrite(LED_BUILTIN, LOW);
delay(250);
}
| 708
|
C++
|
.cpp
| 29
| 21.103448
| 65
| 0.683036
|
oelprinz-org/BlitzboxBL49sp
| 36
| 12
| 0
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,540,055
|
schedule_calcs.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202310/speeduino-202310/speeduino/schedule_calcs.cpp
|
#include "schedule_calcs.h"
byte channelInjEnabled = 0;
int ignition1StartAngle;
int ignition1EndAngle;
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) */
int ignition2StartAngle;
int ignition2EndAngle;
int channel2IgnDegrees; /**< The number of crank degrees until cylinder 2 (and 5/6/7/8) is at TDC */
int ignition3StartAngle;
int ignition3EndAngle;
int channel3IgnDegrees; /**< The number of crank degrees until cylinder 2 (and 5/6/7/8) is at TDC */
int ignition4StartAngle;
int ignition4EndAngle;
int channel4IgnDegrees; /**< The number of crank degrees until cylinder 2 (and 5/6/7/8) is at TDC */
#if (IGN_CHANNELS >= 5)
int ignition5StartAngle;
int ignition5EndAngle;
int channel5IgnDegrees; /**< The number of crank degrees until cylinder 2 (and 5/6/7/8) is at TDC */
#endif
#if (IGN_CHANNELS >= 6)
int ignition6StartAngle;
int ignition6EndAngle;
int channel6IgnDegrees; /**< The number of crank degrees until cylinder 2 (and 5/6/7/8) is at TDC */
#endif
#if (IGN_CHANNELS >= 7)
int ignition7StartAngle;
int ignition7EndAngle;
int channel7IgnDegrees; /**< The number of crank degrees until cylinder 2 (and 5/6/7/8) is at TDC */
#endif
#if (IGN_CHANNELS >= 8)
int ignition8StartAngle;
int ignition8EndAngle;
int channel8IgnDegrees; /**< The number of crank degrees until cylinder 2 (and 5/6/7/8) is at TDC */
#endif
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) */
int channel2InjDegrees; /**< The number of crank degrees until cylinder 2 (and 5/6/7/8) is at TDC */
int channel3InjDegrees; /**< The number of crank degrees until cylinder 3 (and 5/6/7/8) is at TDC */
int channel4InjDegrees; /**< The number of crank degrees until cylinder 4 (and 5/6/7/8) is at TDC */
#if (INJ_CHANNELS >= 5)
int channel5InjDegrees; /**< The number of crank degrees until cylinder 5 is at TDC */
#endif
#if (INJ_CHANNELS >= 6)
int channel6InjDegrees; /**< The number of crank degrees until cylinder 6 is at TDC */
#endif
#if (INJ_CHANNELS >= 7)
int channel7InjDegrees; /**< The number of crank degrees until cylinder 7 is at TDC */
#endif
#if (INJ_CHANNELS >= 8)
int channel8InjDegrees; /**< The number of crank degrees until cylinder 8 is at TDC */
#endif
| 2,383
|
C++
|
.cpp
| 50
| 46.48
| 163
| 0.757745
|
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,056
|
comms.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202310/speeduino-202310/speeduino/comms.cpp
|
/*
Speeduino - Simple engine management for the Arduino Mega 2560 platform
Copyright (C) Josh Stewart
A full copy of the license may be found in the projects root directory
*/
/** @file
* Process Incoming and outgoing serial communications.
*/
#include "globals.h"
#include "comms.h"
#include "comms_secondary.h"
#include "storage.h"
#include "maths.h"
#include "utilities.h"
#include "decoders.h"
#include "TS_CommandButtonHandler.h"
#include "errors.h"
#include "pages.h"
#include "page_crc.h"
#include "logger.h"
#include "comms_legacy.h"
#include "src/FastCRC/FastCRC.h"
#include <avr/pgmspace.h>
#ifdef RTC_ENABLED
#include "rtc_common.h"
#include "comms_sd.h"
#endif
#ifdef SD_LOGGING
#include "SD_logger.h"
#endif
// Forward declarations
/** @brief Processes a message once it has been fully recieved */
void processSerialCommand(void);
/** @brief Should be called when ::serialStatusFlag == SERIAL_TRANSMIT_TOOTH_INPROGRESS, */
void sendToothLog(void);
/** @brief Should be called when ::serialStatusFlag == LOG_SEND_COMPOSITE */
void sendCompositeLog(void);
#define SERIAL_RC_OK 0x00 //!< Success
#define SERIAL_RC_REALTIME 0x01 //!< Unused
#define SERIAL_RC_PAGE 0x02 //!< Unused
#define SERIAL_RC_BURN_OK 0x04 //!< EEPROM write succeeded
#define SERIAL_RC_TIMEOUT 0x80 //!< Timeout error
#define SERIAL_RC_CRC_ERR 0x82 //!< CRC mismatch
#define SERIAL_RC_UKWN_ERR 0x83 //!< Unknown command
#define SERIAL_RC_RANGE_ERR 0x84 //!< Incorrect range. TS will not retry command
#define SERIAL_RC_BUSY_ERR 0x85 //!< TS will wait and retry
#define SERIAL_LEN_SIZE 2U
#define SERIAL_TIMEOUT 3000 //ms
#define SEND_OUTPUT_CHANNELS 48U
//!@{
/** @brief Hard coded response for some TS messages.
* @attention Stored in flash (.text segment) and loaded on demand.
*/
constexpr byte serialVersion[] PROGMEM = {SERIAL_RC_OK, '0', '0', '2'};
constexpr byte canId[] PROGMEM = {SERIAL_RC_OK, 0};
//constexpr byte codeVersion[] PROGMEM = { SERIAL_RC_OK, 's','p','e','e','d','u','i','n','o',' ','2','0','2','3','0','6','-','d','e','v'} ; //Note no null terminator in array and statu variable at the start
//constexpr byte productString[] PROGMEM = { SERIAL_RC_OK, 'S', 'p', 'e', 'e', 'd', 'u', 'i', 'n', 'o', ' ', '2', '0', '2', '3', '.', '0', '6', '-', 'd', 'e', 'v'};
constexpr byte codeVersion[] PROGMEM = { SERIAL_RC_OK, 's','p','e','e','d','u','i','n','o',' ','2','0','2','3','1','0'} ; //Note no null terminator in array and statu variable at the start
constexpr byte productString[] PROGMEM = { SERIAL_RC_OK, 'S', 'p', 'e', 'e', 'd', 'u', 'i', 'n', 'o', ' ', '2', '0', '2', '3', '.', '1', '0'};
constexpr byte testCommsResponse[] PROGMEM = { SERIAL_RC_OK, 255 };
//!@}
/** @brief The number of bytes received or transmitted to date during nonblocking I/O.
*
* @attention We can share one variable between rx & tx because we only support simpex serial comms.
* I.e. we can only be receiving or transmitting at any one time.
*/
static uint16_t serialBytesRxTx = 0;
static uint32_t serialReceiveStartTime = 0; //!< The time at which the serial receive started. Used for calculating whether a timeout has occurred */
static FastCRC32 CRC32_serial; //!< Support accumulation of a CRC during non-blocking operations */
using crc_t = uint32_t;
#ifdef RTC_ENABLED
#undef SERIAL_BUFFER_SIZE
/** @brief Serial payload buffer must be significantly larger for boards that support SD logging.
*
* Large enough to contain 4 sectors + overhead
*/
#define SERIAL_BUFFER_SIZE (2048 + 3)
static uint16_t SDcurrentDirChunk;
static uint32_t SDreadStartSector;
static uint32_t SDreadNumSectors;
static uint32_t SDreadCompletedSectors = 0;
#endif
static uint8_t serialPayload[SERIAL_BUFFER_SIZE]; //!< Serial payload buffer. */
static uint16_t serialPayloadLength = 0; //!< How many bytes in serialPayload were received or sent */
#if defined(CORE_AVR)
#pragma GCC push_options
// These minimize RAM usage at no performance cost
#pragma GCC optimize ("Os")
#endif
static inline bool isTimeout(void) {
return (millis() - serialReceiveStartTime) > SERIAL_TIMEOUT;
}
// ====================================== Endianess Support =============================
/**
* @brief Flush all remaining bytes from the rx serial buffer
*/
void flushRXbuffer(void)
{
while (Serial.available() > 0) { Serial.read(); }
}
/** @brief Reverse the byte order of a uint32_t
*
* @attention noinline is needed to prevent enlarging callers stack frame, which in turn throws
* off free ram reporting.
* */
static __attribute__((noinline)) uint32_t reverse_bytes(uint32_t i)
{
return ((i>>24) & 0xffU) | // move byte 3 to byte 0
((i<<8 ) & 0xff0000U) | // move byte 1 to byte 2
((i>>8 ) & 0xff00U) | // move byte 2 to byte 1
((i<<24) & 0xff000000U);
}
// ====================================== Blocking IO Support ================================
void writeByteReliableBlocking(byte value) {
// Some platforms (I'm looking at you Teensy 3.5) do not mimic the Arduino 1.0
// contract and synchronously block.
// https://github.com/PaulStoffregen/cores/blob/master/teensy3/usb_serial.c#L215
while (!Serial.availableForWrite()) { /* Wait for the buffer to free up space */ }
Serial.write(value);
}
// ====================================== Multibyte Primitive IO Support =============================
/** @brief Read a uint32_t from Serial
*
* @attention noinline is needed to prevent enlarging callers stack frame, which in turn throws
* off free ram reporting.
* */
static __attribute__((noinline)) uint32_t readSerial32Timeout(void)
{
union {
char raw[sizeof(uint32_t)];
uint32_t value;
} buffer;
// Teensy 3.5: Serial.available() should only be used as a boolean test
// See https://www.pjrc.com/teensy/td_serial.html#singlebytepackets
size_t count=0;
while (count < sizeof(buffer.value)) {
if (Serial.available()!=0) {
buffer.raw[count++] =(byte)Serial.read();
} else if(isTimeout()) {
return 0;
} else { /* MISRA - no-op */ }
}
return reverse_bytes(buffer.value);
}
/** @brief Write a uint32_t to Serial
* @returns The value as transmitted on the wire
*/
static uint32_t serialWrite(uint32_t value)
{
value = reverse_bytes(value);
const byte *pBuffer = (const byte*)&value;
writeByteReliableBlocking(pBuffer[0]);
writeByteReliableBlocking(pBuffer[1]);
writeByteReliableBlocking(pBuffer[2]);
writeByteReliableBlocking(pBuffer[3]);
return value;
}
/** @brief Write a uint16_t to Serial */
static void serialWrite(uint16_t value)
{
writeByteReliableBlocking((value >> 8U) & 255U);
writeByteReliableBlocking(value & 255U);
}
// ====================================== Non-blocking IO Support =============================
/** @brief Send as much data as possible without blocking the caller
* @return Number of bytes sent
*/
static uint16_t writeNonBlocking(const byte *buffer, size_t length)
{
uint16_t bytesTransmitted = 0;
while (bytesTransmitted<length
&& Serial.availableForWrite() != 0
// Just in case
&& Serial.write(buffer[bytesTransmitted]) == 1)
{
bytesTransmitted++;
}
return bytesTransmitted;
// This doesn't work on Teensy.
// See https://github.com/PaulStoffregen/cores/issues/10#issuecomment-61514955
// size_t capacity = min((size_t)Serial.availableForWrite(), length);
// return Serial.write(buffer, capacity);
}
/** @brief Write a uint32_t to Serial without blocking the caller
* @return Number of bytes sent
*/
static size_t writeNonBlocking(size_t start, uint32_t value)
{
value = reverse_bytes(value);
const byte *pBuffer = (const byte*)&value;
return writeNonBlocking(pBuffer+start, sizeof(value)-start); //cppcheck-suppress misra-c2012-17.2
}
/** @brief Send the buffer, followed by it's CRC
*
* This is supposed to be called multiple times for the same buffer until
* it's all sent.
*
* @param start Index into the buffer to start sending at. [0, length)
* @param length Total size of the buffer
* @return Cumulative total number of bytes written . I.e. the next start value
*/
static uint16_t sendBufferAndCrcNonBlocking(const byte *buffer, size_t start, size_t length)
{
if (start<length)
{
start = start + writeNonBlocking(buffer+start, length-start);
}
if (start>=length && start<length+sizeof(crc_t))
{
start = start + writeNonBlocking(start-length, CRC32_serial.crc32(buffer, length));
}
return start;
}
/** @brief Start sending the shared serialPayload buffer.
*
* ::serialStatusFlag will be signal the result of the send:<br>
* ::serialStatusFlag == SERIAL_INACTIVE: send is complete <br>
* ::serialStatusFlag == SERIAL_TRANSMIT_INPROGRESS: partial send, subsequent calls to continueSerialTransmission
* will finish sending serialPayload
*
* @param payloadLength How many bytes to send [0, sizeof(serialPayload))
*/
static void sendSerialPayloadNonBlocking(uint16_t payloadLength)
{
//Start new transmission session
serialStatusFlag = SERIAL_TRANSMIT_INPROGRESS;
serialWrite(payloadLength);
serialPayloadLength = payloadLength;
serialBytesRxTx = sendBufferAndCrcNonBlocking(serialPayload, 0, payloadLength);
serialStatusFlag = serialBytesRxTx==payloadLength+sizeof(crc_t) ? SERIAL_INACTIVE : SERIAL_TRANSMIT_INPROGRESS;
}
// ====================================== TS Message Support =============================
/** @brief Send a message to TS containing only a return code.
*
* This is used when TS asks for an action to happen (E.g. start a logger) or
* to signal an error condition to TS
*
* @attention This is a blocking operation
*/
static void sendReturnCodeMsg(byte returnCode)
{
serialWrite((uint16_t)sizeof(returnCode));
writeByteReliableBlocking(returnCode);
serialWrite(CRC32_serial.crc32(&returnCode, sizeof(returnCode)));
}
// ====================================== Command/Action Support =============================
// The functions in this section are abstracted out to prevent enlarging callers stack frame,
// which in turn throws off free ram reporting.
/**
* @brief Update a pages contents from a buffer
*
* @param pageNum The index of the page to update
* @param offset Offset into the page
* @param buffer The buffer to read from
* @param length The buffer length
* @return true if page updated successfully
* @return false if page cannot be updated
*/
static bool updatePageValues(uint8_t pageNum, uint16_t offset, const byte *buffer, uint16_t length)
{
if ( (offset + length) <= getPageSize(pageNum) )
{
for(uint16_t i = 0; i < length; i++)
{
setPageValue(pageNum, (offset + i), buffer[i]);
}
deferEEPROMWritesUntil = micros() + EEPROM_DEFER_DELAY;
return true;
}
return false;
}
/**
* @brief Loads a pages contents into a buffer
*
* @param pageNum The index of the page to update
* @param offset Offset into the page
* @param buffer The buffer to read from
* @param length The buffer length
*/
static void loadPageValuesToBuffer(uint8_t pageNum, uint16_t offset, byte *buffer, uint16_t length)
{
for(uint16_t i = 0; i < length; i++)
{
buffer[i] = getPageValue(pageNum, offset + i);
}
}
/** @brief Send a status record back to tuning/logging SW.
* This will "live" information from @ref currentStatus struct.
* @param offset - Start field number
* @param packetLength - Length of actual message (after possible ack/confirm headers)
* E.g. tuning sw command 'A' (Send all values) will send data from field number 0, LOG_ENTRY_SIZE fields.
*/
static void generateLiveValues(uint16_t offset, uint16_t packetLength)
{
if(firstCommsRequest)
{
firstCommsRequest = false;
currentStatus.secl = 0;
}
currentStatus.spark ^= (-currentStatus.hasSync ^ currentStatus.spark) & (1U << BIT_SPARK_SYNC); //Set the sync bit of the Spark variable to match the hasSync variable
serialPayload[0] = SERIAL_RC_OK;
for(byte x=0; x<packetLength; x++)
{
serialPayload[x+1] = getTSLogEntry(offset+x);
}
// Reset any flags that are being used to trigger page refreshes
BIT_CLEAR(currentStatus.status3, BIT_STATUS3_VSS_REFRESH);
}
/**
* @brief Update the oxygen sensor table from serialPayload
*
* @param offset Offset into serialPayload and the table
* @param chunkSize Number of bytes available in serialPayload
*/
static void loadO2CalibrationChunk(uint16_t offset, uint16_t chunkSize)
{
using pCrcCalc = uint32_t (FastCRC32::*)(const uint8_t *, const uint16_t, bool);
// First pass through the loop, we need to INITIALIZE the CRC
pCrcCalc pCrcFun = offset==0U ? &FastCRC32::crc32 : &FastCRC32::crc32_upd;
uint32_t calibrationCRC = 0U;
//Read through the current chunk (Should be 256 bytes long)
// Note there are 2 loops here:
// [x, chunkSize)
// [offset, offset+chunkSize)
for(uint16_t x = 0; x < chunkSize; ++x, ++offset)
{
//TS sends a total of 1024 bytes of calibration data, broken up into 256 byte chunks
//As we're using an interpolated 2D table, we only need to store 32 values out of this 1024
if( (x % 32U) == 0U )
{
o2Calibration_values[offset/32U] = serialPayload[x+7U]; //O2 table stores 8 bit values
o2Calibration_bins[offset/32U] = offset;
}
//Update the CRC
calibrationCRC = (CRC32_serial.*pCrcFun)(&serialPayload[x+7U], 1, false);
// Subsequent passes through the loop, we need to UPDATE the CRC
pCrcFun = &FastCRC32::crc32_upd;
}
if( offset >= 1023 )
{
//All chunks have been received (1024 values). Finalise the CRC and burn to EEPROM
storeCalibrationCRC32(O2_CALIBRATION_PAGE, ~calibrationCRC);
writeCalibrationPage(O2_CALIBRATION_PAGE);
}
}
/**
* @brief Convert 2 bytes into an offset temperature in degrees Celcius
* @attention Returned value will be offset CALIBRATION_TEMPERATURE_OFFSET
*/
static uint16_t toTemperature(byte lo, byte hi)
{
int16_t tempValue = (int16_t)(word(hi, lo)); //Combine the 2 bytes into a single, signed 16-bit value
tempValue = tempValue / 10; //TS sends values multiplied by 10 so divide back to whole degrees.
tempValue = ((tempValue - 32) * 5) / 9; //Convert from F to C
//Apply the temp offset and check that it results in all values being positive
return max( tempValue + CALIBRATION_TEMPERATURE_OFFSET, 0 );
}
/**
* @brief Update a temperature calibration table from serialPayload
*
* @param calibrationLength The chunk size received from TS
* @param calibrationPage Index of the table
* @param values The table values
* @param bins The table bin values
*/
static void processTemperatureCalibrationTableUpdate(uint16_t calibrationLength, uint8_t calibrationPage, uint16_t *values, uint16_t *bins)
{
//Temperature calibrations are sent as 32 16-bit values
if(calibrationLength == 64U)
{
for (uint16_t x = 0; x < 32U; x++)
{
values[x] = toTemperature(serialPayload[(2U * x) + 7U], serialPayload[(2U * x) + 8U]);
bins[x] = (x * 33U); // 0*33=0 to 31*33=1023
}
storeCalibrationCRC32(calibrationPage, CRC32_serial.crc32(&serialPayload[7], 64));
writeCalibrationPage(calibrationPage);
sendReturnCodeMsg(SERIAL_RC_OK);
}
else
{
sendReturnCodeMsg(SERIAL_RC_RANGE_ERR);
}
}
// ====================================== End Internal Functions =============================
/** Processes the incoming data on the serial buffer based on the command sent.
Can be either data for a new command or a continuation of data for command that is already in progress:
Comands are single byte (letter symbol) commands.
*/
void serialReceive(void)
{
//Check for an existing legacy command in progress
if(serialStatusFlag==SERIAL_COMMAND_INPROGRESS_LEGACY)
{
legacySerialCommand();
return;
}
if (Serial.available()!=0 && serialStatusFlag == SERIAL_INACTIVE)
{
//New command received
//Need at least 2 bytes to read the length of the command
byte highByte = (byte)Serial.peek();
//Check if the command is legacy using the call/response mechanism
if(highByte == 'F')
{
//F command is always allowed as it provides the initial serial protocol version.
legacySerialCommand();
return;
}
else if( (((highByte >= 'A') && (highByte <= 'z')) || (highByte == '?')) && (BIT_CHECK(currentStatus.status4, BIT_STATUS4_ALLOW_LEGACY_COMMS)) )
{
//Handle legacy cases here
legacySerialCommand();
return;
}
else
{
Serial.read();
while(Serial.available() == 0) { /* Wait for the 2nd byte to be received (This will almost never happen) */ }
serialPayloadLength = word(highByte, Serial.read());
serialBytesRxTx = 2;
serialStatusFlag = SERIAL_RECEIVE_INPROGRESS; //Flag the serial receive as being in progress
serialReceiveStartTime = millis();
}
}
//If there is a serial receive in progress, read as much from the buffer as possible or until we receive all bytes
while( (Serial.available() > 0) && (serialStatusFlag == SERIAL_RECEIVE_INPROGRESS) )
{
if (serialBytesRxTx < (serialPayloadLength + SERIAL_LEN_SIZE) )
{
serialPayload[serialBytesRxTx - SERIAL_LEN_SIZE] = (byte)Serial.read();
serialBytesRxTx++;
}
else
{
uint32_t incomingCrc = readSerial32Timeout();
serialStatusFlag = SERIAL_INACTIVE; //The serial receive is now complete
if (!isTimeout()) // CRC read can timeout also!
{
if (incomingCrc == CRC32_serial.crc32(serialPayload, serialPayloadLength))
{
//CRC is correct. Process the command
processSerialCommand();
BIT_CLEAR(currentStatus.status4, BIT_STATUS4_ALLOW_LEGACY_COMMS); //Lock out legacy commands until next power cycle
}
else {
//CRC Error. Need to send an error message
sendReturnCodeMsg(SERIAL_RC_CRC_ERR);
flushRXbuffer();
}
}
// else timeout - code below will kick in.
}
} //Data in serial buffer and serial receive in progress
//Check for a timeout
if( isTimeout() )
{
serialStatusFlag = SERIAL_INACTIVE; //Reset the serial receive
flushRXbuffer();
sendReturnCodeMsg(SERIAL_RC_TIMEOUT);
} //Timeout
}
void serialTransmit(void)
{
switch (serialStatusFlag)
{
case SERIAL_TRANSMIT_INPROGRESS_LEGACY:
sendValues(logItemsTransmitted, inProgressLength, SEND_OUTPUT_CHANNELS, Serial, serialStatusFlag);
break;
case SERIAL_TRANSMIT_TOOTH_INPROGRESS:
sendToothLog();
break;
case SERIAL_TRANSMIT_TOOTH_INPROGRESS_LEGACY:
sendToothLog_legacy(logItemsTransmitted);
break;
case SERIAL_TRANSMIT_COMPOSITE_INPROGRESS:
sendCompositeLog();
break;
case SERIAL_TRANSMIT_INPROGRESS:
serialBytesRxTx = sendBufferAndCrcNonBlocking(serialPayload, serialBytesRxTx, serialPayloadLength);
serialStatusFlag = serialBytesRxTx==serialPayloadLength+sizeof(crc_t) ? SERIAL_INACTIVE : SERIAL_TRANSMIT_INPROGRESS;
break;
default: // Nothing to do
break;
}
}
void processSerialCommand(void)
{
switch (serialPayload[0])
{
case 'A': // send x bytes of realtime values in legacy support format
generateLiveValues(0, LOG_ENTRY_SIZE);
break;
case 'b': // New EEPROM burn command to only burn a single page at a time
if( (micros() > deferEEPROMWritesUntil)) { writeConfig(serialPayload[2]); } //Read the table number and perform burn. Note that byte 1 in the array is unused
else { BIT_SET(currentStatus.status4, BIT_STATUS4_BURNPENDING); }
sendReturnCodeMsg(SERIAL_RC_BURN_OK);
break;
case 'B': // Same as above, but for the comms compat mode. Slows down the burn rate and increases the defer time
BIT_SET(currentStatus.status4, BIT_STATUS4_COMMS_COMPAT); //Force the compat mode
deferEEPROMWritesUntil += (EEPROM_DEFER_DELAY/4); //Add 25% more to the EEPROM defer time
if( (micros() > deferEEPROMWritesUntil)) { writeConfig(serialPayload[2]); } //Read the table number and perform burn. Note that byte 1 in the array is unused
else { BIT_SET(currentStatus.status4, BIT_STATUS4_BURNPENDING); }
sendReturnCodeMsg(SERIAL_RC_BURN_OK);
break;
case 'C': // test communications. This is used by Tunerstudio to see whether there is an ECU on a given serial port
(void)memcpy_P(serialPayload, testCommsResponse, sizeof(testCommsResponse) );
sendSerialPayloadNonBlocking(sizeof(testCommsResponse));
break;
case 'd': // Send a CRC32 hash of a given page
{
uint32_t CRC32_val = reverse_bytes(calculatePageCRC32( serialPayload[2] ));
serialPayload[0] = SERIAL_RC_OK;
(void)memcpy(&serialPayload[1], &CRC32_val, sizeof(CRC32_val));
sendSerialPayloadNonBlocking(5);
break;
}
case 'E': // receive command button commands
(void)TS_CommandButtonsHandler(word(serialPayload[1], serialPayload[2]));
sendReturnCodeMsg(SERIAL_RC_OK);
break;
case 'f': //Send serial capability details
serialPayload[0] = SERIAL_RC_OK;
serialPayload[1] = 2; //Serial protocol version
serialPayload[2] = highByte(BLOCKING_FACTOR);
serialPayload[3] = lowByte(BLOCKING_FACTOR);
serialPayload[4] = highByte(TABLE_BLOCKING_FACTOR);
serialPayload[5] = lowByte(TABLE_BLOCKING_FACTOR);
sendSerialPayloadNonBlocking(6);
break;
case 'F': // send serial protocol version
(void)memcpy_P(serialPayload, serialVersion, sizeof(serialVersion) );
sendSerialPayloadNonBlocking(sizeof(serialVersion));
break;
case 'H': //Start the tooth logger
startToothLogger();
sendReturnCodeMsg(SERIAL_RC_OK);
break;
case 'h': //Stop the tooth logger
stopToothLogger();
sendReturnCodeMsg(SERIAL_RC_OK);
break;
case 'I': // send CAN ID
(void)memcpy_P(serialPayload, canId, sizeof(canId) );
sendSerialPayloadNonBlocking(sizeof(serialVersion));
break;
case 'J': //Start the composite logger
startCompositeLogger();
sendReturnCodeMsg(SERIAL_RC_OK);
break;
case 'j': //Stop the composite logger
stopCompositeLogger();
sendReturnCodeMsg(SERIAL_RC_OK);
break;
case 'k': //Send CRC values for the calibration pages
{
uint32_t CRC32_val = reverse_bytes(readCalibrationCRC32(serialPayload[2])); //Get the CRC for the requested page
serialPayload[0] = SERIAL_RC_OK;
(void)memcpy(&serialPayload[1], &CRC32_val, sizeof(CRC32_val));
sendSerialPayloadNonBlocking(5);
break;
}
case 'M':
{
//New write command
//7 bytes required:
//2 - Page identifier
//2 - offset
//2 - Length
//1 - 1st New value
if (updatePageValues(serialPayload[2], word(serialPayload[4], serialPayload[3]), &serialPayload[7], word(serialPayload[6], serialPayload[5])))
{
sendReturnCodeMsg(SERIAL_RC_OK);
}
else
{
//This should never happen, but just in case
sendReturnCodeMsg(SERIAL_RC_RANGE_ERR);
}
break;
}
case 'O': //Start the composite logger 2nd cam (teritary)
startCompositeLoggerTertiary();
sendReturnCodeMsg(SERIAL_RC_OK);
break;
case 'o': //Stop the composite logger 2nd cam (tertiary)
stopCompositeLoggerTertiary();
sendReturnCodeMsg(SERIAL_RC_OK);
break;
case 'X': //Start the composite logger 2nd cam (teritary)
startCompositeLoggerCams();
sendReturnCodeMsg(SERIAL_RC_OK);
break;
case 'x': //Stop the composite logger 2nd cam (tertiary)
stopCompositeLoggerCams();
sendReturnCodeMsg(SERIAL_RC_OK);
break;
/*
* New method for sending page values (MS command equivalent is 'r')
*/
case 'p':
{
//6 bytes required:
//2 - Page identifier
//2 - offset
//2 - Length
uint16_t length = word(serialPayload[6], serialPayload[5]);
//Setup the transmit buffer
serialPayload[0] = SERIAL_RC_OK;
loadPageValuesToBuffer(serialPayload[2], word(serialPayload[4], serialPayload[3]), &serialPayload[1], length);
sendSerialPayloadNonBlocking(length + 1U);
break;
}
case 'Q': // send code version
(void)memcpy_P(serialPayload, codeVersion, sizeof(codeVersion) );
sendSerialPayloadNonBlocking(sizeof(codeVersion));
break;
case 'r': //New format for the optimised OutputChannels
{
uint8_t cmd = serialPayload[2];
uint16_t offset = word(serialPayload[4], serialPayload[3]);
uint16_t length = word(serialPayload[6], serialPayload[5]);
#ifdef RTC_ENABLED
uint16_t SD_arg1 = word(serialPayload[3], serialPayload[4]);
uint16_t SD_arg2 = word(serialPayload[5], serialPayload[6]);
#endif
if(cmd == SEND_OUTPUT_CHANNELS) //Send output channels command 0x30 is 48dec
{
generateLiveValues(offset, length);
sendSerialPayloadNonBlocking(length + 1U);
}
else if(cmd == 0x0f)
{
//Request for signature
(void)memcpy_P(serialPayload, codeVersion, sizeof(codeVersion) );
sendSerialPayloadNonBlocking(sizeof(codeVersion));
}
#ifdef RTC_ENABLED
else if(cmd == SD_RTC_PAGE) //Request to read SD card RTC
{
serialPayload[0] = SERIAL_RC_OK;
serialPayload[1] = rtc_getSecond(); //Seconds
serialPayload[2] = rtc_getMinute(); //Minutes
serialPayload[3] = rtc_getHour(); //Hours
serialPayload[4] = rtc_getDOW(); //Day of week
serialPayload[5] = rtc_getDay(); //Day of month
serialPayload[6] = rtc_getMonth(); //Month
serialPayload[7] = highByte(rtc_getYear()); //Year
serialPayload[8] = lowByte(rtc_getYear()); //Year
sendSerialPayloadNonBlocking(9);
}
else if(cmd == SD_READWRITE_PAGE) //Request SD card extended parameters
{
//SD read commands use the offset and length fields to indicate the request type
if((SD_arg1 == SD_READ_STAT_ARG1) && (SD_arg2 == SD_READ_STAT_ARG2))
{
//Read the status of the SD card
serialPayload[0] = SERIAL_RC_OK;
serialPayload[1] = currentStatus.TS_SD_Status;
serialPayload[2] = 0; //Error code
//Sector size = 512
serialPayload[3] = 2;
serialPayload[4] = 0;
//Max blocks (4 bytes)
uint32_t sectors = sectorCount();
serialPayload[5] = ((sectors >> 24) & 255);
serialPayload[6] = ((sectors >> 16) & 255);
serialPayload[7] = ((sectors >> 8) & 255);
serialPayload[8] = (sectors & 255);
/*
serialPayload[5] = 0;
serialPayload[6] = 0x20; //1gb dummy card
serialPayload[7] = 0;
serialPayload[8] = 0;
*/
//Max roots (Number of files)
uint16_t numLogFiles = getNextSDLogFileNumber() - 2; // -1 because this returns the NEXT file name not the current one and -1 because TS expects a 0 based index
serialPayload[9] = highByte(numLogFiles);
serialPayload[10] = lowByte(numLogFiles);
//Dir Start (4 bytes)
serialPayload[11] = 0;
serialPayload[12] = 0;
serialPayload[13] = 0;
serialPayload[14] = 0;
//Unknown purpose for last 2 bytes
serialPayload[15] = 0;
serialPayload[16] = 0;
sendSerialPayloadNonBlocking(17);
}
else if((SD_arg1 == SD_READ_DIR_ARG1) && (SD_arg2 == SD_READ_DIR_ARG2))
{
//Send file details
serialPayload[0] = SERIAL_RC_OK;
uint16_t logFileNumber = (SDcurrentDirChunk * 16) + 1;
uint8_t filesInCurrentChunk = 0;
uint16_t payloadIndex = 1;
while((filesInCurrentChunk < 16) && (getSDLogFileDetails(&serialPayload[payloadIndex], logFileNumber) == true))
{
logFileNumber++;
filesInCurrentChunk++;
payloadIndex += 32;
}
serialPayload[payloadIndex] = lowByte(SDcurrentDirChunk);
serialPayload[payloadIndex + 1] = highByte(SDcurrentDirChunk);
//Serial.print("Index:");
//Serial.print(payloadIndex);
sendSerialPayloadNonBlocking(payloadIndex + 2);
}
}
else if(cmd == SD_READFILE_PAGE)
{
//Fetch data from file
if(SD_arg2 == SD_READ_COMP_ARG2)
{
//arg1 is the block number to return
serialPayload[0] = SERIAL_RC_OK;
serialPayload[1] = highByte(SD_arg1);
serialPayload[2] = lowByte(SD_arg1);
uint32_t currentSector = SDreadStartSector + (SD_arg1 * 4);
int32_t numSectorsToSend = 0;
if(SDreadNumSectors > SDreadCompletedSectors)
{
numSectorsToSend = SDreadNumSectors - SDreadCompletedSectors;
if(numSectorsToSend > 4) //Maximum of 4 sectors at a time
{
numSectorsToSend = 4;
}
}
SDreadCompletedSectors += numSectorsToSend;
if(numSectorsToSend <= 0) { sendReturnCodeMsg(SERIAL_RC_OK); }
else
{
readSDSectors(&serialPayload[3], currentSector, numSectorsToSend);
sendSerialPayloadNonBlocking(numSectorsToSend * SD_SECTOR_SIZE + 3);
}
}
}
#endif
else
{
//No other r/ commands should be called
}
break;
}
case 'S': // send code version
(void)memcpy_P(serialPayload, productString, sizeof(productString) );
sendSerialPayloadNonBlocking(sizeof(productString));
currentStatus.secl = 0; //This is required in TS3 due to its stricter timings
break;
case 'T': //Send 256 tooth log entries to Tuner Studios tooth logger
logItemsTransmitted = 0;
if(currentStatus.toothLogEnabled == true) { sendToothLog(); } //Sends tooth log values as ints
else if (currentStatus.compositeTriggerUsed > 0) { sendCompositeLog(); }
else { /* MISRA no-op */ }
break;
case 't': // receive new Calibration info. Command structure: "t", <tble_idx> <data array>.
{
uint8_t cmd = serialPayload[2];
uint16_t offset = word(serialPayload[3], serialPayload[4]);
uint16_t calibrationLength = word(serialPayload[5], serialPayload[6]); // Should be 256
if(cmd == O2_CALIBRATION_PAGE)
{
loadO2CalibrationChunk(offset, calibrationLength);
sendReturnCodeMsg(SERIAL_RC_OK);
Serial.flush(); //This is safe because engine is assumed to not be running during calibration
}
else if(cmd == IAT_CALIBRATION_PAGE)
{
processTemperatureCalibrationTableUpdate(calibrationLength, IAT_CALIBRATION_PAGE, iatCalibration_values, iatCalibration_bins);
}
else if(cmd == CLT_CALIBRATION_PAGE)
{
processTemperatureCalibrationTableUpdate(calibrationLength, CLT_CALIBRATION_PAGE, cltCalibration_values, cltCalibration_bins);
}
else
{
sendReturnCodeMsg(SERIAL_RC_RANGE_ERR);
}
break;
}
case 'U': //User wants to reset the Arduino (probably for FW update)
if (resetControl != RESET_CONTROL_DISABLED)
{
#ifndef SMALL_FLASH_MODE
if (serialStatusFlag == SERIAL_INACTIVE) { Serial.println(F("Comms halted. Next byte will reset the Arduino.")); }
#endif
while (Serial.available() == 0) { }
digitalWrite(pinResetControl, LOW);
}
else
{
#ifndef SMALL_FLASH_MODE
if (serialStatusFlag == SERIAL_INACTIVE) { Serial.println(F("Reset control is currently disabled.")); }
#endif
}
break;
case 'w':
{
#ifdef RTC_ENABLED
uint8_t cmd = serialPayload[2];
uint16_t SD_arg1 = word(serialPayload[3], serialPayload[4]);
uint16_t SD_arg2 = word(serialPayload[5], serialPayload[6]);
if(cmd == SD_READWRITE_PAGE)
{
if((SD_arg1 == SD_WRITE_DO_ARG1) && (SD_arg2 == SD_WRITE_DO_ARG2))
{
/*
SD DO command. Single byte of data where the commands are:
0 Reset
1 Reset
2 Stop logging
3 Start logging
4 Load status variable
5 Init SD card
*/
uint8_t command = serialPayload[7];
if(command == 2) { endSDLogging(); manualLogActive = false; }
else if(command == 3) { beginSDLogging(); manualLogActive = true; }
else if(command == 4) { setTS_SD_status(); }
//else if(command == 5) { initSD(); }
sendReturnCodeMsg(SERIAL_RC_OK);
}
else if((SD_arg1 == SD_WRITE_DIR_ARG1) && (SD_arg2 == SD_WRITE_DIR_ARG2))
{
//Begin SD directory read. Value in payload represents the directory chunk to read
//Directory chunks are each 16 files long
SDcurrentDirChunk = word(serialPayload[7], serialPayload[8]);
sendReturnCodeMsg(SERIAL_RC_OK);
}
else if((SD_arg1 == SD_WRITE_READ_SEC_ARG1) && (SD_arg2 == SD_WRITE_READ_SEC_ARG2))
{
//Read sector Init? Unsure what this is meant to do however it is sent at the beginning of a Card Format request and requires an OK response
//Provided the sector being requested is x0 x0 x0 x0, we treat this as a SD Card format request
if( (serialPayload[7] == 0) && (serialPayload[8] == 0) && (serialPayload[9] == 0) && (serialPayload[10] == 0) )
{
//SD Card format request
formatExFat();
}
sendReturnCodeMsg(SERIAL_RC_OK);
}
else if((SD_arg1 == SD_WRITE_WRITE_SEC_ARG1) && (SD_arg2 == SD_WRITE_WRITE_SEC_ARG2))
{
//SD write sector command
}
else if((SD_arg1 == SD_ERASEFILE_ARG1) && (SD_arg2 == SD_ERASEFILE_ARG2))
{
//Erase file command
//We just need the 4 ASCII characters of the file name
char log1 = serialPayload[7];
char log2 = serialPayload[8];
char log3 = serialPayload[9];
char log4 = serialPayload[10];
deleteLogFile(log1, log2, log3, log4);
sendReturnCodeMsg(SERIAL_RC_OK);
}
else if((SD_arg1 == SD_SPD_TEST_ARG1) && (SD_arg2 == SD_SPD_TEST_ARG2))
{
//Perform a speed test on the SD card
//First 4 bytes are the sector number to write to
uint32_t sector;
uint8_t sector1 = serialPayload[7];
uint8_t sector2 = serialPayload[8];
uint8_t sector3 = serialPayload[9];
uint8_t sector4 = serialPayload[10];
sector = (sector1 << 24) | (sector2 << 16) | (sector3 << 8) | sector4;
//Last 4 bytes are the number of sectors to test
uint32_t testSize;
uint8_t testSize1 = serialPayload[11];
uint8_t testSize2 = serialPayload[12];
uint8_t testSize3 = serialPayload[13];
uint8_t testSize4 = serialPayload[14];
testSize = (testSize1 << 24) | (testSize2 << 16) | (testSize3 << 8) | testSize4;
sendReturnCodeMsg(SERIAL_RC_OK);
}
else if((SD_arg1 == SD_WRITE_COMP_ARG1) && (SD_arg2 == SD_WRITE_COMP_ARG2))
{
//Prepare to read a 2024 byte chunk of data from the SD card
uint8_t sector1 = serialPayload[7];
uint8_t sector2 = serialPayload[8];
uint8_t sector3 = serialPayload[9];
uint8_t sector4 = serialPayload[10];
//SDreadStartSector = (sector1 << 24) | (sector2 << 16) | (sector3 << 8) | sector4;
SDreadStartSector = (sector4 << 24) | (sector3 << 16) | (sector2 << 8) | sector1;
//SDreadStartSector = sector4 | (sector3 << 8) | (sector2 << 16) | (sector1 << 24);
//Next 4 bytes are the number of sectors to write
uint8_t sectorCount1 = serialPayload[11];
uint8_t sectorCount2 = serialPayload[12];
uint8_t sectorCount3 = serialPayload[13];
uint8_t sectorCount4 = serialPayload[14];
SDreadNumSectors = (sectorCount1 << 24) | (sectorCount2 << 16) | (sectorCount3 << 8) | sectorCount4;
//Reset the sector counter
SDreadCompletedSectors = 0;
sendReturnCodeMsg(SERIAL_RC_OK);
}
}
else if(cmd == SD_RTC_PAGE)
{
//Used for setting RTC settings
if((SD_arg1 == SD_RTC_WRITE_ARG1) && (SD_arg2 == SD_RTC_WRITE_ARG2))
{
//Set the RTC date/time
byte second = serialPayload[7];
byte minute = serialPayload[8];
byte hour = serialPayload[9];
//byte dow = serialPayload[10]; //Not used
byte day = serialPayload[11];
byte month = serialPayload[12];
uint16_t year = word(serialPayload[13], serialPayload[14]);
rtc_setTime(second, minute, hour, day, month, year);
sendReturnCodeMsg(SERIAL_RC_OK);
}
}
#endif
break;
}
default:
//Unknown command
sendReturnCodeMsg(SERIAL_RC_UKWN_ERR);
break;
}
}
/**
*
*/
void sendToothLog(void)
{
//We need TOOTH_LOG_SIZE number of records to send to TunerStudio. If there aren't that many in the buffer then we just return and wait for the next call
if (BIT_CHECK(currentStatus.status1, BIT_STATUS1_TOOTHLOG1READY) == false)
{
//If the buffer is not yet full but TS has timed out, pad the rest of the buffer with 0s
while(toothHistoryIndex < TOOTH_LOG_SIZE)
{
toothHistory[toothHistoryIndex] = 0;
toothHistoryIndex++;
}
}
uint32_t CRC32_val = 0;
if(logItemsTransmitted == 0)
{
//Transmit the size of the packet
(void)serialWrite((uint16_t)(sizeof(toothHistory) + 1U)); //Size of the tooth log (uint32_t values) plus the return code
//Begin new CRC hash
const uint8_t returnCode = SERIAL_RC_OK;
CRC32_val = CRC32_serial.crc32(&returnCode, 1, false);
//Send the return code
writeByteReliableBlocking(returnCode);
}
for (; logItemsTransmitted < TOOTH_LOG_SIZE; logItemsTransmitted++)
{
//Check whether the tx buffer still has space
if(Serial.availableForWrite() < 4)
{
//tx buffer is full. Store the current state so it can be resumed later
serialStatusFlag = SERIAL_TRANSMIT_TOOTH_INPROGRESS;
return;
}
//Transmit the tooth time
uint32_t transmitted = serialWrite(toothHistory[logItemsTransmitted]);
CRC32_val = CRC32_serial.crc32_upd((const byte*)&transmitted, sizeof(transmitted), false);
}
BIT_CLEAR(currentStatus.status1, BIT_STATUS1_TOOTHLOG1READY);
serialStatusFlag = SERIAL_INACTIVE;
toothHistoryIndex = 0;
logItemsTransmitted = 0;
//Apply the CRC reflection
CRC32_val = ~CRC32_val;
//Send the CRC
(void)serialWrite(CRC32_val);
}
void sendCompositeLog(void)
{
if ( BIT_CHECK(currentStatus.status1, BIT_STATUS1_TOOTHLOG1READY) == false )
{
//If the buffer is not yet full but TS has timed out, pad the rest of the buffer with 0s
while(toothHistoryIndex < TOOTH_LOG_SIZE)
{
toothHistory[toothHistoryIndex] = toothHistory[toothHistoryIndex-1]; //Composite logger needs a realistic time value to display correctly. Copy the last value
compositeLogHistory[toothHistoryIndex] = 0;
toothHistoryIndex++;
}
}
uint32_t CRC32_val = 0;
if(logItemsTransmitted == 0)
{
//Transmit the size of the packet
(void)serialWrite((uint16_t)(sizeof(toothHistory) + sizeof(compositeLogHistory) + 1U)); //Size of the tooth log (uint32_t values) plus the return code
//Begin new CRC hash
const uint8_t returnCode = SERIAL_RC_OK;
CRC32_val = CRC32_serial.crc32(&returnCode, 1, false);
//Send the return code
writeByteReliableBlocking(returnCode);
}
for (; logItemsTransmitted < TOOTH_LOG_SIZE; logItemsTransmitted++)
{
//Check whether the tx buffer still has space
if((uint16_t)Serial.availableForWrite() < sizeof(toothHistory[logItemsTransmitted])+sizeof(compositeLogHistory[logItemsTransmitted]))
{
//tx buffer is full. Store the current state so it can be resumed later
serialStatusFlag = SERIAL_TRANSMIT_COMPOSITE_INPROGRESS;
return;
}
uint32_t transmitted = serialWrite(toothHistory[logItemsTransmitted]); //This combined runtime (in us) that the log was going for by this record
CRC32_serial.crc32_upd((const byte*)&transmitted, sizeof(transmitted), false);
//The status byte (Indicates the trigger edge, whether it was a pri/sec pulse, the sync status)
writeByteReliableBlocking(compositeLogHistory[logItemsTransmitted]);
CRC32_val = CRC32_serial.crc32_upd((const byte*)&compositeLogHistory[logItemsTransmitted], sizeof(compositeLogHistory[logItemsTransmitted]), false);
}
BIT_CLEAR(currentStatus.status1, BIT_STATUS1_TOOTHLOG1READY);
toothHistoryIndex = 0;
serialStatusFlag = SERIAL_INACTIVE;
logItemsTransmitted = 0;
//Apply the CRC reflection
CRC32_val = ~CRC32_val;
//Send the CRC
(void)serialWrite(CRC32_val);
}
#if defined(CORE_AVR)
#pragma GCC pop_options
#endif
| 41,426
|
C++
|
.cpp
| 1,019
| 34.777233
| 206
| 0.662205
|
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,057
|
comms_legacy.cpp
|
oelprinz-org_BlitzboxBL49sp/software/202310/speeduino-202310/speeduino/comms_legacy.cpp
|
/*
Speeduino - Simple engine management for the Arduino Mega 2560 platform
Copyright (C) Josh Stewart
A full copy of the license may be found in the projects root directory
*/
/** @file
* Process Incoming and outgoing serial communications.
*/
#include "globals.h"
#include "comms_legacy.h"
#include "comms_secondary.h"
#include "storage.h"
#include "maths.h"
#include "utilities.h"
#include "decoders.h"
#include "TS_CommandButtonHandler.h"
#include "errors.h"
#include "pages.h"
#include "page_crc.h"
#include "logger.h"
#include "table3d_axis_io.h"
#ifdef RTC_ENABLED
#include "rtc_common.h"
#endif
static byte currentPage = 1;//Not the same as the speeduino config page numbers
bool firstCommsRequest = true; /**< 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 */
static byte currentCommand; /**< The serial command that is currently being processed. This is only useful when cmdPending=True */
static bool chunkPending = false; /**< Whether or not the current chunk write is complete or not */
static uint16_t chunkComplete = 0; /**< The number of bytes in a chunk write that have been written so far */
static uint16_t chunkSize = 0; /**< The complete size of the requested chunk write */
static int valueOffset; /**< The memory offset within a given page for a value to be read from or written to. Note that we cannot use 'offset' as a variable name, it is a reserved word for several teensy libraries */
byte logItemsTransmitted;
byte inProgressLength;
SerialStatus serialStatusFlag;
SerialStatus serialSecondaryStatusFlag;
static bool isMap(void) {
// Detecting if the current page is a table/map
return (currentPage == veMapPage) || (currentPage == ignMapPage) || (currentPage == afrMapPage) || (currentPage == fuelMap2Page) || (currentPage == ignMap2Page);
}
/** Processes the incoming data on the serial buffer based on the command sent.
Can be either data for a new command or a continuation of data for command that is already in progress:
- cmdPending = If a command has started but is waiting on further data to complete
- chunkPending = Specifically for the new receive value method where TS will send a known number of contiguous bytes to be written to a table
Commands are single byte (letter symbol) commands.
*/
void legacySerialCommand(void)
{
if ( serialStatusFlag == SERIAL_INACTIVE ) { currentCommand = Serial.read(); }
switch (currentCommand)
{
case 'a':
serialStatusFlag = SERIAL_COMMAND_INPROGRESS_LEGACY;
if (Serial.available() >= 2)
{
Serial.read(); //Ignore the first value, it's always 0
Serial.read(); //Ignore the second value, it's always 6
sendValuesLegacy();
serialStatusFlag = SERIAL_INACTIVE;
}
break;
case 'A': // send x bytes of realtime values
sendValues(0, LOG_ENTRY_SIZE, 0x31, Serial, serialStatusFlag); //send values to serial0
firstCommsRequest = false;
break;
case 'b': // New EEPROM burn command to only burn a single page at a time
legacySerialHandler(currentCommand, Serial, serialStatusFlag);
break;
case 'B': // AS above but for the serial compatibility mode.
BIT_SET(currentStatus.status4, BIT_STATUS4_COMMS_COMPAT); //Force the compat mode
legacySerialHandler(currentCommand, Serial, serialStatusFlag);
break;
case 'C': // test communications. This is used by Tunerstudio to see whether there is an ECU on a given serial port
testComm();
break;
case 'c': //Send the current loops/sec value
Serial.write(lowByte(currentStatus.loopsPerSecond));
Serial.write(highByte(currentStatus.loopsPerSecond));
break;
case 'd': // Send a CRC32 hash of a given page
serialStatusFlag = SERIAL_COMMAND_INPROGRESS_LEGACY;
if (Serial.available() >= 2)
{
Serial.read(); //Ignore the first byte value, it's always 0
uint32_t CRC32_val = calculatePageCRC32( Serial.read() );
//Split the 4 bytes of the CRC32 value into individual bytes and send
Serial.write( ((CRC32_val >> 24) & 255) );
Serial.write( ((CRC32_val >> 16) & 255) );
Serial.write( ((CRC32_val >> 8) & 255) );
Serial.write( (CRC32_val & 255) );
serialStatusFlag = SERIAL_INACTIVE;
}
break;
case 'E': // receive command button commands
serialStatusFlag = SERIAL_COMMAND_INPROGRESS_LEGACY;
if(Serial.available() >= 2)
{
byte cmdGroup = (byte)Serial.read();
(void)TS_CommandButtonsHandler(word(cmdGroup, Serial.read()));
serialStatusFlag = SERIAL_INACTIVE;
}
break;
case 'F': // send serial protocol version
Serial.print(F("002"));
break;
//The G/g commands are used for bulk reading and writing to the EEPROM directly. This is typically a non-user feature but will be incorporated into SpeedyLoader for anyone programming many boards at once
case 'G': // Dumps the EEPROM values to serial
//The format is 2 bytes for the overall EEPROM size, a comma and then a raw dump of the EEPROM values
Serial.write(lowByte(getEEPROMSize()));
Serial.write(highByte(getEEPROMSize()));
Serial.print(',');
for(uint16_t x = 0; x < getEEPROMSize(); x++)
{
Serial.write(EEPROMReadRaw(x));
}
serialStatusFlag = SERIAL_INACTIVE;
break;
case 'g': // Receive a dump of raw EEPROM values from the user
{
//Format is similar to the above command. 2 bytes for the EEPROM size that is about to be transmitted, a comma and then a raw dump of the EEPROM values
while(Serial.available() < 3) { delay(1); }
uint16_t eepromSize = word(Serial.read(), Serial.read());
if(eepromSize != getEEPROMSize())
{
//Client is trying to send the wrong EEPROM size. Don't let it
Serial.println(F("ERR; Incorrect EEPROM size"));
break;
}
else
{
for(uint16_t x = 0; x < eepromSize; x++)
{
while(Serial.available() < 3) { delay(1); }
EEPROMWriteRaw(x, Serial.read());
}
}
serialStatusFlag = SERIAL_INACTIVE;
break;
}
case 'H': //Start the tooth logger
startToothLogger();
Serial.write(1); //TS needs an acknowledgement that this was received. I don't know if this is the correct response, but it seems to work
break;
case 'h': //Stop the tooth logger
stopToothLogger();
break;
case 'J': //Start the composite logger
startCompositeLogger();
Serial.write(1); //TS needs an acknowledgement that this was received. I don't know if this is the correct response, but it seems to work
break;
case 'j': //Stop the composite logger
stopCompositeLogger();
break;
case 'L': // List the contents of current page in human readable form
#ifndef SMALL_FLASH_MODE
sendPageASCII();
#endif
break;
case 'm': //Send the current free memory
currentStatus.freeRAM = freeRam();
Serial.write(lowByte(currentStatus.freeRAM));
Serial.write(highByte(currentStatus.freeRAM));
break;
case 'N': // Displays a new line. Like pushing enter in a text editor
Serial.println();
break;
case 'O': //Start the composite logger 2nd cam (teritary)
startCompositeLoggerTertiary();
Serial.write(1); //TS needs an acknowledgement that this was received. I don't know if this is the correct response, but it seems to work
break;
case 'o': //Stop the composite logger 2nd cam (tertiary)
stopCompositeLoggerTertiary();
break;
case 'X': //Start the composite logger 2nd cam (teritary)
startCompositeLoggerCams();
Serial.write(1); //TS needs an acknowledgement that this was received. I don't know if this is the correct response, but it seems to work
break;
case 'x': //Stop the composite logger 2nd cam (tertiary)
stopCompositeLoggerCams();
break;
case 'P': // set the current page
//This is a legacy function and is no longer used by TunerStudio. It is maintained for compatibility with other systems
//A 2nd byte of data is required after the 'P' specifying the new page number.
serialStatusFlag = SERIAL_COMMAND_INPROGRESS_LEGACY;
if (Serial.available() > 0)
{
currentPage = Serial.read();
//This converts the ASCII number char into binary. Note that this will break everything if there are ever more than 48 pages (48 = asci code for '0')
if ((currentPage >= '0') && (currentPage <= '9')) // 0 - 9
{
currentPage -= 48;
}
else if ((currentPage >= 'a') && (currentPage <= 'f')) // 10 - 15
{
currentPage -= 87;
}
else if ((currentPage >= 'A') && (currentPage <= 'F'))
{
currentPage -= 55;
}
serialStatusFlag = SERIAL_INACTIVE;
}
break;
/*
* New method for sending page values
*/
case 'p':
serialStatusFlag = SERIAL_COMMAND_INPROGRESS_LEGACY;
//6 bytes required:
//2 - Page identifier
//2 - offset
//2 - Length
if(Serial.available() >= 6)
{
byte offset1, offset2, length1, length2;
int length;
byte tempPage;
Serial.read(); // First byte of the page identifier can be ignored. It's always 0
tempPage = Serial.read();
//currentPage = 1;
offset1 = Serial.read();
offset2 = Serial.read();
valueOffset = word(offset2, offset1);
length1 = Serial.read();
length2 = Serial.read();
length = word(length2, length1);
for(int i = 0; i < length; i++)
{
Serial.write( getPageValue(tempPage, valueOffset + i) );
}
serialStatusFlag = SERIAL_INACTIVE;
}
break;
case 'Q': // send code version
legacySerialHandler(currentCommand, Serial, serialStatusFlag);
break;
case 'r': //New format for the optimised OutputChannels
serialStatusFlag = SERIAL_COMMAND_INPROGRESS_LEGACY;
byte cmd;
if (Serial.available() >= 6)
{
Serial.read(); //Read the $tsCanId
cmd = Serial.read(); // read the command
uint16_t offset, length;
byte tmp;
tmp = Serial.read();
offset = word(Serial.read(), tmp);
tmp = Serial.read();
length = word(Serial.read(), tmp);
serialStatusFlag = SERIAL_INACTIVE;
if(cmd == 0x30) //Send output channels command 0x30 is 48dec
{
sendValues(offset, length, cmd, Serial, serialStatusFlag);
}
else
{
//No other r/ commands are supported in legacy mode
}
}
break;
case 'S': // send code version
legacySerialHandler(currentCommand, Serial, serialStatusFlag); //Send the bootloader capabilities
currentStatus.secl = 0; //This is required in TS3 due to its stricter timings
break;
case 'T': //Send 256 tooth log entries to Tuner Studios tooth logger
//6 bytes required:
//2 - Page identifier
//2 - offset
//2 - Length
serialStatusFlag = SERIAL_COMMAND_INPROGRESS_LEGACY;
if(Serial.available() >= 6)
{
Serial.read(); // First byte of the page identifier can be ignored. It's always 0
Serial.read(); // First byte of the page identifier can be ignored. It's always 0
Serial.read(); // First byte of the page identifier can be ignored. It's always 0
Serial.read(); // First byte of the page identifier can be ignored. It's always 0
Serial.read(); // First byte of the page identifier can be ignored. It's always 0
Serial.read(); // First byte of the page identifier can be ignored. It's always 0
if(currentStatus.toothLogEnabled == true) { sendToothLog_legacy(0); } //Sends tooth log values as ints
else if (currentStatus.compositeTriggerUsed > 0) { sendCompositeLog_legacy(0); }
serialStatusFlag = SERIAL_INACTIVE;
}
break;
case 't': // receive new Calibration info. Command structure: "t", <tble_idx> <data array>.
byte tableID;
//byte canID;
//The first 2 bytes sent represent the canID and tableID
while (Serial.available() == 0) { }
tableID = Serial.read(); //Not currently used for anything
receiveCalibration(tableID); //Receive new values and store in memory
writeCalibration(); //Store received values in EEPROM
break;
case 'U': //User wants to reset the Arduino (probably for FW update)
if (resetControl != RESET_CONTROL_DISABLED)
{
#ifndef SMALL_FLASH_MODE
if (serialStatusFlag == SERIAL_INACTIVE) { Serial.println(F("Comms halted. Next byte will reset the Arduino.")); }
#endif
while (Serial.available() == 0) { }
digitalWrite(pinResetControl, LOW);
}
else
{
#ifndef SMALL_FLASH_MODE
if (serialStatusFlag == SERIAL_INACTIVE) { Serial.println(F("Reset control is currently disabled.")); }
#endif
}
break;
case 'V': // send VE table and constants in binary
sendPage();
break;
case 'W': // receive new VE obr constant at 'W'+<offset>+<newbyte>
serialStatusFlag = SERIAL_COMMAND_INPROGRESS_LEGACY;
if (isMap())
{
if(Serial.available() >= 3) // 1 additional byte is required on the MAP pages which are larger than 255 bytes
{
byte offset1, offset2;
offset1 = Serial.read();
offset2 = Serial.read();
valueOffset = word(offset2, offset1);
setPageValue(currentPage, valueOffset, Serial.read());
serialStatusFlag = SERIAL_INACTIVE;
}
}
else
{
if(Serial.available() >= 2)
{
valueOffset = Serial.read();
setPageValue(currentPage, valueOffset, Serial.read());
serialStatusFlag = SERIAL_INACTIVE;
}
}
break;
case 'M':
serialStatusFlag = SERIAL_COMMAND_INPROGRESS_LEGACY;
if(chunkPending == false)
{
//This means it's a new request
//7 bytes required:
//2 - Page identifier
//2 - offset
//2 - Length
//1 - 1st New value
if(Serial.available() >= 7)
{
byte offset1, offset2, length1, length2;
Serial.read(); // First byte of the page identifier can be ignored. It's always 0
currentPage = Serial.read();
//currentPage = 1;
offset1 = Serial.read();
offset2 = Serial.read();
valueOffset = word(offset2, offset1);
length1 = Serial.read();
length2 = Serial.read();
chunkSize = word(length2, length1);
//Regular page data
chunkPending = true;
chunkComplete = 0;
}
}
//This CANNOT be an else of the above if statement as chunkPending gets set to true above
if(chunkPending == true)
{
while( (Serial.available() > 0) && (chunkComplete < chunkSize) )
{
setPageValue(currentPage, (valueOffset + chunkComplete), Serial.read());
chunkComplete++;
}
if(chunkComplete >= chunkSize) { serialStatusFlag = SERIAL_INACTIVE; chunkPending = false; }
}
break;
case 'w':
//No w commands are supported in legacy mode. This should never be called
if(Serial.available() >= 7)
{
byte offset1, offset2, length1, length2;
Serial.read(); // First byte of the page identifier can be ignored. It's always 0
currentPage = Serial.read();
//currentPage = 1;
offset1 = Serial.read();
offset2 = Serial.read();
valueOffset = word(offset2, offset1);
length1 = Serial.read();
length2 = Serial.read();
chunkSize = word(length2, length1);
}
break;
case 'Z': //Totally non-standard testing function. Will be removed once calibration testing is completed. This function takes 1.5kb of program space! :S
#ifndef SMALL_FLASH_MODE
Serial.println(F("Coolant"));
for (int x = 0; x < 32; x++)
{
Serial.print(cltCalibration_bins[x]);
Serial.print(", ");
Serial.println(cltCalibration_values[x]);
}
Serial.println(F("Inlet temp"));
for (int x = 0; x < 32; x++)
{
Serial.print(iatCalibration_bins[x]);
Serial.print(", ");
Serial.println(iatCalibration_values[x]);
}
Serial.println(F("O2"));
for (int x = 0; x < 32; x++)
{
Serial.print(o2Calibration_bins[x]);
Serial.print(", ");
Serial.println(o2Calibration_values[x]);
}
Serial.println(F("WUE"));
for (int x = 0; x < 10; x++)
{
Serial.print(configPage4.wueBins[x]);
Serial.print(F(", "));
Serial.println(configPage2.wueValues[x]);
}
Serial.flush();
#endif
break;
case 'z': //Send 256 tooth log entries to a terminal emulator
sendToothLog_legacy(0); //Sends tooth log values as chars
break;
case '`': //Custom 16u2 firmware is making its presence known
serialStatusFlag = SERIAL_COMMAND_INPROGRESS_LEGACY;
if (Serial.available() >= 1) {
configPage4.bootloaderCaps = Serial.read();
serialStatusFlag = SERIAL_INACTIVE;
}
break;
case '?':
#ifndef SMALL_FLASH_MODE
Serial.println
(F(
"\n"
"===Command Help===\n\n"
"All commands are single character and are concatenated with their parameters \n"
"without spaces."
"Syntax: <command>+<parameter1>+<parameter2>+<parameterN>\n\n"
"===List of Commands===\n\n"
"A - Displays 31 bytes of currentStatus values in binary (live data)\n"
"B - Burn current map and configPage values to eeprom\n"
"C - Test COM port. Used by Tunerstudio to see whether an ECU is on a given serial \n"
" port. Returns a binary number.\n"
"N - Print new line.\n"
"P - Set current page. Syntax: P+<pageNumber>\n"
"R - Same as A command\n"
"S - Display signature number\n"
"Q - Same as S command\n"
"V - Display map or configPage values in binary\n"
"W - Set one byte in map or configPage. Expects binary parameters. \n"
" Syntax: W+<offset>+<newbyte>\n"
"t - Set calibration values. Expects binary parameters. Table index is either 0, \n"
" 1, or 2. Syntax: t+<tble_idx>+<newValue1>+<newValue2>+<newValueN>\n"
"Z - Display calibration values\n"
"T - Displays 256 tooth log entries in binary\n"
"r - Displays 256 tooth log entries\n"
"U - Prepare for firmware update. The next byte received will cause the Arduino to reset.\n"
"? - Displays this help page"
));
#endif
break;
default:
//Serial.println(F("Err: Unknown cmd"));
//while(Serial.available() && Serial.peek()!='A') { Serial.read(); }
serialStatusFlag = SERIAL_INACTIVE;
break;
}
}
void legacySerialHandler(byte cmd, Stream &targetPort, SerialStatus &targetStatusFlag)
{
switch (cmd)
{
case 'b': // New EEPROM burn command to only burn a single page at a time
targetStatusFlag = SERIAL_COMMAND_INPROGRESS_LEGACY;
if (targetPort.available() >= 2)
{
targetPort.read(); //Ignore the first table value, it's always 0
writeConfig(targetPort.read());
targetStatusFlag = SERIAL_INACTIVE;
}
break;
case 'B': // AS above but for the serial compatibility mode.
targetStatusFlag = SERIAL_COMMAND_INPROGRESS_LEGACY;
if (targetPort.available() >= 2)
{
targetPort.read(); //Ignore the first table value, it's always 0
writeConfig(targetPort.read());
targetStatusFlag = SERIAL_INACTIVE;
}
break;
case 'd':
targetStatusFlag = SERIAL_COMMAND_INPROGRESS_LEGACY;
if (targetPort.available() >= 2)
{
targetPort.read(); //Ignore the first byte value, it's always 0
uint32_t CRC32_val = calculatePageCRC32( targetPort.read() );
//Split the 4 bytes of the CRC32 value into individual bytes and send
targetPort.write( ((CRC32_val >> 24) & 255) );
targetPort.write( ((CRC32_val >> 16) & 255) );
targetPort.write( ((CRC32_val >> 8) & 255) );
targetPort.write( (CRC32_val & 255) );
targetStatusFlag = SERIAL_INACTIVE;
}
break;
case 'p':
targetStatusFlag = SERIAL_COMMAND_INPROGRESS_LEGACY;
//6 bytes required:
//2 - Page identifier
//2 - offset
//2 - Length
if(targetPort.available() >= 6)
{
byte offset1, offset2, length1, length2;
int length;
byte tempPage;
targetPort.read(); // First byte of the page identifier can be ignored. It's always 0
tempPage = targetPort.read();
//currentPage = 1;
offset1 = targetPort.read();
offset2 = targetPort.read();
valueOffset = word(offset2, offset1);
length1 = targetPort.read();
length2 = targetPort.read();
length = word(length2, length1);
for(int i = 0; i < length; i++)
{
targetPort.write( getPageValue(tempPage, valueOffset + i) );
}
targetStatusFlag = SERIAL_INACTIVE;
}
break;
case 'Q': // send code version
//targetPort.print(F("speeduino 202306-dev"));
targetPort.print(F("speeduino 202310"));
break;
case 'r': //New format for the optimised OutputChannels
targetStatusFlag = SERIAL_COMMAND_INPROGRESS_LEGACY;
byte cmd;
if (targetPort.available() >= 6)
{
targetPort.read(); //Read the $tsCanId
cmd = targetPort.read(); // read the command
uint16_t offset, length;
byte tmp;
tmp = targetPort.read();
offset = word(targetPort.read(), tmp);
tmp = targetPort.read();
length = word(targetPort.read(), tmp);
targetStatusFlag = SERIAL_INACTIVE;
if(cmd == 0x30) //Send output channels command 0x30 is 48dec
{
sendValues(offset, length, cmd, targetPort, targetStatusFlag);
}
else
{
//No other r/ commands are supported in legacy mode
}
}
break;
case 'S': // send code version
//targetPort.print(F("Speeduino 2023.06-dev"));
targetPort.print(F("Speeduino 2023.10"));
break;
}
}
/** Send a status record back to tuning/logging SW.
* This will "live" information from @ref currentStatus struct.
* @param offset - Start field number
* @param packetLength - Length of actual message (after possible ack/confirm headers)
* @param cmd - ??? - Will be used as some kind of ack on secondarySerial
* @param targetPort - The HardwareSerial device that will be transmitted to
* @param targetStatusFlag - The status flag that will be set to indicate the status of the transmission
* E.g. tuning sw command 'A' (Send all values) will send data from field number 0, LOG_ENTRY_SIZE fields.
* @return the current values of a fixed group of variables
*/
void sendValues(uint16_t offset, uint16_t packetLength, byte cmd, Stream &targetPort, SerialStatus &targetStatusFlag)
{
#if defined(secondarySerial_AVAILABLE)
if (&targetPort == &secondarySerial)
{
//CAN serial
if( (configPage9.secondarySerialProtocol == SECONDARY_SERIAL_PROTO_GENERIC) || (configPage9.secondarySerialProtocol == SECONDARY_SERIAL_PROTO_REALDASH))
{
if (cmd == 0x30)
{
secondarySerial.write("r"); //confirm cmd type
secondarySerial.write(cmd);
}
else if (cmd == 0x31)
{
secondarySerial.write("A"); // confirm command type
}
else if (cmd == 0x32)
{
secondarySerial.write("n"); // confirm command type
secondarySerial.write(cmd); // send command type , 0x32 (dec50) is ascii '0'
secondarySerial.write(NEW_CAN_PACKET_SIZE); // send the packet size the receiving device should expect.
}
}
}
else
#endif
{
if(firstCommsRequest)
{
firstCommsRequest = false;
currentStatus.secl = 0;
}
}
//
targetStatusFlag = SERIAL_TRANSMIT_INPROGRESS_LEGACY;
currentStatus.spark ^= (-currentStatus.hasSync ^ currentStatus.spark) & (1U << BIT_SPARK_SYNC); //Set the sync bit of the Spark variable to match the hasSync variable
for(byte x=0; x<packetLength; x++)
{
bool bufferFull = false;
targetPort.write(getTSLogEntry(offset+x));
if( (&targetPort == &Serial) || (configPage9.secondarySerialProtocol != SECONDARY_SERIAL_PROTO_REALDASH) )
{
//If the transmit buffer is full, wait for it to clear. This cannot be used with Read Dash as it will cause a timeout
if(targetPort.availableForWrite() < 1) { bufferFull = true; }
}
//Check whether the tx buffer still has space
if(bufferFull == true)
{
//tx buffer is full. Store the current state so it can be resumed later
logItemsTransmitted = offset + x + 1;
inProgressLength = packetLength - x - 1;
return;
}
}
targetStatusFlag = SERIAL_INACTIVE;
while(targetPort.available()) { targetPort.read(); }
// Reset any flags that are being used to trigger page refreshes
BIT_CLEAR(currentStatus.status3, BIT_STATUS3_VSS_REFRESH);
}
void sendValuesLegacy(void)
{
uint16_t temp;
int bytestosend = 114;
bytestosend -= Serial.write(currentStatus.secl>>8);
bytestosend -= Serial.write(currentStatus.secl);
bytestosend -= Serial.write(currentStatus.PW1>>8);
bytestosend -= Serial.write(currentStatus.PW1);
bytestosend -= Serial.write(currentStatus.PW2>>8);
bytestosend -= Serial.write(currentStatus.PW2);
bytestosend -= Serial.write(currentStatus.RPM>>8);
bytestosend -= Serial.write(currentStatus.RPM);
temp = currentStatus.advance * 10;
bytestosend -= Serial.write(temp>>8);
bytestosend -= Serial.write(temp);
bytestosend -= Serial.write(currentStatus.nSquirts);
bytestosend -= Serial.write(currentStatus.engine);
bytestosend -= Serial.write(currentStatus.afrTarget);
bytestosend -= Serial.write(currentStatus.afrTarget); // send twice so afrtgt1 == afrtgt2
bytestosend -= Serial.write(99); // send dummy data as we don't have wbo2_en1
bytestosend -= Serial.write(99); // send dummy data as we don't have wbo2_en2
temp = currentStatus.baro * 10;
bytestosend -= Serial.write(temp>>8);
bytestosend -= Serial.write(temp);
temp = currentStatus.MAP * 10;
bytestosend -= Serial.write(temp>>8);
bytestosend -= Serial.write(temp);
temp = currentStatus.IAT * 10;
bytestosend -= Serial.write(temp>>8);
bytestosend -= Serial.write(temp);
temp = currentStatus.coolant * 10;
bytestosend -= Serial.write(temp>>8);
bytestosend -= Serial.write(temp);
temp = currentStatus.TPS * 10;
bytestosend -= Serial.write(temp>>8);
bytestosend -= Serial.write(temp);
bytestosend -= Serial.write(currentStatus.battery10>>8);
bytestosend -= Serial.write(currentStatus.battery10);
bytestosend -= Serial.write(currentStatus.O2>>8);
bytestosend -= Serial.write(currentStatus.O2);
bytestosend -= Serial.write(currentStatus.O2_2>>8);
bytestosend -= Serial.write(currentStatus.O2_2);
bytestosend -= Serial.write(99); // knock
bytestosend -= Serial.write(99); // knock
temp = currentStatus.egoCorrection * 10;
bytestosend -= Serial.write(temp>>8); // egocor1
bytestosend -= Serial.write(temp); // egocor1
bytestosend -= Serial.write(temp>>8); // egocor2
bytestosend -= Serial.write(temp); // egocor2
temp = currentStatus.iatCorrection * 10;
bytestosend -= Serial.write(temp>>8); // aircor
bytestosend -= Serial.write(temp); // aircor
temp = currentStatus.wueCorrection * 10;
bytestosend -= Serial.write(temp>>8); // warmcor
bytestosend -= Serial.write(temp); // warmcor
bytestosend -= Serial.write(99); // accelEnrich
bytestosend -= Serial.write(99); // accelEnrich
bytestosend -= Serial.write(99); // tpsFuelCut
bytestosend -= Serial.write(99); // tpsFuelCut
bytestosend -= Serial.write(99); // baroCorrection
bytestosend -= Serial.write(99); // baroCorrection
temp = currentStatus.corrections * 10;
bytestosend -= Serial.write(temp>>8); // gammaEnrich
bytestosend -= Serial.write(temp); // gammaEnrich
temp = currentStatus.VE * 10;
bytestosend -= Serial.write(temp>>8); // ve1
bytestosend -= Serial.write(temp); // ve1
temp = currentStatus.VE2 * 10;
bytestosend -= Serial.write(temp>>8); // ve2
bytestosend -= Serial.write(temp); // ve2
bytestosend -= Serial.write(99); // iacstep
bytestosend -= Serial.write(99); // iacstep
bytestosend -= Serial.write(99); // cold_adv_deg
bytestosend -= Serial.write(99); // cold_adv_deg
temp = currentStatus.tpsDOT;
bytestosend -= Serial.write(temp>>8); // TPSdot
bytestosend -= Serial.write(temp); // TPSdot
temp = currentStatus.mapDOT;
bytestosend -= Serial.write(temp >> 8); // MAPdot
bytestosend -= Serial.write(temp); // MAPdot
temp = currentStatus.dwell * 10;
bytestosend -= Serial.write(temp>>8); // dwell
bytestosend -= Serial.write(temp); // dwell
bytestosend -= Serial.write(99); // MAF
bytestosend -= Serial.write(99); // MAF
bytestosend -= Serial.write(currentStatus.fuelLoad*10); // fuelload
bytestosend -= Serial.write(99); // fuelcor
bytestosend -= Serial.write(99); // fuelcor
bytestosend -= Serial.write(99); // portStatus
temp = currentStatus.advance1 * 10;
bytestosend -= Serial.write(temp>>8);
bytestosend -= Serial.write(temp);
temp = currentStatus.advance2 * 10;
bytestosend -= Serial.write(temp>>8);
bytestosend -= Serial.write(temp);
for(int i = 0; i < bytestosend; i++)
{
// send dummy data to fill remote's buffer
Serial.write(99);
}
}
namespace {
void send_raw_entity(const page_iterator_t &entity)
{
Serial.write((byte *)entity.pData, entity.size);
}
inline void send_table_values(table_value_iterator it)
{
while (!it.at_end())
{
auto row = *it;
Serial.write(&*row, row.size());
++it;
}
}
inline void send_table_axis(table_axis_iterator it)
{
const int16_byte *pConverter = table3d_axis_io::get_converter(it.get_domain());
while (!it.at_end())
{
Serial.write(pConverter->to_byte(*it));
++it;
}
}
void send_table_entity(const page_iterator_t &entity)
{
send_table_values(rows_begin(entity));
send_table_axis(x_begin(entity));
send_table_axis(y_begin(entity));
}
void send_entity(const page_iterator_t &entity)
{
switch (entity.type)
{
case Raw:
return send_raw_entity(entity);
break;
case Table:
return send_table_entity(entity);
break;
case NoEntity:
// No-op
break;
default:
abort();
break;
}
}
}
/** Pack the data within the current page (As set with the 'P' command) into a buffer and send it.
*
* Creates a page iterator by @ref page_begin() (See: pages.cpp). Sends page given in @ref currentPage.
*
* Note that some translation of the data is required to lay it out in the way Megasquirt / TunerStudio expect it.
* Data is sent in binary format, as defined by in each page in the speeduino.ini.
*/
void sendPage(void)
{
page_iterator_t entity = page_begin(currentPage);
while (entity.type!=End)
{
send_entity(entity);
entity = advance(entity);
}
}
namespace {
/// Prints each element in the memory byte range (*first, *last).
void serial_println_range(const byte *first, const byte *last)
{
while (first!=last)
{
Serial.println(*first);
++first;
}
}
void serial_println_range(const uint16_t *first, const uint16_t *last)
{
while (first!=last)
{
Serial.println(*first);
++first;
}
}
void serial_print_space_delimited(const byte *first, const byte *last)
{
while (first!=last)
{
Serial.print(*first);// This displays the values horizontally on the screen
Serial.print(F(" "));
++first;
}
Serial.println();
}
#define serial_print_space_delimited_array(array) serial_print_space_delimited(array, _end_range_address(array))
void serial_print_prepadding(byte value)
{
if (value < 100)
{
Serial.print(F(" "));
if (value < 10)
{
Serial.print(F(" "));
}
}
}
void serial_print_prepadded_value(byte value)
{
serial_print_prepadding(value);
Serial.print(value);
Serial.print(F(" "));
}
void print_row(const table_axis_iterator &y_it, table_row_iterator row)
{
serial_print_prepadded_value(table3d_axis_io::to_byte(y_it.get_domain(), *y_it));
while (!row.at_end())
{
serial_print_prepadded_value(*row);
++row;
}
Serial.println();
}
void print_x_axis(const void *pTable, table_type_t key)
{
Serial.print(F(" "));
auto x_it = x_begin(pTable, key);
const int16_byte *pConverter = table3d_axis_io::get_converter(x_it.get_domain());
while(!x_it.at_end())
{
serial_print_prepadded_value(pConverter->to_byte(*x_it));
++x_it;
}
}
void serial_print_3dtable(const void *pTable, table_type_t key)
{
auto y_it = y_begin(pTable, key);
auto row_it = rows_begin(pTable, key);
while (!row_it.at_end())
{
print_row(y_it, *row_it);
++y_it;
++row_it;
}
print_x_axis(pTable, key);
Serial.println();
}
}
/** Send page as ASCII for debugging purposes.
* Similar to sendPage(), however data is sent in human readable format. Sends page given in @ref currentPage.
*
* This is used for testing only (Not used by TunerStudio) in order to see current map and config data without the need for TunerStudio.
*/
void sendPageASCII(void)
{
switch (currentPage)
{
case veMapPage:
Serial.println(F("\nVE Map"));
serial_print_3dtable(&fuelTable, fuelTable.type_key);
break;
case veSetPage:
Serial.println(F("\nPg 2 Cfg"));
// The following loop displays in human readable form of all byte values in config page 1 up to but not including the first array.
serial_println_range((byte *)&configPage2, configPage2.wueValues);
serial_print_space_delimited_array(configPage2.wueValues);
// This displays all the byte values between the last array up to but not including the first unsigned int on config page 1
serial_println_range(_end_range_byte_address(configPage2.wueValues), (byte*)&configPage2.injAng);
// The following loop displays four unsigned ints
serial_println_range(configPage2.injAng, configPage2.injAng + _countof(configPage2.injAng));
// Following loop displays byte values between the unsigned ints
serial_println_range(_end_range_byte_address(configPage2.injAng), (byte*)&configPage2.mapMax);
Serial.println(configPage2.mapMax);
// Following loop displays remaining byte values of the page
serial_println_range(&configPage2.fpPrime, (byte *)&configPage2 + sizeof(configPage2));
break;
case ignMapPage:
Serial.println(F("\nIgnition Map"));
serial_print_3dtable(&ignitionTable, ignitionTable.type_key);
break;
case ignSetPage:
Serial.println(F("\nPg 4 Cfg"));
Serial.println(configPage4.triggerAngle);// configPage4.triggerAngle is an int so just display it without complication
// Following loop displays byte values after that first int up to but not including the first array in config page 2
serial_println_range((byte*)&configPage4.FixAng, configPage4.taeBins);
serial_print_space_delimited_array(configPage4.taeBins);
serial_print_space_delimited_array(configPage4.taeValues);
serial_print_space_delimited_array(configPage4.wueBins);
Serial.println(configPage4.dwellLimit);// Little lonely byte stuck between two arrays. No complications just display it.
serial_print_space_delimited_array(configPage4.dwellCorrectionValues);
serial_println_range(_end_range_byte_address(configPage4.dwellCorrectionValues), (byte *)&configPage4 + sizeof(configPage4));
break;
case afrMapPage:
Serial.println(F("\nAFR Map"));
serial_print_3dtable(&afrTable, afrTable.type_key);
break;
case afrSetPage:
Serial.println(F("\nPg 6 Config"));
serial_println_range((byte *)&configPage6, configPage6.voltageCorrectionBins);
serial_print_space_delimited_array(configPage6.voltageCorrectionBins);
serial_print_space_delimited_array(configPage6.injVoltageCorrectionValues);
serial_print_space_delimited_array(configPage6.airDenBins);
serial_print_space_delimited_array(configPage6.airDenRates);
serial_println_range(_end_range_byte_address(configPage6.airDenRates), configPage6.iacCLValues);
serial_print_space_delimited_array(configPage6.iacCLValues);
serial_print_space_delimited_array(configPage6.iacOLStepVal);
serial_print_space_delimited_array(configPage6.iacOLPWMVal);
serial_print_space_delimited_array(configPage6.iacBins);
serial_print_space_delimited_array(configPage6.iacCrankSteps);
serial_print_space_delimited_array(configPage6.iacCrankDuty);
serial_print_space_delimited_array(configPage6.iacCrankBins);
// Following loop is for remaining byte value of page
serial_println_range(_end_range_byte_address(configPage6.iacCrankBins), (byte *)&configPage6 + sizeof(configPage6));
break;
case boostvvtPage:
Serial.println(F("\nBoost Map"));
serial_print_3dtable(&boostTable, boostTable.type_key);
Serial.println(F("\nVVT Map"));
serial_print_3dtable(&vvtTable, vvtTable.type_key);
break;
case seqFuelPage:
Serial.println(F("\nTrim 1 Table"));
serial_print_3dtable(&trim1Table, trim1Table.type_key);
break;
case canbusPage:
Serial.println(F("\nPage 9 Cfg"));
serial_println_range((byte *)&configPage9, (byte *)&configPage9 + sizeof(configPage9));
break;
case fuelMap2Page:
Serial.println(F("\n2nd Fuel Map"));
serial_print_3dtable(&fuelTable2, fuelTable2.type_key);
break;
case ignMap2Page:
Serial.println(F("\n2nd Ignition Map"));
serial_print_3dtable(&ignitionTable2, ignitionTable2.type_key);
break;
case boostvvtPage2:
Serial.println(F("\nBoost lookup table"));
serial_print_3dtable(&boostTableLookupDuty, boostTableLookupDuty.type_key);
break;
case warmupPage:
case progOutsPage:
default:
#ifndef SMALL_FLASH_MODE
Serial.println(F("\nPage has not been implemented yet"));
#endif
break;
}
}
/** Processes an incoming stream of calibration data (for CLT, IAT or O2) from TunerStudio.
* Result is store in EEPROM and memory.
*
* @param tableID - calibration table to process. 0 = Coolant Sensor. 1 = IAT Sensor. 2 = O2 Sensor.
*/
void receiveCalibration(byte tableID)
{
void* pnt_TargetTable_values; //Pointer that will be used to point to the required target table values
uint16_t* pnt_TargetTable_bins; //Pointer that will be used to point to the required target table bins
int OFFSET, DIVISION_FACTOR;
switch (tableID)
{
case 0:
//coolant table
pnt_TargetTable_values = (uint16_t *)&cltCalibration_values;
pnt_TargetTable_bins = (uint16_t *)&cltCalibration_bins;
OFFSET = CALIBRATION_TEMPERATURE_OFFSET; //
DIVISION_FACTOR = 10;
break;
case 1:
//Inlet air temp table
pnt_TargetTable_values = (uint16_t *)&iatCalibration_values;
pnt_TargetTable_bins = (uint16_t *)&iatCalibration_bins;
OFFSET = CALIBRATION_TEMPERATURE_OFFSET;
DIVISION_FACTOR = 10;
break;
case 2:
//O2 table
//pnt_TargetTable = (byte *)&o2CalibrationTable;
pnt_TargetTable_values = (uint8_t *)&o2Calibration_values;
pnt_TargetTable_bins = (uint16_t *)&o2Calibration_bins;
OFFSET = 0;
DIVISION_FACTOR = 1;
break;
default:
OFFSET = 0;
pnt_TargetTable_values = (uint16_t *)&iatCalibration_values;
pnt_TargetTable_bins = (uint16_t *)&iatCalibration_bins;
DIVISION_FACTOR = 10;
break; //Should never get here, but if we do, just fail back to main loop
}
int16_t tempValue;
byte tempBuffer[2];
if(tableID == 2)
{
//O2 calibration. Comes through as 1024 8-bit values of which we use every 32nd
for (int x = 0; x < 1024; x++)
{
while ( Serial.available() < 1 ) {}
tempValue = Serial.read();
if( (x % 32) == 0)
{
((uint8_t*)pnt_TargetTable_values)[(x/32)] = (byte)tempValue; //O2 table stores 8 bit values
pnt_TargetTable_bins[(x/32)] = (x);
}
}
}
else
{
//Temperature calibrations are sent as 32 16-bit values
for (uint16_t x = 0; x < 32; x++)
{
while ( Serial.available() < 2 ) {}
tempBuffer[0] = Serial.read();
tempBuffer[1] = Serial.read();
tempValue = (int16_t)(word(tempBuffer[1], tempBuffer[0])); //Combine the 2 bytes into a single, signed 16-bit value
tempValue = div(tempValue, DIVISION_FACTOR).quot; //TS sends values multiplied by 10 so divide back to whole degrees.
tempValue = ((tempValue - 32) * 5) / 9; //Convert from F to C
//Apply the temp offset and check that it results in all values being positive
tempValue = tempValue + OFFSET;
if (tempValue < 0) { tempValue = 0; }
((uint16_t*)pnt_TargetTable_values)[x] = tempValue; //Both temp tables have 16-bit values
pnt_TargetTable_bins[x] = (x * 32U);
writeCalibration();
}
}
writeCalibration();
}
/** Send 256 tooth log entries to serial.
* if useChar is true, the values are sent as chars to be printed out by a terminal emulator
* if useChar is false, the values are sent as a 2 byte integer which is readable by TunerStudios tooth logger
*/
void sendToothLog_legacy(byte startOffset) /* Blocking */
{
//We need TOOTH_LOG_SIZE number of records to send to TunerStudio. If there aren't that many in the buffer then we just return and wait for the next call
if (BIT_CHECK(currentStatus.status1, BIT_STATUS1_TOOTHLOG1READY)) //Sanity check. Flagging system means this should always be true
{
serialStatusFlag = SERIAL_TRANSMIT_TOOTH_INPROGRESS_LEGACY;
for (int x = startOffset; x < TOOTH_LOG_SIZE; x++)
{
Serial.write(toothHistory[x] >> 24);
Serial.write(toothHistory[x] >> 16);
Serial.write(toothHistory[x] >> 8);
Serial.write(toothHistory[x]);
}
BIT_CLEAR(currentStatus.status1, BIT_STATUS1_TOOTHLOG1READY);
serialStatusFlag = SERIAL_INACTIVE;
toothHistoryIndex = 0;
}
else
{
//TunerStudio has timed out, send a LOG of all 0s
for(int x = 0; x < (4*TOOTH_LOG_SIZE); x++)
{
Serial.write(static_cast<byte>(0x00)); //GCC9 fix
}
serialStatusFlag = SERIAL_INACTIVE;
}
}
void sendCompositeLog_legacy(byte startOffset) /* Non-blocking */
{
if (BIT_CHECK(currentStatus.status1, BIT_STATUS1_TOOTHLOG1READY)) //Sanity check. Flagging system means this should always be true
{
serialStatusFlag = SERIAL_TRANSMIT_COMPOSITE_INPROGRESS_LEGACY;
for (int x = startOffset; x < TOOTH_LOG_SIZE; x++)
{
//Check whether the tx buffer still has space
if(Serial.availableForWrite() < 4)
{
//tx buffer is full. Store the current state so it can be resumed later
logItemsTransmitted = x;
return;
}
uint32_t inProgressCompositeTime = toothHistory[x]; //This combined runtime (in us) that the log was going for by this record)
Serial.write(inProgressCompositeTime >> 24);
Serial.write(inProgressCompositeTime >> 16);
Serial.write(inProgressCompositeTime >> 8);
Serial.write(inProgressCompositeTime);
Serial.write(compositeLogHistory[x]); //The status byte (Indicates the trigger edge, whether it was a pri/sec pulse, the sync status)
}
BIT_CLEAR(currentStatus.status1, BIT_STATUS1_TOOTHLOG1READY);
toothHistoryIndex = 0;
serialStatusFlag = SERIAL_INACTIVE;
}
else
{
//TunerStudio has timed out, send a LOG of all 0s
for(int x = 0; x < (5*TOOTH_LOG_SIZE); x++)
{
Serial.write(static_cast<byte>(0x00)); //GCC9 fix
}
serialStatusFlag = SERIAL_INACTIVE;
}
}
void testComm(void)
{
Serial.write(1);
return;
}
| 44,983
|
C++
|
.cpp
| 1,133
| 33.415711
| 216
| 0.658937
|
oelprinz-org/BlitzboxBL49sp
| 36
| 12
| 0
|
GPL-3.0
|
9/20/2024, 10:45:08 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,540,058
|
LambdaCtrl.h
|
oelprinz-org_BlitzboxBL49sp/software/Onboard_WB_Lambda_V0.0.6-V0.1.1/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 /* BlitzBoxBL49sp PWM output (0.5-4.5V) */
#define EN_INPUT_PIN 16 /* Enable pin, low when engine running */
/* 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 allowerd calibration value
#define UR_MIN_VALUE 150 // Min allowed calibration value
#define UR_MAX_VALUE 300 // Max allowerd 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 3 // 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) */
/* Define stoichiometric mixture variable */
/* Gasoline = 14.70 | E85 Alcohol = 9.77 | E100 Alcohol = 9.01 | Alcohol (Methanol) = 6.40 | Propane = 15.50 | Diesel = 14.50 | Nitro = 1.70 */
const float STOICH_MIXTURE = 14.7;
/* 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)
int AFR;
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);
| 7,819
|
C++
|
.h
| 198
| 36.535354
| 144
| 0.68987
|
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,059
|
tests_maths.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/test/test_misc/tests_maths.h
|
extern void testMaths();
void test_maths_percent_U8(void);
void test_maths_percent_U16(void);
void test_maths_percent_U32(void);
void test_maths_halfpercent_U8(void);
void test_maths_halfpercent_U16(void);
void test_maths_halfpercent_U32(void);
void test_maths_div100_U8(void);
void test_maths_div100_U16(void);
void test_maths_div100_U32(void);
void test_maths_div100_S8(void);
void test_maths_div100_S16(void);
void test_maths_div100_S32(void);
void test_maths_div10_U8(void);
void test_maths_div10_U16(void);
void test_maths_div10_U32(void);
| 547
|
C++
|
.h
| 16
| 33.0625
| 38
| 0.79206
|
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,060
|
tests_init.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/test/test_misc/tests_init.h
|
#define UNKNOWN_PIN 0xFF
extern void testInitialisation();
void test_initialisation_complete(void);
void test_initialisation_ports(void);
void test_initialisation_outputs_V03(void);
void test_initialisation_outputs_V04(void);
void test_initialisation_outputs_MX5_8995(void);
uint8_t getPinMode(uint8_t);
| 304
|
C++
|
.h
| 8
| 37
| 48
| 0.834459
|
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,061
|
test_corrections.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/test/test_fuel/test_corrections.h
|
void testCorrections();
void test_corrections_WUE(void);
void test_corrections_cranking(void);
void test_corrections_ASE(void);
void test_corrections_floodclear(void);
void test_corrections_closedloop(void);
void test_corrections_flex(void);
void test_corrections_bat(void);
void test_corrections_iatdensity(void);
void test_corrections_baro(void);
void test_corrections_launch(void);
void test_corrections_dfco(void);
| 418
|
C++
|
.h
| 12
| 33.916667
| 39
| 0.82801
|
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,062
|
test_PW.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/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();
| 259
|
C++
|
.h
| 8
| 31.5
| 46
| 0.781746
|
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,063
|
test_schedules.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/test/test_schedules/test_schedules.h
|
#if !defined(__TEST_SCHEDULE_H__)
#define __TEST_SCHEDULE_H__
void testSchedules();
void test_status_initial_off(void);
void test_status_off_to_pending(void);
void test_status_pending_to_running(void);
void test_status_running_to_off(void);
void test_status_running_to_pending(void);
void test_accuracy_timeout(void);
void test_accuracy_duration(void);
#endif // __TEST_SCHEDULE_H__
| 385
|
C++
|
.h
| 11
| 33.818182
| 42
| 0.771505
|
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,064
|
sensors.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/speeduino/sensors.h
|
#ifndef SENSORS_H
#define SENSORS_H
#include "Arduino.h"
// The following are alpha values for the ADC filters.
// Their values are from 0 to 240, with 0 being no filtering and 240 being maximum
#define ADCFILTER_TPS_DEFAULT 50
#define ADCFILTER_CLT_DEFAULT 180
#define ADCFILTER_IAT_DEFAULT 180
#define ADCFILTER_O2_DEFAULT 128
#define ADCFILTER_BAT_DEFAULT 128
#define ADCFILTER_MAP_DEFAULT 20 //This is only used on Instantaneous MAP readings and is intentionally very weak to allow for faster response
#define ADCFILTER_BARO_DEFAULT 64
#define ADCFILTER_PSI_DEFAULT 150 //not currently configurable at runtime, used for misc pressure sensors, oil, fuel, etc.
#define FILTER_FLEX_DEFAULT 75
#define BARO_MIN 65
#define BARO_MAX 108
#define KNOCK_MODE_DIGITAL 1
#define KNOCK_MODE_ANALOG 2
#define VSS_GEAR_HYSTERESIS 10
#define VSS_SAMPLES 4 //Must be a power of 2 and smaller than 255
#define TPS_READ_FREQUENCY 30 //ONLY VALID VALUES ARE 15 or 30!!!
/*
#if defined(CORE_AVR)
#define ANALOG_ISR
#endif
*/
volatile byte flexCounter = 0;
volatile unsigned long flexStartTime;
volatile unsigned long flexPulseWidth;
#if defined(CORE_AVR)
#define READ_FLEX() ((*flex_pin_port & flex_pin_mask) ? true : false)
#else
#define READ_FLEX() digitalRead(pinFlex)
#endif
volatile byte knockCounter = 0;
volatile uint16_t knockAngle;
unsigned long MAPrunningValue; //Used for tracking either the total of all MAP readings in this cycle (Event average) or the lowest value detected in this cycle (event minimum)
unsigned long EMAPrunningValue; //As above but for EMAP
unsigned int MAPcount; //Number of samples taken in the current MAP cycle
uint32_t MAPcurRev; //Tracks which revolution we're sampling on
bool auxIsEnabled;
byte TPSlast; /**< The previous TPS reading */
unsigned long TPS_time; //The time the TPS sample was taken
unsigned long TPSlast_time; //The time the previous TPS sample was taken
byte MAPlast; /**< The previous MAP reading */
unsigned long MAP_time; //The time the MAP sample was taken
unsigned long MAPlast_time; //The time the previous MAP sample was taken
volatile unsigned long vssTimes[VSS_SAMPLES] = {0};
volatile byte vssIndex;
//These variables are used for tracking the number of running sensors values that appear to be errors. Once a threshold is reached, the sensor reading will go to default value and assume the sensor is faulty
byte mapErrorCount = 0;
byte iatErrorCount = 0;
byte cltErrorCount = 0;
/**
* @brief Simple low pass IIR filter macro for the analog inputs
* This is effectively implementing the smooth filter from playground.arduino.cc/Main/Smooth
* But removes the use of floats and uses 8 bits of fixed precision.
*/
#define ADC_FILTER(input, alpha, prior) (((long)input * (256 - alpha) + ((long)prior * alpha))) >> 8
static inline void instanteneousMAPReading() __attribute__((always_inline));
static inline void readMAP() __attribute__((always_inline));
static inline void validateMAP();
void initialiseADC();
void readTPS(bool=true); //Allows the option to override the use of the filter
void readO2_2();
void flexPulse();
uint32_t vssGetPulseGap(byte);
void vssPulse();
uint16_t getSpeed();
byte getGear();
byte getFuelPressure();
byte getOilPressure();
uint16_t readAuxanalog(uint8_t analogPin);
uint16_t readAuxdigital(uint8_t digitalPin);
void readCLT(bool=true); //Allows the option to override the use of the filter
void readIAT();
void readO2();
void readBat();
void readBaro();
#if defined(ANALOG_ISR)
volatile int AnChannel[15];
//Analog ISR interrupt routine
/*
ISR(ADC_vect)
{
byte nChannel;
int result = ADCL | (ADCH << 8);
//ADCSRA = 0x6E; - ADC disabled by clearing bit 7(ADEN)
//BIT_CLEAR(ADCSRA, ADIE);
nChannel = ADMUX & 0x07;
#if defined(__AVR_ATmega1281__) || defined(__AVR_ATmega2561__)
if (nChannel==7) { ADMUX = 0x40; }
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
if(ADCSRB & 0x08) { nChannel += 8; } //8 to 15
if(nChannel == 15)
{
ADMUX = 0x40; //channel 0
ADCSRB = 0x00; //clear MUX5 bit
}
else if (nChannel == 7) //channel 7
{
ADMUX = 0x40;
ADCSRB = 0x08; //Set MUX5 bit
}
#endif
else { ADMUX++; }
AnChannel[nChannel-1] = result;
//BIT_SET(ADCSRA, ADIE);
//ADCSRA = 0xEE; - ADC Interrupt Flag enabled
}
*/
ISR(ADC_vect)
{
byte nChannel = ADMUX & 0x07;
int result = ADCL | (ADCH << 8);
BIT_CLEAR(ADCSRA, ADEN); //Disable ADC for Changing Channel (see chapter 26.5 of datasheet)
#if defined(__AVR_ATmega1281__) || defined(__AVR_ATmega2561__)
if (nChannel==7) { ADMUX = 0x40; }
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
if( (ADCSRB & 0x08) > 0) { nChannel += 8; } //8 to 15
if(nChannel == 15)
{
ADMUX = 0x40; //channel 0
ADCSRB = 0x00; //clear MUX5 bit
}
else if (nChannel == 7) //channel 7
{
ADMUX = 0x40;
ADCSRB = 0x08; //Set MUX5 bit
}
#endif
else { ADMUX++; }
AnChannel[nChannel] = result;
BIT_SET(ADCSRA, ADEN); //Enable ADC
}
#endif
#endif // SENSORS_H
| 5,106
|
C++
|
.h
| 137
| 34.854015
| 207
| 0.724863
|
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,065
|
storage.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/speeduino/storage.h
|
#ifndef STORAGE_H
#define STORAGE_H
/** @file storage.h
* @brief Functions for reading and writing user settings to/from EEPROM
*
* Current layout of EEPROM is as follows (Version 18):
*
* |Offset (Dec)|Size (Bytes)| Description | Reference |
* | ---------: | :--------: | :----------------------------------: | :--------------------------------- |
* | 0 |1 | EEPROM version | @ref EEPROM_DATA_VERSION |
* | 1 |2 | X and Y sizes for fuel table | |
* | 3 |256 | Fuel table (16x16) | @ref EEPROM_CONFIG1_MAP |
* | 259 |16 | Fuel table (X axis) (RPM) | |
* | 275 |16 | Fuel table (Y axis) (MAP/TPS) | |
* | 291 |128 | Page 2 settings | @ref EEPROM_CONFIG2_START |
* | 419 |2 | X and Y sizes for ignition table | |
* | 421 |256 | Ignition table (16x16) | @ref EEPROM_CONFIG3_MAP |
* | 677 |16 | Ignition table (X axis) (RPM) | |
* | 693 |16 | Ignition table (Y axis) (MAP/TPS) | |
* | 709 |128 | Page 4 settings | @ref EEPROM_CONFIG4_START |
* | 837 |2 | X and Y sizes for AFR target table | |
* | 839 |256 | AFR target table (16x16) | @ref EEPROM_CONFIG5_MAP |
* | 1095 |16 | AFR target table (X axis) (RPM) | |
* | 1111 |16 | AFR target table (Y axis) (MAP/TPS) | |
* | 1127 |128 | Page 6 settings | @ref EEPROM_CONFIG6_START |
* | 1255 |2 | X and Y sizes for boost table | |
* | 1257 |64 | Boost table (8x8) | @ref EEPROM_CONFIG7_MAP1 |
* | 1321 |8 | Boost table (X axis) (RPM) | |
* | 1329 |8 | Boost table (Y axis) (TPS) | |
* | 1337 |2 | X and Y sizes for vvt table | |
* | 1339 |64 | VVT table (8x8) | @ref EEPROM_CONFIG7_MAP2 |
* | 1403 |8 | VVT table (X axis) (RPM) | |
* | 1411 |8 | VVT table (Y axis) (MAP) | |
* | 1419 |2 | X and Y sizes for staging table | |
* | 1421 |64 | Staging table (8x8) | @ref EEPROM_CONFIG7_MAP3 |
* | 1485 |8 | Staging table (X axis) (RPM) | |
* | 1493 |8 | Staging table (Y axis) (MAP) | |
* | 1501 |2 | X and Y sizes for trim1 table | |
* | 1503 |36 | Trim1 table (6x6) | @ref EEPROM_CONFIG8_MAP1 |
* | 1539 |6 | Trim1 table (X axis) (RPM) | |
* | 1545 |6 | Trim1 table (Y axis) (MAP) | |
* | 1551 |2 | X and Y sizes for trim2 table | |
* | 1553 |36 | Trim2 table (6x6) | @ref EEPROM_CONFIG8_MAP2 |
* | 1589 |6 | Trim2 table (X axis) (RPM) | |
* | 1595 |6 | Trim2 table (Y axis) (MAP) | |
* | 1601 |2 | X and Y sizes for trim3 table | |
* | 1603 |36 | Trim3 table (6x6) | @ref EEPROM_CONFIG8_MAP3 |
* | 1639 |6 | Trim3 table (X axis) (RPM) | |
* | 1545 |6 | Trim3 table (Y axis) (MAP) | |
* | 1651 |2 | X and Y sizes for trim4 table | |
* | 1653 |36 | Trim4 table (6x6) | @ref EEPROM_CONFIG8_MAP4 |
* | 1689 |6 | Trim4 table (X axis) (RPM) | |
* | 1595 |6 | Trim4 table (Y axis) (MAP) | |
* | 1701 |9 | HOLE ?? | |
* | 1710 |192 | Page 9 settings | @ref EEPROM_CONFIG9_START |
* | 1902 |192 | Page 10 settings | @ref EEPROM_CONFIG10_START |
* | 2094 |2 | X and Y sizes for fuel2 table | |
* | 2096 |256 | Fuel2 table (16x16) | @ref EEPROM_CONFIG11_MAP |
* | 2352 |16 | Fuel2 table (X axis) (RPM) | |
* | 2368 |16 | Fuel2 table (Y axis) (MAP/TPS) | |
* | 2384 |1 | HOLE ?? | |
* | 2385 |2 | X and Y sizes for WMI table | |
* | 2387 |64 | WMI table (8x8) | @ref EEPROM_CONFIG12_MAP |
* | 2451 |8 | WMI table (X axis) (RPM) | |
* | 2459 |8 | WMI table (Y axis) (MAP) | |
* | 2467 |2 | X and Y sizes VVT2 table | |
* | 2469 |64 | VVT2 table (8x8) | @ref EEPROM_CONFIG12_MAP2 |
* | 2553 |8 | VVT2 table (X axis) (RPM) | |
* | 2541 |8 | VVT2 table (Y axis) (MAP) | |
* | 2549 |2 | X and Y sizes dwell table | |
* | 2551 |16 | Dwell table (4x4) | @ref EEPROM_CONFIG12_MAP3 |
* | 2567 |4 | Dwell table (X axis) (RPM) | |
* | 2571 |4 | Dwell table (Y axis) (MAP) | |
* | 2575 |5 | HOLE ?? | |
* | 2580 |128 | Page 13 settings | @ref EEPROM_CONFIG13_START |
* | 2708 |2 | X and Y sizes for ignition2 table | |
* | 2710 |256 | Ignition2 table (16x16) | @ref EEPROM_CONFIG14_MAP |
* | 2966 |16 | Ignition2 table (X axis) (RPM) | |
* | 2982 |16 | Ignition2 table (Y axis) (MAP/TPS) | |
* | 2998 |1 | HOLE ?? | |
* | 2999 |2 | X and Y sizes for trim5 table | |
* | 3001 |36 | Trim5 table (6x6) | @ref EEPROM_CONFIG8_MAP5 |
* | 3037 |6 | Trim5 table (X axis) (RPM) | |
* | 3043 |6 | Trim5 table (Y axis) (MAP) | |
* | 3049 |2 | X and Y sizes for trim6 table | |
* | 3051 |36 | Trim6 table (6x6) | @ref EEPROM_CONFIG8_MAP6 |
* | 3087 |6 | Trim6 table (X axis) (RPM) | |
* | 3093 |6 | Trim6 table (Y axis) (MAP) | |
* | 3099 |2 | X and Y sizes for trim7 table | |
* | 3101 |36 | Trim7 table (6x6) | @ref EEPROM_CONFIG8_MAP7 |
* | 3137 |6 | Trim7 table (X axis) (RPM) | |
* | 3143 |6 | Trim7 table (Y axis) (MAP) | |
* | 3149 |2 | X and Y sizes for trim8 table | |
* | 3151 |36 | Trim8 table (6x6) | @ref EEPROM_CONFIG8_MAP8 |
* | 3187 |6 | Trim8 table (X axis) (RPM) | |
* | 3193 |6 | Trim8 table (Y axis) (MAP) | |
* | 3199 |487 | EMPTY | |
* | 3686 |56 | Page CRC32 sums (4x14) | Last first, 14 -> 1 |
* | 3742 |1 | Baro value saved at init | @ref EEPROM_LAST_BARO |
* | 3743 |64 | O2 Calibration Bins | @ref EEPROM_CALIBRATION_O2_BINS |
* | 3807 |32 | O2 Calibration Values | @ref EEPROM_CALIBRATION_O2_VALUES |
* | 3839 |64 | IAT Calibration Bins | @ref EEPROM_CALIBRATION_IAT_BINS |
* | 3903 |64 | IAT Calibration Values | @ref EEPROM_CALIBRATION_IAT_VALUES |
* | 3967 |64 | CLT Calibration Bins | @ref EEPROM_CALIBRATION_CLT_BINS |
* | 4031 |64 | CLT Calibration Values | @ref EEPROM_CALIBRATION_CLT_VALUES |
* | 4095 | | END | |
*
*/
void writeAllConfig();
void writeConfig(uint8_t pageNum);
void loadConfig();
void loadCalibration();
void writeCalibration();
void writeCalibrationPage(uint8_t pageNum);
void resetConfigPages();
void enableForceBurn();
void disableForceBurn();
//These are utility functions that prevent other files from having to use EEPROM.h directly
byte readLastBaro();
void storeLastBaro(byte);
uint8_t readEEPROMVersion();
void storeEEPROMVersion(uint8_t);
void storePageCRC32(uint8_t pageNum, uint32_t crcValue);
uint32_t readPageCRC32(uint8_t pageNum);
bool isEepromWritePending();
#define EEPROM_CONFIG1_MAP 3
#define EEPROM_CONFIG2_START 291
#define EEPROM_CONFIG2_END 419
#define EEPROM_CONFIG3_MAP 421
#define EEPROM_CONFIG4_START 709
#define EEPROM_CONFIG4_END 837
#define EEPROM_CONFIG5_MAP 839
#define EEPROM_CONFIG6_START 1127
#define EEPROM_CONFIG6_END 1255
#define EEPROM_CONFIG7_MAP1 1257
#define EEPROM_CONFIG7_MAP2 1339
#define EEPROM_CONFIG7_MAP3 1421
#define EEPROM_CONFIG7_END 1501
#define EEPROM_CONFIG8_MAP1 1503
#define EEPROM_CONFIG8_MAP2 1553
#define EEPROM_CONFIG8_MAP3 1603
#define EEPROM_CONFIG8_MAP4 1653
#define EEPROM_CONFIG9_START 1710
#define EEPROM_CONFIG9_END 1902
#define EEPROM_CONFIG10_START 1902
#define EEPROM_CONFIG10_END 2094
#define EEPROM_CONFIG11_MAP 2096
#define EEPROM_CONFIG11_END 2385
#define EEPROM_CONFIG12_MAP 2387
#define EEPROM_CONFIG12_MAP2 2469
#define EEPROM_CONFIG12_MAP3 2551
#define EEPROM_CONFIG12_END 2575
#define EEPROM_CONFIG13_START 2580
#define EEPROM_CONFIG13_END 2708
#define EEPROM_CONFIG14_MAP 2710
#define EEPROM_CONFIG14_END 2998
//This is OUT OF ORDER as Page 8 was expanded to add fuel trim tables 5-8. The EEPROM for them is simply added here so as not to impact existing tunes
#define EEPROM_CONFIG8_MAP5 3001
#define EEPROM_CONFIG8_MAP6 3051
#define EEPROM_CONFIG8_MAP7 3101
#define EEPROM_CONFIG8_MAP8 3151
//These were the values used previously when all calibration tables were 512 long. They need to be retained so the update process (202005 -> 202008) can work
#define EEPROM_CALIBRATION_O2_OLD 2559
#define EEPROM_CALIBRATION_IAT_OLD 3071
#define EEPROM_CALIBRATION_CLT_OLD 3583
#endif // STORAGE_H
| 13,039
|
C++
|
.h
| 166
| 76.873494
| 157
| 0.376963
|
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,066
|
pages.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/speeduino/pages.h
|
#pragma once
#include <Arduino.h>
#include "table3d.h"
/**
* Page count, as defined in the INI file
*/
uint8_t getPageCount();
/**
* Page size in bytes
*/
uint16_t getPageSize(byte pageNum /**< [in] The page number */ );
// These are the page numbers that the Tuner Studio serial protocol uses to transverse the different map and config pages.
#define veMapPage 2
#define veSetPage 1 //Note that this and the veMapPage were swapped in Feb 2019 as the 'algorithm' field must be declared in the ini before it's used in the fuel table
#define ignMapPage 3
#define ignSetPage 4//Config Page 2
#define afrMapPage 5
#define afrSetPage 6//Config Page 3
#define boostvvtPage 7
#define seqFuelPage 8
#define canbusPage 9//Config Page 9
#define warmupPage 10 //Config Page 10
#define fuelMap2Page 11
#define wmiMapPage 12
#define progOutsPage 13
#define ignMap2Page 14
// ============================== Per-byte page access ==========================
/**
* Gets a single value from a page, with data aligned as per the ini file
*/
byte getPageValue( byte pageNum, /**< [in] The page number to retrieve data from. */
uint16_t offset /**< [in] The address in the page that should be returned. This is as per the page definition in the ini. */
);
/**
* Sets a single value from a page, with data aligned as per the ini file
*/
void setPageValue( byte pageNum, /**< [in] The page number to retrieve data from. */
uint16_t offset, /**< [in] The address in the page that should be returned. This is as per the page definition in the ini. */
byte value /**< [in] The new value */
);
// ============================== Page Iteration ==========================
// A logical TS page is actually multiple in memory entities. Allow iteration
// over those entities.
// Type of entity
enum entity_type {
Raw, // A block of memory
Table, // A 3D table
NoEntity, // No entity, but a valid offset
End // The offset was past any known entity for the page
};
// A entity on a logical page.
struct page_iterator_t {
void *pData;
table_type_t table_key;
uint8_t page; // The page the entity belongs to
uint16_t start; // The start position of the entity, in bytes, from the start of the page
uint16_t size; // Size of the entity in bytes
entity_type type;
};
/**
* Initiates iteration over a pages entities.
* Test `entity.type==End` to determine the end of the page.
*/
page_iterator_t page_begin(byte pageNum /**< [in] The page number to iterate over. */);
/**
* Moves the iterator to the next sub-entity on the page
*/
page_iterator_t advance(const page_iterator_t &it /**< [in] The current iterator */);
/**
* Convert page iterator to table value iterator.
*/
table_value_iterator rows_begin(const page_iterator_t &it);
/**
* Convert page iterator to table x axis iterator.
*/
table_axis_iterator x_begin(const page_iterator_t &it);
/**
* Convert page iterator to table y axis iterator.
*/
table_axis_iterator y_begin(const page_iterator_t &it);
| 3,173
|
C++
|
.h
| 80
| 36.4625
| 170
| 0.661144
|
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,067
|
board_stm32_generic.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/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 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) ) //Forbiden 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
/*
***********************************************************************************************************
* Auxilliaries
*/
#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 &CANSerial = Serial2;
#else //libmaple core aka STM32DUINO
HardwareSerial &CANSerial = Serial2;
#endif
#endif //CORE_STM32
#endif //STM32_H
| 8,655
|
C++
|
.h
| 195
| 40.892308
| 155
| 0.618104
|
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,068
|
board_same51.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/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
#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) ) //Forbiden 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)
/*
***********************************************************************************************************
* Auxilliaries
*/
//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 CANSerial (&sercom3, 0, 1, SERCOM_RX_PAD_1, UART_TX_PAD_0);
#endif //CORE_SAMD21
#endif //SAMD21_H
| 8,528
|
C++
|
.h
| 171
| 46.842105
| 178
| 0.669906
|
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,069
|
engineProtection.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/speeduino/engineProtection.h
|
byte checkEngineProtect();
byte checkRevLimit();
byte checkBoostLimit();
byte checkOilPressureLimit();
byte checkAFRLimit();
| 128
|
C++
|
.h
| 5
| 24
| 29
| 0.833333
|
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,070
|
maths.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/speeduino/maths.h
|
#ifndef MATH_H
#define MATH_H
#include "globals.h"
#define USE_LIBDIVIDE
int fastMap1023toX(int, int);
unsigned long percentage(byte, unsigned long);
unsigned long halfPercentage(byte, unsigned long);
inline long powint(int, unsigned int);
int32_t divs100(int32_t);
unsigned long divu100(unsigned long);
uint32_t divu10(uint32_t);
#define DIV_ROUND_CLOSEST(n, d) ((((n) < 0) ^ ((d) < 0)) ? (((n) - (d)/2)/(d)) : (((n) + (d)/2)/(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
| 939
|
C++
|
.h
| 18
| 50.777778
| 155
| 0.717724
|
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,071
|
scheduledIO.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/speeduino/scheduledIO.h
|
#ifndef SCHEDULEDIO_H
#define SCHEDULEDIO_H
#include <Arduino.h>
inline void openInjector1();
inline void closeInjector1();
inline void openInjector2();
inline void closeInjector2();
inline void openInjector3();
inline void closeInjector3();
inline void openInjector4();
inline void closeInjector4();
inline void openInjector5();
inline void closeInjector5();
inline void openInjector6();
inline void closeInjector6();
inline void openInjector7();
inline void closeInjector7();
inline void openInjector8();
inline void closeInjector8();
// These are for Semi-Sequential and 5 Cylinder injection
void openInjector1and4();
void closeInjector1and4();
void openInjector2and3();
void closeInjector2and3();
void openInjector3and5();
void closeInjector3and5();
void openInjector2and5();
void closeInjector2and5();
void openInjector3and6();
void closeInjector3and6();
void openInjector1and5();
void closeInjector1and5();
void openInjector2and6();
void closeInjector2and6();
void openInjector3and7();
void closeInjector3and7();
void openInjector4and8();
void closeInjector4and8();
void injector1Toggle();
void injector2Toggle();
void injector3Toggle();
void injector4Toggle();
void injector5Toggle();
void injector6Toggle();
void injector7Toggle();
void injector8Toggle();
inline void beginCoil1Charge();
inline void endCoil1Charge();
inline void beginCoil2Charge();
inline void endCoil2Charge();
inline void beginCoil3Charge();
inline void endCoil3Charge();
inline void beginCoil4Charge();
inline void endCoil4Charge();
inline void beginCoil5Charge();
inline void endCoil5Charge();
inline void beginCoil6Charge();
inline void endCoil6Charge();
inline void beginCoil7Charge();
inline void endCoil7Charge();
inline void beginCoil8Charge();
inline void endCoil8Charge();
//The following functions are used specifically for the trailing coil on rotary engines. They are separate as they also control the switching of the trailing select pin
inline void beginTrailingCoilCharge();
inline void endTrailingCoilCharge1();
inline void endTrailingCoilCharge2();
//And the combined versions of the above for simplicity
void beginCoil1and3Charge();
void endCoil1and3Charge();
void beginCoil2and4Charge();
void endCoil2and4Charge();
//For 6-cyl cop
void beginCoil1and4Charge();
void endCoil1and4Charge();
void beginCoil2and5Charge();
void endCoil2and5Charge();
void beginCoil3and6Charge();
void endCoil3and6Charge();
//For 8-cyl cop
void beginCoil1and5Charge();
void endCoil1and5Charge();
void beginCoil2and6Charge();
void endCoil2and6Charge();
void beginCoil3and7Charge();
void endCoil3and7Charge();
void beginCoil4and8Charge();
void endCoil4and8Charge();
void coil1Toggle();
void coil2Toggle();
void coil3Toggle();
void coil4Toggle();
void coil5Toggle();
void coil6Toggle();
void coil7Toggle();
void coil8Toggle();
/*
#ifndef USE_MC33810
#define openInjector1() *inj1_pin_port |= (inj1_pin_mask); BIT_SET(currentStatus.status1, BIT_STATUS1_INJ1)
#define closeInjector1() *inj1_pin_port &= ~(inj1_pin_mask); BIT_CLEAR(currentStatus.status1, BIT_STATUS1_INJ1)
#define openInjector2() *inj2_pin_port |= (inj2_pin_mask); BIT_SET(currentStatus.status1, BIT_STATUS1_INJ2)
#define closeInjector2() *inj2_pin_port &= ~(inj2_pin_mask); BIT_CLEAR(currentStatus.status1, BIT_STATUS1_INJ2)
#define openInjector3() *inj3_pin_port |= (inj3_pin_mask); BIT_SET(currentStatus.status1, BIT_STATUS1_INJ3)
#define closeInjector3() *inj3_pin_port &= ~(inj3_pin_mask); BIT_CLEAR(currentStatus.status1, BIT_STATUS1_INJ3)
#define openInjector4() *inj4_pin_port |= (inj4_pin_mask); BIT_SET(currentStatus.status1, BIT_STATUS1_INJ4)
#define closeInjector4() *inj4_pin_port &= ~(inj4_pin_mask); BIT_CLEAR(currentStatus.status1, BIT_STATUS1_INJ4)
#define openInjector5() *inj5_pin_port |= (inj5_pin_mask);
#define closeInjector5() *inj5_pin_port &= ~(inj5_pin_mask);
#define openInjector6() *inj6_pin_port |= (inj6_pin_mask);
#define closeInjector6() *inj6_pin_port &= ~(inj6_pin_mask);
#define openInjector7() *inj7_pin_port |= (inj7_pin_mask);
#define closeInjector7() *inj7_pin_port &= ~(inj7_pin_mask);
#define openInjector8() *inj8_pin_port |= (inj8_pin_mask);
#define closeInjector8() *inj8_pin_port &= ~(inj8_pin_mask);
#else
#include "acc_mc33810.h"
#define openInjector1() openInjector1_MC33810()
#define closeInjector1() closeInjector1_MC33810()
#define openInjector2() openInjector2_MC33810()
#define closeInjector2() closeInjector2_MC33810()
#define openInjector3() openInjector3_MC33810()
#define closeInjector3() closeInjector3_MC33810()
#define openInjector4() openInjector4_MC33810()
#define closeInjector4() closeInjector4_MC33810()
#define openInjector5() openInjector5_MC33810()
#define closeInjector5() closeInjector5_MC33810()
#define openInjector6() openInjector6_MC33810()
#define closeInjector6() closeInjector6_MC33810()
#define openInjector7() openInjector7_MC33810()
#define closeInjector7() closeInjector7_MC33810()
#define openInjector8() openInjector8_MC33810()
#define closeInjector8() closeInjector8_MC33810()
#endif
#define openInjector1and4() openInjector1(); openInjector4()
#define closeInjector1and4() closeInjector1(); closeInjector4()
#define openInjector2and3() openInjector2(); openInjector3()
#define closeInjector2and3() closeInjector2(); closeInjector3()
//5 cylinder support doubles up injector 3 as being closese to inj 5 (Crank angle)
#define openInjector3and5() openInjector3(); openInjector5()
#define closeInjector3and5() closeInjector3(); closeInjector5()
*/
//Macros are used to define how each injector control system functions. These are then called by the master openInjectx() function.
//The DIRECT macros (ie individual pins) are defined below. Others should be defined in their relevant acc_x.h file
#define openInjector1_DIRECT() { *inj1_pin_port |= (inj1_pin_mask); BIT_SET(currentStatus.status1, BIT_STATUS1_INJ1); }
#define closeInjector1_DIRECT() { *inj1_pin_port &= ~(inj1_pin_mask); BIT_CLEAR(currentStatus.status1, BIT_STATUS1_INJ1); }
#define openInjector2_DIRECT() { *inj2_pin_port |= (inj2_pin_mask); BIT_SET(currentStatus.status1, BIT_STATUS1_INJ2); }
#define closeInjector2_DIRECT() { *inj2_pin_port &= ~(inj2_pin_mask); BIT_CLEAR(currentStatus.status1, BIT_STATUS1_INJ2); }
#define openInjector3_DIRECT() { *inj3_pin_port |= (inj3_pin_mask); BIT_SET(currentStatus.status1, BIT_STATUS1_INJ3); }
#define closeInjector3_DIRECT() { *inj3_pin_port &= ~(inj3_pin_mask); BIT_CLEAR(currentStatus.status1, BIT_STATUS1_INJ3); }
#define openInjector4_DIRECT() { *inj4_pin_port |= (inj4_pin_mask); BIT_SET(currentStatus.status1, BIT_STATUS1_INJ4); }
#define closeInjector4_DIRECT() { *inj4_pin_port &= ~(inj4_pin_mask); BIT_CLEAR(currentStatus.status1, BIT_STATUS1_INJ4); }
#define openInjector5_DIRECT() { *inj5_pin_port |= (inj5_pin_mask); }
#define closeInjector5_DIRECT() { *inj5_pin_port &= ~(inj5_pin_mask); }
#define openInjector6_DIRECT() { *inj6_pin_port |= (inj6_pin_mask); }
#define closeInjector6_DIRECT() { *inj6_pin_port &= ~(inj6_pin_mask); }
#define openInjector7_DIRECT() { *inj7_pin_port |= (inj7_pin_mask); }
#define closeInjector7_DIRECT() { *inj7_pin_port &= ~(inj7_pin_mask); }
#define openInjector8_DIRECT() { *inj8_pin_port |= (inj8_pin_mask); }
#define closeInjector8_DIRECT() { *inj8_pin_port &= ~(inj8_pin_mask); }
#define coil1Low_DIRECT() (*ign1_pin_port &= ~(ign1_pin_mask))
#define coil1High_DIRECT() (*ign1_pin_port |= (ign1_pin_mask))
#define coil2Low_DIRECT() (*ign2_pin_port &= ~(ign2_pin_mask))
#define coil2High_DIRECT() (*ign2_pin_port |= (ign2_pin_mask))
#define coil3Low_DIRECT() (*ign3_pin_port &= ~(ign3_pin_mask))
#define coil3High_DIRECT() (*ign3_pin_port |= (ign3_pin_mask))
#define coil4Low_DIRECT() (*ign4_pin_port &= ~(ign4_pin_mask))
#define coil4High_DIRECT() (*ign4_pin_port |= (ign4_pin_mask))
#define coil5Low_DIRECT() (*ign5_pin_port &= ~(ign5_pin_mask))
#define coil5High_DIRECT() (*ign5_pin_port |= (ign5_pin_mask))
#define coil6Low_DIRECT() (*ign6_pin_port &= ~(ign6_pin_mask))
#define coil6High_DIRECT() (*ign6_pin_port |= (ign6_pin_mask))
#define coil7Low_DIRECT() (*ign7_pin_port &= ~(ign7_pin_mask))
#define coil7High_DIRECT() (*ign7_pin_port |= (ign7_pin_mask))
#define coil8Low_DIRECT() (*ign8_pin_port &= ~(ign8_pin_mask))
#define coil8High_DIRECT() (*ign8_pin_port |= (ign8_pin_mask))
//Set the value of the coil pins to the coilHIGH or coilLOW state
#define coil1Charging_DIRECT() (configPage4.IgInv == GOING_HIGH ? coil1Low_DIRECT() : coil1High_DIRECT())
#define coil1StopCharging_DIRECT() (configPage4.IgInv == GOING_HIGH ? coil1High_DIRECT() : coil1Low_DIRECT())
#define coil2Charging_DIRECT() (configPage4.IgInv == GOING_HIGH ? coil2Low_DIRECT() : coil2High_DIRECT())
#define coil2StopCharging_DIRECT() (configPage4.IgInv == GOING_HIGH ? coil2High_DIRECT() : coil2Low_DIRECT())
#define coil3Charging_DIRECT() (configPage4.IgInv == GOING_HIGH ? coil3Low_DIRECT() : coil3High_DIRECT())
#define coil3StopCharging_DIRECT() (configPage4.IgInv == GOING_HIGH ? coil3High_DIRECT() : coil3Low_DIRECT())
#define coil4Charging_DIRECT() (configPage4.IgInv == GOING_HIGH ? coil4Low_DIRECT() : coil4High_DIRECT())
#define coil4StopCharging_DIRECT() (configPage4.IgInv == GOING_HIGH ? coil4High_DIRECT() : coil4Low_DIRECT())
#define coil5Charging_DIRECT() (configPage4.IgInv == GOING_HIGH ? coil5Low_DIRECT() : coil5High_DIRECT())
#define coil5StopCharging_DIRECT() (configPage4.IgInv == GOING_HIGH ? coil5High_DIRECT() : coil5Low_DIRECT())
#define coil6Charging_DIRECT() (configPage4.IgInv == GOING_HIGH ? coil6Low_DIRECT() : coil6High_DIRECT())
#define coil6StopCharging_DIRECT() (configPage4.IgInv == GOING_HIGH ? coil6High_DIRECT() : coil6Low_DIRECT())
#define coil7Charging_DIRECT() (configPage4.IgInv == GOING_HIGH ? coil7Low_DIRECT() : coil7High_DIRECT())
#define coil7StopCharging_DIRECT() (configPage4.IgInv == GOING_HIGH ? coil7High_DIRECT() : coil7Low_DIRECT())
#define coil8Charging_DIRECT() (configPage4.IgInv == GOING_HIGH ? coil8Low_DIRECT() : coil8High_DIRECT())
#define coil8StopCharging_DIRECT() (configPage4.IgInv == GOING_HIGH ? coil8High_DIRECT() : coil8Low_DIRECT())
#define coil1Charging_MC33810() coil1High_MC33810()
#define coil1StopCharging_MC33810() coil1Low_MC33810()
#define coil2Charging_MC33810() coil2High_MC33810()
#define coil2StopCharging_MC33810() coil2Low_MC33810()
#define coil3Charging_MC33810() coil3High_MC33810()
#define coil3StopCharging_MC33810() coil3Low_MC33810()
#define coil4Charging_MC33810() coil4High_MC33810()
#define coil4StopCharging_MC33810() coil4Low_MC33810()
#define coil5Charging_MC33810() coil5High_MC33810()
#define coil5StopCharging_MC33810() coil5Low_MC33810()
#define coil6Charging_MC33810() coil6High_MC33810()
#define coil6StopCharging_MC33810() coil6Low_MC33810()
#define coil7Charging_MC33810() coil7High_MC33810()
#define coil7StopCharging_MC33810() coil7Low_MC33810()
#define coil8Charging_MC33810() coil8High_MC33810()
#define coil8StopCharging_MC33810() coil8Low_MC33810()
#define coil1Toggle_DIRECT() (*ign1_pin_port ^= ign1_pin_mask )
#define coil2Toggle_DIRECT() (*ign2_pin_port ^= ign2_pin_mask )
#define coil3Toggle_DIRECT() (*ign3_pin_port ^= ign3_pin_mask )
#define coil4Toggle_DIRECT() (*ign4_pin_port ^= ign4_pin_mask )
#define coil5Toggle_DIRECT() (*ign5_pin_port ^= ign5_pin_mask )
#define coil6Toggle_DIRECT() (*ign6_pin_port ^= ign6_pin_mask )
#define coil7Toggle_DIRECT() (*ign7_pin_port ^= ign7_pin_mask )
#define coil8Toggle_DIRECT() (*ign8_pin_port ^= ign8_pin_mask )
#define injector1Toggle_DIRECT() (*inj1_pin_port ^= inj1_pin_mask )
#define injector2Toggle_DIRECT() (*inj2_pin_port ^= inj2_pin_mask )
#define injector3Toggle_DIRECT() (*inj3_pin_port ^= inj3_pin_mask )
#define injector4Toggle_DIRECT() (*inj4_pin_port ^= inj4_pin_mask )
#define injector5Toggle_DIRECT() (*inj5_pin_port ^= inj5_pin_mask )
#define injector6Toggle_DIRECT() (*inj6_pin_port ^= inj6_pin_mask )
#define injector7Toggle_DIRECT() (*inj7_pin_port ^= inj7_pin_mask )
#define injector8Toggle_DIRECT() (*inj8_pin_port ^= inj8_pin_mask )
void nullCallback();
#endif
| 12,236
|
C++
|
.h
| 225
| 53.204444
| 168
| 0.757664
|
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,072
|
globals.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/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 "logger.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 defintion (Because they don't exist on the MCU), so it will not cause any isses
#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 virable
#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 decelleration 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 //Decelleration 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_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_UNUSED5 4
#define BIT_STATUS4_UNUSED6 5
#define BIT_STATUS4_UNUSED7 6
#define BIT_STATUS4_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 2
#define IAT_CALIBRATION_PAGE 1
#define CLT_CALIBRATION_PAGE 0
#define COMPOSITE_LOG_PRI 0
#define COMPOSITE_LOG_SEC 1
#define COMPOSITE_LOG_TRIG 2
#define COMPOSITE_LOG_SYNC 3
#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 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 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 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 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 downards 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
#ifndef CORE_TEENSY41
#define FUEL_PUMP_ON() *pump_pin_port |= (pump_pin_mask)
#define FUEL_PUMP_OFF() *pump_pin_port &= ~(pump_pin_mask)
#else
//Special compatibility case for TEENSY 41 (for now)
#define FUEL_PUMP_ON() digitalWrite(pinFuelPump, HIGH);
#define FUEL_PUMP_OFF() digitalWrite(pinFuelPump, LOW);
#endif
#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 FastCRC32 CRC32;
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 vvtTable; //8x8 vvt map
extern struct table3d8RpmLoad vvt2Table; //8x8 vvt map
extern struct table3d8RpmLoad wmiTable; //8x8 wmi map
extern struct table3d6RpmLoad trim1Table; //6x6 Fuel trim 1 map
extern struct table3d6RpmLoad trim2Table; //6x6 Fuel trim 2 map
extern struct table3d6RpmLoad trim3Table; //6x6 Fuel trim 3 map
extern struct table3d6RpmLoad trim4Table; //6x6 Fuel trim 4 map
extern struct table3d6RpmLoad trim5Table; //6x6 Fuel trim 5 map
extern struct table3d6RpmLoad trim6Table; //6x6 Fuel trim 6 map
extern struct table3d6RpmLoad trim7Table; //6x6 Fuel trim 7 map
extern struct table3d6RpmLoad 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 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 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 bool channel1InjEnabled;
extern bool channel2InjEnabled;
extern bool channel3InjEnabled;
extern bool channel4InjEnabled;
extern bool channel5InjEnabled;
extern bool channel6InjEnabled;
extern bool channel7InjEnabled;
extern bool channel8InjEnabled;
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 uint16_t softStartTime; //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 unsigned long previousLoopTime; /**< The time (in uS) that the previous 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 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) == 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) )
#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 inital 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 */
byte tpsDOT; /**< TPS delta over time. Measures the % per second that the TPS is changing. Value is divided by 10 to be stored in a byte */
byte mapDOT; /**< MAP delta over time. Measures the kpa per second that the MAP is changing. Value is divided by 10 to be stored in a byte */
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)
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 accleration 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 idleDuty; /**< The current idle duty cycle amount if PWM idle is selected and active */
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 everytime 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;
bool compositeLogEnabled;
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
};
/** 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;
//Display config bits
byte displayType : 3; //21
byte display1 : 3;
byte display2 : 2;
byte display3 : 3; //22
byte display4 : 2;
byte display5 : 3;
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 multiplyMAP_old : 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=diable, 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 behavior
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 ouputs == number cyls, timed over full cycle, 2 crank revs) */
byte perToothIgn : 1; ///< Experimental / New ign. 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 iacCLminDuty;
byte iacCLmaxDuty;
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 unused2_95[2];
#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 unusedBits4 : 7;
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 cylces 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 fueling
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 unused_bit : 1; //Previously was VVTasOnOff
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 unused10_67;
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 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 unused10_166;
byte unused10_167;
byte unused10_168;
byte unused10_169;
byte unused10_170;
byte unused10_171;
byte unused10_172;
byte unused10_173;
byte unused10_174;
byte unused10_175;
byte unused10_176;
byte unused10_177;
byte unused10_178;
byte unused10_179;
byte unused10_180;
byte unused10_181;
byte unused10_182;
byte unused10_183;
byte unused10_184;
byte unused10_185;
byte unused10_186;
byte unused10_187;
byte unused10_188;
byte unused10_189;
byte unused10_190;
byte unused10_191;
#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]; //Byets 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 unused11_187_191[2]; //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 dependant(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_thr_on; // "pin", 0, 0, 0, 1, 255, 0 ;
byte unused12_125_127[2];
#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 ouput to relay/pump/solenoid
extern byte pinMC33810_1_CS;
extern byte pinMC33810_2_CS;
#ifdef USE_SPI_EEPROM
extern byte pinSPIFlash_CS;
#endif
/* 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 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 */
#endif // GLOBALS_H
| 69,350
|
C++
|
.h
| 1,327
| 49.780708
| 354
| 0.732774
|
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,073
|
speeduino.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/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 auxilliary 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"
void setup();
void loop();
uint16_t PW(int REQ_FUEL, byte VE, long MAP, uint16_t corrections, int injOpen);
byte getVE1();
byte getAdvance1();
uint16_t calculateInjectorStartAngle(uint16_t, int16_t);
void calculateIgnitionAngle1(int);
void calculateIgnitionAngle2(int);
void calculateIgnitionAngle3(int);
void calculateIgnitionAngle3(int, int);
void calculateIgnitionAngle4(int);
void calculateIgnitionAngle4(int, int);
void calculateIgnitionAngle5(int);
void calculateIgnitionAngle6(int);
void calculateIgnitionAngle7(int);
void calculateIgnitionAngle8(int);
void calculateIgnitionAngles(int);
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 maxIgnOutputs; /**< Used for rolling rev limiter to indicate how many total ignition channels should currently be firing */
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 */
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 */
/** @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
| 4,439
|
C++
|
.h
| 70
| 61.871429
| 170
| 0.763883
|
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,074
|
board_teensy41.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/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();
#define PORT_TYPE uint32_t //Size of the port variables
#define PINMASK_TYPE uint32_t
#define COMPARE_TYPE uint32_t
#define COUNTER_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 SD_LOGGING //SD logging enabled by default for Teensy 4.1 as it has the slot built in
#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 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) ) //Forbiden 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() TMR1_CSCTRL0 &= ~TMR_CSCTRL_TCF1EN
#define FUEL6_TIMER_DISABLE() TMR1_CSCTRL1 &= ~TMR_CSCTRL_TCF1EN
#define FUEL7_TIMER_DISABLE() TMR1_CSCTRL2 &= ~TMR_CSCTRL_TCF1EN
#define FUEL8_TIMER_DISABLE() TMR1_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
//Clock is 150Mhz
#define MAX_TIMER_PERIOD 55923 // 0.85333333uS * 65535
#define uS_TO_TIMER_COMPARE(uS) ((uS * 75) >> 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
*/
/*
***********************************************************************************************************
* Auxilliaries
*/
#define ENABLE_BOOST_TIMER() TMR3_CSCTRL0 |= TMR_CSCTRL_TCF1EN
#define DISABLE_BOOST_TIMER() TMR3_CSCTRL0 &= ~TMR_CSCTRL_TCF1EN
#define ENABLE_VVT_TIMER() TMR3_CSCTRL0 |= TMR_CSCTRL_TCF2EN
#define DISABLE_VVT_TIMER() TMR3_CSCTRL0 &= ~TMR_CSCTRL_TCF2EN
#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
void boostInterrupt();
void vvtInterrupt();
/*
***********************************************************************************************************
* Idle
*/
#define IDLE_COUNTER 0
#define IDLE_COMPARE PIT_LDVAL0
#define IDLE_TIMER_ENABLE() TMR3_CSCTRL1 |= TMR_CSCTRL_TCF1EN
#define IDLE_TIMER_DISABLE() TMR3_CSCTRL1 &= ~TMR_CSCTRL_TCF1EN
void idleInterrupt();
/*
***********************************************************************************************************
* 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,460
|
C++
|
.h
| 155
| 45.296774
| 155
| 0.689688
|
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,075
|
comms.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/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 COMMS_H
#define COMMS_H
extern byte currentPage;//Not the same as the speeduino config page numbers
extern bool isMap; /**< Whether or not the currentPage contains only a 3D map that would require translation */
extern unsigned long requestCount; /**< 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 currentCommand; /**< The serial command that is currently being processed. This is only useful when cmdPending=True */
extern bool cmdPending; /**< Whether or not a serial request has only been partially received. This occurs when a command character has been received in the serial buffer, but not all of its arguments have yet been received. If true, the active command will be stored in the currentCommand variable */
extern bool chunkPending; /**< Whether or not the current chucnk write is complete or not */
extern uint16_t chunkComplete; /**< The number of bytes in a chunk write that have been written so far */
extern uint16_t chunkSize; /**< The complete size of the requested chunk write */
extern int valueOffset; /**< THe memory offset within a given page for a value to be read from or written to. Note that we cannot use 'offset' as a variable name, it is a reserved word for several teensy libraries */
extern byte tsCanId; // current tscanid requested
extern byte inProgressOffset;
extern byte inProgressLength;
extern bool legacySerial;
extern uint32_t inProgressCompositeTime;
extern bool serialInProgress;
extern bool toothLogSendInProgress;
extern bool compositeLogSendInProgress;
void command();//This is the heart of the Command Line Interpeter. All that needed to be done was to make it human readable.
void sendValues(uint16_t, uint16_t,byte, byte);
void sendValuesLegacy();
void saveConfig();
void sendPage();
void sendPageASCII();
void receiveCalibration(byte);
void sendToothLog_old(uint8_t);
void testComm();
void commandButtons(int16_t);
void sendCompositeLog_old(uint8_t);
#endif // COMMS_H
| 2,358
|
C++
|
.h
| 39
| 59.076923
| 301
| 0.791271
|
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,076
|
board_template.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/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 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) ) //Forbiden 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.
/*
***********************************************************************************************************
* Auxilliaries
*/
//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,088
|
C++
|
.h
| 126
| 45.52381
| 178
| 0.675312
|
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,077
|
board_stm32_official.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/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"
#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 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
#ifdef SD_LOGGING
#define RTC_ENABLED
#endif
#define USE_SERIAL3
//When building for Black board Serial1 is instanciated,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 alow compile 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) ) //Forbiden pins like USB
#else
#define pinIsReserved(pin) ( ((pin) == PA11) || ((pin) == PA12) || ((pin) == PB3) || ((pin) == PB4) || ((pin) == PB5) || ((pin) == PB0) ) //Forbiden 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)->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
#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
/*
***********************************************************************************************************
* Auxilliaries
*/
#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
*/
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
| 11,911
|
C++
|
.h
| 284
| 40.165493
| 178
| 0.674099
|
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,078
|
cancomms.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/speeduino/cancomms.h
|
#ifndef CANCOMMS_H
#define CANCOMMS_H
#define NEW_CAN_PACKET_SIZE 122
#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();//This is the heart of the Command Line Interpeter. 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 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);
#endif // CANCOMMS_H
| 1,163
|
C++
|
.h
| 27
| 40.740741
| 138
| 0.784452
|
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,079
|
decoders.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/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)
#else
#define READ_PRI_TRIGGER() digitalRead(pinTrigger)
#define READ_SEC_TRIGGER() digitalRead(pinTrigger2)
#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
//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 loggerSecondaryISR();
//All of the below are the 6 required functions for each decoder / pattern
void triggerSetup_missingTooth();
void triggerPri_missingTooth();
void triggerSec_missingTooth();
void triggerThird_missingTooth();
uint16_t getRPM_missingTooth();
int getCrankAngle_missingTooth();
extern void triggerSetEndTeeth_missingTooth();
void triggerSetup_DualWheel();
void triggerPri_DualWheel();
void triggerSec_DualWheel();
uint16_t getRPM_DualWheel();
int getCrankAngle_DualWheel();
void triggerSetEndTeeth_DualWheel();
void triggerSetup_BasicDistributor();
void triggerPri_BasicDistributor();
void triggerSec_BasicDistributor();
uint16_t getRPM_BasicDistributor();
int getCrankAngle_BasicDistributor();
void triggerSetEndTeeth_BasicDistributor();
void triggerSetup_GM7X();
void triggerPri_GM7X();
void triggerSec_GM7X();
uint16_t getRPM_GM7X();
int getCrankAngle_GM7X();
void triggerSetEndTeeth_GM7X();
void triggerSetup_4G63();
void triggerPri_4G63();
void triggerSec_4G63();
uint16_t getRPM_4G63();
int getCrankAngle_4G63();
void triggerSetEndTeeth_4G63();
void triggerSetup_24X();
void triggerPri_24X();
void triggerSec_24X();
uint16_t getRPM_24X();
int getCrankAngle_24X();
void triggerSetEndTeeth_24X();
void triggerSetup_Jeep2000();
void triggerPri_Jeep2000();
void triggerSec_Jeep2000();
uint16_t getRPM_Jeep2000();
int getCrankAngle_Jeep2000();
void triggerSetEndTeeth_Jeep2000();
void triggerSetup_Audi135();
void triggerPri_Audi135();
void triggerSec_Audi135();
uint16_t getRPM_Audi135();
int getCrankAngle_Audi135();
void triggerSetEndTeeth_Audi135();
void triggerSetup_HondaD17();
void triggerPri_HondaD17();
void triggerSec_HondaD17();
uint16_t getRPM_HondaD17();
int getCrankAngle_HondaD17();
void triggerSetEndTeeth_HondaD17();
void triggerSetup_Miata9905();
void triggerPri_Miata9905();
void triggerSec_Miata9905();
uint16_t getRPM_Miata9905();
int getCrankAngle_Miata9905();
void triggerSetEndTeeth_Miata9905();
int getCamAngle_Miata9905();
void triggerSetup_MazdaAU();
void triggerPri_MazdaAU();
void triggerSec_MazdaAU();
uint16_t getRPM_MazdaAU();
int getCrankAngle_MazdaAU();
void triggerSetEndTeeth_MazdaAU();
void triggerSetup_non360();
void triggerPri_non360();
void triggerSec_non360();
uint16_t getRPM_non360();
int getCrankAngle_non360();
void triggerSetEndTeeth_non360();
void triggerSetup_Nissan360();
void triggerPri_Nissan360();
void triggerSec_Nissan360();
uint16_t getRPM_Nissan360();
int getCrankAngle_Nissan360();
void triggerSetEndTeeth_Nissan360();
void triggerSetup_Subaru67();
void triggerPri_Subaru67();
void triggerSec_Subaru67();
uint16_t getRPM_Subaru67();
int getCrankAngle_Subaru67();
void triggerSetEndTeeth_Subaru67();
void triggerSetup_Daihatsu();
void triggerPri_Daihatsu();
void triggerSec_Daihatsu();
uint16_t getRPM_Daihatsu();
int getCrankAngle_Daihatsu();
void triggerSetEndTeeth_Daihatsu();
void triggerSetup_Harley();
void triggerPri_Harley();
void triggerSec_Harley();
uint16_t getRPM_Harley();
int getCrankAngle_Harley();
void triggerSetEndTeeth_Harley();
void triggerSetup_ThirtySixMinus222();
void triggerPri_ThirtySixMinus222();
void triggerSec_ThirtySixMinus222();
uint16_t getRPM_ThirtySixMinus222();
int getCrankAngle_ThirtySixMinus222();
void triggerSetEndTeeth_ThirtySixMinus222();
void triggerSetup_ThirtySixMinus21();
void triggerPri_ThirtySixMinus21();
void triggerSec_ThirtySixMinus21();
uint16_t getRPM_ThirtySixMinus21();
int getCrankAngle_ThirtySixMinus21();
void triggerSetEndTeeth_ThirtySixMinus21();
void triggerSetup_420a();
void triggerPri_420a();
void triggerSec_420a();
uint16_t getRPM_420a();
int getCrankAngle_420a();
void triggerSetEndTeeth_420a();
void triggerPri_Webber();
void triggerSec_Webber();
void triggerSetup_FordST170();
void triggerSec_FordST170();
uint16_t getRPM_FordST170();
int getCrankAngle_FordST170();
void triggerSetEndTeeth_FordST170();
void triggerSetup_DRZ400();
void triggerSec_DRZ400();
void triggerSetup_NGC();
void triggerPri_NGC();
void triggerSec_NGC4();
void triggerSec_NGC68();
uint16_t getRPM_NGC();
void triggerSetEndTeeth_NGC();
extern void (*triggerHandler)(); //Pointer for the trigger function (Gets pointed to the relevant decoder)
extern void (*triggerSecondaryHandler)(); //Pointer for the secondary trigger function (Gets pointed to the relevant decoder)
extern void (*triggerTertiaryHandler)(); //Pointer for the tertiary trigger function (Gets pointed to the relevant decoder)
extern uint16_t (*getRPM)(); //Pointer to the getRPM function (Gets pointed to the relevant decoder)
extern int (*getCrankAngle)(); //Pointer to the getCrank Angle function (Gets pointed to the relevant decoder)
extern void (*triggerSetEndTeeth)(); //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 curTime3;
extern volatile unsigned long curGap3;
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 (Onec 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 volatile 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 volatile bool validTrigger; //Is set true when the last trigger (Primary or secondary) was valid (ie passed filters)
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 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 decoderIsLowRes; //Is set true, certain extra calculations are performed for better timing accuracy
extern bool decoderHasSecondary; //Whether or not the pattern uses a secondary input
extern bool decoderHasFixedCrankingTiming; //Whether or not the decoder supports fixed cranking timing
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 1
#endif
| 11,407
|
C++
|
.h
| 233
| 47.746781
| 310
| 0.80185
|
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,080
|
int16_ref.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/speeduino/int16_ref.h
|
/**
* @addtogroup table_3d
* @{
*/
#pragma once
#include <stdint.h>
#include "src/libdivide/libdivide.h"
/** @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_ref
{
public:
#pragma pack(push, 1)
struct scalar {
uint8_t _factor;
libdivide::libdivide_s16_t divider;
};
#pragma pack(pop)
/**
* @brief Construct
* @param value The \c int16_t to encapsulate.
* @param factor The factor to scale the \c int16_t value by when converting to/from a \c byte
*/
int16_ref(int16_t &value, const scalar *pScalar)
: _value(value), _pScalar(pScalar)
{
}
/** @brief Convert to a \c byte */
inline byte operator*() const { return (byte)libdivide::libdivide_s16_do(_value, &_pScalar->divider); }
/** @brief Convert to a \c byte */
inline explicit operator byte() const { return **this; }
/** @brief Convert from a \c byte */
inline int16_ref &operator=( byte in ) { _value = (int16_t)in * (int16_t)(_pScalar->_factor); return *this; }
private:
int16_t &_value;
const scalar *_pScalar;
};
/** @} */
| 1,463
|
C++
|
.h
| 44
| 29.431818
| 115
| 0.652236
|
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,081
|
SD_logger.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/speeduino/SD_logger.h
|
#ifndef SD_LOGGER_H
#define SD_LOGGER_H
#ifdef SD_LOGGING
#include <SD.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 /**< File has been openeed and preallocated, 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
#ifdef CORE_TEENSY
#define SD_CS_PIN BUILTIN_SDCARD
#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<FsFile, 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 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
| 2,776
|
C++
|
.h
| 64
| 42
| 124
| 0.723396
|
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,082
|
board_teensy35.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/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 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) ) //Forbiden 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.
/*
***********************************************************************************************************
* Auxilliaries
*/
#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,912
|
C++
|
.h
| 149
| 43.550336
| 155
| 0.663601
|
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,083
|
table3d.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/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-infnite
* - 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:
* - The X axis is conventional: <c>x[0]</c> stores \c X-Min
* - The Y-axis is inverted: <c>y[0]</c> stores \c Y-Max
* - 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
* identifer 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_XAXIS(size, xDom, yDom) xaxis_t; \
typedef TABLE3D_TYPENAME_YAXIS(size, xDom, 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; \
TABLE3D_TYPENAME_VALUE(size, xDom, yDom) values; \
TABLE3D_TYPENAME_XAXIS(size, xDom, yDom) axisX; \
TABLE3D_TYPENAME_YAXIS(size, xDom, yDom) axisY; \
};
TABLE3D_GENERATOR(TABLE3D_GEN_TYPE)
// Generate get3DTableValue() functions
#define TABLE3D_GEN_GET_TABLE_VALUE(size, xDom, yDom) \
inline int 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 y_begin(const void *pTable, table_type_t key);
/** @} */
| 4,765
|
C++
|
.h
| 109
| 39.385321
| 117
| 0.614258
|
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,084
|
newComms.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/speeduino/newComms.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
//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
#define SERIAL_CRC_LENGTH 4
#define SERIAL_LEN_SIZE 2
#define SERIAL_OVERHEAD_SIZE (SERIAL_LEN_SIZE + SERIAL_CRC_LENGTH) //The overhead for each serial command is 6 bytes. 2 bytes for the length and 4 bytes for the CRC
#define SERIAL_TIMEOUT 3000 //ms
#ifdef RTC_ENABLED
#define SD_FILE_TRANSMIT_BUFFER_SIZE 2048 + 3
extern uint8_t serialSDTransmitPayload[SD_FILE_TRANSMIT_BUFFER_SIZE];
extern uint16_t SDcurrentDirChunk;
extern uint32_t SDreadStartSector;
extern uint32_t SDreadNumSectors; //Number of sectors to read
extern uint32_t SDreadCompletedSectors; //Number of sectors that have been read
#endif
//Serial return codes
#define SERIAL_RC_OK 0x00
#define SERIAL_RC_REALTIME 0x01
#define SERIAL_RC_PAGE 0x02
#define SERIAL_RC_BURN_OK 0x04
#define SERIAL_RC_TIMEOUT 0x80 //Timeout error
#define SERIAL_RC_CRC_ERR 0x82
#define SERIAL_RC_UKWN_ERR 0x83 //Unkwnown command
#define SERIAL_RC_RANGE_ERR 0x84 //Incorrect range. TS will not retry command
#define SERIAL_RC_BUSY_ERR 0x85 //TS will wait and retry
extern bool serialWriteInProgress;
void parseSerial();//This is the heart of the Command Line Interpeter. All that needed to be done was to make it human readable.
void processSerialCommand();
void sendSerialReturnCode(byte returnCode);
void sendSerialPayload(void*, uint16_t payloadLength);
void generateLiveValues(uint16_t, uint16_t);
void saveConfig();
void sendToothLog(uint8_t);
void commandButtons(int16_t);
void sendCompositeLog(uint8_t);
void continueSerialTransmission();
#endif // COMMS_H
| 3,026
|
C++
|
.h
| 74
| 39.418919
| 164
| 0.776114
|
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,085
|
board_avr2560.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/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
#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();
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) ) //Forbiden 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
/*
***********************************************************************************************************
* Auxilliaries
*/
#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,062
|
C++
|
.h
| 141
| 54.255319
| 183
| 0.657132
|
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,086
|
table3d_typedefs.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/speeduino/table3d_typedefs.h
|
/**
* @addtogroup table_3d
* @{
*/
/** \file
* @brief Typedefs for primitive 3D table elements
*
* These used are for consistency across functions that work on 3D table data.
* For example:<br>
* <c>table3d_value_t foo(table3d_axis_t input);</c><br>
* instead of:<br>
* <c>uint8_t foo(int16_t input);</c>
*/
#pragma once
#include <stdint.h>
/** @brief Encodes the \b length of the axes */
typedef uint8_t table3d_dim_t;
/** @brief The type of each table value */
typedef uint8_t table3d_value_t;
/** @brief The type of each axis value */
typedef int16_t table3d_axis_t;
/** @brief Core 3d table generation macro
*
* We have a fixed number of table types: they are defined by this macro.
* GENERATOR is expected to be another macros that takes at least 3 arguments:
* axis length, x-axis domain, y-axis domain
*/
#define TABLE3D_GENERATOR(GENERATOR, ...) \
GENERATOR(6, Rpm, Load, ##__VA_ARGS__) \
GENERATOR(4, Rpm, Load, ##__VA_ARGS__) \
GENERATOR(8, Rpm, Load, ##__VA_ARGS__) \
GENERATOR(8, Rpm, Tps, ##__VA_ARGS__) \
GENERATOR(16, Rpm, Load, ##__VA_ARGS__)
// Each 3d table is given a distinct type based on size & axis domains
// This encapsulates the generation of the type name
#define TABLE3D_TYPENAME_BASE(size, xDom, yDom) table3d ## size ## xDom ## yDom
#define CAT_HELPER(a, b) a ## b
#define CONCAT(A, B) CAT_HELPER(A, B)
/** @} */
| 1,398
|
C++
|
.h
| 39
| 33.538462
| 79
| 0.675315
|
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,087
|
logger.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/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 eith by TunerStudio directly or to be written to an SD card
*
*/
#ifndef LOGGER_H
#define LOGGER_H
#include <assert.h>
#ifndef UNIT_TEST // Scope guard for unit testing
#define LOG_ENTRY_SIZE 122 /**< The size of the live data packet. This MUST match ochBlockSize setting in the ini file */
#define SD_LOG_ENTRY_SIZE 122 /**< 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 89 /**< 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);
int16_t getReadableLogEntry(uint16_t);
bool is2ByteEntry(uint8_t);
// 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, 25, 27, 32, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 75, 77, 79, 81, 85, 87, 89, 93, 97, 102, 109, 119 };
//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 = "";
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,271
|
C++
|
.h
| 277
| 29.841155
| 174
| 0.419694
|
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,088
|
idle.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/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 STEPPER_FORWARD 0
#define STEPPER_BACKWARD 1
#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 targetted step is
volatile StepperStatus stepperStatus;
volatile unsigned long stepStartTime; //The time the curren
byte lessAirDirection;
byte moreAirDirection;
};
struct table2D iacClosedLoopTable;
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
byte idleUpOutputHIGH = HIGH; // Used to invert the idle Up Output
byte idleUpOutputLOW = LOW; // Used to invert the idle Up Output
void initialiseIdle();
void initialiseIdleUpOutput();
void disableIdle();
void idleInterrupt();
#endif
| 2,521
|
C++
|
.h
| 62
| 39.209677
| 190
| 0.806214
|
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,089
|
table2d.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/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.
};
void table2D_setSize(struct table2D*, byte);
int16_t table2D_getAxisValue(struct table2D*, byte);
int16_t table2D_getRawValue(struct table2D*, byte);
int table2D_getValue(struct table2D *fromTable, int);
#endif // TABLE_H
| 1,262
|
C++
|
.h
| 33
| 36.030303
| 250
| 0.755738
|
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,090
|
utilities.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/speeduino/utilities.h
|
/*
These are some utility functions and variables used through the main code
*/
#ifndef UTILS_H
#define UTILS_H
#include <Arduino.h>
#define CONCATS(s1, s2) (s1" " s2) //needed for some reason. not defined correctly because of utils.h file of speeduino (same name as one in arduino core)
#define COMPARATOR_EQUAL 0
#define COMPARATOR_NOT_EQUAL 1
#define COMPARATOR_GREATER 2
#define COMPARATOR_GREATER_EQUAL 3
#define COMPARATOR_LESS 4
#define COMPARATOR_LESS_EQUAL 5
#define COMPARATOR_AND 6
#define COMPARATOR_XOR 7
#define BITWISE_DISABLED 0
#define BITWISE_AND 1
#define BITWISE_OR 2
#define BITWISE_XOR 3
#define REUSE_RULES 240
extern uint8_t ioOutDelay[sizeof(configPage13.outputPin)];
extern uint8_t ioDelay[sizeof(configPage13.outputPin)];
extern uint8_t pinIsValid;
extern uint8_t currentRuleStatus;
//uint8_t outputPin[sizeof(configPage13.outputPin)];
void setResetControlPinState();
byte pinTranslate(byte);
byte pinTranslateAnalog(byte);
void initialiseProgrammableIO();
void checkProgrammableIO();
int16_t ProgrammableIOGetData(uint16_t index);
#if !defined(UNUSED)
#define UNUSED(x) (void)(x)
#endif
#define _countof(x) (sizeof(x) / sizeof (x[0]))
#define _end_range_address(array) (array + _countof(array))
#define _end_range_byte_address(array) (((byte*)array) + sizeof(array))
// Pre-processor arithmetic increment (pulled from Boost.Preprocessor)
#define PP_INC(x) PP_INC_I(x)
#define PP_INC_I(x) PP_INC_ ## x
#define PP_INC_0 1
#define PP_INC_1 2
#define PP_INC_2 3
#define PP_INC_3 4
#define PP_INC_4 5
#define PP_INC_5 6
#define PP_INC_6 7
#define PP_INC_7 8
#define PP_INC_8 9
#define PP_INC_9 10
#define PP_INC_10 11
#define PP_INC_11 12
#define PP_INC_12 13
#endif // UTILS_H
| 1,713
|
C++
|
.h
| 54
| 30.5
| 154
| 0.782028
|
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,091
|
TS_CommandButtonHandler.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/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 */
void TS_CommandButtonsHandler(uint16_t);
| 2,110
|
C++
|
.h
| 66
| 30.80303
| 115
| 0.742141
|
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,092
|
errors.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/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();
byte setError(byte);
void clearError(byte);
extern byte errorCount;
#endif
| 2,001
|
C++
|
.h
| 47
| 41.191489
| 103
| 0.720966
|
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,093
|
auxiliaries.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/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.
void initialiseAuxPWM();
void boostControl();
void boostDisable();
void boostByGear();
void idleControl();
void vvtControl();
void initialiseFan();
void nitrousControl();
void fanControl();
void wmiControl();
#define SIMPLE_BOOST_P 1
#define SIMPLE_BOOST_I 1
#define SIMPLE_BOOST_D 1
#define BOOST_PIN_LOW() *boost_pin_port &= ~(boost_pin_mask)
#define BOOST_PIN_HIGH() *boost_pin_port |= (boost_pin_mask)
#define VVT1_PIN_LOW() *vvt1_pin_port &= ~(vvt1_pin_mask)
#define VVT1_PIN_HIGH() *vvt1_pin_port |= (vvt1_pin_mask)
#define VVT2_PIN_LOW() *vvt2_pin_port &= ~(vvt2_pin_mask)
#define VVT2_PIN_HIGH() *vvt2_pin_port |= (vvt2_pin_mask)
#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 FAN_PIN_LOW() *fan_pin_port &= ~(fan_pin_mask)
#define FAN_PIN_HIGH() *fan_pin_port |= (fan_pin_mask)
#define N2O_STAGE1_PIN_LOW() *n2o_stage1_pin_port &= ~(n2o_stage1_pin_mask)
#define N2O_STAGE1_PIN_HIGH() *n2o_stage1_pin_port |= (n2o_stage1_pin_mask)
#define N2O_STAGE2_PIN_LOW() *n2o_stage2_pin_port &= ~(n2o_stage2_pin_mask)
#define N2O_STAGE2_PIN_HIGH() *n2o_stage2_pin_port |= (n2o_stage2_pin_mask)
#define READ_N2O_ARM_PIN() ((*n2o_arming_pin_port & n2o_arming_pin_mask) ? true : false)
#define VVT_TIME_DELAY_MULTIPLIER 50
#define FAN_ON() ((configPage6.fanInv) ? FAN_PIN_LOW() : FAN_PIN_HIGH())
#define FAN_OFF() ((configPage6.fanInv) ? FAN_PIN_HIGH() : FAN_PIN_LOW())
#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 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();
#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 vvtInterrupt();
#endif
| 3,393
|
C++
|
.h
| 85
| 38.752941
| 155
| 0.752352
|
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,094
|
updates.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/speeduino/updates.h
|
#ifndef UPDATES_H
#define UPDATES_H
#include "table3d.h"
void doUpdates();
void multiplyTableLoad(const void*, table_type_t, uint8_t); //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*, table_type_t, uint8_t); //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
| 505
|
C++
|
.h
| 7
| 70.714286
| 211
| 0.758065
|
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,095
|
init.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/speeduino/init.h
|
#ifndef INIT_H
#define INIT_H
void initialiseAll();
void initialiseTriggers();
void setPinMapping(byte);
#endif
| 113
|
C++
|
.h
| 6
| 17.666667
| 26
| 0.820755
|
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,096
|
crankMaths.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/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 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, byte);
uint16_t timeToAngle(unsigned long, byte);
void doCrankSpeedCalcs();
volatile uint16_t timePerDegree;
volatile uint16_t timePerDegreex16;
volatile uint16_t degreesPeruSx2048;
volatile unsigned long degreesPeruSx32768;
//These are only part of the experimental 2nd deriv calcs
byte deltaToothCount = 0; //The last tooth that was used with the deltaV calc
int rpmDelta;
#endif
| 1,361
|
C++
|
.h
| 23
| 57.869565
| 183
| 0.773854
|
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,097
|
table3d_interpolate.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/speeduino/table3d_interpolate.h
|
#pragma once
#include "table3d_typedefs.h"
// A table location.
struct coord2d
{
table3d_axis_t x;
table3d_axis_t y;
};
struct table3DGetValueCache {
// Store the upper *index* of the X and Y axis bins that were last hit.
// This is used to make the next check faster since very likely the x & y values have
// only changed by a small amount & are in the same bin (or an adjacent bin).
//
// It's implicit that the other bin index is max bin index - 1 (a single axis
// value can't span 2 axis bins). This saves 1 byte.
//
// E.g. 6 element x-axis contents:
// [ 8| 9|12|15|18|21]
// indices:
// 0, 1, 2, 3, 4, 5
// If lastXBinMax==3, the min index must be 2. I.e. the last X value looked
// up was between 12<X<=15.
table3d_dim_t lastXBinMax = 1;
table3d_dim_t lastYBinMax = 1;
//Store the last input and output values, again for caching purposes
coord2d last_lookup = { INT16_MAX, INT16_MAX };
table3d_value_t lastOutput;
};
inline void invalidate_cache(table3DGetValueCache *pCache)
{
pCache->last_lookup.x = INT16_MAX;
}
/*
3D Tables have an origin (0,0) in the top left hand corner. Vertical axis is expressed first.
Eg: 2x2 table
-----
|2 7|
|1 4|
-----
(0,1) = 7
(0,0) = 2
(1,0) = 1
*/
table3d_value_t get3DTableValue(struct table3DGetValueCache *pValueCache,
table3d_dim_t axisSize,
const table3d_value_t *pValues,
const table3d_axis_t *pXAxis,
const table3d_axis_t *pYAxis,
table3d_axis_t y, table3d_axis_t x);
| 1,585
|
C++
|
.h
| 49
| 28.102041
| 93
| 0.654224
|
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,098
|
timers.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/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 {DEACTIVE, READY, ACTIVE}; //The 3 statuses that the tacho output pulse can have
volatile uint8_t tachoEndTime; //The time (in ms) that the tacho pulse needs to end at
volatile TachoOutputStatus tachoOutputFlag;
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();
#elif defined (ARDUINO_ARCH_STM32)
void oneMSInterval();
#endif
void initialiseTimers();
#endif // TIMERS_H
| 2,023
|
C++
|
.h
| 36
| 54.638889
| 213
| 0.791688
|
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,099
|
corrections.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/speeduino/corrections.h
|
/*
All functions in the gamma file return
*/
#ifndef CORRECTIONS_H
#define CORRECTIONS_H
void initialiseCorrections();
uint16_t correctionsFuel();
byte correctionWUE(); //Warmup enrichment
uint16_t correctionCranking(); //Cranking enrichment
byte correctionASE(); //After Start Enrichment
uint16_t correctionAccel(); //Acceleration Enrichment
byte correctionFloodClear(); //Check for flood clear on cranking
byte correctionAFRClosedLoop(); //Closed loop AFR adjustment
byte correctionFlex(); //Flex fuel adjustment
byte correctionFuelTemp(); //Fuel temp correction
byte correctionBatVoltage(); //Battery voltage correction
byte correctionIATDensity(); //Inlet temp density correction
byte correctionBaro(); //Barometric pressure correction
byte correctionLaunch(); //Launch control correction
bool correctionDFCO(); //Decelleration fuel cutoff
int8_t correctionsIgn(int8_t advance);
int8_t correctionFixedTiming(int8_t);
int8_t correctionCrankingFixedTiming(int8_t);
int8_t correctionFlexTiming(int8_t);
int8_t correctionWMITiming(int8_t);
int8_t correctionIATretard(int8_t);
int8_t correctionCLTadvance(int8_t);
int8_t correctionIdleAdvance(int8_t);
int8_t correctionSoftRevLimit(int8_t);
int8_t correctionNitrous(int8_t);
int8_t correctionSoftLaunch(int8_t);
int8_t correctionSoftFlatShift(int8_t);
int8_t correctionKnock(int8_t);
uint16_t correctionsDwell(uint16_t dwell);
extern int MAP_rateOfChange;
extern int TPS_rateOfChange;
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 uint16_t aseTaperStart;
extern uint16_t dfcoStart;
extern uint16_t idleAdvStart;
#endif // CORRECTIONS_H
| 2,001
|
C++
|
.h
| 47
| 41.340426
| 94
| 0.827249
|
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,100
|
scheduler.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/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 explicitely 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
extern void (*inj1StartFunction)();
extern void (*inj1EndFunction)();
extern void (*inj2StartFunction)();
extern void (*inj2EndFunction)();
extern void (*inj3StartFunction)();
extern void (*inj3EndFunction)();
extern void (*inj4StartFunction)();
extern void (*inj4EndFunction)();
extern void (*inj5StartFunction)();
extern void (*inj5EndFunction)();
extern void (*inj6StartFunction)();
extern void (*inj6EndFunction)();
extern void (*inj7StartFunction)();
extern void (*inj7EndFunction)();
extern void (*inj8StartFunction)();
extern void (*inj8EndFunction)();
/** @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)();
extern void (*ign1EndFunction)();
extern void (*ign2StartFunction)();
extern void (*ign2EndFunction)();
extern void (*ign3StartFunction)();
extern void (*ign3EndFunction)();
extern void (*ign4StartFunction)();
extern void (*ign4EndFunction)();
extern void (*ign5StartFunction)();
extern void (*ign5EndFunction)();
extern void (*ign6StartFunction)();
extern void (*ign6EndFunction)();
extern void (*ign7StartFunction)();
extern void (*ign7EndFunction)();
extern void (*ign8StartFunction)();
extern void (*ign8EndFunction)();
/** @} */
void initialiseSchedulers();
void beginInjectorPriming();
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 seprate functions for their ISRs
#if defined(ARDUINO_ARCH_STM32) || defined(CORE_TEENSY)
static inline void fuelSchedule1Interrupt();
static inline void fuelSchedule2Interrupt();
static inline void fuelSchedule3Interrupt();
static inline void fuelSchedule4Interrupt();
#if (INJ_CHANNELS >= 5)
static inline void fuelSchedule5Interrupt();
#endif
#if (INJ_CHANNELS >= 6)
static inline void fuelSchedule6Interrupt();
#endif
#if (INJ_CHANNELS >= 7)
static inline void fuelSchedule7Interrupt();
#endif
#if (INJ_CHANNELS >= 8)
static inline void fuelSchedule8Interrupt();
#endif
#if (IGN_CHANNELS >= 1)
static inline void ignitionSchedule1Interrupt();
#endif
#if (IGN_CHANNELS >= 2)
static inline void ignitionSchedule2Interrupt();
#endif
#if (IGN_CHANNELS >= 3)
static inline void ignitionSchedule3Interrupt();
#endif
#if (IGN_CHANNELS >= 4)
static inline void ignitionSchedule4Interrupt();
#endif
#if (IGN_CHANNELS >= 5)
static inline void ignitionSchedule5Interrupt();
#endif
#if (IGN_CHANNELS >= 6)
static inline void ignitionSchedule6Interrupt();
#endif
#if (IGN_CHANNELS >= 7)
static inline void ignitionSchedule7Interrupt();
#endif
#if (IGN_CHANNELS >= 8)
static inline void ignitionSchedule8Interrupt();
#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 implementes 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
| 11,671
|
C++
|
.h
| 252
| 44.281746
| 205
| 0.764959
|
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,101
|
table3d_values.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/speeduino/table3d_values.h
|
/**
* @addtogroup table_3d
* @{
*/
/** \file
* @brief 3D table value structs and iterators
*/
#pragma once
#include "table3d_typedefs.h"
// ========================= INTRA-ROW ITERATION =========================
/** @brief Iterate through a table row. I.e. constant Y, changing X
*
* Instances of this class are normally created via a table_value_iterator instance.
*/
class table_row_iterator {
public:
/**
* @brief Construct
* @param pRowStart Pointer to the 1st element in the row
* @param rowWidth The number of elements to in the row
*/
table_row_iterator(const table3d_value_t *pRowStart, table3d_dim_t rowWidth)
: pValue(pRowStart), pEnd(pRowStart+rowWidth)
{
}
/** @brief Pointer to the end of the row */
inline const table3d_value_t* end() const { return pEnd; }
/** @copydoc table_row_iterator::end() const */
inline table3d_value_t* end() { return const_cast<table3d_value_t *>(pEnd); }
/** @brief Advance the iterator
* @param steps The number of elements to move the iterator
*/
inline table_row_iterator& advance(table3d_dim_t steps)
{
pValue = pValue + steps;
return *this;
}
/** @brief Increment the iterator by one element*/
inline table_row_iterator& operator++()
{
return advance(1);
}
/** @brief Test for end of iteration */
inline bool at_end() const
{
return pValue == pEnd;
}
/** @brief Dereference the iterator */
inline const table3d_value_t& operator*() const
{
return *pValue;
}
/** @copydoc table_row_iterator::operator*() const */
inline table3d_value_t& operator*()
{
return *const_cast<table3d_value_t *>(pValue);
}
/** @brief Number of elements available */
inline table3d_dim_t size() const { return pEnd-pValue; }
private:
const table3d_value_t *pValue;
const table3d_value_t *pEnd;
};
// ========================= INTER-ROW ITERATION =========================
/** @brief Iterate through a tables values, row by row. */
class table_value_iterator
{
public:
/**
* @brief Construct
* @param pValues Pointer to the 1st value in a 1-d array
* @param axisSize The number of columns & elements per row (square tables only)
*/
table_value_iterator(const table3d_value_t *pValues, table3d_dim_t axisSize)
: pRowsStart(pValues + (axisSize*(axisSize-1))),
pRowsEnd(pValues - axisSize),
rowWidth(axisSize)
{
// Table values are not linear in memory - rows are in reverse order
// E.g. a 4x4 table with logical element [0][0] at the bottom left
// (normal cartesian coordinates) has this layout.
// 0 1 2 3
// 4 5 6 7
// 8 9 10 11
// 12 13 14 15
// So we start at row 3 (index 12 of the array) and iterate towards
// the start of the array
//
// This all supports fast 3d interpolation.
}
/** @brief Advance the iterator
* @param rows The number of \b rows to move
*/
inline table_value_iterator& advance(table3d_dim_t rows)
{
pRowsStart = pRowsStart - (rowWidth * rows);
return *this;
}
/** @brief Increment the iterator by one \b row */
inline table_value_iterator& operator++()
{
return advance(1);
}
/** @brief Dereference the iterator to access a row of data */
inline const table_row_iterator operator*() const
{
return table_row_iterator(pRowsStart, rowWidth);
}
/** @copydoc table_value_iterator::operator*() const */
inline table_row_iterator operator*()
{
return table_row_iterator(pRowsStart, rowWidth);
}
/** @brief Test for end of iteration */
inline bool at_end() const
{
return pRowsStart == pRowsEnd;
}
private:
const table3d_value_t *pRowsStart;
const table3d_value_t *pRowsEnd;
table3d_dim_t rowWidth;
};
#define TABLE3D_TYPENAME_VALUE(size, xDom, yDom) CONCAT(TABLE3D_TYPENAME_BASE(size, xDom, yDom), _values)
#define TABLE3D_GEN_VALUES(size, xDom, yDom) \
/** @brief The values for a 3D table with size x size dimensions, xDom x-axis and yDom y-axis */ \
struct TABLE3D_TYPENAME_VALUE(size, xDom, yDom) { \
/** @brief The number of items in a row. I.e. it's length */ \
static constexpr table3d_dim_t row_size = size; \
/** @brief The number of rows */ \
static constexpr table3d_dim_t num_rows = size; \
/** \
@brief The row values \
@details Table values are not linear in memory - rows are in reverse order<br> \
E.g. a 3x3 table with logical element [0][0] at the bottom left \
(normal cartesian coordinates) has this layout:<br> \
6, 7, 8, 3, 4, 5, 0, 1, 2 \
*/ \
table3d_value_t values[row_size*num_rows]; \
\
/** @brief Iterate over the values */ \
inline table_value_iterator begin() \
{ \
return table_value_iterator(values, row_size); \
} \
\
/** \
@brief Direct access to table value element from a linear index \
@details Since table values aren't laid out linearly, converting a linear \
offset to the equivalent memory address requires a modulus operation.<br> \
<br> \
This is slow, since AVR hardware has no divider. We can gain performance \
in 2 ways:<br> \
1. Forcing uint8_t calculations. These are much faster than 16-bit calculations<br> \
2. Compiling this per table *type*. This encodes the axis length as a constant \
thus allowing the optimizing compiler more opportunity. E.g. for axis lengths \
that are a power of 2, the modulus can be optimised to add/multiply/shift - much \
cheaper than calling a software division routine such as __udivmodqi4<br> \
<br> \
THIS IS WORTH 20% to 30% speed up<br> \
<br> \
This limits us to 16x16 tables. If we need bigger and move to 16-bit \
operations, consider using libdivide. <br> \
*/ \
inline table3d_value_t& value_at(table3d_dim_t linear_index) \
{ \
static_assert(row_size<17, "Table is too big"); \
static_assert(num_rows<17, "Table is too big"); \
constexpr table3d_dim_t first_index = row_size*(num_rows-1); \
const table3d_dim_t index = first_index + (2*(linear_index % row_size)) - linear_index; \
return values[index]; \
} \
};
TABLE3D_GENERATOR(TABLE3D_GEN_VALUES)
/** @} */
| 6,696
|
C++
|
.h
| 175
| 31.697143
| 105
| 0.613112
|
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,102
|
acc_mc33810.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/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();
#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,375
|
C++
|
.h
| 87
| 141.08046
| 221
| 0.786721
|
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,103
|
table3d_axes.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/speeduino/table3d_axes.h
|
/**
* @addtogroup table_3d
* @{
*/
/** \file
* @brief 3D table axis types and iterators
*/
#pragma once
#include "table3d_typedefs.h"
#include "int16_ref.h"
#include "src/libdivide/constant_fast_div.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(const table3d_axis_t *pStart, const table3d_axis_t *pEnd, const int16_ref::scalar *pScalar, int8_t stride)
: _pAxis(pStart), _pAxisEnd(pEnd), _stride(stride), _pScalar(pScalar)
{
}
/** @brief Advance the iterator
* @param steps The number of elements to move the iterator
*/
inline table_axis_iterator& advance(table3d_dim_t steps)
{
_pAxis = _pAxis + (_stride * steps);
return *this;
}
/** @brief Increment the iterator by one element*/
inline table_axis_iterator& operator++()
{
return advance(1);
}
/** @brief Test for end of iteration */
inline bool at_end() const
{
return _pAxis == _pAxisEnd;
}
/** @brief Dereference the iterator */
inline int16_ref operator*()
{
return int16_ref(*const_cast<table3d_axis_t*>(_pAxis), _pScalar);
}
/** @copydoc table_axis_iterator::operator*() */
inline const int16_ref operator*() const
{
return int16_ref(*const_cast<table3d_axis_t*>(_pAxis), _pScalar);
}
/** @brief Reverse the iterator direction
*
* Iterate from the end to the start. <b>This is only meant to be called on a freshly constructed iterator.</b>
*/
inline table_axis_iterator& reverse()
{
const table3d_axis_t *_pOldAxis = _pAxis;
_pAxis = _pAxisEnd - _stride;
_pAxisEnd = _pOldAxis - _stride;
_stride = (int8_t)(_stride * -1);
return *this;
}
private:
const table3d_axis_t *_pAxis;
const table3d_axis_t *_pAxisEnd;
int8_t _stride;
const int16_ref::scalar *_pScalar;
};
/** @brief Shared code for the axis types */
class table3d_axis_base {
protected:
static constexpr const int16_ref::scalar* domain_to_scalar(axis_domain domain) {
// This really, really needs to be done at compile time, hence the contexpr
return domain==axis_domain_Rpm ? &scalar_100 :
domain==axis_domain_Load ? &scalar_2 : &scalar_1;
}
private:
static constexpr const int16_ref::scalar scalar_100 = { 100, { S16_MAGIC(100), S16_MORE(100) } };
static constexpr const int16_ref::scalar scalar_2 = { 2, { S16_MAGIC(2), S16_MORE(2) } };
static constexpr const int16_ref::scalar scalar_1 = { 1, { S16_MAGIC(1), S16_MORE(1) } };
};
#define TABLE3D_TYPENAME_XAXIS(size, xDom, yDom) CONCAT(TABLE3D_TYPENAME_BASE(size, xDom, yDom), _xaxis)
#define TABLE3D_GEN_XAXIS(size, xDom, yDom) \
/** @brief The x-axis for a 3D table with size x size dimensions, xDom x-axis and yDom y-axis */ \
struct TABLE3D_TYPENAME_XAXIS(size, xDom, yDom) : public table3d_axis_base { \
/** @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_ ## xDom; \
/**
@brief The axis elements \
@details The x-axis is conventional: axis[0] is the minimum \
*/ \
table3d_axis_t axis[size]; \
\
/** @brief Iterate over the axis elements */ \
inline table_axis_iterator begin() \
{ \
return table_axis_iterator(axis, axis+size, domain_to_scalar(domain), 1); \
} \
};
TABLE3D_GENERATOR(TABLE3D_GEN_XAXIS)
#define TABLE3D_TYPENAME_YAXIS(size, xDom, yDom) CONCAT(TABLE3D_TYPENAME_BASE(size, xDom, yDom), _yaxis)
#define TABLE3D_GEN_YAXIS(size, xDom, yDom) \
/** @brief The y-axis for a 3D table with size x size dimensions, xDom x-axis and yDom y-axis */ \
struct CONCAT(TABLE3D_TYPENAME_BASE(size, xDom, yDom), _yaxis) : public table3d_axis_base { \
/** @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_ ## yDom; \
/**
@brief The axis elements \
@details The y-axis is reversed: axis[n-1] is the minimum \
*/ \
table3d_axis_t axis[size]; \
\
/** @brief Iterate over the axis elements */ \
inline table_axis_iterator begin() \
{ \
return table_axis_iterator(axis+(size-1), axis-1, domain_to_scalar(domain), -1); \
} \
};
TABLE3D_GENERATOR(TABLE3D_GEN_YAXIS)
/** @} */
| 4,987
|
C++
|
.h
| 133
| 31.699248
| 130
| 0.628595
|
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,107
|
PID_v1.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/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
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,269
|
C++
|
.h
| 162
| 48.623457
| 133
| 0.566276
|
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,109
|
STM32_CAN.h
|
oelprinz-org_BlitzboxBL49sp/software/202202/speeduino-202202/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 enabled. If it causes problems, use begin(false) to disable it.
void begin(bool retransmission = true);
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,297
|
C++
|
.h
| 161
| 35.78882
| 199
| 0.705111
|
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,110
|
test_utils.h
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/test/test_utils.h
|
#pragma once
// Unity macro to reduce memory usage (RAM, .bss)
//
// Unity supplied RUN_TEST captures the function name
// using #func directly in the call to UnityDefaultTestRun.
// This is a raw string that is placed in the data segment,
// which consumes RAM.
//
// So instead, place the function name in flash memory and
// load it at run time.
#define RUN_TEST_P(func) \
{ \
char funcName[64]; \
strcpy_P(funcName, PSTR(#func)); \
UnityDefaultTestRun(func, funcName, __LINE__); \
}
| 505
|
C++
|
.h
| 16
| 29.4375
| 59
| 0.708419
|
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,111
|
test_corrections.h
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/test/test_fuel/test_corrections.h
|
void testCorrections();
void test_corrections_WUE(void);
void test_corrections_cranking(void);
void test_corrections_ASE(void);
void test_corrections_floodclear(void);
void test_corrections_closedloop(void);
void test_corrections_flex(void);
void test_corrections_bat(void);
void test_corrections_iatdensity(void);
void test_corrections_baro(void);
void test_corrections_launch(void);
void test_corrections_dfco(void);
void test_corrections_TAE(void);
| 451
|
C++
|
.h
| 13
| 33.769231
| 39
| 0.826879
|
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,112
|
sensors.h
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/sensors.h
|
#ifndef SENSORS_H
#define SENSORS_H
#include "Arduino.h"
// The following are alpha values for the ADC filters.
// Their values are from 0 to 240, with 0 being no filtering and 240 being maximum
#define ADCFILTER_TPS_DEFAULT 50
#define ADCFILTER_CLT_DEFAULT 180
#define ADCFILTER_IAT_DEFAULT 180
#define ADCFILTER_O2_DEFAULT 128
#define ADCFILTER_BAT_DEFAULT 128
#define ADCFILTER_MAP_DEFAULT 20 //This is only used on Instantaneous MAP readings and is intentionally very weak to allow for faster response
#define ADCFILTER_BARO_DEFAULT 64
#define ADCFILTER_PSI_DEFAULT 150 //not currently configurable at runtime, used for misc pressure sensors, oil, fuel, etc.
#define FILTER_FLEX_DEFAULT 75
#define BARO_MIN 65
#define BARO_MAX 108
#define KNOCK_MODE_DIGITAL 1
#define KNOCK_MODE_ANALOG 2
#define VSS_GEAR_HYSTERESIS 10
#define VSS_SAMPLES 4 //Must be a power of 2 and smaller than 255
#define TPS_READ_FREQUENCY 30 //ONLY VALID VALUES ARE 15 or 30!!!
/*
#if defined(CORE_AVR)
#define ANALOG_ISR
#endif
*/
volatile byte flexCounter = 0;
volatile unsigned long flexStartTime;
volatile unsigned long flexPulseWidth;
#if defined(CORE_AVR)
#define READ_FLEX() ((*flex_pin_port & flex_pin_mask) ? true : false)
#else
#define READ_FLEX() digitalRead(pinFlex)
#endif
volatile byte knockCounter = 0;
volatile uint16_t knockAngle;
unsigned long MAPrunningValue; //Used for tracking either the total of all MAP readings in this cycle (Event average) or the lowest value detected in this cycle (event minimum)
unsigned long EMAPrunningValue; //As above but for EMAP
unsigned int MAPcount; //Number of samples taken in the current MAP cycle
uint32_t MAPcurRev; //Tracks which revolution we're sampling on
bool auxIsEnabled;
uint16_t MAPlast; /**< The previous MAP reading */
unsigned long MAP_time; //The time the MAP sample was taken
unsigned long MAPlast_time; //The time the previous MAP sample was taken
volatile unsigned long vssTimes[VSS_SAMPLES] = {0};
volatile byte vssIndex;
//These variables are used for tracking the number of running sensors values that appear to be errors. Once a threshold is reached, the sensor reading will go to default value and assume the sensor is faulty
byte mapErrorCount = 0;
byte iatErrorCount = 0;
byte cltErrorCount = 0;
/**
* @brief Simple low pass IIR filter macro for the analog inputs
* This is effectively implementing the smooth filter from playground.arduino.cc/Main/Smooth
* But removes the use of floats and uses 8 bits of fixed precision.
*/
#define ADC_FILTER(input, alpha, prior) (((long)input * (256 - alpha) + ((long)prior * alpha))) >> 8
static inline void instanteneousMAPReading(void) __attribute__((always_inline));
static inline void readMAP(void) __attribute__((always_inline));
static inline void validateMAP(void);
void initialiseADC(void);
void readTPS(bool useFilter=true); //Allows the option to override the use of the filter
void readO2_2(void);
void flexPulse(void);
uint32_t vssGetPulseGap(byte toothHistoryIndex);
void vssPulse(void);
uint16_t getSpeed(void);
byte getGear(void);
byte getFuelPressure(void);
byte getOilPressure(void);
uint16_t readAuxanalog(uint8_t analogPin);
uint16_t readAuxdigital(uint8_t digitalPin);
void readCLT(bool useFilter=true); //Allows the option to override the use of the filter
void readIAT(void);
void readO2(void);
void readBat(void);
void readBaro(void);
#if defined(ANALOG_ISR)
volatile int AnChannel[15];
//Analog ISR interrupt routine
/*
ISR(ADC_vect)
{
byte nChannel;
int result = ADCL | (ADCH << 8);
//ADCSRA = 0x6E; - ADC disabled by clearing bit 7(ADEN)
//BIT_CLEAR(ADCSRA, ADIE);
nChannel = ADMUX & 0x07;
#if defined(__AVR_ATmega1281__) || defined(__AVR_ATmega2561__)
if (nChannel==7) { ADMUX = 0x40; }
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
if(ADCSRB & 0x08) { nChannel += 8; } //8 to 15
if(nChannel == 15)
{
ADMUX = 0x40; //channel 0
ADCSRB = 0x00; //clear MUX5 bit
}
else if (nChannel == 7) //channel 7
{
ADMUX = 0x40;
ADCSRB = 0x08; //Set MUX5 bit
}
#endif
else { ADMUX++; }
AnChannel[nChannel-1] = result;
//BIT_SET(ADCSRA, ADIE);
//ADCSRA = 0xEE; - ADC Interrupt Flag enabled
}
*/
ISR(ADC_vect)
{
byte nChannel = ADMUX & 0x07;
int result = ADCL | (ADCH << 8);
BIT_CLEAR(ADCSRA, ADEN); //Disable ADC for Changing Channel (see chapter 26.5 of datasheet)
#if defined(__AVR_ATmega1281__) || defined(__AVR_ATmega2561__)
if (nChannel==7) { ADMUX = 0x40; }
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
if( (ADCSRB & 0x08) > 0) { nChannel += 8; } //8 to 15
if(nChannel == 15)
{
ADMUX = 0x40; //channel 0
ADCSRB = 0x00; //clear MUX5 bit
}
else if (nChannel == 7) //channel 7
{
ADMUX = 0x40;
ADCSRB = 0x08; //Set MUX5 bit
}
#endif
else { ADMUX++; }
AnChannel[nChannel] = result;
BIT_SET(ADCSRA, ADEN); //Enable ADC
}
#endif
#endif // SENSORS_H
| 5,028
|
C++
|
.h
| 134
| 35.074627
| 207
| 0.728225
|
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,113
|
storage.h
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/storage.h
|
#ifndef STORAGE_H
#define STORAGE_H
/** @file storage.h
* @brief Functions for reading and writing user settings to/from EEPROM
*
* Current layout of EEPROM is as follows (Version 18):
*
* |Offset (Dec)|Size (Bytes)| Description | Reference |
* | ---------: | :--------: | :----------------------------------: | :--------------------------------- |
* | 0 |1 | EEPROM version | @ref EEPROM_DATA_VERSION |
* | 1 |2 | X and Y sizes for fuel table | |
* | 3 |256 | Fuel table (16x16) | @ref EEPROM_CONFIG1_MAP |
* | 259 |16 | Fuel table (X axis) (RPM) | |
* | 275 |16 | Fuel table (Y axis) (MAP/TPS) | |
* | 291 |128 | Page 2 settings | @ref EEPROM_CONFIG2_START |
* | 419 |2 | X and Y sizes for ignition table | |
* | 421 |256 | Ignition table (16x16) | @ref EEPROM_CONFIG3_MAP |
* | 677 |16 | Ignition table (X axis) (RPM) | |
* | 693 |16 | Ignition table (Y axis) (MAP/TPS) | |
* | 709 |128 | Page 4 settings | @ref EEPROM_CONFIG4_START |
* | 837 |2 | X and Y sizes for AFR target table | |
* | 839 |256 | AFR target table (16x16) | @ref EEPROM_CONFIG5_MAP |
* | 1095 |16 | AFR target table (X axis) (RPM) | |
* | 1111 |16 | AFR target table (Y axis) (MAP/TPS) | |
* | 1127 |128 | Page 6 settings | @ref EEPROM_CONFIG6_START |
* | 1255 |2 | X and Y sizes for boost table | |
* | 1257 |64 | Boost table (8x8) | @ref EEPROM_CONFIG7_MAP1 |
* | 1321 |8 | Boost table (X axis) (RPM) | |
* | 1329 |8 | Boost table (Y axis) (TPS) | |
* | 1337 |2 | X and Y sizes for vvt table | |
* | 1339 |64 | VVT table (8x8) | @ref EEPROM_CONFIG7_MAP2 |
* | 1403 |8 | VVT table (X axis) (RPM) | |
* | 1411 |8 | VVT table (Y axis) (MAP) | |
* | 1419 |2 | X and Y sizes for staging table | |
* | 1421 |64 | Staging table (8x8) | @ref EEPROM_CONFIG7_MAP3 |
* | 1485 |8 | Staging table (X axis) (RPM) | |
* | 1493 |8 | Staging table (Y axis) (MAP) | |
* | 1501 |2 | X and Y sizes for trim1 table | |
* | 1503 |36 | Trim1 table (6x6) | @ref EEPROM_CONFIG8_MAP1 |
* | 1539 |6 | Trim1 table (X axis) (RPM) | |
* | 1545 |6 | Trim1 table (Y axis) (MAP) | |
* | 1551 |2 | X and Y sizes for trim2 table | |
* | 1553 |36 | Trim2 table (6x6) | @ref EEPROM_CONFIG8_MAP2 |
* | 1589 |6 | Trim2 table (X axis) (RPM) | |
* | 1595 |6 | Trim2 table (Y axis) (MAP) | |
* | 1601 |2 | X and Y sizes for trim3 table | |
* | 1603 |36 | Trim3 table (6x6) | @ref EEPROM_CONFIG8_MAP3 |
* | 1639 |6 | Trim3 table (X axis) (RPM) | |
* | 1545 |6 | Trim3 table (Y axis) (MAP) | |
* | 1651 |2 | X and Y sizes for trim4 table | |
* | 1653 |36 | Trim4 table (6x6) | @ref EEPROM_CONFIG8_MAP4 |
* | 1689 |6 | Trim4 table (X axis) (RPM) | |
* | 1595 |6 | Trim4 table (Y axis) (MAP) | |
* | 1701 |9 | HOLE ?? | |
* | 1710 |192 | Page 9 settings | @ref EEPROM_CONFIG9_START |
* | 1902 |192 | Page 10 settings | @ref EEPROM_CONFIG10_START |
* | 2094 |2 | X and Y sizes for fuel2 table | |
* | 2096 |256 | Fuel2 table (16x16) | @ref EEPROM_CONFIG11_MAP |
* | 2352 |16 | Fuel2 table (X axis) (RPM) | |
* | 2368 |16 | Fuel2 table (Y axis) (MAP/TPS) | |
* | 2384 |1 | HOLE ?? | |
* | 2385 |2 | X and Y sizes for WMI table | |
* | 2387 |64 | WMI table (8x8) | @ref EEPROM_CONFIG12_MAP |
* | 2451 |8 | WMI table (X axis) (RPM) | |
* | 2459 |8 | WMI table (Y axis) (MAP) | |
* | 2467 |2 | X and Y sizes VVT2 table | |
* | 2469 |64 | VVT2 table (8x8) | @ref EEPROM_CONFIG12_MAP2 |
* | 2553 |8 | VVT2 table (X axis) (RPM) | |
* | 2541 |8 | VVT2 table (Y axis) (MAP) | |
* | 2549 |2 | X and Y sizes dwell table | |
* | 2551 |16 | Dwell table (4x4) | @ref EEPROM_CONFIG12_MAP3 |
* | 2567 |4 | Dwell table (X axis) (RPM) | |
* | 2571 |4 | Dwell table (Y axis) (MAP) | |
* | 2575 |5 | HOLE ?? | |
* | 2580 |128 | Page 13 settings | @ref EEPROM_CONFIG13_START |
* | 2708 |2 | X and Y sizes for ignition2 table | |
* | 2710 |256 | Ignition2 table (16x16) | @ref EEPROM_CONFIG14_MAP |
* | 2966 |16 | Ignition2 table (X axis) (RPM) | |
* | 2982 |16 | Ignition2 table (Y axis) (MAP/TPS) | |
* | 2998 |1 | HOLE ?? | |
* | 2999 |2 | X and Y sizes for trim5 table | |
* | 3001 |36 | Trim5 table (6x6) | @ref EEPROM_CONFIG8_MAP5 |
* | 3037 |6 | Trim5 table (X axis) (RPM) | |
* | 3043 |6 | Trim5 table (Y axis) (MAP) | |
* | 3049 |2 | X and Y sizes for trim6 table | |
* | 3051 |36 | Trim6 table (6x6) | @ref EEPROM_CONFIG8_MAP6 |
* | 3087 |6 | Trim6 table (X axis) (RPM) | |
* | 3093 |6 | Trim6 table (Y axis) (MAP) | |
* | 3099 |2 | X and Y sizes for trim7 table | |
* | 3101 |36 | Trim7 table (6x6) | @ref EEPROM_CONFIG8_MAP7 |
* | 3137 |6 | Trim7 table (X axis) (RPM) | |
* | 3143 |6 | Trim7 table (Y axis) (MAP) | |
* | 3149 |2 | X and Y sizes for trim8 table | |
* | 3151 |36 | Trim8 table (6x6) | @ref EEPROM_CONFIG8_MAP8 |
* | 3187 |6 | Trim8 table (X axis) (RPM) | |
* | 3193 |6 | Trim8 table (Y axis) (MAP) | |
* | 3199 |2 | X and Y sizes boostLUT table | |
* | 3201 |64 | boostLUT table (8x8) | @ref EEPROM_CONFIG15_MAP |
* | 3265 |8 | boostLUT table (X axis) (RPM) | |
* | 3273 |8 | boostLUT table (Y axis) (targetBoost)| |
* | 3281 |1 | boostLUT enable | @ref EEPROM_CONFIG15_START |
* | 3282 |1 | boostDCWhenDisabled | |
* | 3283 |1 | boostControlEnableThreshold | |
* | 3284 |14 | A/C Control Settings | |
* | 3298 |159 | Page 15 spare | |
* | 3457 |217 | EMPTY | |
* | 3674 |4 | CLT Calibration CRC32 | |
* | 3678 |4 | IAT Calibration CRC32 | |
* | 3682 |4 | O2 Calibration CRC32 | |
* | 3686 |56 | Page CRC32 sums (4x14) | Last first, 14 -> 1 |
* | 3742 |1 | Baro value saved at init | @ref EEPROM_LAST_BARO |
* | 3743 |64 | O2 Calibration Bins | @ref EEPROM_CALIBRATION_O2_BINS |
* | 3807 |32 | O2 Calibration Values | @ref EEPROM_CALIBRATION_O2_VALUES |
* | 3839 |64 | IAT Calibration Bins | @ref EEPROM_CALIBRATION_IAT_BINS |
* | 3903 |64 | IAT Calibration Values | @ref EEPROM_CALIBRATION_IAT_VALUES |
* | 3967 |64 | CLT Calibration Bins | @ref EEPROM_CALIBRATION_CLT_BINS |
* | 4031 |64 | CLT Calibration Values | @ref EEPROM_CALIBRATION_CLT_VALUES |
* | 4095 | | END | |
*
*/
void writeAllConfig(void);
void writeConfig(uint8_t pageNum);
void EEPROMWriteRaw(uint16_t address, uint8_t data);
uint8_t EEPROMReadRaw(uint16_t address);
void loadConfig(void);
void loadCalibration(void);
void writeCalibration(void);
void writeCalibrationPage(uint8_t pageNum);
void resetConfigPages(void);
//These are utility functions that prevent other files from having to use EEPROM.h directly
byte readLastBaro(void);
void storeLastBaro(byte newValue);
uint8_t readEEPROMVersion(void);
void storeEEPROMVersion(byte newVersion);
void storePageCRC32(uint8_t pageNum, uint32_t crcValue);
uint32_t readPageCRC32(uint8_t pageNum);
void storeCalibrationCRC32(uint8_t calibrationPageNum, uint32_t calibrationCRC);
uint32_t readCalibrationCRC32(uint8_t calibrationPageNum);
uint16_t getEEPROMSize(void);
bool isEepromWritePending(void);
extern uint32_t deferEEPROMWritesUntil;
#define EEPROM_CONFIG1_MAP 3
#define EEPROM_CONFIG2_START 291
#define EEPROM_CONFIG2_END 419
#define EEPROM_CONFIG3_MAP 421
#define EEPROM_CONFIG4_START 709
#define EEPROM_CONFIG4_END 837
#define EEPROM_CONFIG5_MAP 839
#define EEPROM_CONFIG6_START 1127
#define EEPROM_CONFIG6_END 1255
#define EEPROM_CONFIG7_MAP1 1257
#define EEPROM_CONFIG7_MAP2 1339
#define EEPROM_CONFIG7_MAP3 1421
#define EEPROM_CONFIG7_END 1501
#define EEPROM_CONFIG8_MAP1 1503
#define EEPROM_CONFIG8_MAP2 1553
#define EEPROM_CONFIG8_MAP3 1603
#define EEPROM_CONFIG8_MAP4 1653
#define EEPROM_CONFIG9_START 1710
#define EEPROM_CONFIG9_END 1902
#define EEPROM_CONFIG10_START 1902
#define EEPROM_CONFIG10_END 2094
#define EEPROM_CONFIG11_MAP 2096
#define EEPROM_CONFIG11_END 2385
#define EEPROM_CONFIG12_MAP 2387
#define EEPROM_CONFIG12_MAP2 2469
#define EEPROM_CONFIG12_MAP3 2551
#define EEPROM_CONFIG12_END 2575
#define EEPROM_CONFIG13_START 2580
#define EEPROM_CONFIG13_END 2708
#define EEPROM_CONFIG14_MAP 2710
#define EEPROM_CONFIG14_END 2998
//This is OUT OF ORDER as Page 8 was expanded to add fuel trim tables 5-8. The EEPROM for them is simply added here so as not to impact existing tunes
#define EEPROM_CONFIG8_MAP5 3001
#define EEPROM_CONFIG8_MAP6 3051
#define EEPROM_CONFIG8_MAP7 3101
#define EEPROM_CONFIG8_MAP8 3151
//Page 15 added after OUT OF ORDER page 8
#define EEPROM_CONFIG15_MAP 3199
#define EEPROM_CONFIG15_START 3281
#define EEPROM_CONFIG15_END 3457
#define EEPROM_CALIBRATION_CLT_CRC 3674
#define EEPROM_CALIBRATION_IAT_CRC 3678
#define EEPROM_CALIBRATION_O2_CRC 3682
//These were the values used previously when all calibration tables were 512 long. They need to be retained so the update process (202005 -> 202008) can work
#define EEPROM_CALIBRATION_O2_OLD 2559
#define EEPROM_CALIBRATION_IAT_OLD 3071
#define EEPROM_CALIBRATION_CLT_OLD 3583
#define EEPROM_DEFER_DELAY 1000000UL //1.0 second pause after large comms before writing to EEPROM
#endif // STORAGE_H
| 15,008
|
C++
|
.h
| 190
| 77.321053
| 157
| 0.387966
|
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,114
|
board_stm32_generic.h
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/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 &CANSerial = Serial2;
#else //libmaple core aka STM32DUINO
HardwareSerial &CANSerial = Serial2;
#endif
#endif //CORE_STM32
#endif //STM32_H
| 8,724
|
C++
|
.h
| 196
| 41.015306
| 155
| 0.618762
|
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,115
|
board_same51.h
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/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 CANSerial (&sercom3, 0, 1, SERCOM_RX_PAD_1, UART_TX_PAD_0);
#endif //CORE_SAMD21
#endif //SAMD21_H
| 8,597
|
C++
|
.h
| 172
| 46.947674
| 178
| 0.670158
|
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,116
|
comms_legacy.h
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/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;
/**
* @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 sendValues(uint16_t offset, uint16_t packetLength, byte cmd, byte portNum);
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,256
|
C++
|
.h
| 78
| 39.205128
| 173
| 0.773258
|
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,117
|
maths.h
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/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);
#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,359
|
C++
|
.h
| 72
| 30.625
| 155
| 0.716352
|
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,118
|
scheduledIO.h
|
oelprinz-org_BlitzboxBL49sp/software/202305/speeduino-202305/speeduino/scheduledIO.h
|
#ifndef SCHEDULEDIO_H
#define SCHEDULEDIO_H
#include <Arduino.h>
inline void openInjector1(void);
inline void closeInjector1(void);
inline void openInjector2(void);
inline void closeInjector2(void);
inline void openInjector3(void);
inline void closeInjector3(void);
inline void openInjector4(void);
inline void closeInjector4(void);
inline void openInjector5(void);
inline void closeInjector5(void);
inline void openInjector6(void);
inline void closeInjector6(void);
inline void openInjector7(void);
inline void closeInjector7(void);
inline void openInjector8(void);
inline void closeInjector8(void);
// These are for Semi-Sequential and 5 Cylinder injection
void openInjector1and3(void);
void closeInjector1and3(void);
void openInjector2and4(void);
void closeInjector2and4(void);
void openInjector1and4(void);
void closeInjector1and4(void);
void openInjector2and3(void);
void closeInjector2and3(void);
void openInjector3and5(void);
void closeInjector3and5(void);
void openInjector2and5(void);
void closeInjector2and5(void);
void openInjector3and6(void);
void closeInjector3and6(void);
void openInjector1and5(void);
void closeInjector1and5(void);
void openInjector2and6(void);
void closeInjector2and6(void);
void openInjector3and7(void);
void closeInjector3and7(void);
void openInjector4and8(void);
void closeInjector4and8(void);
void injector1Toggle(void);
void injector2Toggle(void);
void injector3Toggle(void);
void injector4Toggle(void);
void injector5Toggle(void);
void injector6Toggle(void);
void injector7Toggle(void);
void injector8Toggle(void);
inline void beginCoil1Charge(void);
inline void endCoil1Charge(void);
inline void beginCoil2Charge(void);
inline void endCoil2Charge(void);
inline void beginCoil3Charge(void);
inline void endCoil3Charge(void);
inline void beginCoil4Charge(void);
inline void endCoil4Charge(void);
inline void beginCoil5Charge(void);
inline void endCoil5Charge(void);
inline void beginCoil6Charge(void);
inline void endCoil6Charge(void);
inline void beginCoil7Charge(void);
inline void endCoil7Charge(void);
inline void beginCoil8Charge(void);
inline void endCoil8Charge(void);
//The following functions are used specifically for the trailing coil on rotary engines. They are separate as they also control the switching of the trailing select pin
inline void beginTrailingCoilCharge(void);
inline void endTrailingCoilCharge1(void);
inline void endTrailingCoilCharge2(void);
//And the combined versions of the above for simplicity
void beginCoil1and3Charge(void);
void endCoil1and3Charge(void);
void beginCoil2and4Charge(void);
void endCoil2and4Charge(void);
//For 6-cyl cop
void beginCoil1and4Charge(void);
void endCoil1and4Charge(void);
void beginCoil2and5Charge(void);
void endCoil2and5Charge(void);
void beginCoil3and6Charge(void);
void endCoil3and6Charge(void);
//For 8-cyl cop
void beginCoil1and5Charge(void);
void endCoil1and5Charge(void);
void beginCoil2and6Charge(void);
void endCoil2and6Charge(void);
void beginCoil3and7Charge(void);
void endCoil3and7Charge(void);
void beginCoil4and8Charge(void);
void endCoil4and8Charge(void);
void coil1Toggle(void);
void coil2Toggle(void);
void coil3Toggle(void);
void coil4Toggle(void);
void coil5Toggle(void);
void coil6Toggle(void);
void coil7Toggle(void);
void coil8Toggle(void);
void tachoOutputOn(void);
void tachoOutputOff(void);
/*
#ifndef USE_MC33810
#define openInjector1() *inj1_pin_port |= (inj1_pin_mask); BIT_SET(currentStatus.status1, BIT_STATUS1_INJ1)
#define closeInjector1() *inj1_pin_port &= ~(inj1_pin_mask); BIT_CLEAR(currentStatus.status1, BIT_STATUS1_INJ1)
#define openInjector2() *inj2_pin_port |= (inj2_pin_mask); BIT_SET(currentStatus.status1, BIT_STATUS1_INJ2)
#define closeInjector2() *inj2_pin_port &= ~(inj2_pin_mask); BIT_CLEAR(currentStatus.status1, BIT_STATUS1_INJ2)
#define openInjector3() *inj3_pin_port |= (inj3_pin_mask); BIT_SET(currentStatus.status1, BIT_STATUS1_INJ3)
#define closeInjector3() *inj3_pin_port &= ~(inj3_pin_mask); BIT_CLEAR(currentStatus.status1, BIT_STATUS1_INJ3)
#define openInjector4() *inj4_pin_port |= (inj4_pin_mask); BIT_SET(currentStatus.status1, BIT_STATUS1_INJ4)
#define closeInjector4() *inj4_pin_port &= ~(inj4_pin_mask); BIT_CLEAR(currentStatus.status1, BIT_STATUS1_INJ4)
#define openInjector5() *inj5_pin_port |= (inj5_pin_mask);
#define closeInjector5() *inj5_pin_port &= ~(inj5_pin_mask);
#define openInjector6() *inj6_pin_port |= (inj6_pin_mask);
#define closeInjector6() *inj6_pin_port &= ~(inj6_pin_mask);
#define openInjector7() *inj7_pin_port |= (inj7_pin_mask);
#define closeInjector7() *inj7_pin_port &= ~(inj7_pin_mask);
#define openInjector8() *inj8_pin_port |= (inj8_pin_mask);
#define closeInjector8() *inj8_pin_port &= ~(inj8_pin_mask);
#else
#include "acc_mc33810.h"
#define openInjector1() openInjector1_MC33810()
#define closeInjector1() closeInjector1_MC33810()
#define openInjector2() openInjector2_MC33810()
#define closeInjector2() closeInjector2_MC33810()
#define openInjector3() openInjector3_MC33810()
#define closeInjector3() closeInjector3_MC33810()
#define openInjector4() openInjector4_MC33810()
#define closeInjector4() closeInjector4_MC33810()
#define openInjector5() openInjector5_MC33810()
#define closeInjector5() closeInjector5_MC33810()
#define openInjector6() openInjector6_MC33810()
#define closeInjector6() closeInjector6_MC33810()
#define openInjector7() openInjector7_MC33810()
#define closeInjector7() closeInjector7_MC33810()
#define openInjector8() openInjector8_MC33810()
#define closeInjector8() closeInjector8_MC33810()
#endif
#define openInjector1and4() openInjector1(); openInjector4()
#define closeInjector1and4() closeInjector1(); closeInjector4()
#define openInjector2and3() openInjector2(); openInjector3()
#define closeInjector2and3() closeInjector2(); closeInjector3()
//5 cylinder support doubles up injector 3 as being closese to inj 5 (Crank angle)
#define openInjector3and5() openInjector3(); openInjector5()
#define closeInjector3and5() closeInjector3(); closeInjector5()
*/
//Macros are used to define how each injector control system functions. These are then called by the master openInjectx() function.
//The DIRECT macros (ie individual pins) are defined below. Others should be defined in their relevant acc_x.h file
#define openInjector1_DIRECT() { *inj1_pin_port |= (inj1_pin_mask); BIT_SET(currentStatus.status1, BIT_STATUS1_INJ1); }
#define closeInjector1_DIRECT() { *inj1_pin_port &= ~(inj1_pin_mask); BIT_CLEAR(currentStatus.status1, BIT_STATUS1_INJ1); }
#define openInjector2_DIRECT() { *inj2_pin_port |= (inj2_pin_mask); BIT_SET(currentStatus.status1, BIT_STATUS1_INJ2); }
#define closeInjector2_DIRECT() { *inj2_pin_port &= ~(inj2_pin_mask); BIT_CLEAR(currentStatus.status1, BIT_STATUS1_INJ2); }
#define openInjector3_DIRECT() { *inj3_pin_port |= (inj3_pin_mask); BIT_SET(currentStatus.status1, BIT_STATUS1_INJ3); }
#define closeInjector3_DIRECT() { *inj3_pin_port &= ~(inj3_pin_mask); BIT_CLEAR(currentStatus.status1, BIT_STATUS1_INJ3); }
#define openInjector4_DIRECT() { *inj4_pin_port |= (inj4_pin_mask); BIT_SET(currentStatus.status1, BIT_STATUS1_INJ4); }
#define closeInjector4_DIRECT() { *inj4_pin_port &= ~(inj4_pin_mask); BIT_CLEAR(currentStatus.status1, BIT_STATUS1_INJ4); }
#define openInjector5_DIRECT() { *inj5_pin_port |= (inj5_pin_mask); }
#define closeInjector5_DIRECT() { *inj5_pin_port &= ~(inj5_pin_mask); }
#define openInjector6_DIRECT() { *inj6_pin_port |= (inj6_pin_mask); }
#define closeInjector6_DIRECT() { *inj6_pin_port &= ~(inj6_pin_mask); }
#define openInjector7_DIRECT() { *inj7_pin_port |= (inj7_pin_mask); }
#define closeInjector7_DIRECT() { *inj7_pin_port &= ~(inj7_pin_mask); }
#define openInjector8_DIRECT() { *inj8_pin_port |= (inj8_pin_mask); }
#define closeInjector8_DIRECT() { *inj8_pin_port &= ~(inj8_pin_mask); }
#define coil1Low_DIRECT() (*ign1_pin_port &= ~(ign1_pin_mask))
#define coil1High_DIRECT() (*ign1_pin_port |= (ign1_pin_mask))
#define coil2Low_DIRECT() (*ign2_pin_port &= ~(ign2_pin_mask))
#define coil2High_DIRECT() (*ign2_pin_port |= (ign2_pin_mask))
#define coil3Low_DIRECT() (*ign3_pin_port &= ~(ign3_pin_mask))
#define coil3High_DIRECT() (*ign3_pin_port |= (ign3_pin_mask))
#define coil4Low_DIRECT() (*ign4_pin_port &= ~(ign4_pin_mask))
#define coil4High_DIRECT() (*ign4_pin_port |= (ign4_pin_mask))
#define coil5Low_DIRECT() (*ign5_pin_port &= ~(ign5_pin_mask))
#define coil5High_DIRECT() (*ign5_pin_port |= (ign5_pin_mask))
#define coil6Low_DIRECT() (*ign6_pin_port &= ~(ign6_pin_mask))
#define coil6High_DIRECT() (*ign6_pin_port |= (ign6_pin_mask))
#define coil7Low_DIRECT() (*ign7_pin_port &= ~(ign7_pin_mask))
#define coil7High_DIRECT() (*ign7_pin_port |= (ign7_pin_mask))
#define coil8Low_DIRECT() (*ign8_pin_port &= ~(ign8_pin_mask))
#define coil8High_DIRECT() (*ign8_pin_port |= (ign8_pin_mask))
//Set the value of the coil pins to the coilHIGH or coilLOW state
#define coil1Charging_DIRECT() (configPage4.IgInv == GOING_HIGH ? coil1Low_DIRECT() : coil1High_DIRECT())
#define coil1StopCharging_DIRECT() (configPage4.IgInv == GOING_HIGH ? coil1High_DIRECT() : coil1Low_DIRECT())
#define coil2Charging_DIRECT() (configPage4.IgInv == GOING_HIGH ? coil2Low_DIRECT() : coil2High_DIRECT())
#define coil2StopCharging_DIRECT() (configPage4.IgInv == GOING_HIGH ? coil2High_DIRECT() : coil2Low_DIRECT())
#define coil3Charging_DIRECT() (configPage4.IgInv == GOING_HIGH ? coil3Low_DIRECT() : coil3High_DIRECT())
#define coil3StopCharging_DIRECT() (configPage4.IgInv == GOING_HIGH ? coil3High_DIRECT() : coil3Low_DIRECT())
#define coil4Charging_DIRECT() (configPage4.IgInv == GOING_HIGH ? coil4Low_DIRECT() : coil4High_DIRECT())
#define coil4StopCharging_DIRECT() (configPage4.IgInv == GOING_HIGH ? coil4High_DIRECT() : coil4Low_DIRECT())
#define coil5Charging_DIRECT() (configPage4.IgInv == GOING_HIGH ? coil5Low_DIRECT() : coil5High_DIRECT())
#define coil5StopCharging_DIRECT() (configPage4.IgInv == GOING_HIGH ? coil5High_DIRECT() : coil5Low_DIRECT())
#define coil6Charging_DIRECT() (configPage4.IgInv == GOING_HIGH ? coil6Low_DIRECT() : coil6High_DIRECT())
#define coil6StopCharging_DIRECT() (configPage4.IgInv == GOING_HIGH ? coil6High_DIRECT() : coil6Low_DIRECT())
#define coil7Charging_DIRECT() (configPage4.IgInv == GOING_HIGH ? coil7Low_DIRECT() : coil7High_DIRECT())
#define coil7StopCharging_DIRECT() (configPage4.IgInv == GOING_HIGH ? coil7High_DIRECT() : coil7Low_DIRECT())
#define coil8Charging_DIRECT() (configPage4.IgInv == GOING_HIGH ? coil8Low_DIRECT() : coil8High_DIRECT())
#define coil8StopCharging_DIRECT() (configPage4.IgInv == GOING_HIGH ? coil8High_DIRECT() : coil8Low_DIRECT())
#define coil1Charging_MC33810() if(configPage4.IgInv == GOING_HIGH) { coil1Low_MC33810(); } else { coil1High_MC33810(); }
#define coil1StopCharging_MC33810() if(configPage4.IgInv == GOING_HIGH) { coil1High_MC33810(); } else { coil1Low_MC33810(); }
#define coil2Charging_MC33810() if(configPage4.IgInv == GOING_HIGH) { coil2Low_MC33810(); } else { coil2High_MC33810(); }
#define coil2StopCharging_MC33810() if(configPage4.IgInv == GOING_HIGH) { coil2High_MC33810(); } else { coil2Low_MC33810(); }
#define coil3Charging_MC33810() if(configPage4.IgInv == GOING_HIGH) { coil3Low_MC33810(); } else { coil3High_MC33810(); }
#define coil3StopCharging_MC33810() if(configPage4.IgInv == GOING_HIGH) { coil3High_MC33810(); } else { coil3Low_MC33810(); }
#define coil4Charging_MC33810() if(configPage4.IgInv == GOING_HIGH) { coil4Low_MC33810(); } else { coil4High_MC33810(); }
#define coil4StopCharging_MC33810() if(configPage4.IgInv == GOING_HIGH) { coil4High_MC33810(); } else { coil4Low_MC33810(); }
#define coil5Charging_MC33810() if(configPage4.IgInv == GOING_HIGH) { coil5Low_MC33810(); } else { coil5High_MC33810(); }
#define coil5StopCharging_MC33810() if(configPage4.IgInv == GOING_HIGH) { coil5High_MC33810(); } else { coil5Low_MC33810(); }
#define coil6Charging_MC33810() if(configPage4.IgInv == GOING_HIGH) { coil6Low_MC33810(); } else { coil6High_MC33810(); }
#define coil6StopCharging_MC33810() if(configPage4.IgInv == GOING_HIGH) { coil6High_MC33810(); } else { coil6Low_MC33810(); }
#define coil7Charging_MC33810() if(configPage4.IgInv == GOING_HIGH) { coil7Low_MC33810(); } else { coil7High_MC33810(); }
#define coil7StopCharging_MC33810() if(configPage4.IgInv == GOING_HIGH) { coil7High_MC33810(); } else { coil7Low_MC33810(); }
#define coil8Charging_MC33810() if(configPage4.IgInv == GOING_HIGH) { coil8Low_MC33810(); } else { coil8High_MC33810(); }
#define coil8StopCharging_MC33810() if(configPage4.IgInv == GOING_HIGH) { coil8High_MC33810(); } else { coil8Low_MC33810(); }
#define coil1Toggle_DIRECT() (*ign1_pin_port ^= ign1_pin_mask )
#define coil2Toggle_DIRECT() (*ign2_pin_port ^= ign2_pin_mask )
#define coil3Toggle_DIRECT() (*ign3_pin_port ^= ign3_pin_mask )
#define coil4Toggle_DIRECT() (*ign4_pin_port ^= ign4_pin_mask )
#define coil5Toggle_DIRECT() (*ign5_pin_port ^= ign5_pin_mask )
#define coil6Toggle_DIRECT() (*ign6_pin_port ^= ign6_pin_mask )
#define coil7Toggle_DIRECT() (*ign7_pin_port ^= ign7_pin_mask )
#define coil8Toggle_DIRECT() (*ign8_pin_port ^= ign8_pin_mask )
#define injector1Toggle_DIRECT() (*inj1_pin_port ^= inj1_pin_mask )
#define injector2Toggle_DIRECT() (*inj2_pin_port ^= inj2_pin_mask )
#define injector3Toggle_DIRECT() (*inj3_pin_port ^= inj3_pin_mask )
#define injector4Toggle_DIRECT() (*inj4_pin_port ^= inj4_pin_mask )
#define injector5Toggle_DIRECT() (*inj5_pin_port ^= inj5_pin_mask )
#define injector6Toggle_DIRECT() (*inj6_pin_port ^= inj6_pin_mask )
#define injector7Toggle_DIRECT() (*inj7_pin_port ^= inj7_pin_mask )
#define injector8Toggle_DIRECT() (*inj8_pin_port ^= inj8_pin_mask )
void nullCallback(void);
typedef void (*voidVoidCallback)(void);
#endif
| 13,949
|
C++
|
.h
| 232
| 58.943966
| 168
| 0.756271
|
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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.