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-06-08
- Revision:
- 2:8e7b51353f32
- Parent:
- 1:450090bdb6f4
- Child:
- 3:43cb067ecd00
File content as of revision 2:8e7b51353f32:
#include "mbed.h"
#include "Alternator.h"
/*
Test 6th June 2020 - i2c sda=grey, scl=white
*/
float dpd = 0.0;
/*
* 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
*/
/*
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 < TICKOVER_RPM (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
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 - 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 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
*/
// 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 (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
// 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; // 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 ;
// 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;
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_Pot_rd = 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:
flag_V_rd = true;
// 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:
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:
// 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 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;
}
//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
}
}
}
/**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
}
/*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 ());
}
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;
}
/**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
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);
}
}
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()
{
const double filt = 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
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);
#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");
// 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 ();
//***** 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
if (flag_V_rd) {
flag_V_rd = false;
volt_reading >>= 1; // Result = Result / 2
volt_reading += Ain_SystemVolts.read_u16 (); // Result = Result + New Reading
}
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();
}
} // 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
// 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
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;
}
}
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);
} // End of if(flag_12Hz5)
// END 12.5Hz stuff
ticks25Hz++; // advances @ 25Hz
if (ticks25Hz > 24) { // once per sec stuff
// BEGIN 1Hz stuff
ticks25Hz = 0;
// secs++;
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));
}
// 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