3-phase PV router
Loading...
Searching...
No Matches
processing.cpp
Go to the documentation of this file.
1
12
13#include <Arduino.h>
14
15#include "config_derived.h"
16#include "dualtariff.h"
17#include "processing.h"
18#include "utils_pins.h"
19#include "shared_var.h"
20#include "mult_asm.h"
21#include "ct_filter.h"
22#include "energy_bucket.h"
23#include "load_priorities.h"
24#include "adc_chain.h"
25#include "datalog_math.h"
26
27// Analogue input pins, ADC reference and left-aligned result of each conversion: adc_chain.h.
28// The reference is AVCC (= VCC, 5 V or 3.3 V) on the old board, the internal 1.1 V on the new one
29// (buffered from AREF). ADLAR=1 enables left-aligned ADC for efficient fixed-point math.
30static_assert(AdcChain::BIT_REFS1 == REFS1 && AdcChain::BIT_REFS0 == REFS0 && AdcChain::BIT_ADLAR == ADLAR, "adc_chain.h: ADMUX bits differ from avr/io.h");
31static_assert(AdcChain::NO_OF_CONVERSIONS == 2 * NO_OF_PHASES, "adc_chain.h: a V and an I conversion per phase");
32// ------------------------------------------
33
34// Define ideal bias, ADC mid-range, left aligned.
35constexpr uint16_t i_DCoffset_V_nom{ 511U << 6 };
37
43constexpr float f_offsetOfEnergyThresholdsInAFmode{ 0.1F };
44
45// The sums of a datalog period, in ADC steps: at most MAX_SAMPLE_SETS_PER_DATALOG samples
46// (config_derived.h), each adding at most 2^18 (|V_ADC x I_ADC| or V_ADC^2, x1 scale).
47constexpr uint32_t FULL_SCALE_PER_SAMPLE{ 1UL << 18 };
48// the sample sets, the divisor of the datalog power and voltage, in 16 bits (30 s at most, validation.h)
49static_assert(MAX_SAMPLE_SETS_PER_DATALOG <= UINT16_MAX, "******** The counter of the sample sets of a datalog period would overflow ! ********");
50// the power, scaled down by 16 when the period needs it: without the shift, it holds full-span
51// sines (2^17 on average per sample, Datalog::powerShift()); with it, any signal
52static_assert(DATALOG_POWER_SHIFT == 0 || MAX_SAMPLE_SETS_PER_DATALOG * (FULL_SCALE_PER_SAMPLE >> DATALOG_POWER_SHIFT) <= static_cast< uint32_t >(INT32_MAX),
53 "******** The datalog power sum would overflow ! ********");
54
58
61
63
64bool b_diversionStarted{ false };
65
72constexpr int32_t initThreshold(const bool lower)
73{
74 return static_cast< int32_t >(lower
77}
78
79constexpr int32_t l_lowerThreshold_default{ initThreshold(true) };
80constexpr int32_t l_upperThreshold_default{ initThreshold(false) };
81
83
87
89
90int32_t l_sumP[NO_OF_PHASES]{};
93
96
99
101
103
104// For an enhanced polarity detection mechanism, which includes a persistence check
108
111
113
114uint8_t perSecondCounter{ 0 };
115
116bool beyondStartUpPeriod{ false };
117
151template< typename T, size_t N >
152constexpr void initializeArray(T (&array)[N], T value)
153{
154 for (size_t i = 0; i < N; ++i)
155 {
156 array[i] = value;
157 }
158}
159
174constexpr uint16_t getOutputPins()
175{
176 uint16_t output_pins{ 0 };
177
178 // Local TRIAC pins, plus the optional status LED of each remote load
179 for (const auto &loadEntry : physicalLoadPin)
180 {
181 const uint8_t pin{ Load::pinOf(loadEntry) };
182
183 if (!Load::isLocal(loadEntry) && (pin == 0))
184 continue; // remote load without a status LED
185
186 if (bit_read(output_pins, pin))
187 return 0;
188
189 bit_set(output_pins, pin);
190 }
191
192 if constexpr (WATCHDOG_PIN_PRESENT)
193 {
194 if (bit_read(output_pins, watchDogPin))
195 return 0;
196
197 bit_set(output_pins, watchDogPin);
198 }
199
200 if constexpr (RELAY_DIVERSION)
201 {
202 for (uint8_t idx = 0; idx < relayDiverter.size(); ++idx)
203 {
204 const auto relayPin = relayDiverter.get_relay(idx).get_pin();
205
206 if (bit_read(output_pins, relayPin))
207 return 0;
208
209 bit_set(output_pins, relayPin);
210 }
211 }
212
213 return output_pins;
214}
215
231constexpr uint16_t getInputPins()
232{
233 uint16_t input_pins{ 0 };
234
235 if constexpr (DUAL_TARIFF)
236 {
237 if (bit_read(input_pins, dualTariffPin))
238 return 0;
239
240 bit_set(input_pins, dualTariffPin);
241 }
242
243 if constexpr (DIVERSION_PIN_PRESENT)
244 {
245 if (bit_read(input_pins, diversionPin))
246 return 0;
247
248 bit_set(input_pins, diversionPin);
249 }
250
251 if constexpr (ROUTER_OFF_PIN_PRESENT)
252 {
253 if (bit_read(input_pins, routerOffPin))
254 return 0;
255
256 bit_set(input_pins, routerOffPin);
257 }
258
259 if constexpr (PRIORITY_ROTATION == RotationModes::PIN)
260 {
261 if (bit_read(input_pins, rotationPin))
262 return 0;
263
264 bit_set(input_pins, rotationPin);
265 }
266
267 if constexpr (OVERRIDE_PIN_PRESENT)
268 {
269 // Add all configured override pins
270 for (uint8_t i = 0; i < overrideTable.size(); ++i)
271 {
272 const uint8_t pin = overrideTable.getPin(i);
273 if (bit_read(input_pins, pin))
274 return 0;
275
276 bit_set(input_pins, pin);
277 }
278 }
279
280 return input_pins;
281}
282
297{
298 // Initialize DC offset in Q16.16 format: (0x8000 << 16) for left-aligned ADC
299 // 0x8000 is the mid-point of a left-aligned 10-bit ADC result
300 initializeArray(i_DCoffset_V, i_DCoffset_V_nom); // nominal mid-point value of ADC left-aligned, x64 scale
301
302 constexpr uint32_t filterDC_V_nom = static_cast< uint32_t >(i_DCoffset_V_nom) << 15;
303 initializeArray(l_filterDC_V, filterDC_V_nom); // nominal mid-point value of ADC left-aligned
304
305 setPinsAsOutput< getOutputPins() >(); // set the output pins as OUTPUT
306 setPinsAsInputPullup< getInputPins() >(); // set the input pins as INPUT_PULLUP
307
308 uint8_t i{ NO_OF_DUMPLOADS };
309 do
310 {
311 --i;
314 } while (i);
315
316 if constexpr (RF_CHIP_PRESENT)
317 {
318 // Initialize shared RF module
319 if (initialize_rf())
320 {
321 infoln(F("RF module initialized"));
322 }
323 else
324 {
325 infoln(F("RF module initialization FAILED"));
326 }
327 }
328
329 if constexpr (REMOTE_LOADS_PRESENT)
330 {
331 remoteLoads.reset();
332 infoln(F("Remote loads initialized"));
333 }
334
335 // The ADC runs free: each conversion starts the next one, and each end of conversion
336 // raises the ADC interrupt, where the samples are processed (1664 CPU cycles per call).
337 ADCSRA = 0; // ADC off while it is set up
338 ADCSRB = 0; // ADTS2:0 = 0: the auto-trigger source is the ADC itself (free running)
339
340 // Reference and left-aligned result for the first conversion too, on the first channel (V1)
342
343 ADCSRA = bit(ADEN) // ADC on
344 | bit(ADSC) // first conversion, the next ones start by themselves
345 | bit(ADATE) // auto-trigger, from the source set in ADCSRB
346 | bit(ADIE) // interrupt at the end of each conversion
347 | bit(ADPS2) | bit(ADPS1) | bit(ADPS0); // ADC clock 16 MHz / 128 = 125 kHz: 104 µs per conversion
348
349 sei(); // Enable Global Interrupts
350}
351
359constexpr uint16_t getLoadPins()
360{
361 uint16_t load_pins{ 0 };
362
363 for (const auto &loadEntry : physicalLoadPin)
364 {
365 const uint8_t pin{ Load::pinOf(loadEntry) };
366
367 if (Load::isLocal(loadEntry) || (pin != 0))
368 {
369 bit_set(load_pins, pin);
370 }
371 }
372
373 return load_pins;
374}
375
393{
394 uint16_t pinsON{ 0 };
395 uint16_t pinsOFF{ 0 };
396
397 // One pass over the load map. A local load drives its TRIAC pin; a remote load is
398 // driven over RF and only drives its optional status LED here, if it has one.
399 uint8_t i{ NO_OF_DUMPLOADS };
400 do
401 {
402 --i;
403
404 const uint8_t loadEntry{ physicalLoadPin[i] };
405 // with an all-local map both of these fold away at compile time, leaving the original code
406 const uint8_t pin{ REMOTE_LOADS_PRESENT ? Load::pinOf(loadEntry) : loadEntry };
407 const bool bDrivesAPin{ !REMOTE_LOADS_PRESENT || Load::isLocal(loadEntry) || (pin != 0) };
408
410 {
411 if (bDrivesAPin)
412 {
413 pinsOFF |= bit(pin);
414 }
415 }
416 else
417 {
418 // count ON-cycles on the load's *state*, so remote loads are datalogged too
419 ++countLoadON[i];
420
421 if (bDrivesAPin)
422 {
423 pinsON |= bit(pin);
424 }
425 }
426 } while (i);
427
428 setPinsState< getLoadPins() >(pinsON, pinsOFF);
429}
430
456{
457 if constexpr (NO_OF_DUMPLOADS == 0)
458 {
459 return;
460 }
461
462 if constexpr (PRIORITY_ROTATION != RotationModes::OFF)
463 {
465 {
466 rotationTable.rotate(loadPrioritiesAndState); // each rotation group, among its own places
467
469 }
470 }
471
472 // Diversion OFF stops the surplus diversion only: a forced load stays ON. With the router
473 // OFF, the main loop clears the overrides and disables diversion: every load is OFF.
474 const bool bDiversionEnabled{ Shared::b_diversionEnabled };
475 // the override bitmasks are read once: the same snapshot for every load of this cycle
476 const uint16_t overrideBitmask{ Shared::overrideBitmask };
477 const uint8_t remoteOverrideBitmask{ REMOTE_LOADS_PRESENT ? Shared::remoteOverrideBitmask : uint8_t{ 0 } };
478
480 loadPrioritiesAndState, physicalLoadState, bDiversionEnabled,
481 [overrideBitmask, remoteOverrideBitmask](const uint8_t iLoad) __attribute__((always_inline)) {
482 // A local load has its pin's bit in the local override bitmask, a remote load its
483 // ordinal's bit in the remote one; the other mask is 0. With an all-local map, the
484 // remote test folds away.
485 bool bOverrideActive{ (overrideBitmask & pgm_read_word(&overrideMasks.local[iLoad])) != 0 };
486 if constexpr (REMOTE_LOADS_PRESENT)
487 {
488 bOverrideActive = bOverrideActive || ((remoteOverrideBitmask & pgm_read_byte(&overrideMasks.remote[iLoad])) != 0);
489 }
490 return bOverrideActive;
491 });
492}
493
511void processPolarity(const uint8_t phase, const uint16_t rawSample)
512{
513 // With left-aligned ADC and Q16.16 bias, simply subtract the integer part
514 // rawSample is already left-aligned (16-bit), extract bias from Q16.16 (upper 16 bits)
515 // Add 0.5 for the rounding, +32 when 10-bits left aligned `1<<(15-10)`
516 i_sampleVminusDC[phase] = (rawSample | 32U) - i_DCoffset_V[phase]; // +0.5 for the rounding
517
519}
520
538void processCurrentRawSample(const uint8_t phase, const uint16_t rawSample)
539{
540 // remove most of the DC offset from the current sample.
541 // Use the voltage bias, it's most likely more accurate than the default mid-range.
542 // Add 0.5 for the rounding, +32 when 10-bits left aligned `1<<(15-10)`
543 int16_t sampleIminusDC = (rawSample | 32U) - i_DCoffset_V[phase];
544
545 // extra filtering to offset the HPF effect of CTx
546 // Using if constexpr ensures zero overhead when CT filtering is disabled
547 if constexpr (lpf_gain != 0.0F && alpha != 0.0F)
548 {
549 // Robin's filter in fixed point, one state per phase (ct_filter.h); the settings are checked in validation.h
550 static CtFilter::LowPassBoost ctFilter[NO_OF_PHASES]; // for offsetting the behaviour of CTx as a HPF
551 constexpr CtFilter::Coefficients ctFilterCoefficients{ CtFilter::coefficientsOf(lpf_gain, alpha) };
552
553 sampleIminusDC = ctFilter[phase].apply(sampleIminusDC, ctFilterCoefficients); // at x256, saturated to int16
554 }
555
556 // calculate the "real power" in this sample pair and add to the accumulated sum
557 // Reduce to 14-bits (x16 scale) before multiplication for efficiency on 8-bit MCU
558 const int16_t filtV_div4{ i_sampleVminusDC[phase] >> 2 }; // reduce to 14-bits (now x16, or 2^4)
559 const int16_t filtI_div4{ sampleIminusDC >> 2 }; // reduce to 14-bits (now x16, or 2^4)
560
561 // Using optimized assembly multiplication for ~3x speedup in ISR
562 int32_t instP;
563 multS16x16_to32(instP, filtV_div4, filtI_div4); // 32-bits (now x256, or 2^8)
564 instP >>= 8; // scaling is now x1, as for Mk2 (V_ADC x I_ADC)
565
566 l_sumP[phase] += instP; // cumulative power, scaling as for Mk2 (V_ADC x I_ADC)
567
568 // for the datalog: scaled down by 16, rounded, when the period needs it (DATALOG_POWER_SHIFT);
569 // the main code scales the average back up (Datalog::averagePower())
570 if constexpr (DATALOG_POWER_SHIFT != 0)
571 {
572 l_sumP_atSupplyPoint[phase] += (instP + (1L << (DATALOG_POWER_SHIFT - 1))) >> DATALOG_POWER_SHIFT;
573 }
574 else
575 {
576 l_sumP_atSupplyPoint[phase] += instP;
577 }
578}
579
596void confirmPolarity(const uint8_t phase)
597{
598 static uint8_t count[NO_OF_PHASES]{};
599
601 {
602 count[phase] = 0;
603 return;
604 }
605
606 if (++count[phase] > PERSISTENCE_FOR_POLARITY_CHANGE)
607 {
608 count[phase] = 0;
610 }
611}
612
630void processVoltage(const uint8_t phase)
631{
632 // for the Vrms calculation (for datalogging only)
633 // Reduce to 14-bits (x16 scale) before multiplication for efficiency on 8-bit MCU
634 const int16_t filtV_div4{ i_sampleVminusDC[phase] >> 2 }; // reduce to 14-bits (now x16, or 2^4)
635
636 // Using optimized assembly multiplication for ~3x speedup in ISR
637 int32_t inst_Vsquared_signed;
638 multS16x16_to32(inst_Vsquared_signed, filtV_div4, filtV_div4);
639 uint32_t inst_Vsquared = static_cast< uint32_t >(inst_Vsquared_signed);
640
641 // Shift strategy verified safe by unit tests for all datalog periods and voltages.
642 // Datalog::vrmsFactor() compensates the x1/16 scaling: keep both conditions the same.
643 if constexpr (DATALOG_PERIOD_IN_SECONDS > 10)
644 {
645 inst_Vsquared >>= 12; // scaling is now x1/16 (V_ADC x V_ADC)
646 }
647 else
648 {
649 inst_Vsquared >>= 8; // scaling is now x1 (V_ADC x V_ADC)
650 }
651
652 l_sum_Vsquared[phase] += inst_Vsquared; // cumulative V^2 (V_ADC x V_ADC)
653 //
654 // store items for use during next loop
655 l_filterDC_V[phase] += i_sampleVminusDC[phase]; // for use with LP filter
656 polarityConfirmedOfLastSampleV[phase] = polarityConfirmed[phase]; // for identification of half cycle boundaries
657 ++n_samplesDuringThisMainsCycle[phase]; // for real power calculations
658}
659
677void processStartUp(const uint8_t phase)
678{
679 // Every phase starts afresh at each of its crossings during the start-up period: the crossing
680 // that ends it is the first phase's to come, and the others then hold one cycle at most, not
681 // the sums and the sample count of the whole start-up period. Done here, for the crossing
682 // phase only, rather than for all phases at the end: a loop over the phases, inlined or
683 // called, makes the ISR spill to a stack frame on every call.
684 l_sumP[phase] = 0;
685 l_sumP_atSupplyPoint[phase] = 0;
686 l_sum_Vsquared[phase] = 0; // with the sample set count: the first datalog period holds its own samples (one cycle more at most for the other phases)
688
689 // wait until the DC-blocking filters have had time to settle
690 if (millis() <= (initialDelay + startUpPeriod))
691 {
692 return; // still settling
693 }
694
695 // the DC-blocking filters have had time to settle
696 beyondStartUpPeriod = true;
698
700 // can't say "Go!" here 'cos we're in an ISR!
701}
702
720{
721 // may switch one load ON or OFF (load_priorities.h)
723
724 updatePhysicalLoadStates(); // allows the logical-to-physical mapping to be changed
725
726 updatePortsStates(); // update the control ports for each of the physical loads
727
728 if constexpr (REMOTE_LOADS_PRESENT)
729 {
730 // Rebuild the RF payloads AFTER local physical ports are updated.
731 // The actual transmission happens in loop(), never here.
733 }
734
736 {
738 }
739 else
740 {
742 }
743
744 // Now that the energy-related decisions have been taken, min and max limits can now
745 // be applied to the level of the energy bucket. This is to ensure correct operation
746 // when conditions change, i.e. when import changes to export, and vice versa.
747 //
749 {
751 }
752 else if (l_energyInBucket_main < 0)
753 {
755 }
756
757 // one 'tick' per mains cycle for use by the main code, once the cycle's work is done: the 1-Wire
758 // transactions start when the loop sees it, their slots must not delay this call
760}
761
782void processMinusHalfCycle(const uint8_t phase)
783{
784 // This is a convenient point to refresh the DC offset for the phase being processed.
785 // Bits 15..30 of the integrator, as '>> 15' into a uint16_t, but without its 15-turn
786 // shift loop (~105 cycles, 4 here): '<< 1' only drops bit 31, which the uint16_t drops
787 // too. Identical for all 2^32 values (checked exhaustively).
788 i_DCoffset_V[phase] = static_cast< uint16_t >((l_filterDC_V[phase] << 1) >> 16);
789}
790
806void processLatestContribution(const uint8_t phase)
807{
808 // for efficiency, the energy scale is Joules * SUPPLY_FREQUENCY, in integer fixed point
809 // add the latest energy contribution to the main energy accumulator
810 // (sumP / n) x cal == sumP x (cal / n): cal / n comes from the table, so there is no division
811 const uint8_t n{ n_samplesDuringThisMainsCycle[phase] };
812 int32_t sumP{ l_sumP[phase] };
813 uint8_t index{ static_cast< uint8_t >(n - N_MIN) };
814
815 if ((n < N_MIN) || (n > N_MAX))
816 {
817 // unexpected cycle length (start-up, missing phase): rescale the sum to N_MIN samples
818 sumP = (sumP / n) * N_MIN;
819 index = 0;
820 }
821
822 l_energyInBucket_main += Energy::contribution(sumP, pgm_read_word(&powerCalPerSample.value[phase][index]), powerCalPerSampleShift);
823
824 // apply any adjustment that is required.
825 if (0 == phase)
826 {
827 // If diversion hasn't started yet, use start threshold, otherwise use regular offset
829 {
831
832 // Check if we've exceeded the threshold to start diversion
834 {
835 b_diversionStarted = true;
836 // Once started, we divert all surplus according to the configured fixed offset
837 }
838 }
839 else
840 {
841 // When diversion is already started, apply normal export offset if configured
842 // Comment or remove this if you want to divert ALL surplus once started
844 }
845 }
846 // Applying max and min limits to the main accumulator's level
847 // is deferred until after the energy related decisions have been taken
848 //
849}
850
866{
868 {
869 return; // data logging period not yet reached
870 }
871
873
874 uint8_t phase{ NO_OF_PHASES };
875 do
876 {
877 --phase;
879 l_sumP_atSupplyPoint[phase] = 0;
880
882 l_sum_Vsquared[phase] = 0;
883 } while (phase);
884
885 uint8_t i{ NO_OF_DUMPLOADS };
886 do
887 {
888 --i;
890 countLoadON[i] = 0;
891 } while (i);
892
896
899
900 // signal the main processor that logging data are available (beyond the start-up period)
902}
903
922void processPlusHalfCycle(const uint8_t phase)
923{
924 processLatestContribution(phase); // runs at 6.6 ms intervals
925
926 // A performance check to monitor and display the minimum number of sets of
927 // ADC samples per mains cycle, the expected number being 20ms / (104us * 6) = 32.05
928 //
929 if (0 == phase)
930 {
932 {
934 }
935
937
938 // the seconds without diversion
940 {
942
944 {
946 // Reset diversion state if we've had no diversion for a full second
947 b_diversionStarted = false;
948 }
949 else
951 }
952 }
953
954 l_sumP[phase] = 0;
956}
957
975void processRawSamples(const uint8_t phase)
976{
977 // The raw V and I samples are processed in "phase pairs"
978 const auto &lastPolarity{ polarityConfirmedOfLastSampleV[phase] };
979
981 {
982 // the polarity of this sample is positive
983 if (Polarities::POSITIVE != lastPolarity)
984 {
985 // This is the start of a new +ve half cycle, for this phase, just after the zero-crossing point.
987 {
989 }
990 else
991 {
992 processStartUp(phase);
993 }
994 }
995
996 // still processing samples where the voltage is POSITIVE ...
997 // check to see whether the trigger device can now be reliably armed
998 if ((0 == phase) && beyondStartUpPeriod && (2 == n_samplesDuringThisMainsCycle[0])) // lower value for larger sample set
999 {
1000 // This code is executed once per 20mS, shortly after the start of each new mains cycle on phase 0.
1002 }
1003 }
1004 else
1005 {
1006 // the polarity of this sample is negative
1007 if (Polarities::NEGATIVE != lastPolarity)
1008 {
1009 // This is the start of a new -ve half cycle (just after the zero-crossing point)
1010 processMinusHalfCycle(phase);
1011 }
1012 }
1013}
1014
1032void processVoltageRawSample(const uint8_t phase, const uint16_t rawSample)
1033{
1034 processPolarity(phase, rawSample);
1035 confirmPolarity(phase);
1036
1037 processRawSamples(phase); // deals with aspects that only occur at particular stages of each mains cycle
1038
1039 processVoltage(phase);
1040
1041 if (phase == 0)
1042 {
1044 }
1045}
1046
1061{
1062 // display relevant settings for selected output mode
1063 info(F("Output mode: "));
1065 {
1066 infoln(F("normal"));
1067 }
1068 else
1069 {
1070 infoln(F("anti-flicker"));
1071 constexpr int32_t offsetOfEnergyThresholds_x100{ SerialOutput::toDecimals(f_offsetOfEnergyThresholdsInAFmode, 2) };
1072 info(F("\toffsetOfEnergyThresholds = "));
1073 infolnDecimals(offsetOfEnergyThresholds_x100, 2);
1074 }
1075 info(F("\tl_capacityOfEnergyBucket_main = "));
1077 info(F("\tl_lowerEnergyThreshold = "));
1079 info(F("\tl_upperEnergyThreshold = "));
1081}
1082
1113
1114// ADC optimization: circular linked list for channels (private implementation)
1115
1127{
1128 struct adc_ctx_t *next;
1129 uint8_t index;
1130 uint8_t admux;
1131};
1132
1133// ADC optimization: circular linked list for channel management. The ADMUX written after a
1134// conversion applies to the conversion after next (adc_chain.h); every entry is a constant.
1136 { .next = &_channels[1], .index = static_cast< uint8_t >(AdcChain::Channel::V1), .admux = AdcChain::admuxWrittenAfter(PCB_VERSION, AdcChain::Channel::V1) }, // V1 -> setup for V2
1137 { .next = &_channels[2], .index = static_cast< uint8_t >(AdcChain::Channel::I1), .admux = AdcChain::admuxWrittenAfter(PCB_VERSION, AdcChain::Channel::I1) }, // I1 -> setup for I2
1138 { .next = &_channels[3], .index = static_cast< uint8_t >(AdcChain::Channel::V2), .admux = AdcChain::admuxWrittenAfter(PCB_VERSION, AdcChain::Channel::V2) }, // V2 -> setup for V3
1139 { .next = &_channels[4], .index = static_cast< uint8_t >(AdcChain::Channel::I2), .admux = AdcChain::admuxWrittenAfter(PCB_VERSION, AdcChain::Channel::I2) }, // I2 -> setup for I3
1140 { .next = &_channels[5], .index = static_cast< uint8_t >(AdcChain::Channel::V3), .admux = AdcChain::admuxWrittenAfter(PCB_VERSION, AdcChain::Channel::V3) }, // V3 -> setup for V1
1141 { .next = &_channels[0], .index = static_cast< uint8_t >(AdcChain::Channel::I3), .admux = AdcChain::admuxWrittenAfter(PCB_VERSION, AdcChain::Channel::I3) } // I3 -> setup for I1
1142};
1143
1145
1146ISR(ADC_vect)
1147{
1148 uint16_t adc_raw = ADC;
1149
1150 if ((_ctx->index & 1) == 0)
1151 { // even=voltage, odd=current
1152 // process voltage channel
1153 processVoltageRawSample(_ctx->index >> 1, adc_raw);
1154 }
1155 else
1156 {
1157 // process current channel
1158 processCurrentRawSample(_ctx->index >> 1, adc_raw);
1159 }
1160
1161 // Set ADMUX at the end of the interrupt to ensure at least 128 CPU cycles
1162 // have passed since the trigger event (ATmega328p datasheet requirement)
1163 ADMUX = _ctx->admux;
1164
1165 _ctx = _ctx->next;
1166} // end of ISR
The six ADC conversions of the 3-phase board, and the ADMUX pipeline of the free-running ADC.
constexpr float alpha
Definition calibration.h:73
constexpr float lpf_gain
Definition calibration.h:72
constexpr uint8_t loadPrioritiesAtStartup[NO_OF_DUMPLOADS]
Definition config.h:91
constexpr bool ROUTER_OFF_PIN_PRESENT
Definition config.h:58
constexpr bool RELAY_DIVERSION
Definition config.h:63
constexpr bool OVERRIDE_PIN_PRESENT
Definition config.h:60
constexpr uint8_t dualTariffPin
Definition config.h:103
constexpr PcbVersion PCB_VERSION
Definition config.h:21
constexpr uint8_t physicalLoadPin[NO_OF_DUMPLOADS]
Definition config.h:50
constexpr bool DUAL_TARIFF
Definition config.h:64
constexpr uint8_t diversionPin
Definition config.h:104
constexpr uint8_t NO_OF_DUMPLOADS
Definition config.h:40
constexpr uint8_t routerOffPin
Definition config.h:105
constexpr bool WATCHDOG_PIN_PRESENT
Definition config.h:62
constexpr bool DIVERSION_PIN_PRESENT
Definition config.h:57
constexpr uint8_t rotationPin
Definition config.h:106
constexpr uint8_t watchDogPin
Definition config.h:107
The configuration as the firmware uses it: the settings, and what is built from them.
RemoteLoadCore< NO_OF_REMOTE_UNITS > remoteLoads
The one and only remote-load controller.
constexpr Rotation::Table rotationTable
The priority places each rotation group rotates in.
constexpr uint32_t MAX_SAMPLE_SETS_PER_DATALOG
constexpr bool REMOTE_LOADS_PRESENT
constexpr RelayDiverter relayDiverter
constexpr uint8_t N_MIN
constexpr float f_powerCal[NO_OF_PHASES]
constexpr uint8_t N_MAX
constexpr uint8_t DATALOG_POWER_SHIFT
constexpr OverrideTable overrideTable
constexpr int16_t REQUIRED_EXPORT_IN_WATTS
constexpr uint32_t WORKING_ZONE_IN_JOULES
constexpr conditional< DATALOG_PERIOD_IN_SECONDS *SUPPLY_FREQUENCY >=UINT8_MAX, uint16_t, uint8_t >::type DATALOG_PERIOD_IN_MAINS_CYCLES
constexpr uint8_t DATALOG_PERIOD_IN_SECONDS
constexpr uint8_t NO_OF_PHASES
constexpr uint8_t SUPPLY_FREQUENCY
constexpr int16_t DIVERSION_START_THRESHOLD_WATTS
The CT filter: a low-pass of the current added back with a gain, one per phase.
Integer arithmetic of the datalog: power and RMS voltage per phase.
void infoln(const Args &... args)
Print an informational message and a line end, as Serial.println() does.
Definition debug.h:67
void info(const Args &... args)
Print an informational message, as Serial.print() does.
Definition debug.h:57
void infolnDecimals(const int32_t value, const uint8_t decimals)
Print a value given as an integer with a fixed number of decimals, and a line end.
Definition debug.h:100
The scheduled boosts of the dual tariff, resolved at compile time.
constexpr BoostTable boostTable PROGMEM
Definition dualtariff.h:52
uint8_t i
Integer arithmetic of the energy bucket.
constexpr uint16_t getLoadPins()
The pins the loads drive: the local TRIACs, plus the status LED of each remote load.
constexpr void initializeArray(T(&array)[N], T value)
Initializes all elements of a given array to a specified value.
constexpr uint16_t getInputPins()
Retrieves the input pins configuration.
void printParamsForSelectedOutputMode()
Print the settings used for the selected output mode.
constexpr uint16_t getOutputPins()
Retrieves the output pins configuration.
void initializeProcessing()
Initializes the processing engine, including ports, load states, and ADC setup.
void updatePhysicalLoadStates()
Updates the physical load states based on logical load priorities and states.
void processLatestContribution(const uint8_t phase)
Process the latest contribution after each phase-specific new cycle.
void updatePortsStates()
Updates the control ports for each of the physical loads.
void processStartUp(const uint8_t phase)
Processes the startup period for the router.
static void multS16x16_to32(int32_t &result, A a, B b)
Optimized 16×16→32 signed multiplication with assembly.
Definition mult_asm.h:47
void processStartNewCycle()
Processes the start of a new mains cycle on phase 0.
void processMinusHalfCycle(const uint8_t phase)
Processes the start of a new negative half cycle for the specified phase.
void processRawSamples(const uint8_t phase)
Processes raw voltage and current samples for the specified phase.
void processPolarity(const uint8_t phase, const uint16_t rawSample)
Processes the polarity of the current voltage sample for a specific phase.
void processPlusHalfCycle(const uint8_t phase)
Process the start of a new positive half cycle for the specified phase.
void processDataLogging()
Process data logging at the end of each logging period.
void processCurrentRawSample(const uint8_t phase, const uint16_t rawSample)
Processes the current raw sample for the specified phase.
void processVoltageRawSample(const uint8_t phase, const uint16_t rawSample)
Processes the current voltage raw sample for the specified phase.
void confirmPolarity(const uint8_t phase)
Confirms the polarity of the current voltage sample for a specific phase.
void processVoltage(const uint8_t phase)
Processes the current voltage sample for the specified phase.
LoadStates
Definition load_map.h:32
The load priority state machine: which load to switch at each mains cycle.
constexpr uint8_t loadStateMask
constexpr uint8_t loadStateOnBit
Assembly-optimized multiplication functions for AVR microcontrollers.
constexpr uint8_t admuxOf(const PcbVersion board, const Channel ch)
The ADMUX value that converts a channel: reference, left-adjusted result, analog input.
Definition adc_chain.h:81
constexpr uint8_t BIT_REFS0
Definition adc_chain.h:48
constexpr uint8_t BIT_REFS1
Definition adc_chain.h:47
constexpr uint8_t BIT_ADLAR
Definition adc_chain.h:49
constexpr uint8_t admuxWrittenAfter(const PcbVersion board, const Channel converted)
The ADMUX value the interrupt writes after the conversion of a channel.
Definition adc_chain.h:107
constexpr uint8_t NO_OF_CONVERSIONS
Definition adc_chain.h:44
constexpr Coefficients coefficientsOf(const float gain, const float alpha)
Converts the float settings to fixed point, at compile time.
Definition ct_filter.h:72
int32_t contribution(const int32_t averagePower, const uint16_t calFixed, const uint8_t shift)
Contribution of one mains cycle of one phase to the bucket.
constexpr PerSampleCalibration< NMin, NMax, N > toFixedPerSample(const float(&cal)[N])
Build the per-sample calibration table at compile time.
constexpr int32_t fromWatts(const int32_t watts)
A power in watts, in bucket units per mains cycle.
void toPhysical(const uint8_t(&priorities)[N], LoadStates(&physical)[N], const bool diversionEnabled, IsOverridden isOverridden)
Maps the logical load states to the physical ones.
constexpr bool isLocal(uint8_t entry)
True if the entry describes a locally driven load.
Definition load_map.h:89
constexpr uint8_t pinOf(uint8_t entry)
The pin of the entry: TRIAC pin if local, status LED (0 = none) if remote.
Definition load_map.h:101
constexpr OverrideMasks< N > overrideMasks(const uint8_t(&map)[N])
Build the override bits of a load map.
Definition load_map.h:230
constexpr int32_t toDecimals(float value, uint8_t decimals)
A float constant as an integer with the given number of decimals, rounded.
volatile uint16_t overrideBitmask
Definition shared_var.h:15
volatile bool b_datalogEventPending
Definition shared_var.h:11
volatile bool b_reOrderLoads
Definition shared_var.h:13
volatile uint16_t copyOf_sampleSetsDuringThisDatalogPeriod
Definition shared_var.h:27
volatile int32_t copyOf_sumP_atSupplyPoint[NO_OF_PHASES]
Definition shared_var.h:23
volatile int32_t copyOf_energyInBucket_main
Definition shared_var.h:25
volatile uint8_t copyOf_lowestNoOfSampleSetsPerMainsCycle
Definition shared_var.h:26
volatile uint16_t copyOf_countLoadON[NO_OF_DUMPLOADS]
Definition shared_var.h:28
volatile uint8_t remoteOverrideBitmask
Definition shared_var.h:16
volatile uint16_t absenceOfDivertedEnergyCountInSeconds
Definition shared_var.h:18
volatile uint32_t copyOf_sum_Vsquared[NO_OF_PHASES]
Definition shared_var.h:24
volatile bool b_newMainsCycle
Definition shared_var.h:12
volatile bool b_diversionEnabled
Definition shared_var.h:14
Polarities polarityConfirmedOfLastSampleV[NO_OF_PHASES]
ISR(ADC_vect)
uint8_t n_lowestNoOfSampleSetsPerMainsCycle
static adc_ctx_t _channels[AdcChain::NO_OF_CONVERSIONS]
constexpr OutputModes outputMode
uint32_t absenceOfDivertedEnergyCountInMC
constexpr int32_t l_capacityOfEnergyBucket_main
uint16_t countLoadON[NO_OF_DUMPLOADS]
constexpr float f_offsetOfEnergyThresholdsInAFmode
bool b_diversionStarted
static adc_ctx_t * _ctx
LoadPriorities::Switching< NO_OF_DUMPLOADS > loadSwitching
remove_cv< remove_reference< decltype(DATALOG_PERIOD_IN_MAINS_CYCLES)>::type >::type n_cycleCountForDatalogging
LoadStates physicalLoadState[NO_OF_DUMPLOADS]
constexpr uint8_t powerCalPerSampleShift
constexpr LoadPriorities::Bucket bucketLevels
constexpr int32_t l_upperThreshold_default
uint32_t l_filterDC_V[NO_OF_PHASES]
int32_t l_sumP[NO_OF_PHASES]
constexpr int32_t l_midPointOfEnergyBucket_main
Polarities polarityConfirmed[NO_OF_PHASES]
uint8_t n_samplesDuringThisMainsCycle[NO_OF_PHASES]
constexpr int32_t initThreshold(const bool lower)
set default threshold at compile time so the variable can be read-only
int16_t i_sampleVminusDC[NO_OF_PHASES]
bool beyondStartUpPeriod
constexpr uint16_t i_DCoffset_V_nom
Polarities polarityOfMostRecentSampleV[NO_OF_PHASES]
uint16_t i_sampleSetsDuringThisDatalogPeriod
constexpr int32_t l_lowerThreshold_default
uint32_t l_sum_Vsquared[NO_OF_PHASES]
constexpr uint32_t FULL_SCALE_PER_SAMPLE
uint16_t i_DCoffset_V[NO_OF_PHASES]
int32_t l_sumP_atSupplyPoint[NO_OF_PHASES]
uint8_t perSecondCounter
int32_t l_energyInBucket_main
Public functions/variables of processing engine.
constexpr uint16_t startUpPeriod
Definition processing.h:23
constexpr uint8_t PERSISTENCE_FOR_POLARITY_CHANGE
Definition processing.h:20
uint8_t loadPrioritiesAndState[NO_OF_DUMPLOADS]
Definition processing.h:18
constexpr uint16_t initialDelay
Definition processing.h:22
The coefficients of the filter, in fixed point: the multiples the filter needs, ready.
Definition ct_filter.h:55
The state of the filter of one CT (one per phase), and the filter itself.
Definition ct_filter.h:117
int16_t apply(const int16_t sampleMinusDC, const Coefficients &coefficients)
Filters one sample.
Definition ct_filter.h:137
cal / n for every phase and every expected sample count n, in fixed point.
The fixed levels of the energy bucket, in bucket units.
The switching decision, once per mains cycle, and its state.
Override bit of each load, in the local or in the remote override bitmask.
Definition load_map.h:216
Interrupt Service Routine - Interrupt-Driven Analog Conversion.
struct adc_ctx_t * next
uint8_t admux
uint8_t index
Polarities
Definition types.h:32
@ NEGATIVE
Definition types.h:33
@ POSITIVE
Definition types.h:34
OutputModes
Definition types.h:39
@ ANTI_FLICKER
Definition types.h:40
constexpr void bit_set(T &_dest, const uint8_t bit)
Set the specified bit to 1.
Definition utils_bits.h:30
constexpr uint8_t bit_read(const T &_src, const uint8_t bit)
Read the specified bit.
Definition utils_bits.h:44
Some utility functions for pins manipulation.
void setPinsState(uint16_t pinsON, uint16_t pinsOFF)
Switch pins ON and OFF, with one write per port.
Definition utils_pins.h:160
void setPinsAsInputPullup()
Set the pins as INPUT_PULLUP.
Definition utils_pins.h:224
void setPinsAsOutput()
Set the pins as OUTPUT.
Definition utils_pins.h:204
constexpr bool RF_CHIP_PRESENT
Definition utils_rf.h:25
bool initialize_rf()
Initialize the shared RF module.
Definition utils_rf.h:57