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
main.cpp
- Committer:
- JonFreeman
- Date:
- 2020-04-25
- Revision:
- 1:450090bdb6f4
- Parent:
- 0:77803b3ee157
- Child:
- 2:8e7b51353f32
File content as of revision 1:450090bdb6f4:
#include "mbed.h"
#include "Alternator.h"
/*
Alternator Regulator
Jon Freeman
June 2019 - Feb 2020
** Prototype built using Nucleo L432KC. Final design likely to use F401RE. Code should compile for either. **
** 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
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 < 2000 (or some such) RPM, field current OFF (by pwm 0)
BEGIN
Loop forever at 100 Hz {
Read engine RPM by monitoring engine tacho signal present on engine On/Off switch line
Read alternator output load current
Using RPM and current readings, regulate engine rpm via model control servo
Adjust Alternator field current max limit according to RPM (analogue regulator limits output voltage)
Measure system voltage (just in case this is ever useful)
Respond to any commands arriving at serial port (setup and test link to laptop)
Flash LED at 8 Hz as proof of life
}
END
INPUTS AnalogIn x 2 - Ammeter chip - current and offset AnalogIns
INPUT AnalogIn - System voltage for info only.
INPUT AnalogIn - ExtRevDemand
INPUT AnalogIn - DriverPot
INPUT Pulse engine speed indicator, speed checked against EEPROM data to select max pwm duty ratio for this speed
INPUT Final pwm gate drive wired back to InterruptIn ** MAYBE USEFUL OR NOT ** Could read this back via serial to laptop
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
BufferedSerial LocalCom (PA_9, PA_10); // New March 2019
// 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 Ammeter_Ref (A0); // Ref output from ASC709LLFTR used to set ammeter zero (pin 25)
// Nov 2019. Not convinced Ext_Rev_Demand is useful
AnalogIn Ext_Rev_Demand (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
/*
MODULE PIN USAGE
1 PA_9 D1 LocalCom Tx
2 PA_10 D0 LocalCom Rx
3 NRST
4 GND
5 PA12_D2 NEW June 2019 - Output engine tacho cleaned-up, brought out to testpoint 4
6 PB_0 D3 AnalogIn Ext_Rev_Demand
7 PB_7 D4 SDA i2c to 24LC memory
8 PB_6 D5 SCL i2c to 24LC memory
9 PB_12 D6 PwmOut PWM_OSC_IN Timebase for pwm, also determines max duty ratio
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
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
17 3V3
18 AREF
19 PA_0 A0 AnalogIn Ammeter_Ref
20 PA_1 A1 AnalogIn Ammeter_In
21 PA_3 A2 PWM analogue out
22 PA_4 A3 AnalogIn Driver_Pot
23 PA_5 A4 n.c. SDA_IN paralleled to i2c pin, necessary because i2c has to be bit banged
24 PA_6 A5 n.c. SCL_IN paralleled to i2c pin, necessary because i2c has to be bit banged
25 PA_7 A6 AnalogIn V_Sample system link voltage
26 PA_2 A7 Not used
27 5V
28 NRST
29 GND
30 VIN
*/
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
// 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 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
Timer microsecs;
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 ;
// 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 //semaphore = 0,
speed_control_factor= 75000, // fiddled from cli to tweak engine speed controller response
volt_reading = 0, // Global updated by interrupt driven read of Battery Volts
ext_rev_req = 0,
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 amp_reading = 0.0,
amp_offset = 0.0,
raw_amp_reading = 0.0,
raw_amp_offset = 0.0;
double servo_position = 0.2; // set in speed control loop
// const double throttle_limit = 0.4;
double throttle_limit = SERVO_MAX;
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;
const int AMP_FILTER_FACTOR = 6;
/* 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;
Scope_probe = 1; // To show how much time spent in interrupt handler
switch (t) {
case 0:
volt_reading >>= 1; // Result = Result / 2
volt_reading += Ain_SystemVolts.read_u16 (); // Result = Result + New Reading
break;
case 1:
raw_amp_reading = (double) Ammeter_In.read();
break;
case 2:
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:
driver_reading >>= 1; // Result = Result / 2
driver_reading += Driver_Pot.read_u16();
// break;
// 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
flag_25Hz = true; // flag gets set 25 times per sec. Other code may clear flag and make use of this
default:
break;
}
t++;
if (t > 9)
t = 0;
Scope_probe = 0; // To show how much time spent in interrupt handler
}
// New stuff November 2019
/**
* Obtaining Amps_Deliverable from RPM.
* Lucas workshop sheet shows exponential relationship between RPM over threshold, and Amps_Deliverable,
* That is Amps_Deliverable rises steeply with RPM, flattening off towards 6000 RPM
* Curve modeled by eqn
* I_del = I_max (1 - exp(-(RPM-3000)/Const1)) where Const1 = 1000 is a starting point
* This is probably fine when driving alternator with BIG engine.
* When using small engine, rising load current sags engine RPM.
* Using a linear relationship builds in a good safety margin, possible eqn
* I_del = I_max (RPM - 3000) / 3000 for use over RPM range 3000-6000
*/
const double RPM_Threshold = 3000.0;
const double RPM_Max = 6000.0;
//const double I_max = 30.0;
const double RPM_Range = RPM_Max - RPM_Threshold;
//#define BIG_ENGINE
double Calculate_Amps_Deliverable (uint32_t RPM) {
double r = (double)RPM - RPM_Threshold;
r /= RPM_Range;
if (r < 0.0)
r = 0.0;
if (r > 1.0)
r = 1.0;
#ifdef BIG_ENGINE
const double Const1 = -3.2; // Tweak this to adjust shape of exponential function
return (1.0 - exp(r*Const1));
#else
return r;
#endif
}
class one_over_s_integrator { // Need this to drive servo Jan 2020 why?
double internal_integral, max, min, Hz, gain;
public:
one_over_s_integrator () { internal_integral = 0.0; max = 1.0; min = -1.0; Hz = 100.0; gain = 1.0;}
double integral (double input) ;
void set_max (double) ;
void set_min (double) ;
void set_gain (double) ;
void set_sample_time (double) ;
} ;
void one_over_s_integrator::set_max (double in) {
max = in;
}
void one_over_s_integrator::set_min (double in) {
min = in;
}
void one_over_s_integrator::set_gain (double in) {
gain = in;
}
void one_over_s_integrator::set_sample_time (double in) {
Hz = 1.0 / in;
}
double one_over_s_integrator::integral (double input) {
internal_integral += gain * input / Hz; // 100 for 100Hz update rate
if (internal_integral > max)
internal_integral = max;
if (internal_integral < min)
internal_integral = min;
return internal_integral;
}
//double one_over_s ()
// End of New stuff November 2019
// New stuff June 2019
bool magneto_stretch = false;
Timeout magneto_timo;
uint32_t magneto_times[8] = {0,0,0,0,0,0,0,0}; // June 2019, only 2 of these used
/**
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)
{
if (!magneto_stretch)
{
uint32_t new_time = microsecs.read_us();
if (new_time < magneto_times[1]) // rollover detection
magneto_times[1] = 0;
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_stretch = true;
magneto_timo.attach_us (&magneto_timeout, 5000); // To ignore ringing and multiple counts on magneto output, all settled within about 5ms
tacho_count++;
EngineTachoOut = 1; // Cleaned tacho output brought out to pin to look at with scope
}
}
// Endof New stuff June 2019
const double shrink = 0.2;
/*double lpf_4th_order_asym (double input) {
*
* input is driver's control pot.
* This needs regular calling, maybe 8Hz - 32Hz
*
* Output from 4th stage of cascaded Butterworth lpf section
* Used to delay rising input to motor controller allowing time for engine revs to rise
*/
double lpf_4th_order_asym (double input) {
static double lpfs[] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
if (input < 0.0) input = 0.0;
if (input > 1.0) input = 1.0;
lpfs[0] = input; // zeroth order filter
double tmp;
for (int order = 1; order < 5; order++) {
tmp = (lpfs[order] * (1.0 - shrink))
+ (lpfs[order - 1] * shrink);
if (tmp > input)
tmp = input;
lpfs[order] = tmp;
}
return tmp;
}
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
uint32_t tmp = microsecs.read_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_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 ()
{
uint32_t time_since_last_spark = microsecs.read_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_AlternatorAmps ()
{
int32_t diff = amp_reading - amp_offset;
double amps = ((double) diff) / (1 << AMP_FILTER_FACTOR);
amps -= 365.0; // offset probably specific to particular board.
amps /= 1433.0; // fiddle factor
return amps;
}
double Read_BatteryVolts ()
{
return ((double) volt_reading) / 3282.5; // divisor fiddled to make voltage reading correct !
}
void Read_Ammeter (double * p)
{
p[0] = amp_reading;
p[1] = amp_offset;
}
/**
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;
}
uint32_t RPM_demand = 0; // For test, set from cli 'sv'
/**
*/
void set_RPM_demand (uint32_t d) {
if (d < 10)
d = 10;
if (d > MAX_RPM_LIMIT)
d = MAX_RPM_LIMIT;
RPM_demand = d;
}
/**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) {
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
// 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
}
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);
}
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 () ;
// Programme Entry Point
int main()
{
// local variable declarations
// double servo_position = 0.2; // set in speed control loop
double revs_error;
double Amps_Deliverable = 0.0; // New Nov 2019
// double tempfilt = 0.0, servo_fucker = 0.01;
int32_t RPM_ave = 0, RPM_filt = 0, RPM_tmp;
int32_t irevs_error;
uint32_t ticks = 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
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.
PWM_OSC_IN.pulsewidth_us (PWM_PERIOD_US / 2); // value is int
// PWM_OSC_IN.pulsewidth_us (PWM_PERIOD_US); // value is int
#ifdef TARGET_NUCLEO_F401RE //
A_OUT.period_us (100); // pwm as analogue out
A_OUT.pulsewidth_us (19);
#endif
Throttle = servo_position;
pc.printf ("\r\n\n\n\n\nAlternator Regulator 2020, Jon Freeman, SystemCoreClock=%d\r\n", SystemCoreClock);
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");
// 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
//***** 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
command_line_interpreter () ; // Proceed beyond here once loop_timer ticker ISR has set loop_flag true
} // 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;
amp_reading += (raw_amp_reading - 0.5) * AMPS_CAL;
amp_reading /= 2.0;
amp_offset += (raw_amp_offset - 0.5) * AMPS_CAL; // This reading probably not useful
amp_offset /= 2.0;
Amps_Deliverable = Calculate_Amps_Deliverable (ReadEngineRPM ()); // Added Nov 2019, not yet used. Returns normalised 0.0 to 1.0
// PWM_OSC_IN.pulsewidth_us (user_settings.get_pwm(ReadEngineRPM())); // Update field current limit according to latest measured RPM
// while (LocalCom.readable()) {
// int q = LocalCom.getc();
// //q++;
// pc.putc (q);
// }
// END 100Hz stuff
if (flag_25Hz) {
flag_25Hz = false;
// BEGIN 25Hz stuff
// END 25Hz stuff
// BEGIN 12.5Hz stuff
flag_12Hz5 = !flag_12Hz5;
if (flag_12Hz5) { // Do any even stuff to be done 12.5 times per second
#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;
}
}
RPM_ave = 0; // Reset needed
#endif
}
else { // Do odd 12.5 times per sec stuff
flag_12Hz5 = false;
myled = !myled;
LocalCom.printf ("%d\r\n", volt_reading);
//void set_pwm (double d) {
// set_pwm (user_settings.get_pwm(ReadEngineRPM()));
/* servo_position += servo_fucker;
if (servo_position > 1.0 || servo_position < 0.0)
servo_fucker *= -1.0;
Throttle = servo_position;
*/
} // End of if(flag_12Hz5)
// END 12.5Hz stuff
ticks++; // advances @ 25Hz
if (ticks > 24) { // once per sec stuff
// BEGIN 1Hz stuff
ticks = 0;
if (query_toggle) {
pc.printf ("V=%.1f\tI=%.1f\tRPM=%d\tservo%.2f\r\n", Read_BatteryVolts(), amp_reading, ReadEngineRPM (), servo_position);
}
// pc.printf ("Tick %d\r\n", flag_12Hz5);
// tempfilt *= 0.99;
// tempfilt += Read_AlternatorAmps() * 0.01;
// pc.printf ("RPM %d, err %.1f, s_p %.2f, lut %.3f\r\n", ReadEngineRPM (), revs_error, servo_position, user_settings.get_pwm(ReadEngineRPM()));
// pc.printf ("Vbat %.2f, servo %.3f, amps %.3f, filt %.3f\r\n", Read_BatteryVolts(), servo_position, Read_AlternatorAmps(), tempfilt);
// 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