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-08-07
- Revision:
- 4:28cc0cf01570
- Parent:
- 3:43cb067ecd00
- Child:
- 5:6ca3e7ffc553
File content as of revision 4:28cc0cf01570:
#include "mbed.h"
#include "Alternator.h"
#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 - June 2020
** 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 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 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 {
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
*/
/**
* Jumpers fitted to small mbed Nucleo boards - D5 - A5 and D4 - A4 CHECK - yes
*/
//#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
// INPUTS :
AnalogIn Ain_Link_Volts (A6); // Sniff of alternator output, not used in control loop as done using analogue MCP1630
AnalogIn Ammeter_In (A0); // Output of ASC709LLFTR ammeter chip (pin 20), used to increase engine revs if need be
// 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 (A1); // Moved 31/07/2020 from A3 to free up A3 for use as AnalogOut
BufferedSerial gps_module (D1, D0, 2048, 4, NULL); // For gps - added July 2020
/*
MODULE PIN USAGE - Updated Aug 2020
1 PA_9 D1 LocalCom Tx
2 PA_10 D0 LocalCom Rx GPS maybe
3 NRST
4 GND
5 PA12_D2 InterruptIn VEXT PWM controller output folded back for cpu to monitor, useful on test to read what pwm required to do what
6 PB_0 D3 AnalogIn Field supply voltage
7 PB_7 D4 SDA i2c to 24LC memory
8 PB_6 D5 SCL i2c to 24LC memory
9 PB_12 D6 DigitalOut CHARGE_PUMP new Aug 2020
10 N.C.
11 N.C.
12 PA_8 D9 InterruptIn pulse_tacho from engine magneto, used to measure rpm
13 PA_11 D10 Speed_Control servo
14 PB_5 D11 NEW June 2019 - Output engine tacho cleaned-up, brought out to testpoint 4 NOT REALLY USEFUL
15 PB_4 D12 Scope_probe NOT REALLY USEFUL
16 PB_3 D13 LED Onboard LED
17 3V3
18 AREF
19 PA_0 A0 AnalogIn Driver Pot
20 PA_1 A1 AnalogIn Ammeter_In
21 PA_3 A2 PwmOut PWM_OSC_IN Timebase for pwm, also determines max duty ratio
//22 PA_4 A3 AnalogOut A_OUT control signal to following traction motor ESC
22 PA_4 A3 AnalogOut REF_VAR reference voltage to MCP1630, allows software to set alternator output voltage
23 PA_5 A4 AnalogOut A_OUT control signal to following traction motor ESC
24 PA_6 A5 Spare
25 PA_7 A6 AnalogIn V_Sample system link voltage
26 PA_2 A7 Not useable, taken by uart
27 5V
28 NRST
29 GND
30 VIN
*/
// Test 6/6/2020 to get i2c working
//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)
// 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 :
AnalogOut REF_VAR (A4); // Variable REF to MCP1630 enables software control of output voltage - NEW Aug 2020
AnalogOut A_OUT (A3); // Control voltage out to traction motor ESCs
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 NOW DONE IN CLASS
//PwmOut A_OUT (A2); // Can alter prescaler can not use A5 PIN STOLEN BY PWM_OSC_IN
//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
extern char * get_mode_text (uint32_t mode) ;
DigitalOut CHARGE_PUMP (D6);
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
FieldControl Field (A2, D2); // PWM pin for MCP1630 PWM_OSC_IN, InterruptIn for signal out of MCP1630 VEXTFB
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 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_link_V_rd = false;
bool flag_field_V_rd = false;
bool flag_A_rd = false;
bool flag_Pot_rd = false;
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, u25 = 0;
Scope_probe = 1; // To show how much time spent in interrupt handler
CHARGE_PUMP = !CHARGE_PUMP;
switch (t) {
case 0: // Alternator output voltage
flag_link_V_rd = true;
break;
case 1: // Ammeter
flag_A_rd = true;
break;
case 2: // Driver's Pot
flag_Pot_rd = true;
break;
case 3: // Field supply voltage
flag_field_V_rd = true;
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
u25++;
if (u25 == 25) {
u25 = 0;
flag_1Hz = true;
seconds++;
}
}
default:
break;
}
t++;
if (t > 9)
t = 0;
Scope_probe = 0; // To show how much time spent in interrupt handler
}
// **** End of Interrupt Service Routines ****
/*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_Link_Volts ()
{
return link_volt_reading * 39.9; // divisor fiddled to make voltage reading correct !
}
double Read_Field_Volts ()
{
return field_volt_reading * 42.85; // divisor fiddled to make voltage reading correct !
}
double Read_Ammeter ()
{
return amp_reading * 93.28; // Amp range corrected here
}
void query_system (struct parameters & a) {
query_toggle = !query_toggle;
}
void set_pwm (double d) { // Range 0.0 to 1.0 called from cli
Field.set_pwm (d);
}
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);
}
int32_t set_engine_RPM_pct (uint32_t RPMrequest) { // Returns actual speed
return Engine.set_RPM_percent (RPMrequest);
}
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
enum {AUTO_TEST_INACTIVE, AUTO_TEST_BEGIN, AUTO_TEST_ABORT, AUTO_TEST_IN_PROGRESS } ;
// Programme Entry Point
int main()
{
const double PI = (2.0 * acos(0.0));
const double filt = 0.2;
const double ampfilt = 0.2;
const double vfilt = 0.2;
// local variable declarations
double driver_pot = 0.0, dtmp;
// double theta = 0.0;
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];
A_OUT = 0.0;
REF_VAR = 0.0;
microsecs.reset() ; // timer = 0
microsecs.start () ; // 64 bit, counts micro seconds and times out in half million years
#ifdef GPS_
gps_mod gps;
#endif
//- 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
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
// 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;
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
Engine.manager_core (); // This belongs right here, update regularly, keeps 'filtered()' fresh and keeps engine to set rpm
#ifdef GPS_
gps.update ();
#endif
/* theta += 0.05;
if (theta > PI)
theta -= 2.0 * PI;
sinout = 0.5 + sin(theta) / 2.0;
cosout = 0.5 + cos(theta) / 2.0;
*/
// 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
// 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;
}
}
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;
} // End of if(flag_12Hz5)
// END 12.5Hz stuff
if (flag_1Hz) {
// BEGIN 1Hz stuff
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) {
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