PageRenderTime 64ms CodeModel.GetById 35ms RepoModel.GetById 0ms app.codeStats 0ms

/src/main/init.c

https://github.com/fredcooke/freeems-vanilla
C | 699 lines | 306 code | 92 blank | 301 comment | 2 complexity | 713cc8e4c6ab34200daebe67961956ea MD5 | raw file
  1. /* FreeEMS - the open source engine management system
  2. *
  3. * Copyright 2008-2013 Fred Cooke
  4. *
  5. * This file is part of the FreeEMS project.
  6. *
  7. * FreeEMS software is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * FreeEMS software is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with any FreeEMS software. If not, see http://www.gnu.org/licenses/
  19. *
  20. * We ask that if you make any changes to this file you email them upstream to
  21. * us at admin(at)diyefi(dot)org or, even better, fork the code on github.com!
  22. *
  23. * Thank you for choosing FreeEMS to run your engine!
  24. */
  25. /** @file
  26. *
  27. * @brief Initialise the devices state
  28. *
  29. * Setup, configure and initialise all aspects of the devices state including
  30. * but not limited to:
  31. *
  32. * - Setup the bus clock speed
  33. * - Configuration based variable initialisation
  34. * - I/O register behaviour and initial state
  35. * - Configure and enable interrupts
  36. * - Copy tunable data up to RAM from flash
  37. * - Configure peripheral module behaviour
  38. */
  39. #define INIT_C
  40. #include "inc/freeEMS.h"
  41. #include "inc/interrupts.h"
  42. #include "inc/utils.h"
  43. #include "inc/commsISRs.h"
  44. #include "inc/pagedLocationBuffers.h"
  45. #include "inc/init.h"
  46. #include "inc/decoderInterface.h"
  47. #include "inc/xgateVectors.h"
  48. #include <string.h>
  49. /** @brief The main top level init
  50. *
  51. * The main init function to be called from main.c before entering the main
  52. * loop. This function is simply a delegator to the finer grained special
  53. * purpose init functions.
  54. */
  55. void init(){
  56. ATOMIC_START(); /* Disable ALL interrupts while we configure the board ready for use */
  57. initPLL(); /* Set up the PLL and use it */
  58. initGPIO();
  59. initPWM();
  60. initADC();
  61. initAllPagedRAM(); /* Copy table and config blocks of data from flash to the paged RAM blocks for fast data lookup */
  62. initVariables(); /* Initialise the rest of the running variables etc */
  63. initFlash(); /* TODO, finalise this */
  64. initECTTimer(); /* TODO move this to inside config in an organised way. Set up the timer module and its various aspects */
  65. // initPITTimer(); /* TODO ditto... */
  66. initSCIStuff(); /* Setup the sci module(s) that we will use. */
  67. initConfiguration(); /* TODO Set user/feature/config up here! */
  68. #ifdef XGATE
  69. initXgate(); /* Fred is a legend, for good reason as of now */
  70. #endif
  71. initInterrupts(); /* still last, reset timers, enable interrupts here TODO move this to inside config in an organised way. Set up the rest of the individual interrupts */
  72. ATOMIC_END(); /* Re-enable any configured interrupts */
  73. }
  74. #ifdef XGATE
  75. #include "xgateInit.c"
  76. #endif
  77. /** @brief Set the PLL clock frequency
  78. *
  79. * Set the Phase Locked Loop to our desired frequency (80MHz) and enable PLL.
  80. */
  81. void initPLL(){
  82. CLKSEL &= PLLSELOFF; /* Switches to base external OSCCLK to ensure PLL is not being used (off out of reset, but not sure if the monitor turns it on before passing control or not) */
  83. PLLCTL &= PLLOFF; /* Turn the PLL device off to adjust its speed (on by default out of reset) */
  84. REFDV = PLLDIVISOR; /* 16MHz / (3 + 1) = 4MHz Bus frequency */
  85. SYNR = PLLMULTIPLIER; /* 4MHz * (9 + 1) = 40MHz Bus frequency */
  86. PLLCTL |= PLLON; /* Turn the PLL device back on again at 80MHz */
  87. enablePLL();
  88. }
  89. /** @brief Switch to using PLL
  90. *
  91. * Switch to using PLL for clock (40MHz bus speed). Interrupt is enabled elsewhere.
  92. *
  93. * Note: Requires busy wait loop, only for init and emergency use.
  94. *
  95. * @todo Should be limited, and have break out with error code and fall back mechanism.
  96. */
  97. void enablePLL(){
  98. while (!(CRGFLG & PLLLOCK)){
  99. /* Do nothing while we wait till the PLL loop locks onto the target frequency. */
  100. /* Target frequency is given by (2 * (crystal frequency / (REFDV + 1)) * (SYNR + 1)) */
  101. /* Bus frequency is half PLL frequency and given by ((crystal frequency / (REFDV + 1)) * (SYNR + 1)) */
  102. }
  103. CLKSEL = PLLSEL; /* Switches to PLL clock for internal bus frequency */
  104. /* from MC9S12XDP512V2.pdf Section 2.4.1.1.2 page 101 Third paragraph */
  105. /* "This takes a MAXIMUM of 4 OSCCLK clock cylces PLUS 4 PLL clock cycles" */
  106. /* "During this time ALL clocks freeze, and CPU activity ceases" */
  107. /* Therefore there is no point waiting for this to occur, we already are... */
  108. }
  109. /// Set up the analogue inputs
  110. void initADC(){
  111. // Currently not true, and may never be: TODO When the port something uses
  112. // is changed via the tuning interface, the configuration will be done on
  113. // the fly, and the value burned to flash such that next boot happens
  114. // correctly and current running devices are used in that way.
  115. /* Digital input buffers on the ATD channels are off by default, leave them this way! */
  116. //ATD0DIEN = ZEROS; /* You are out of your mind if you waste this on digital Inputs */
  117. //ATD1DIEN0 = ZEROS; /* You are out of your mind if you waste this on digital Inputs (NOT-bonded, can't use) */
  118. //ATD1DIEN1 = ZEROS; /* You are out of your mind if you waste this on digital Inputs */
  119. /* And configure them all for analog input */
  120. //ATD0CTL0 = 0x07/* With mult turned on this is required to be set to cause wrap around, but is correct out of reset */
  121. //ATD0CTL1 = 0x07/* Trigger and interrupt configuration, unused for now. */
  122. ATD0CTL2 = 0xC0; /* Turns on the ADC block and sets auto flag clear */
  123. ATD0CTL3 = 0x40; /* Set sequence length = 8 */
  124. ATD0CTL4 = 0x73; /* Set the ADC clock and sample period for best accuracy */
  125. ATD0CTL5 = 0xB0; /* Sets justification to right, multiplex and scan all channels. Writing to this causes conversions to begin */
  126. /* And configure them all for analog input */
  127. ATD1CTL0 = 0x07; /* TODO bring this out of config based on chip variant variable. Sets wrap on 8th ADC because we can't use the other 8 on 112 pin version */
  128. //ATD0CTL1 = 0x07/* Trigger and interrupt configuration, unused for now. */
  129. ATD1CTL2 = 0xC0; /* Turns on the ADC block and sets auto flag clear */
  130. ATD1CTL3 = 0x40; /* Set sequence length = 8 */
  131. ATD1CTL4 = 0x73; /* Set the ADC clock and sample period for best accuracy */
  132. ATD1CTL5 = 0xB0; /* Sets justification to right, multiplex and scan all channels. Writing to this causes conversions to begin */
  133. }
  134. /// Set up the PWM module from configuration
  135. void initPWM(){
  136. /* TODO PWM channel concatenation for high resolution */
  137. // join channel pairs together here (needs 16 bit regs enabled too)
  138. /* TODO Initialise pwm channels with frequency, and initial duty for real use */
  139. // initial PWM settings for testing
  140. PWMPER0 = fixedConfigs2.inputOutputSettings.PWMPeriod0;
  141. PWMPER1 = fixedConfigs2.inputOutputSettings.PWMPeriod1;
  142. PWMPER2 = fixedConfigs2.inputOutputSettings.PWMPeriod2;
  143. PWMPER3 = fixedConfigs2.inputOutputSettings.PWMPeriod3;
  144. PWMPER4 = fixedConfigs2.inputOutputSettings.PWMPeriod4;
  145. PWMPER5 = fixedConfigs2.inputOutputSettings.PWMPeriod5;
  146. PWMPER6 = fixedConfigs2.inputOutputSettings.PWMPeriod6;
  147. PWMPER7 = fixedConfigs2.inputOutputSettings.PWMPeriod7;
  148. PWMDTY0 = fixedConfigs2.inputOutputSettings.PWMInitialDuty0;
  149. PWMDTY1 = fixedConfigs2.inputOutputSettings.PWMInitialDuty1;
  150. PWMDTY2 = fixedConfigs2.inputOutputSettings.PWMInitialDuty2;
  151. PWMDTY3 = fixedConfigs2.inputOutputSettings.PWMInitialDuty3;
  152. PWMDTY4 = fixedConfigs2.inputOutputSettings.PWMInitialDuty4;
  153. PWMDTY5 = fixedConfigs2.inputOutputSettings.PWMInitialDuty5;
  154. PWMDTY6 = fixedConfigs2.inputOutputSettings.PWMInitialDuty6;
  155. PWMDTY7 = fixedConfigs2.inputOutputSettings.PWMInitialDuty7;
  156. PWMCLK = fixedConfigs2.inputOutputSettings.PWMClock;
  157. PWMPRCLK = fixedConfigs2.inputOutputSettings.PWMClockPrescaler;
  158. PWMSCLA = fixedConfigs2.inputOutputSettings.PWMScalerA;
  159. PWMSCLB = fixedConfigs2.inputOutputSettings.PWMScalerB;
  160. PWMPOL = fixedConfigs2.inputOutputSettings.PWMPolarity;
  161. PWMCAE = fixedConfigs2.inputOutputSettings.PWMCenterAlign;
  162. PWMCTL = fixedConfigs2.inputOutputSettings.PWMControl & 0xF0; // Disallow access to power saving and reserved bits
  163. PWME = fixedConfigs2.inputOutputSettings.PWMEnable; // MUST be done after concatenation with PWMCTL
  164. }
  165. /// Set up all the pin states as per configuration, but protect key states.
  166. void initGPIO(){
  167. // Set the initial pin state of pins configured as output
  168. PORTA = fixedConfigs2.inputOutputSettings.PortInitialValueA | BIT6 | BIT7; // Mask the fuel pump relay and CEL pins on
  169. PORTB = fixedConfigs2.inputOutputSettings.PortInitialValueB;
  170. PORTC = fixedConfigs2.inputOutputSettings.PortInitialValueC;
  171. PORTD = fixedConfigs2.inputOutputSettings.PortInitialValueD;
  172. PORTE = (fixedConfigs2.inputOutputSettings.PortInitialValueE | BIT7) & (NBIT5 & NBIT6); // 7 should be high, and 5 and 6 low, to reduce current draw. The rest don't matter. 0 and 1 are not outputs.
  173. PORTH = fixedConfigs2.inputOutputSettings.PortInitialValueH;
  174. PORTJ = fixedConfigs2.inputOutputSettings.PortInitialValueJ;
  175. PORTK = fixedConfigs2.inputOutputSettings.PortInitialValueK;
  176. PORTM = fixedConfigs2.inputOutputSettings.PortInitialValueM;
  177. PORTP = fixedConfigs2.inputOutputSettings.PortInitialValueP;
  178. PORTS = fixedConfigs2.inputOutputSettings.PortInitialValueS | 0x02; // Mask the SCI0 TX pin to high between transmissions!
  179. PORTT = 0x00; // Set all ECT pins to off state, only matters for 2-7, and only if being used. TODO mask this dynamically based on decoder type and configured channels.
  180. /* AD0PT1 You are out of your mind if you waste this on digital Inputs */
  181. /* AD1PT1 You are out of your mind if you waste this on digital Inputs */
  182. // Initialise the Data Direction Registers
  183. DDRA = fixedConfigs2.inputOutputSettings.PortDirectionA | BIT6 | BIT7; // Mask the fuel pump relay and CEL pins as outputs
  184. DDRB = fixedConfigs2.inputOutputSettings.PortDirectionB;
  185. DDRC = fixedConfigs2.inputOutputSettings.PortDirectionC;
  186. DDRD = fixedConfigs2.inputOutputSettings.PortDirectionD;
  187. DDRE = fixedConfigs2.inputOutputSettings.PortDirectionE; // No need to mask off bits 0 and 1, they have no effect and are always inputs.
  188. DDRH = fixedConfigs2.inputOutputSettings.PortDirectionH;
  189. DDRJ = fixedConfigs2.inputOutputSettings.PortDirectionJ;
  190. DDRK = fixedConfigs2.inputOutputSettings.PortDirectionK;
  191. DDRM = fixedConfigs2.inputOutputSettings.PortDirectionM;
  192. DDRP = fixedConfigs2.inputOutputSettings.PortDirectionP;
  193. DDRS = fixedConfigs2.inputOutputSettings.PortDirectionS & 0xFE; // Mask the SCI0 RX pin as input between receiving
  194. DDRT = 0xFC; // Set ECT pins 0,1 to IC and 2:7 to OC (8) TODO mask this dynamically based on decoder type and configured channels.
  195. /* AD0DDR1 You are out of your mind if you waste this on digital Inputs */
  196. /* AD1DDR1 You are out of your mind if you waste this on digital Inputs */
  197. }
  198. /** @brief Buffer lookup tables addresses
  199. *
  200. * Save pointers to the lookup tables which live in paged flash.
  201. */
  202. void initLookupAddresses(){
  203. IATTransferTableLocation = (void*)&IATTransferTable;
  204. CHTTransferTableLocation = (void*)&CHTTransferTable;
  205. MAFTransferTableLocation = (void*)&MAFTransferTable;
  206. TestTransferTableLocation = (void*)&TestTransferTable;
  207. }
  208. /** @brief Buffer fuel tables addresses
  209. *
  210. * Save pointers to the fuel tables which live in paged flash.
  211. */
  212. void initFuelAddresses(){
  213. /* Setup addresses within the page to avoid warnings */
  214. VETableMainFlashLocation = (void*)&VETableMainFlash;
  215. VETableSecondaryFlashLocation = (void*)&VETableSecondaryFlash;
  216. AirflowTableFlashLocation = (void*)&AirflowTableFlash;
  217. LambdaTableFlashLocation = (void*)&LambdaTableFlash;
  218. VETableMainFlash2Location = (void*)&VETableMainFlash2;
  219. VETableSecondaryFlash2Location = (void*)&VETableSecondaryFlash2;
  220. AirflowTableFlash2Location = (void*)&AirflowTableFlash2;
  221. LambdaTableFlash2Location = (void*)&LambdaTableFlash2;
  222. }
  223. /** @brief Copy fuel tables to RAM
  224. *
  225. * Initialises the fuel tables in RAM by copying them up from flash.
  226. */
  227. void initPagedRAMFuel(void){
  228. /* Copy the tables from flash to RAM */
  229. RPAGE = RPAGE_FUEL_ONE;
  230. memcpy((void*)&TablesA, VETableMainFlashLocation, sizeof(mainTable));
  231. memcpy((void*)&TablesB, VETableSecondaryFlashLocation, sizeof(mainTable));
  232. memcpy((void*)&TablesC, AirflowTableFlashLocation, sizeof(mainTable));
  233. memcpy((void*)&TablesD, LambdaTableFlashLocation, sizeof(mainTable));
  234. RPAGE = RPAGE_FUEL_TWO;
  235. memcpy((void*)&TablesA, VETableMainFlash2Location, sizeof(mainTable));
  236. memcpy((void*)&TablesB, VETableSecondaryFlash2Location, sizeof(mainTable));
  237. memcpy((void*)&TablesC, AirflowTableFlash2Location, sizeof(mainTable));
  238. memcpy((void*)&TablesD, LambdaTableFlash2Location, sizeof(mainTable));
  239. }
  240. /** @brief Buffer timing tables addresses
  241. *
  242. * Save pointers to the timing tables which live in paged flash.
  243. */
  244. void initTimingAddresses(){
  245. /* Setup addresses within the page to avoid warnings */
  246. IgnitionAdvanceTableMainFlashLocation = (void*)&IgnitionAdvanceTableMainFlash;
  247. IgnitionAdvanceTableSecondaryFlashLocation = (void*)&IgnitionAdvanceTableSecondaryFlash;
  248. InjectionAdvanceTableMainFlashLocation = (void*)&InjectionAdvanceTableMainFlash;
  249. InjectionAdvanceTableSecondaryFlashLocation = (void*)&InjectionAdvanceTableSecondaryFlash;
  250. IgnitionAdvanceTableMainFlash2Location = (void*)&IgnitionAdvanceTableMainFlash2;
  251. IgnitionAdvanceTableSecondaryFlash2Location = (void*)&IgnitionAdvanceTableSecondaryFlash2;
  252. InjectionAdvanceTableMainFlash2Location = (void*)&InjectionAdvanceTableMainFlash2;
  253. InjectionAdvanceTableSecondaryFlash2Location = (void*)&InjectionAdvanceTableSecondaryFlash2;
  254. }
  255. /** @brief Copy timing tables to RAM
  256. *
  257. * Initialises the timing tables in RAM by copying them up from flash.
  258. */
  259. void initPagedRAMTime(){
  260. /* Copy the tables from flash to RAM */
  261. RPAGE = RPAGE_TIME_ONE;
  262. memcpy((void*)&TablesA, IgnitionAdvanceTableMainFlashLocation, sizeof(mainTable));
  263. memcpy((void*)&TablesB, IgnitionAdvanceTableSecondaryFlashLocation, sizeof(mainTable));
  264. memcpy((void*)&TablesC, InjectionAdvanceTableMainFlashLocation, sizeof(mainTable));
  265. memcpy((void*)&TablesD, InjectionAdvanceTableSecondaryFlashLocation, sizeof(mainTable));
  266. RPAGE = RPAGE_TIME_TWO;
  267. memcpy((void*)&TablesA, IgnitionAdvanceTableMainFlash2Location, sizeof(mainTable));
  268. memcpy((void*)&TablesB, IgnitionAdvanceTableSecondaryFlash2Location, sizeof(mainTable));
  269. memcpy((void*)&TablesC, InjectionAdvanceTableMainFlash2Location, sizeof(mainTable));
  270. memcpy((void*)&TablesD, InjectionAdvanceTableSecondaryFlash2Location, sizeof(mainTable));
  271. }
  272. /** @brief Buffer tunable tables addresses
  273. *
  274. * Save pointers to the tunable tables which live in paged flash and their
  275. * sub-sections too.
  276. */
  277. void initTunableAddresses(){
  278. /* Setup addresses within the page to avoid warnings */
  279. SmallTablesAFlashLocation = (void*)&SmallTablesAFlash;
  280. SmallTablesBFlashLocation = (void*)&SmallTablesBFlash;
  281. SmallTablesCFlashLocation = (void*)&SmallTablesCFlash;
  282. SmallTablesDFlashLocation = (void*)&SmallTablesDFlash;
  283. SmallTablesAFlash2Location = (void*)&SmallTablesAFlash2;
  284. SmallTablesBFlash2Location = (void*)&SmallTablesBFlash2;
  285. SmallTablesCFlash2Location = (void*)&SmallTablesCFlash2;
  286. SmallTablesDFlash2Location = (void*)&SmallTablesDFlash2;
  287. /* TablesA */
  288. dwellDesiredVersusVoltageTableLocation = (void*)&SmallTablesAFlash.dwellDesiredVersusVoltageTable;
  289. dwellDesiredVersusVoltageTable2Location = (void*)&SmallTablesAFlash2.dwellDesiredVersusVoltageTable;
  290. injectorDeadTimeTableLocation = (void*)&SmallTablesAFlash.injectorDeadTimeTable;
  291. injectorDeadTimeTable2Location = (void*)&SmallTablesAFlash2.injectorDeadTimeTable;
  292. postStartEnrichmentTableLocation = (void*)&SmallTablesAFlash.postStartEnrichmentTable;
  293. postStartEnrichmentTable2Location = (void*)&SmallTablesAFlash2.postStartEnrichmentTable;
  294. engineTempEnrichmentTableFixedLocation = (void*)&SmallTablesAFlash.engineTempEnrichmentTableFixed;
  295. engineTempEnrichmentTableFixed2Location = (void*)&SmallTablesAFlash2.engineTempEnrichmentTableFixed;
  296. primingVolumeTableLocation = (void*)&SmallTablesAFlash.primingVolumeTable;
  297. primingVolumeTable2Location = (void*)&SmallTablesAFlash2.primingVolumeTable;
  298. engineTempEnrichmentTablePercentLocation = (void*)&SmallTablesAFlash.engineTempEnrichmentTablePercent;
  299. engineTempEnrichmentTablePercent2Location = (void*)&SmallTablesAFlash2.engineTempEnrichmentTablePercent;
  300. dwellVersusRPMTableLocation = (void*)&SmallTablesAFlash.dwellVersusRPMTable;
  301. dwellVersusRPMTable2Location = (void*)&SmallTablesAFlash2.dwellVersusRPMTable;
  302. blendVersusRPMTableLocation = (void*)&SmallTablesAFlash.blendVersusRPMTable;
  303. blendVersusRPMTable2Location = (void*)&SmallTablesAFlash2.blendVersusRPMTable;
  304. /* TablesB */
  305. loggingSettingsLocation = (void*)&SmallTablesBFlash.loggingSettings;
  306. loggingSettings2Location = (void*)&SmallTablesBFlash2.loggingSettings;
  307. perCylinderFuelTrimsLocation = (void*)&SmallTablesBFlash.perCylinderFuelTrims;
  308. perCylinderFuelTrims2Location = (void*)&SmallTablesBFlash2.perCylinderFuelTrims;
  309. /* TablesC */
  310. // TODO
  311. /* TablesD */
  312. // TODO
  313. /* filler defs */
  314. fillerALocation = (void*)&SmallTablesAFlash.filler;
  315. fillerA2Location = (void*)&SmallTablesAFlash2.filler;
  316. fillerBLocation = (void*)&SmallTablesBFlash.filler;
  317. fillerB2Location = (void*)&SmallTablesBFlash2.filler;
  318. fillerCLocation = (void*)&SmallTablesCFlash.filler;
  319. fillerC2Location = (void*)&SmallTablesCFlash2.filler;
  320. fillerDLocation = (void*)&SmallTablesDFlash.filler;
  321. fillerD2Location = (void*)&SmallTablesDFlash2.filler;
  322. }
  323. /**
  324. *
  325. */
  326. void initPagedRAMTune(){
  327. /* Copy the tables from flash to RAM */
  328. RPAGE = RPAGE_TUNE_ONE;
  329. memcpy((void*)&TablesA, SmallTablesAFlashLocation, sizeof(mainTable));
  330. memcpy((void*)&TablesB, SmallTablesBFlashLocation, sizeof(mainTable));
  331. memcpy((void*)&TablesC, SmallTablesCFlashLocation, sizeof(mainTable));
  332. memcpy((void*)&TablesD, SmallTablesDFlashLocation, sizeof(mainTable));
  333. RPAGE = RPAGE_TUNE_TWO;
  334. // &&&&&&&&&&&&&&&&&&&&&&&&&&&&&& WARNING &&&&&&&&&&&&&&&&&&&&&&&&&&&&&& //
  335. // You will get garbage if you use table switching at this time!!! //
  336. // XGATE code being run from this region temporarily!!! //
  337. // Writing to these tables WILL corrupt XGATE code/kill your engine! //
  338. // &&&&&&&&&&&&&&&&&&&&&&&&&&&&&& WARNING &&&&&&&&&&&&&&&&&&&&&&&&&&&&&& //
  339. //memcpy(xgateSchedRAMAddress, xgateSchedFlashAddress, (xgateSchedEnd - xgateSched));
  340. //memcpy(xgateInjectorsOnRAMAddress, xgateInjectorsOnFlashAddress, (xgateInjectorsOnEnd - xgateInjectorsOn));
  341. //memcpy(xgateInjectorsOffRAMAddress, xgateInjectorsOffFlashAddress, (xgateInjectorsOffEnd - xgateInjectorsOff));
  342. // memcpy((void*)&TablesA, SmallTablesAFlash2Location, sizeof(mainTable));
  343. // memcpy((void*)&TablesB, SmallTablesBFlash2Location, sizeof(mainTable));
  344. // memcpy((void*)&TablesC, SmallTablesCFlash2Location, sizeof(mainTable));
  345. // memcpy((void*)&TablesD, SmallTablesDFlash2Location, sizeof(mainTable));
  346. }
  347. /** @brief Buffer addresses of paged data
  348. *
  349. * Save the paged memory addresses to variables such that we can access them
  350. * from another paged block with no warnings.
  351. *
  352. * If you try to access paged data from the wrong place you get nasty warnings.
  353. * These calls to functions that live in the same page that they are addressing
  354. * prevent those warnings.
  355. *
  356. * @note Many thanks to Jean BĂ©langer for the inspiration/idea to do this!
  357. */
  358. void initAllPagedAddresses(){
  359. /* Setup pointers to lookup tables */
  360. initLookupAddresses();
  361. /* Setup pointers to the main tables */
  362. initFuelAddresses();
  363. initTimingAddresses();
  364. initTunableAddresses();
  365. }
  366. /** @brief Copies paged flash to RAM
  367. *
  368. * Take the tables and config from flash up to RAM to allow live tuning.
  369. *
  370. * For the main tables and other paged config we need to adjust
  371. * the RPAGE value to the appropriate one before copying up.
  372. *
  373. * This function is simply a delegator to the ones for each flash page. Each
  374. * one lives in the same paged space as the data it is copying up.
  375. */
  376. void initAllPagedRAM(){
  377. /* Setup the flash block pointers before copying flash to RAM using them */
  378. initAllPagedAddresses();
  379. /* Copy the tables up to their paged RAM blocks through the window from flash */
  380. initPagedRAMFuel();
  381. initPagedRAMTime();
  382. initPagedRAMTune();
  383. /* Default to page one for now, perhaps read the configured port straight out of reset in future? TODO */
  384. setupPagedRAM(TRUE); // probably something like (PORTA & TableSwitchingMask)
  385. }
  386. /* Initialise and set up all running variables that require a non-zero start value here */
  387. /* All other variables are initialised to zero by the premain built in code */
  388. void initVariables(){
  389. /* And the opposite for the other halves */
  390. CoreVars = &CoreVars0;
  391. DerivedVars = &DerivedVars0;
  392. ADCBuffers = &ADCBuffers0;
  393. ADCBuffersRecord = &ADCBuffers1;
  394. ticksPerDegree = &ticksPerDegree0; // TODO temp, remove, maybe
  395. ticksPerDegreeRecord = &ticksPerDegree1; // TODO temp, remove, maybe
  396. /* Setup the pointers to the registers for fueling use, this does NOT work if done in global.c, I still don't know why. */
  397. ectMainTimeRegisters[0] = TC2_ADDR;
  398. ectMainTimeRegisters[1] = TC3_ADDR;
  399. ectMainTimeRegisters[2] = TC4_ADDR;
  400. ectMainTimeRegisters[3] = TC5_ADDR;
  401. ectMainTimeRegisters[4] = TC6_ADDR;
  402. ectMainTimeRegisters[5] = TC7_ADDR;
  403. ectMainControlRegisters[0] = TCTL2_ADDR;
  404. ectMainControlRegisters[1] = TCTL2_ADDR;
  405. ectMainControlRegisters[2] = TCTL1_ADDR;
  406. ectMainControlRegisters[3] = TCTL1_ADDR;
  407. ectMainControlRegisters[4] = TCTL1_ADDR;
  408. ectMainControlRegisters[5] = TCTL1_ADDR;
  409. coreStatusA |= FUEL_PUMP_PRIME;
  410. // Initial state is NOT to fire... can be configured by scheduler if required.
  411. outputEventInputEventNumbers[0] = 0xFF;
  412. outputEventInputEventNumbers[1] = 0xFF;
  413. outputEventInputEventNumbers[2] = 0xFF;
  414. outputEventInputEventNumbers[3] = 0xFF;
  415. outputEventInputEventNumbers[4] = 0xFF;
  416. outputEventInputEventNumbers[5] = 0xFF;
  417. outputEventInputEventNumbers[6] = 0xFF;
  418. outputEventInputEventNumbers[7] = 0xFF;
  419. outputEventInputEventNumbers[8] = 0xFF;
  420. outputEventInputEventNumbers[9] = 0xFF;
  421. outputEventInputEventNumbers[10] = 0xFF;
  422. outputEventInputEventNumbers[11] = 0xFF;
  423. outputEventInputEventNumbers[12] = 0xFF;
  424. outputEventInputEventNumbers[13] = 0xFF;
  425. outputEventInputEventNumbers[14] = 0xFF;
  426. outputEventInputEventNumbers[15] = 0xFF;
  427. outputEventInputEventNumbers[16] = 0xFF;
  428. outputEventInputEventNumbers[17] = 0xFF;
  429. outputEventInputEventNumbers[18] = 0xFF;
  430. outputEventInputEventNumbers[19] = 0xFF;
  431. outputEventInputEventNumbers[20] = 0xFF;
  432. outputEventInputEventNumbers[21] = 0xFF;
  433. outputEventInputEventNumbers[22] = 0xFF;
  434. outputEventInputEventNumbers[23] = 0xFF;
  435. // TODO perhaps read from the ds1302 once at start up and init the values or different ones with the actual time and date then update them in RTI
  436. }
  437. /** @brief Flash module setup
  438. *
  439. * Initialise configuration registers for the flash module to allow burning of
  440. * non-volatile flash memory from within the firmware.
  441. *
  442. * The FCLKDIV register can be written once only after reset, thus the lower
  443. * seven bits and the PRDIV8 bit must be set at the same time.
  444. *
  445. * We want to put the flash clock as high as possible between 150kHz and 200kHz
  446. *
  447. * The oscillator clock is 16MHz and because that is above 12.8MHz we will set
  448. * the PRDIV8 bit to further divide by 8 bits as per the manual.
  449. *
  450. * 16MHz = 16000KHz which pre-divided by 8 is 2000kHz
  451. *
  452. * 2000kHz / 200kHz = 10 thus we want to set the divide register to 10 or 0x0A
  453. *
  454. * Combining 0x0A with PRDIV8 gives us 0x4A (0x0A | 0x40 = 0x4A) so we use that
  455. *
  456. * @author Sean Keys
  457. *
  458. * @note If you use a different crystal lower than 12.8MHz PRDIV8 should not be set.
  459. *
  460. * @warning If the frequency you end up with is outside 150kHz - 200kHz you may
  461. * damage your flash module or get corrupt data written to it.
  462. */
  463. void initFlash(){
  464. FCLKDIV = 0x4A; /* Set the flash clock frequency */
  465. FPROT = 0xFF; /* Disable all flash protection */
  466. FSTAT = FSTAT | (PVIOL | ACCERR); /* Clear any errors */
  467. }
  468. /* Set up the timer module and its various interrupts */
  469. void initECTTimer(){
  470. /** @todo TODO Take the configuration from the decoder (as is) and mask it such that it does not affect the 6 other channels.
  471. * Take the the number of output channels required from configuration and configure that many as outputs
  472. * Configure the balance in whatever way is specified in the GPIO configuration - allow second input to be reused as GPI only.
  473. *
  474. * This stuff affects:
  475. * - TIE = 0x01 or 0x03, only. OC channels enabled as required and IC only for RPM/position.
  476. * - TIOS = nope, always 0xFC for 2 IC and 6 OC
  477. * - TCTL (1,2,3,4) 4 = 0x0? mask off high 4 bits and allow low 4 to come from decoder config/init
  478. * - PORTT = zeros, with balance from config
  479. * - DDRT = 0,1 inputs, or if unused by decoder, from config
  480. */
  481. // TODO rearrange the order of this stuff and pull enable and interrupt enable out to the last function call of init.
  482. /* Timer channel interrupts */
  483. TIE = 0x03; /* 0,1 IC interrupts enabled for reading engine position and RPM, 6 OC channels disabled such that no injector switching happens till scheduled */
  484. TFLG = ONES; /* Clear all the flags such that we are up and running before they first occur */
  485. TFLGOF = ONES; /* Clear all the flags such that we are up and running before they first occur */
  486. /* TODO Turn the timer on and set the rate and overflow interrupt */
  487. // DLYCT = 0xFF; /* max noise filtering as experiment for volvo this will come from flash config */ // just hiding a wiring/circuit issue...
  488. TSCR1 = 0x88; /* 0b_1000_1000 Timer enabled, and precision timer turned on */
  489. TSCR2 = 0x87; /* 0b_1000_0111 Overflow interrupt enable, divide by 256 if precision turned off */
  490. // PTPSR = 0x03; /* 4 prescaler gives .1uS resolution and max period of 7ms measured */
  491. PTPSR = 0x1F; /* 32 prescaler gives 0.8uS resolution and max period of 52.4288ms measured */
  492. // PTPSR = 0x3F; /* 64 prescaler gives 1.6uS resolution and max period of 105ms measured */
  493. // PTPSR = 0xFF; /* 256 prescaler gives 6.4uS resolution and max period of 400ms measured */
  494. // PTPSR = 0x7F; /* 128 prescaler gives 3.2uS resolution and max period of 200ms measured */
  495. /* http://duckduckgo.com/?q=1+%2F+%2840MHz+%2F+32+%29 */
  496. /* http://duckduckgo.com/?q=%281+%2F+%2840MHz+%2F+32+%29%29+*+2^16 */
  497. /* www.mecheng.adelaide.edu.au/robotics_novell/WWW_Devs/Dragon12/LM4_Timer.pdf */
  498. /* Initial actions */
  499. TIOS = 0xFC; /* 0b_1111_1100 0 and 1 are input capture, 2 through 7 are output compare */
  500. TCTL1 = ZEROS; /* Set disabled at startup time, use these and other flags to switch fueling on and off inside the decoder */
  501. TCTL2 = ZEROS; /* 0,1 have compare turned off regardless as they are in IC mode. */
  502. TCTL3 = ZEROS; /* Capture off for 4 - 7 */
  503. TCTL4 = 0x0F; /* Capture on both edges of two pins for IC (0,1), capture off for 2,3 */
  504. // TODO setup delay counters on 0 and 1 to filter noise (nice feature!)
  505. //DLYCT = ??; built in noise filter
  506. // PTMCPSR = 0xFF // Precision prescaler - fastest is 1 represented by 0, slowest/longest possible is 256 represented by 255 or 0xFF
  507. // MCCNT = ONES16; // init to slowest possible, first
  508. // MCCTL = 0xC4; // turn on and setup the mod down counter
  509. // MCFLG = 0x80; // clear the flag up front
  510. decoderInitPreliminary();
  511. }
  512. /* Configure the PIT timers for their various uses. */
  513. void initPITTimer(){
  514. // // set micro periods
  515. // PITMTLD0 = 0x1F; /* 32 prescaler gives 0.8uS resolution and max period of 52.4288ms measured */
  516. // PITMTLD1 = 0x1F; /* ditto */
  517. // /* http://duckduckgo.com/?q=1+%2F+%2840MHz+%2F+32+%29 Exactly the same as for ECT */
  518. //
  519. // // set timers running
  520. // PITLD0 = dwellPeriod;
  521. // // enable module
  522. // PITCFLMT = 0x80;
  523. // // enable channels
  524. // //PITCE = 0x03;
  525. // // enable interrupt
  526. // PITINTE = 0x01;
  527. // // clear flags
  528. // //PITFLT = ONES;
  529. }
  530. /* Setup the sci module(s) that we need to use. */
  531. void initSCIStuff(){
  532. /* The alternative register set selector defaults to zero */
  533. // set the baud/data speed
  534. SCI0BD = fixedConfigs1.serialSettings.baudDivisor;
  535. // etc
  536. /* Switch to alternative register set? */
  537. // etc
  538. /* Switch back again? */
  539. /*
  540. * 0 = LOOPS (normal two wire operation)
  541. * 0 = SCISWAI (Wait mode on)
  542. * 0 = RSRC (if loops=1, int/ext wiring)
  543. * 1 = M MODE (9 bit operation)
  544. * 0 = WAKE (idle line wakeup)
  545. * 0 = ILT (idle line type count start pos)
  546. * 1 = PE (parity on)
  547. * 1 = PT (odd parity)
  548. *
  549. * 0x13 = ODD (default)
  550. * 0x12 = EVEN
  551. * 0x00 = NONE
  552. */
  553. SCI0CR1 = 0x13;
  554. /*
  555. * 0 = TIE (tx data empty isr disabled)
  556. * 0 = TCIE (tx complete isr disabled)
  557. * 1 = RIE (rx full isr enabled)
  558. * 0 = ILIE (idle line isr disabled)
  559. * 0 = TE (transmit disabled)
  560. * 1 = RE (receive enabled)
  561. * 0 = RWU (rx wake up normal)
  562. * 0 = SBK (send break off)
  563. */
  564. SCI0CR2 = 0x24;
  565. }
  566. /* TODO Load and calculate all configuration data required to run */
  567. void initConfiguration(){
  568. // // TODO Calc TPS ADC range on startup or every time? this depends on whether we ensure that things work without a re init or reset or not.
  569. /* Add in tunable physical parameters at boot time TODO move to init.c TODO duplicate for secondary fuel? or split somehow?
  570. *nstant = ((masterConst * perCylinderVolume) / (stoichiometricAFR * injectorFlow));
  571. *nstant = ((139371764 * 16384) / (15053 * 4096));
  572. * OR
  573. *nstant = ((masterConst / injectorFlow) * perCylinderVolume) / stoichiometricAFR;
  574. *nstant = ((139371764 / 4096) * 16384) / 15053;
  575. * http://duckduckgo.com/?q=%28%28139371764++%2F+4096%29+*+16384%29+%2F+15053 */
  576. bootFuelConst = ((unsigned long)(masterFuelConstant / fixedConfigs1.engineSettings.injectorFlow) * fixedConfigs1.engineSettings.perCylinderVolume) / fixedConfigs1.engineSettings.stoichiometricAFR;
  577. /* The ADC range used to generate TPS percentage */
  578. if(fixedConfigs2.sensorRanges.TPSMaximumADC > fixedConfigs2.sensorRanges.TPSMinimumADC){
  579. TPSADCRange = fixedConfigs2.sensorRanges.TPSMaximumADC - fixedConfigs2.sensorRanges.TPSMinimumADC;
  580. }else{
  581. TPSADCRange = fixedConfigs2.sensorRanges.TPSMinimumADC - fixedConfigs2.sensorRanges.TPSMaximumADC;
  582. }
  583. }
  584. /* Set up all the remaining interrupts */
  585. void initInterrupts(){
  586. /* IMPORTANT : Set the s12x vector base register (Thanks Karsten!!) */
  587. IVBR = 0xF7; /* Without this the interrupts will never find your code! */
  588. /* Set up the Real Time Interrupt */
  589. RTICTL = 0x81; /* 0b_1000_0001 0.125ms/125us period http://duckduckgo.com/?q=1+%2F+%2816MHz+%2F+%282+*+10^3%29+%29 */
  590. // RTICTL = 0xF9; /* 0b_1111_1001 0.125s/125ms period http://duckduckgo.com/?q=1+%2F+%2816MHz+%2F+%282*10^6%29+%29 */
  591. CRGINT |= (RTIE | PLLLOCKIE | SCMIE); /* Enable the Real Time Interrupt, PLL Lock Interrupt, and Self Clock Mode Interrupt */
  592. CRGFLG = (RTIF | PLLLOCKIF | SCMIF); /* Clear the RTI, LOCKI, and SCMI flags */
  593. RAMWPC |= AVIE; // Enable the access protection interrupt for XGATE RAM
  594. // set up port H for testing
  595. PPSH = ZEROS; // falling edge/pull up for all
  596. PIEH = ONES; // enable all pins interrupts
  597. PIFH = ONES; // clear all port H interrupt flags
  598. // TODO set up irq and xirq for testing
  599. // IRQCR for IRQ
  600. /* VReg API setup (only for wait mode? i think so) */
  601. // VREGAPIR = 0x09C3; /* For 500ms period : (500ms - 0.2ms) / 0.2ms = 0b100111000011 = 2499 */
  602. // VREGAPICL = 0x02; /* Enable the interrupt */
  603. // VREGAPICL = 0x04; /* Start the counter running */
  604. /* Writing a one to the flag will set it if it is unset, so best not to mess with it here as it probably starts off unset */
  605. /* LVI Low Voltage Interrupt enable */
  606. VREGCTRL = 0x02; // Counts bad power events for diagnosis reasons
  607. }