Code for 'Smart Regulator' featured in 'Model Engineer', November 2020 on. Contains all work to August 2020 including all code described. Top level algorithm development is quite spares, leaving some work for you! Any questions - jon@jons-workshop.com
Dependencies: mbed BufferedSerial Servo2 PCT2075 I2CEeprom FastPWM
Diff: main.cpp
- Revision:
- 3:43cb067ecd00
- Parent:
- 2:8e7b51353f32
- Child:
- 4:28cc0cf01570
--- a/main.cpp Mon Jun 08 13:46:52 2020 +0000 +++ b/main.cpp Mon Jul 27 08:44:59 2020 +0000 @@ -1,31 +1,48 @@ #include "mbed.h" #include "Alternator.h" -/* -Test 6th June 2020 - i2c sda=grey, scl=white -*/ -float dpd = 0.0; +#include "BufferedSerial.h" +#include "I2CEeprom.h" +#include "LM75B.h" // New I2C temp sensor code March 2020 (to suit possible next board issue, harmless otherwise) +#include "rpm.h" +#include "field.h" +//#include "gps_mod.h" +//#include "baro.h" + +#ifdef TARGET_NUCLEO_L432KC // 24LC and LM75 work +// #define SDA_PIN D0 // good +// #define SCL_PIN D1 + #define SDA_PIN D4 // good + #define SCL_PIN D5 +#endif + +/******************************************************************************* + DON'T FORGET TO REMOVE SOLDER LINKS SB16 AND SB18 ON L432KC BOARD +*******************************************************************************/ +//During test LED across field has been useful visual aid. Incorporate similar on new board. /* * May 2020 NOTE input circuit to analogue in driver pot zeners input to 3v6, then pot reduces by about 1/3. * This makes input reading only about 0.0 to 0.66 * Temp bodge, mult by 1.5 + + * Two voltages now measured. Link voltage (alternator output), and field supply (which may come from battery when main output low) */ /* Alternator Regulator Jon Freeman - June 2019 - Feb 2020 + June 2019 - June 2020 - ** Prototype built using Nucleo L432KC. Final design likely to use F401RE. Code should compile for either. ** + ** Prototype built using Nucleo L432KC. Having solved i2c problem, this looks good for final product ** main loop frequency upped from 32Hz to 100Hz ** WHAT THIS PROGRAMME DOES - Controls 4 stroke petrol engine driving vehicle alternator with new custom regulator - Electronics powered by higher voltage of small 12v backup battery, or alternator field output supply + Electronics powered by higher voltage of small 12v backup battery, or alternator output Note only Field+ and MAX5035 supplied thus, all else powered from MAX outputs. Starting engine provides rectified tickle from magneto to enable MAX5035 creating +5 and +3v3 supplies. - Alternative, selected by jumper pposition, is external switch - battery+ to MAX enable circuit. - Anytime engine revs measured < TICKOVER_RPM (or some such) RPM, field current OFF (by pwm 0) + Alternative, selected by jumper position, is external switch - battery+ to MAX enable circuit. ** Review this ** + Anytime engine revs measured < TICKOVER_RPM (or some such) RPM, field current OFF (by pwm 0) , see speed related pwm limit table BEGIN Loop forever at 100 Hz { @@ -46,42 +63,31 @@ OUTPUT pwm to MCP1630. This is clock to pwm chip. Also limits max duty ratio RS232 serial via USB to setup eeprom data */ -// Uses software bit banged I2C - DONE (because no attempt to get I2C working on these small boards has ever worked) /** * Jumpers fitted to small mbed Nucleo boards - D5 - A5 and D4 - A4 CHECK - yes */ -//#ifdef TARGET_NUCLEO_F303K8 // Code too large to fit -#ifdef TARGET_NUCLEO_L432KC // -/* - declared in file i2c_bit_banged.cpp -DigitalInOut SDA (D4); // Horrible bodge to get i2c working using bit banging. -DigitalInOut SCL (D5); // DigitalInOut do not work as you might expect. Fine if used only as OpenDrain opuputs though! -DigitalIn SDA_IN (A4); // That means paralleling up with two other pins as inputs -DigitalIn SCL_IN (A5); // This works but is a pain. Inbuilt I2C should have worked but never does on small boards with 32 pin cpu. -*/ -Serial pc (USBTX, USBRX); // Comms port to pc or terminal using USB lead - - +//#ifdef TARGET_NUCLEO_L432KC // Has to be, quite settled now on this, having solved i2c problems +BufferedSerial pc (USBTX, USBRX, 4096, 4, NULL); // Comms port to pc or terminal using USB lead //BufferedSerial LocalCom (PA_9, PA_10); // New March 2019 - Taken out for i2c test 6/6/2020 - -// Above combo of Serial and BufferedSerial is the only one to work ! - // INPUTS : -AnalogIn Ain_SystemVolts (A6); // Sniff of alternator output, not used in control loop as done using analogue MCP1630 -//AnalogIn Ammeter_In (A1); // Output of ASC709LLFTR ammeter chip (pin 20), used to increase engine revs if need be +AnalogIn Ain_Link_Volts (A6); // Sniff of alternator output, not used in control loop as done using analogue MCP1630 +AnalogIn Ammeter_In (A1); // Output of ASC709LLFTR ammeter chip (pin 20), used to increase engine revs if need be //AnalogIn Ammeter_Ref (A0); // Ref output from ASC709LLFTR used to set ammeter zero (pin 25) -// Nov 2019. Not convinced Ext_Rev_Demand is useful +// Nov 2019. Not convinced Ext_Rev_Demand is useful ** July 2020 - repurposed, voltmeter Field_Supply_V //AnalogIn Ext_Rev_Demand (D3); // Servo determines engine revs, servo out to be higher of Ext_Rev_Demand and internal calc +AnalogIn Field_Supply_V (D3); // Servo determines engine revs, servo out to be higher of Ext_Rev_Demand and internal calc AnalogIn Driver_Pot (A3); // If whole control system can be made to fit +BufferedSerial gps_module (D1, D0, 2048, 4, NULL); // For gps - added July 2020 + /* MODULE PIN USAGE -1 PA_9 D1 LocalCom Tx -2 PA_10 D0 LocalCom Rx +1 PA_9 D1 LocalCom Tx FUTURE i2c to enable 3rd independent pwm +2 PA_10 D0 LocalCom Rx FUTURE i2c to enable 3rd independent pwm 3 NRST 4 GND 5 PA12_D2 NEW June 2019 - Output engine tacho cleaned-up, brought out to testpoint 4 @@ -92,7 +98,7 @@ 10 N.C. 11 N.C. 12 PA_8 D9 InterruptIn pulse_tacho from engine magneto, used to measure rpm -13 PA_11 D10 Throttle servo +13 PA_11 D10 Speed_Control servo 14 PB_5 D11 // InterruptIn VEXT PWM controller output folded back for cpu to monitor, useful on test to read what pwm required to do what 15 PB_4 D12 Scope_probe 16 PB_3 D13 LED Onboard LED @@ -113,120 +119,96 @@ */ // Test 6/6/2020 to get i2c working -//I2C i2c (D0, D1); // For 24LC64 eeprom -//I2C i2c (D0, D1); // For 24LC64 eeprom - -I2C i2c (D0, D1); // For 24LC64 eeprom +//I2C i2c (D0, D1); // For 24LC64 eeprom correct //I2C i2c (D1, D0); // For 24LC64 eeprom DEFINITELY WRONG // Test 6/6/2020 to get i2c working - -InterruptIn pulse_tacho (D9); // Signal from engine magneto (clipped by I limit resistor and 3v3 zener) -InterruptIn VEXT (D2); // PWM controller output folded back for cpu to monitor, useful on test to read what pwm required to do what +//InterruptIn pulse_tacho (D9); // Signal from engine magneto (clipped by I limit resistor and 3v3 zener) +// Note D9 still used but taken to rpm class object +//InterruptIn VEXT (D2); // PWM controller output folded back for cpu to monitor, useful on test to read what pwm required to do what +// Note D2 still used but taken to field class object // OUTPUTS : DigitalOut Scope_probe (D12); // Handy pin to hang scope probe onto while developing code DigitalOut myled (LED1); // Green LED on board is PB_3 D13 -PwmOut PWM_OSC_IN (A2); // Can alter prescaler can not use A5 +//PwmOut PWM_OSC_IN (A2); // Can alter prescaler can not use A5 NOW DONE IN CLASS //PwmOut A_OUT (A2); // Can alter prescaler can not use A5 PIN STOLEN BY PWM_OSC_IN -Servo Throttle (D10); // Changed from A2, June 2019 -DigitalOut EngineTachoOut (D11); // New June 2019 -#endif - -#ifdef TARGET_NUCLEO_F401RE // -//Serial pc (USBTX, USBRX); // Comms port to pc or terminal using USB lead -BufferedSerial pc (PA_2, PA_3, 2048, 4, NULL); // Pins 16, 17 tx, rx to pc via usb lead -//BufferedSerial pc (USBTX, USBRX); // Pins 16, 17 tx, rx to pc via usb lead -BufferedSerial LocalCom (PC_6, PC_7); // Pins 37, 38 tx, rx to Touch Screen Controller - -// INPUTS : -AnalogIn Ain_SystemVolts (PB_1); // Sniff of alternator output, not used in control loop as done using analogue MCP1630 -//AnalogIn Ammeter_In (PC_5); // Output of ASC709LLFTR ammeter chip (pin 20), used to increase engine revs if need be -//AnalogIn Ammeter_Ref (PB_0); // Ref output from ASC709LLFTR used to set ammeter zero (pin 25) -//AnalogIn Ext_Rev_Demand (PC_1); // Servo determines engine revs, servo out to be higher of Ext_Rev_Demand and internal calc -AnalogIn Driver_Pot (PC_2); // If whole control system can be made to fit -/* - MODULE PIN USAGE -*/ - -InterruptIn pulse_tacho (PB_15); // Signal from engine magneto (clipped by I limit resistor and 3v3 zener) -InterruptIn VEXT (PC_12); // PWM controller output folded back for cpu to monitor, useful on test to read what pwm required to do what -// OUTPUTS : - -DigitalOut Scope_probe (PB_3); // Handy pin to hang scope probe onto while developing code -DigitalOut myled (PA_5); // Green LED on board is PA_5 -//PwmOut PWM_OSC_IN (PA_10); // PA_10 is pwm1/3 Can alter prescaler can not use A5 -PwmOut PWM_OSC_IN (PB_9); // PA_10 is pwm4/4 Can alter prescaler can not use A5 -PwmOut A_OUT (PB_5); // PB_5 is pwm3/2 Can alter prescaler can not use A5 PIN STOLEN BY PWM_OSC_IN -Servo Throttle (PA_0); // PA_8 is pwm1/1 Changed from A2, June 2019 -DigitalOut EngineTachoOut (PA_7); // New June 2019 - -I2C i2c (PB_7, PB_6); // Pins 58, 59 For 24LC64 eeprom -//#define SDA_PIN PB_7 -//#define SCL_PIN PB_6 - -#endif - +//PwmOut Test_RPM (PA_6); Timer microsecs; // 64 bit counter, rolls over in half million years Ticker loop_timer; // Device to cause periodic interrupts, used to sync iterations of main programme loop - slow -//const double AMPS_CAL = 90.0; -extern eeprom_settings user_settings ; +extern char * get_mode_text (uint32_t mode) ; + + +I2CEeprom eeprom (SDA_PIN, SCL_PIN, 0xa0, eeprom_page_size, 8192, 100000); +extern ee_settings_2020 user_settings ; +Engine_Manager Engine (D9, D11, D10); // Pins are magneto in, cleaned magneto out, servo, const debounce time microsecs +FieldControl Field (A2, D2); // PWM pin for MCP1630, InterruptIn for signal out of MCP1630 +PCT2075 temp_sensor( SDA_PIN, SCL_PIN ); // or LM75B temp_sensor( p?, p? ); Added March 2020 + +//class MPL3115A2 baro ; + // SYSTEM CONSTANTS /* Please Do Not Alter these */ const int MAIN_LOOP_REPEAT_TIME_US = 10000; // 10000 us, with TACHO_TAB_SIZE = 100 means tacho_ticks_per_time is tacho_ticks_per_second /* End of Please Do Not Alter these */ /* Global variable declarations */ -uint32_t - volt_reading = 0, // Global updated by interrupt driven read of Battery Volts - driver_reading = 0, -// tacho_count = 0, // Global incremented on each transition of InterruptIn pulse_tacho - sys_timer100Hz = 0; // gets incremented by our Ticker ISR every MAIN_LOOP_REPEAT_TIME_US -double servo_position = 0.2; // set in speed control loop -double throttle_limit = SERVO_MAX; +uint32_t sys_timer100Hz = 0; // gets incremented by our Ticker ISR every MAIN_LOOP_REPEAT_TIME_US +uint32_t seconds = 0; +double link_volt_reading = 0.0; // Global updated by interrupt driven read of Battery Volts at rate of 100 Hz +double field_volt_reading = 0.0; // Global updated by interrupt driven read of Battery Volts at rate of 100 Hz +double amp_reading = 0.0; bool loop_flag = false; // made true in ISR_loop_timer, picked up and made false again in main programme loop bool flag_25Hz = false; // As loop_flag but repeats 25 times per sec bool flag_12Hz5 = false; // As loop_flag but repeats 12.5 times per sec bool flag_1Hz = false; // As loop_flag but repeats 1 times per sec bool query_toggle = false; -bool flag_V_rd = false; +bool flag_link_V_rd = false; +bool flag_field_V_rd = false; +bool flag_A_rd = false; bool flag_Pot_rd = false; -//const int AMP_FILTER_FACTOR = 6; +bool auto_test_flag = false; + +enum {SAFE_NOTHING, POT_SERVO_DIRECT, VARIABLE_VOLTAGE, FIXED_VOLTAGE, ENG_REVS_CTRL, POT_SETS_ENGINE_RPM, CURRENT_FEEDBACK_CTRL, AUTO_TEST} ; /* End of Global variable declarations */ //void ISR_fast_interrupt () { // here at 10 times main loop repeat rate (i.e. 1000Hz, 1.0ms) void ISR_fast_interrupt () { - static uint32_t t = 0; + static uint32_t t = 0, u25 = 0; Scope_probe = 1; // To show how much time spent in interrupt handler switch (t) { case 0: - flag_V_rd = true; -// volt_reading >>= 1; // Result = Result / 2 -// volt_reading += Ain_SystemVolts.read_u16 (); // Result = Result + New Reading + flag_link_V_rd = true; break; -// case 1: -// raw_amp_reading = (double) Ammeter_In.read(); -// break; + case 1: + flag_A_rd = true; + break; case 2: flag_Pot_rd = true; // raw_amp_offset = Ammeter_Ref.read(); // Feb 2020 Not convinced this is useful break; -// case 3: -// ext_rev_req >>= 1; // Result = Result / 2 -// ext_rev_req += Ext_Rev_Demand.read_u16(); -// break; - case 4: + case 3: + flag_field_V_rd = true; + break; +// case 4: // driver_reading >>= 1; // Result = Result / 2 // driver_reading += Driver_Pot.read_u16(); // break; -// case 5: + case 5: loop_flag = true; // set flag to allow main programme loop to proceed sys_timer100Hz++; // Just a handy measure of elapsed time for anything to use - if ((sys_timer100Hz & 0x03) == 0) // is now 12.5Hz, not 8 + if ((sys_timer100Hz & 0x03) == 0) { // is now 12.5Hz, not 8 flag_25Hz = true; // flag gets set 25 times per sec. Other code may clear flag and make use of this + u25++; + if (u25 == 25) { + u25 = 0; + flag_1Hz = true; + seconds++; + } + } default: break; } @@ -236,361 +218,148 @@ Scope_probe = 0; // To show how much time spent in interrupt handler } - -// New stuff June 2019 -// Decent way of measuring engine speed -bool magneto_stretch = false; -Timeout magneto_timo; -uint64_t magneto_times[4] = {13543,0,0,0}; // June 2019, only 2 of these used. Big non-zero prevents div0 error on first pass - - -/** - void magneto_timeout () - Here 5ms after magneto pulse detected - This is sufficient time for ringing to cease, not long enough to lose next pulse even at max engine revs. - Reset 'magneto_stretch' flag set and used in 'ISR_magneto_tacho' -*/ -void magneto_timeout () -{ - magneto_stretch = false; // Magneto ringing finished by now, re-enable magneto pulse count - EngineTachoOut = 0; // Cleaned tacho output brought out to pin to look at with scope -} - -/** -void ISR_magneto_tacho () ; // New June 2019 - // Engine On/Off switch turns engine off by shorting ignition volts magneto to ground. - // Therefore when engine running, have pulse signal one pulse per rev (even though 4 stroke, spark delivered at 2 stroke rate) - // Pulse spacing 20ms @ 3000 RPM, 60ms @ 1000 RPM, 6ms @ 10000 RPM - - Magneto signal rings, is quite unclean, therefore a cleanup strategy is needed. - Solution - On arrival at this interrupt handler, - If flag 'magneto_stretch' true, do nothing and return (to avoid multiple pulse count) - Set flag 'magneto_stretch' true; - Start timer 'magneto_timo' to cause 'magneto_timeout' interrupt in a time longer than ringing bt shorter than shortest time to next spark - Record time between most recent two sparks and set output bit for scope monitoring -*/ -void ISR_magneto_tacho () // This interrupt initiated by rising (or falling) edge of magneto output, (not both) -{ - uint64_t new_time; - if (!magneto_stretch) // May get this interrupt more than once per magneto pulse, respond to first, lock out subsequent - { // until magneto_timeout time has elapsed - magneto_stretch = true; - new_time = microsecs.read_high_resolution_us(); - magneto_times[0] = new_time - magneto_times[1]; // microsecs between most recent two sparks - magneto_times[1] = new_time; // actual time microsecs of most recent spark - magneto_timo.attach_us (&magneto_timeout, 5000); // To ignore ringing and multiple counts on magneto output, all settled within about 5ms - EngineTachoOut = 1; // Cleaned tacho output brought out to pin to look at with scope - } -} - -// Endof New stuff June 2019 - - - VEXT_Data Field; - - -void ISR_VEXT_rise () // InterruptIn interrupt service -{ // Here is possible to read back how regulator has controlled pwm - may or may not be useful - uint64_t tmp = microsecs.read_high_resolution_us(); - Field.measured_period = tmp - Field.t_on; - Field.t_on = tmp; - Field.rise_count++; -} -void ISR_VEXT_fall () // InterruptIn interrupt service -{ - Field.fall_count++; - Field.t_off = microsecs.read_high_resolution_us(); - Field.measured_pw_us = Field.t_off - Field.t_on; -} // **** End of Interrupt Service Routines **** - -/** uint32_t ReadEngineRPM () -* -* June 2019 - Replaced count of alternator frequency by count of engine magneto pulses. -* -*/ -uint32_t ReadEngineRPM () -{ - uint64_t time_since_last_spark = microsecs.read_high_resolution_us() - magneto_times[1]; - if (time_since_last_spark > 250000) // if engine probably stopped, return old method RPM - return 0; - return (60000000 / magneto_times[0]); // 60 million / microsecs between two most recent sparks, eg 10,000us between sparks @ 6000 RPM -} - /*double Read_Ext_Rev_Req () { double rv = (double) ext_rev_req; return rv / 4096.0; }*/ - +/* double Read_Driver_Pot () { double rv = (double) driver_reading; return rv / 4096.0; -} - -double Read_BatteryVolts () -{ - return ((double) volt_reading) / 3282.5; // divisor fiddled to make voltage reading correct ! -} +}*/ -/** -void set_servo (double p) { // Only for test, called from cli -*/ -void set_servo (double p) { // Only for test, called from cli - Throttle = p; -} - -double normalise (double * p) { - if (*p > 0.999) - *p = 0.999; - if (*p < 0.001) - *p = 0.001; - return * p; +double Read_Link_Volts () +{ + return link_volt_reading * 39.9; // divisor fiddled to make voltage reading correct ! } - - -//const double DRIVER_NEUTRAL = 0.18; -/**void throttle_setter () { - * - * - * - * - * - * -*/ -void throttle_setter () { -// double Driver_demand = Read_Driver_Pot(); - const double local_hysterics = 0.03; - static double most_recent_throttle = 0.0; - double Driver_demand = dpd; -// pc.printf ("Pot\t%.2f \r\n", Driver_demand); -// pc.printf ("Pot\t%d\t%.3f \r\n", driver_reading, dpd); // Shown pot drives servo over full range. - if (Driver_demand < DRIVER_NEUTRAL) { // In braking or park - Throttle = 0.0; - } - else { // Driving - Driver_demand -= DRIVER_NEUTRAL; - Driver_demand /= (1.0 - DRIVER_NEUTRAL); // Re-normalise what's left - if ((most_recent_throttle - Driver_demand < -local_hysterics) || (most_recent_throttle - Driver_demand > local_hysterics)) { - Throttle = Driver_demand; - most_recent_throttle = Driver_demand; - servo_position = Driver_demand; // Copy to global for pc.printf only May 2020 - } - } +double Read_Field_Volts () +{ + return field_volt_reading * 42.85; // divisor fiddled to make voltage reading correct ! } -/**void set_pwm (double d) { Range 0.0 to 1.0 - This PWM used to limit max duty ratio of alternator field energisation. - With R25=33k and C4=100n controlling ramp input to CS pin of MCP1630 (not MCP1630V), - ramp terminates fet 'on' pulse after a max of approx 980 us. - With const int PWM_PERIOD_US = 2000 , duty ratio is thus limited to approx 50% max. - This is about right when using 12V alternator on 24V systems - A 1.225V reference (U7) is fed to the MCP1630 error amp which compares this to fed-back proportion of system voltage. - This adjusts final PWM down to zero % as needed to maintain alternator output voltage. -*/ -void set_pwm (double d) { -const double pwm_factor = MAX_FIELD_PWM * (double)PWM_PERIOD_US; - uint32_t i; - if (d < 0.0) - d = 0.0; - if (d > 1.0) - d = 1.0; -// i = (uint32_t)(d * (PWM_PERIOD_US / 2)); // div 2 when using 12v alternator in 24v system - i = (uint32_t)(d * pwm_factor); // div 2 when using 12v alternator in 24v system -// pc.printf ("Setting PWM to %d\r\n", i); - PWM_OSC_IN.pulsewidth_us (PWM_PERIOD_US - i); // Note PWM is inverted as MCP1630 uses inverted OSC_IN signal +double Read_Ammeter () +{ + return amp_reading * 93.28; // Amp range corrected here } -/*void speed_control_factor_set (struct parameters & a) { - uint32_t v = (uint32_t)a.dbl[0]; - if (v > 10) - speed_control_factor = v; - pc.printf ("speed_control_factor %d\r\n", speed_control_factor); -}*/ - -void set_throttle_limit (struct parameters & a) { - if (a.dbl[0] > 0.01 && a.dbl[0] < 1.001) - throttle_limit = a.dbl[0]; - pc.printf ("throttle_limit %.2f\r\n", throttle_limit); -} void query_system (struct parameters & a) { query_toggle = !query_toggle; -// pc.printf ("Stuff about current state of system\r\n"); -// pc.printf ("RPM=%d, servo%.2f\r\n", ReadEngineRPM (), servo_position); -// pc.printf ("RPM=%d\r\n", ReadEngineRPM ()); +} + +void set_pwm (double d) { // Range 0.0 to 1.0 called from cli + Field.set_pwm (d); } - uint8_t madetab[340]; -void maketable () { // Uses first 17 nums of user_settings relating to lim to be applied at 0, 500, 1000 --- 8000 RPM - double tabvals[20]; - double diff, val = 0.0; - uint32_t tabptr = 0; - for (int i = 0; i < 17; i++) { - tabvals[i] = (double)user_settings.rd (i); - pc.printf ("%d\t%.0f\r\n", i*500, tabvals[i]); - } - for (int i = 1; i < 17; i++) { - diff = tabvals[i] - tabvals[i - 1]; - diff /= 20.0; // 40 entries 25RPM apart per kRPM - for (int j = 0; j < 20; j++) { -// pc.printf ("%.0f\t", val); - madetab[tabptr++] = (uint8_t) val; - val += diff; - } - } - pc.printf ("\r\nEnd of table creation with tabptr = %d\r\n", tabptr); - while (tabptr < 340) - madetab[tabptr++] = (uint8_t) val; +double get_temperature () { + return (double) temp_sensor; +} + +void maketable () { + Field.maketable (); } +int32_t set_engine_RPM_lit (uint32_t RPMrequest) { // Returns actual speed + return Engine.set_RPM_literal (RPMrequest); +} -/**void set_pwm_limit () { // May 2020 - * - * Uses pure look up table to tailor pwm limit according to engine speed - * - * - * - * -*/ -void set_pwm_limit (uint32_t rpm) { // May 2020 -//const uint8_t pwmtab [] = unsigned char array of percentages 0 to 99, spaced at 25RPM intervals -/*const uint8_t pwmtab [] = { - 02,02,02,02,02,02,02,02, // 0 - 0175RPM // Slightly above 0 just to see signal on scope - 02,02,02,02,02,02,02,02, // 0200 - 0375RPM - 02,02,02,02,02,02,02,02, // 0400 - 0575RPM - 02,02,02,02,02,02,02,02, // 0600 - 0775RPM - 02,02,02,02,02,02,02,02, // 0800 - 0975RPM - 02,02,02,02,02,02,02,02, // 1000 - 1175RPM - 02,02,02,02,02,02,02,02, // 1200 - 1375RPM - 02,02,02,02,02,02,02,02, // 1400 - 1575RPM - 02,03,04,05,06,07, 8, 9, // 1600 - 1775RPM - 10,11,12,13,14,15,16,17, // 1800 - 1975RPM - 18,19,20,21,22,23,24,25, // 2000 - 2175RPM - 26,27,28,29,30,31,32,33, // 2200 - 2375RPM - 34,35,36,37,38,39,40,40, // 2400 - 2575RPM - 41,41,41,42,42,42,43,43, // 2600 - 2775RPM - 43,44,44,44,45,45,45,46, // 2800 - 2975RPM - 46,46,47,47,47,48,48,48, // 3000 - 3175RPM - 49,49,49,50,50,50,51,51, // 3200 - 3375RPM - 52,52,52,53,53,53,54,54, // 3400 - 3575RPM - 54,55,55,55,56,56,56,57, // 3600 - 3775RPM - 57,57,58,58,58,59,59,59, // 3800 - 3975RPM - 60,60,60,61,61,61,62,62, // 4000 - 4175RPM - 62,63,63,63,64,64,64,65, // 4200 - 4375RPM - 65,65,66,66,66,67,67,67, // 4400 - 4575RPM - 68,68,68,69,69,69,70,70, // 4600 - 4775RPM - 71,71,72,72,73,73,74,74, // 4800 - 4975RPM - 75,75,76,76,77,77,78,78, // 5000 - 5175RPM - 79,79,80,80,81,81,82,82, // 5200 - 5375RPM +int32_t set_engine_RPM_pct (uint32_t RPMrequest) { // Returns actual speed + return Engine.set_RPM_percent (RPMrequest); +} - 83,83,84,84,85,85,86,86, // 5400 - 5575RPM - 87,87,88,88,89,89,90,90, // 5600 - 5775RPM - 91,91,92,92,93,93,94,94, // 5800 - 5975RPM - 95,95,96,96,97,97,98,98, // 6000 - 6175RPM - 99,99,99,99,99,99,99,99, // 6200 - 6375RPM - 99,99,99,99,99,99,99,99, // 6400 - 6575RPM - 99,99,99,99,99,99,99,99, // 6600 - 6775RPM - 99,99,99,99,99,99,99,99, // 6800 - 6975RPM - 99,99,99,99,99,99,99,99, // 7000 - 7175RPM - 99,99,99,99,99,99,99,99, // 7200 - 7375RPM - 99,99,99,99,99,99,99,99, // 7400 - 7575RPM - 99,99,99,99,99,99,99,99, // 7600 - 7775RPM - 99,99,99,99,99,99,99,99, // 7800 - 7975RPM - 99,99,99,99,99,99,99,99, // 8000 - 8175RPM - } ; -*/ -// uint32_t rpm = ReadEngineRPM (); - static uint32_t oldpcent = 1000; - uint32_t index, pcent; - double pwm = 0.0; - if (rpm > 8000) - rpm = 8000; - index = rpm / 25; // to fit lut spacing of 25rpm intervals, turns rpm into index -// pcent = pwmtab[index]; - pcent = madetab[index]; - if (pcent != oldpcent) { - oldpcent = pcent; - pwm = (double)pcent; - pwm /= 99.0; - set_pwm (pwm); +void auto_test_initiate (int bulb_count) { + if (Engine.running()) { + auto_test_flag = true; + pc.printf ("Requesting Auto-Test for load of %d lamps\r\n", bulb_count); + } + else { + pc.printf ("Engine not running. Can't perform auto test\r\n"); + auto_test_flag = false; } } +void is_eng_running () { + pc.printf ("Engine%sRunning\r\n", Engine.running() ? " IS " : " NOT "); +} + extern void command_line_interpreter () ; // Comms with optional pc or device using serial port through board USB socket -extern bool i2c_init () ; -extern int check_24LC64 () ; + +enum {AUTO_TEST_INACTIVE, AUTO_TEST_BEGIN, AUTO_TEST_ABORT, AUTO_TEST_IN_PROGRESS } ; // Programme Entry Point int main() { const double filt = 0.2; + const double ampfilt = 0.2; + const double vfilt = 0.2; // local variable declarations -// double revs_error; - - int32_t RPM_ave = 0, RPM_filt = 0, RPM_tmp; -// int32_t irevs_error; - uint32_t ticks25Hz = 0; - - pulse_tacho.fall (&ISR_magneto_tacho); // 1 pulse per engine rev - VEXT.rise (&ISR_VEXT_rise); // Handles - MCP1630 has just turned mosfet on - VEXT.fall (&ISR_VEXT_fall); // Handles - MCP1630 has just turned mosfet off + double driver_pot = 0.0, dtmp; + int32_t temp, startup_delay, print_position = 0; + int32_t field_pct = 0, auto_test_timer = 0, auto_test_state = AUTO_TEST_INACTIVE, auto_test_step = 0; + bool up_and_running = false; + char text[64]; + microsecs.reset() ; // timer = 0 microsecs.start () ; // 64 bit, counts micro seconds and times out in half million years - PWM_OSC_IN.period_us (PWM_PERIOD_US); // about 313Hz * 2 -// PROBLEM using same pwm, common prescaler, can't update servo that fast, can't pwm field that slow. - - set_pwm (0.02); // set_pwm(0.02) good for production. Set higher for test - -#ifdef TARGET_NUCLEO_F401RE // - A_OUT.period_us (100); // pwm as analogue out - A_OUT.pulsewidth_us (19); +#ifdef GPS_ + gps_mod gps; #endif - Throttle = servo_position; -// pc.printf ("\r\n\n\n\n\nAlternator Regulator 2020, Jon Freeman, SystemCoreClock=%d\r\n", SystemCoreClock); - pc.printf ("\r\n\n\n\n\nAlternator Regulator 2020, Jon Freeman\r\n"); - if (!i2c_init()) - pc.printf ("i2c bus failed init\r\n"); - pc.printf ("check_24LC64 returned 0x%x\r\n", check_24LC64()); - user_settings.load () ; // Fetch values from eeprom, also builds table of speed -> pwm lookups -// pc.printf ("Loaded\r\n"); +//- Clear the screen, move to (0,0): +// \033[2J + pc.printf ("\033[2JAlternator Regulator 2020, Jon Freeman\r\n"); + user_settings.load () ; // Fetch values from eeprom // Setup Complete ! Can now start main control forever loop. loop_timer.attach_us (&ISR_fast_interrupt, MAIN_LOOP_REPEAT_TIME_US / 10); // Start periodic interrupt generator 1000us at Feb 2020 - maketable (); + Field.maketable () ; // Here to ensure eeprom has been setup + Field.set_for_speed (0); + Engine.Speed_Control (((double)user_settings.rd(WARMUP_SERVO_POS)) / 100.0); + startup_delay = user_settings.rd(WARM_UP_DELAY); + pc.printf ("Operating Mode is [%s]\r\n", get_mode_text (user_settings.rd(OP_MODE))); + //***** START OF MAIN LOOP while (1) { // Loop forever, repeats synchroised by waiting for ticker Interrupt Service Routine to set 'loop_flag' true while (!loop_flag) { // Most of the time is spent in this loop, repeatedly re-checking for commands from pc port +#ifdef GPS_ + while (gps_module.readable()) + pc.putc (gps_module.getc()); +#endif command_line_interpreter () ; // Proceed beyond here once loop_timer ticker ISR has set loop_flag true - if (flag_V_rd) { - flag_V_rd = false; - volt_reading >>= 1; // Result = Result / 2 - volt_reading += Ain_SystemVolts.read_u16 (); // Result = Result + New Reading + // A to D converters all read at 100 Hz + if (flag_link_V_rd) { + flag_link_V_rd = false; + link_volt_reading *= (1.0 - vfilt); // + link_volt_reading += vfilt * (double) Ain_Link_Volts.read(); // Volt fiddle factor NOT corrected here } if (flag_Pot_rd) { flag_Pot_rd = false; - dpd *= (1.0 - filt); - dpd += filt * (Driver_Pot * 1.5); // Includes bodge around zener over-clipping input - driver_reading >>= 1; // Result = Result / 2 - driver_reading += Driver_Pot.read_u16(); + driver_pot *= (1.0 - filt); + driver_pot += filt * ((double)Driver_Pot.read() * 1.5); // Includes bodge around zener over-clipping input + } + if (flag_A_rd) { + flag_A_rd = false; + amp_reading *= (1.0 - ampfilt); + amp_reading += ampfilt * ((double) Ammeter_In.read() - 0.5); // Amp range NOT corrected here + } + if (flag_field_V_rd) { + flag_field_V_rd = false; + field_volt_reading *= (1.0 - vfilt); // + field_volt_reading += vfilt * (double) Field_Supply_V.read(); // Volt fiddle factor NOT corrected here } } // Jun 2019 pass here 100 times per sec // BEGIN 100Hz stuff - loop_flag = false; // Clear flag set by ticker interrupt handler - - // Three variations on engine rpm. - RPM_tmp = ReadEngineRPM (); - RPM_ave += RPM_tmp; // Rising sum needs dividing and resetting to 0 when used - RPM_filt += RPM_tmp; - RPM_filt >>= 1; - - set_pwm_limit (RPM_tmp); // according to RPM - + loop_flag = false; // Clear flag set by ticker interrupt handler + Engine.manager_core (); // This belongs right here, update regularly, keeps 'filtered()' fresh and keeps engine to set rpm +#ifdef GPS_ + gps.update (); +#endif // END 100Hz stuff if (flag_25Hz) { flag_25Hz = false; @@ -600,47 +369,179 @@ // BEGIN 12.5Hz stuff flag_12Hz5 = !flag_12Hz5; if (flag_12Hz5) { // Do any even stuff to be done 12.5 times per second - throttle_setter(); -/*#ifdef SPEED_CONTROL_ENABLE - if (RPM_demand < TICKOVER_RPM) - servo_position = Throttle = 0.0; - else { - RPM_ave /= 8; -// irevs_error = RPM_demand - ReadEngineRPM (); - irevs_error = RPM_demand - RPM_filt; - revs_error = (double) irevs_error; - if (abs(revs_error) > 3.0) { // if speed error > 3rpm, tweak, otherwise deadband - //servo_position += (revs_error / 7500.0); - servo_position += (revs_error / speed_control_factor); - servo_position = normalise(&servo_position); - if (servo_position < 0.0 || servo_position > 1.0) - pc.printf ("servo_position error %f\r\n", servo_position); - if (servo_position > throttle_limit) - servo_position = throttle_limit; - Throttle = servo_position; +// if (up_and_running && Engine.running()) { + if (up_and_running) { + switch (user_settings.rd(OP_MODE)) { +/* +enum {SAFE_NOTHING, // + POT_SERVO_DIRECT, // + VARIABLE_VOLTAGE, // Batteryless, controllerless Low Cost Loco - alternator connects direct to DC motors + FIXED_VOLTAGE, // + ENG_REVS_CTRL, // + POT_SETS_ENGINE_RPM, // + CURRENT_FEEDBACK_CTRL, // + AUTO_TEST }; // + "0\tSafe nothing mode for cli cmd testing", + "1\tPot to Servo direct, field OFF", + "2\tVariable voltage", + "3\tFixed voltage", + "4\tEngine Revs Control", + "5\tSet Engine to Driver's Pot", + "6\tControl Engine by Current Load", +*/ + case SAFE_NOTHING: // Safe nothing mode for cli cmd testing + // Use this to test command line commands e.g. Speed_Control, direct field setting etc + break; + + case POT_SERVO_DIRECT: // Driver_pot --> servo direct. Field OFF + Engine.Speed_Control (driver_pot); + Field.set_for_speed (0); // Safe, no output + break; + + case VARIABLE_VOLTAGE: // Variable Voltage + Engine.Speed_Control (driver_pot); // Driver_pot --> servo direct. Field ON + if (driver_pot > DRIVER_NEUTRAL) // if pot not close to zero + Field.set_for_speed (Engine.RPM_latest()); // according to RPM + else + Field.set_for_speed (0); // Field OFF + break; + + case FIXED_VOLTAGE: // Fixed Voltage + Field.set_for_speed (Engine.RPM_latest()); // according to RPM + break; + + case ENG_REVS_CTRL: // Engine revs control - Pot to control revs over range tickover to MAX_RPM_LIMIT + Field.set_for_speed (Engine.RPM_latest()); + break; + + case POT_SETS_ENGINE_RPM: // Set engine to driver pot + dtmp = driver_pot * (MAX_RPM_LIMIT - TICKOVER_RPM) + TICKOVER_RPM; + temp = (int32_t) dtmp; + Engine.set_RPM_literal (temp); // this sets engine speed controller + Field.set_for_speed (Engine.RPM_latest()); // according to RPM + break; + +// case CURRENT_MODE: // Set engine speed determined by current drawn + case CURRENT_FEEDBACK_CTRL: // Set engine speed determined by current drawn + temp = 0; // an integer. Engine set to tickover when no power demand + if (driver_pot > DRIVER_NEUTRAL) // if pot not close to zero + temp = 1 + (int32_t)abs(Read_Ammeter() * 8.0); // Sets max amps to 100 / 8.0 + Engine.set_RPM_percent (temp); // this sets engine speed controller + Field.set_for_speed (Engine.RPM_latest()); // according to RPM + break; + + case AUTO_TEST: // cli command may initiate test sequence implemented here. Wait for flag to proceed. + switch (auto_test_state) { + case AUTO_TEST_INACTIVE: + if (auto_test_flag) // cli has requested auto test sequence + auto_test_state = AUTO_TEST_BEGIN; + break; + + case AUTO_TEST_BEGIN: // set engine, field etc, then initiate settling time delay + Engine.set_RPM_percent (1); // this sets engine speed controller for min useful revs + Field.set_for_speed (0); + pc.printf ("Starting auto test sequence, user field limit values :\r\n"); + for (int i = 0; i < 21; i++) + pc.printf ("%d, ", user_settings.rd(i)); + pc.printf ("\r\n"); + auto_test_step = 0; + auto_test_timer = 0; + auto_test_state = AUTO_TEST_IN_PROGRESS; + break; + + case AUTO_TEST_IN_PROGRESS: // take sets of readings, then timeout back to INACTIVE + field_pct = Field.set_for_speed (Engine.RPM_latest()); // according to RPM + switch (auto_test_timer++) { // When active, get here @ 12.5Hz + case 30: case 40: case 50: case 60: // take readings at these times + case 35: case 45: case 55: case 65: +// pc.printf ("\tTaking auto_test readings %d, Volts, Amps, RPM req, RPM got, servo position, measured duty ratio\r\n", auto_test_timer); + /* + Need to collect here, + Volts, Amps, RPM got latest, RPM got filtered, servo position, measured duty ratio, lut pcent + */ + pc.printf ("\t%.2f, %.2f, %.2f, %d, %d, %.2f, %.3f, %d\r\n", Read_Link_Volts(), Read_Field_Volts(), + Read_Ammeter(), Engine.RPM_latest(), Engine.RPM_filtered(), + Engine.get_servo_position(), Field.get_duty_ratio(), field_pct); + break; + case 66: // After final set of readings + auto_test_step++; + if (auto_test_step > 10) + auto_test_state = AUTO_TEST_ABORT; + else { // set conditions for next set of readings + temp = Engine.RPM_percent_to_actual(auto_test_step * 10); + Engine.set_RPM_percent (auto_test_step * 10); + auto_test_timer = 0; + pc.printf ("Setting rig for %d percent, %d RPM\r\n", auto_test_step * 10, temp); + } + break; + default: + break; + } + break; + + case AUTO_TEST_ABORT: // Here at test end or because auto_test_flag made false somewhere somehow + Engine.set_RPM_percent (0); // this sets engine speed controller + Field.set_for_speed (0); + auto_test_state = AUTO_TEST_INACTIVE; + auto_test_flag = false; + pc.printf ("Ending auto test sequence\r\n"); + break; + default: + break; + } // END OF SWITCH auto_test_state + break; + default: + user_settings.wr (0, OP_MODE); // set to safe non-mode 0 + break; } } - RPM_ave = 0; // Reset needed -#endif */ + else { // Engine not running + Field.set_for_speed (0); // according to RPM + } } else { // Do odd 12.5 times per sec stuff flag_12Hz5 = false; myled = !myled; -// LocalCom.printf ("%d\r\n", volt_reading); } // End of if(flag_12Hz5) // END 12.5Hz stuff - ticks25Hz++; // advances @ 25Hz - if (ticks25Hz > 24) { // once per sec stuff + if (flag_1Hz) { // BEGIN 1Hz stuff - ticks25Hz = 0; -// secs++; + flag_1Hz = false; + if (!up_and_running) { + if (startup_delay == 0) { + up_and_running = true; + pc.printf ("Warmup ended, starting proper ops\r\n"); + Engine.Speed_Control (0.0); + } + else { + pc.printf ("In Startup warmup delay %d\r", startup_delay--); + } + } if (query_toggle) { - pc.printf ("V = %.2f\tRPM = %u\tservo%.2f \r", Read_BatteryVolts(), /*amp_reading, */ReadEngineRPM (), servo_position); -// pc.printf ("\tRPM = %u (time %u seconds) \r", ReadEngineRPM (), (uint32_t)(microsecs.read_high_resolution_us() / 1000000)); + sprintf (text, "\033[%d;0HI=%.1fA, V=%.2fV, ", 20 + print_position, Read_Ammeter() , Read_Link_Volts()); + pc.printf ("%sRPM %d, rpm_set %d, pot %.3f, servo %.3f \r\n", text, Engine.RPM_latest(), Engine.get_RPM_requested (), driver_pot, Engine.get_servo_position()); + print_position++; + if (print_position > 10) + print_position = 0; } +//printf("\033[6;3HHello\n"); +// pc.printf ("\033[0;1HSecs %d \r\n", seconds); +// pc.printf ("Temp = %.1f\r", get_temperature()); +// gps.update(); +#ifdef GPS_ + if (gps.new_data()) { + myled = !myled; + pc.printf("\033[0;1H%s, %s, %s \r\n", gps.time(), gps.latitude(), gps.longitude()); + pc.printf("alt ^%s^, sats %s lat mer %f, lon mer %f \r\n", gps.altitude(), gps.sat_count(), gps.lat_merged(), gps.lon_merged()); + pc.printf("%s, heading %s, mph %s \r\n", gps.date(), gps.heading(), gps.mph()); + pc.printf("%s\r\n \n .\r\n ", gps.message(1)); + } +#endif +// while (gps_module.readable()) +// pc.putc (gps_module.getc()); // END 1Hz stuff } // eo once per second stuff } // End of 100Hz stuff } // End of main programme loop } // End of main function - end of programme -//***** END OF MAIN LOOP +