1-phase PV router
Loading...
Searching...
No Matches
Time-critical functions

Functions used by the ISR. More...

Functions

void confirmPolarity ()
 Confirms the polarity of the current voltage sample.
 
 ISR (ADC_vect)
 Interrupt Service Routine - Interrupt-Driven Analog Conversion.
 
uint8_t nextLogicalLoadToBeAdded ()
 Retrieve the next load that could be removed (be aware of the reverse-order).
 
uint8_t nextLogicalLoadToBeRemoved ()
 Process with data logging.
 
void proceedHighEnergyLevel ()
 Process the case of high energy level, some action may be required.
 
void proceedLowEnergyLevel ()
 Process the case of low energy level, some action may be required.
 
void processDataLogging ()
 Process with data logging.
 
void processDivertedCurrentRawSample (const int16_t rawSample)
 Processes the raw current sample for the diverted connection point.
 
void processGridCurrentRawSample (const int16_t rawSample)
 Processes the raw current sample for the grid connection point.
 
void processLatestContribution ()
 Process the latest contribution after each new cycle.
 
void processMinusHalfCycle ()
 Process the start of a new -ve half cycle, just after the zero-crossing point.
 
void processPlusHalfCycle ()
 Process the start of a new +ve half cycle, just after the zero-crossing point.
 
void processPolarity (const int16_t rawSample)
 Processes the polarity of the current voltage sample.
 
void processRawSamples ()
 This routine is called by the ISR when a pair of V & I samples becomes available.
 
void processStartNewCycle ()
 This code is executed once per 20ms, shortly after the start of each new mains cycle on phase 0.
 
void processStartUp ()
 Process the startup period for the router.
 
void processVoltage ()
 Process the calculation for the current voltage sample.
 
void processVoltageRawSample (const int16_t rawSample)
 Process the current voltage raw sample.
 
void updatePhysicalLoadStates ()
 This function provides the link between the logical and physical loads.
 
void updatePortsStates ()
 Updates the control ports for each of the physical loads.
 

Detailed Description

Functions used by the ISR.

This group contains functions that are executed within the Interrupt Service Routine (ISR) or are closely tied to time-sensitive operations. These functions are optimized for speed and efficiency to ensure the system operates without delays or interruptions.

Note
These functions handle tasks such as ADC sampling, zero-crossing detection, and real-time data processing.

Function Documentation

◆ confirmPolarity()

void confirmPolarity ( )
inline

Confirms the polarity of the current voltage sample.

This function ensures that a zero-crossing point is not declared until a specified number of consecutive samples in the opposite half of the waveform have been encountered. It helps to stabilize polarity detection and avoid false zero-crossing detections.

  • Compares the polarity of the most recent voltage sample with the last confirmed polarity.
  • If the polarities match, the counter is reset.
  • If the polarities differ, the counter is incremented.
  • Once the counter exceeds the persistence threshold (PERSISTENCE_FOR_POLARITY_CHANGE), the polarity is confirmed and updated.

Definition at line 483 of file processing.cpp.

References PERSISTENCE_FOR_POLARITY_CHANGE, polarityConfirmed, polarityConfirmedOfLastSampleV, and polarityOfMostRecentVsample.

Referenced by processVoltageRawSample().

Here is the caller graph for this function:

◆ ISR()

ISR ( ADC_vect )

Interrupt Service Routine - Interrupt-Driven Analog Conversion.

This ISR is triggered whenever an ADC conversion is completed, approximately every 104 µs in free-running mode. It processes the results of the completed conversion and sets up the next conversion in sequence. The ISR handles voltage and current samples for the grid and diverted connections, ensuring real-time processing of energy data.

An Interrupt Service Routine is now defined which instructs the ADC to perform a conversion for each of the voltage and current sensors in turn.

This Interrupt Service Routine is for use when the ADC is in the free-running mode. It is executed whenever an ADC conversion has finished, approx every 104 µs. In free-running mode, the ADC has already started its next conversion by the time that the ISR is executed. The ISR therefore needs to "look ahead".

At the end of conversion Type N, conversion Type N+1 will start automatically. The ISR which runs at this point therefore needs to capture the results of conversion Type N, and set up the conditions for conversion Type N+2, and so on.

By means of various helper functions, all of the time-critical activities are processed within the ISR.

The main code is notified by means of a flag when fresh copies of loggable data are available.

Note
Guidelines for writing an ISR:
  • Keep it short and efficient.
  • Avoid using delay() or serial prints.
  • Use volatile for shared variables.
  • Protect shared variables with critical sections if necessary.
  • Avoid enabling or disabling interrupts within the ISR.

Definition at line 1221 of file processing.cpp.

References currentSensor_diverted, currentSensor_grid, processDivertedCurrentRawSample(), processGridCurrentRawSample(), processVoltageRawSample(), and voltageSensor.

Here is the call graph for this function:

◆ nextLogicalLoadToBeAdded()

uint8_t nextLogicalLoadToBeAdded ( )
inline

Retrieve the next load that could be removed (be aware of the reverse-order).

This function identifies the next logical load that can be switched OFF based on the reverse order of load priorities. It ensures that the highest-priority load remains active while deactivating lower-priority loads as needed.

Returns
The load number if successful, NO_OF_DUMPLOADS in case of failure.
  • Iterates through the load priorities in reverse order.
  • Checks if a load is currently ON and eligible for deactivation.
  • Returns the load number if a suitable load is found.
  • Returns NO_OF_DUMPLOADS if no load can be deactivated.

Definition at line 1068 of file processing.cpp.

References loadPrioritiesAndState, loadStateOnBit, and NO_OF_DUMPLOADS.

Referenced by proceedHighEnergyLevel().

Here is the caller graph for this function:

◆ nextLogicalLoadToBeRemoved()

uint8_t nextLogicalLoadToBeRemoved ( )
inline

Process with data logging.

At the end of each datalogging period, this function copies the relevant variables for use by the main code. These variables are then reset for the next datalogging period.

  • Checks if the datalogging period has elapsed.
  • Copies accumulated power, energy, and sample data for the current period.
  • Resets the accumulators for the next datalogging period.
  • Signals the main processor that new logging data are available.

Definition at line 1095 of file processing.cpp.

References loadPrioritiesAndState, loadStateOnBit, and NO_OF_DUMPLOADS.

Referenced by proceedLowEnergyLevel().

Here is the caller graph for this function:

◆ proceedHighEnergyLevel()

void proceedHighEnergyLevel ( )
inline

Process the case of high energy level, some action may be required.

This function determines whether additional loads can be switched ON when the energy level in the bucket exceeds the upper threshold. It ensures that the energy thresholds remain within valid limits and handles load activation during the post-transition period.

  • Identifies the next logical load to be added.
  • Updates the upper energy threshold during the post-transition period.
  • Ensures only the active load can be switched during the post-transition period.
  • Activates the identified load and updates the transition state.

Definition at line 963 of file processing.cpp.

References activeLoad, capacityOfEnergyBucket_long, energyInBucket_prediction, loadPrioritiesAndState, loadStateOnBit, nextLogicalLoadToBeAdded(), NO_OF_DUMPLOADS, postTransitionCount, recentTransition, and upperEnergyThreshold.

Referenced by processRawSamples().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ proceedLowEnergyLevel()

void proceedLowEnergyLevel ( )
inline

Process the case of low energy level, some action may be required.

This function determines whether loads can be switched OFF when the energy level in the bucket falls below the lower threshold. It ensures that the energy thresholds remain within valid limits and handles load deactivation during the post-transition period.

  • Identifies the next logical load to be removed.
  • Updates the lower energy threshold during the post-transition period.
  • Ensures only the active load can be switched during the post-transition period.
  • Deactivates the identified load and updates the transition state.

Definition at line 1015 of file processing.cpp.

References activeLoad, energyInBucket_prediction, loadPrioritiesAndState, loadStateMask, lowerEnergyThreshold, nextLogicalLoadToBeRemoved(), NO_OF_DUMPLOADS, postTransitionCount, and recentTransition.

Referenced by processRawSamples().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ processDataLogging()

void processDataLogging ( )
inline

Process with data logging.

At the end of each datalogging period, this function copies the relevant variables for use by the main code. These variables are then reset for the next datalogging period.

  • Checks if the datalogging period has elapsed.
  • Copies accumulated power, energy, and sample data for the current period.
  • Resets the accumulators for the next datalogging period.
  • Signals the main processor that new logging data are available.

Definition at line 1124 of file processing.cpp.

References Shared::b_datalogEventPending, beyondStartUpPeriod, Shared::copyOf_countLoadON, Shared::copyOf_divertedEnergyTotal_Wh_forDL, Shared::copyOf_energyInBucket_long, Shared::copyOf_lowestNoOfSampleSetsPerMainsCycle, Shared::copyOf_sampleSetsDuringThisDatalogPeriod, Shared::copyOf_sum_Vsquared, Shared::copyOf_sumP_diverted_overDL_Period, Shared::copyOf_sumP_grid_overDL_Period, countLoadON, DATALOG_PERIOD_IN_MAINS_CYCLES, divertedEnergyTotal_Wh, energyInBucket_long, i, l_sum_Vsquared, lowestNoOfSampleSetsPerMainsCycle, n_cycleCountForDatalogging, NO_OF_DUMPLOADS, sampleSetsDuringThisDatalogPeriod, sumP_diverted_overDL_Period, and sumP_grid_overDL_Period.

Referenced by processPlusHalfCycle().

Here is the caller graph for this function:

◆ processDivertedCurrentRawSample()

void processDivertedCurrentRawSample ( const int16_t rawSample)
inline

Processes the raw current sample for the diverted connection point.

This function calculates the real power at the diverted connection point using the raw current sample from the ADC. It applies a low-pass filter (LPF) to offset the high-pass filter (HPF) effect of the current transformer (CT). The filtered current sample is then used to compute the instantaneous power, which is accumulated for further processing.

  • Removes the DC offset from the raw current sample.
  • Calculates the instantaneous power using the filtered voltage and current samples.
  • Accumulates the power for the current mains cycle and the datalogging period.
  • Skips processing if the load is overridden.
Parameters
rawSampleThe raw current sample from the ADC.

Definition at line 447 of file processing.cpp.

References Shared::b_diversionEnabled, Shared::b_overrideLoadOn, DCoffset_I, sampleVminusDC_long, sumP_diverted, and sumP_diverted_overDL_Period.

Referenced by ISR().

Here is the caller graph for this function:

◆ processGridCurrentRawSample()

void processGridCurrentRawSample ( const int16_t rawSample)
inline

Processes the raw current sample for the grid connection point.

This function calculates the real power at the grid connection point using the raw current sample from the ADC. It applies a low-pass filter (LPF) to offset the high-pass filter (HPF) effect of the current transformer (CT). The filtered current sample is then used to compute the instantaneous power, which is accumulated for further processing.

  • Removes the DC offset from the raw current sample.
  • Applies an LPF to counteract the HPF effect of the CT.
  • Calculates the instantaneous power using the filtered voltage and current samples.
  • Accumulates the power for the current mains cycle and the datalogging period.
Parameters
rawSampleThe raw current sample from the ADC.

Definition at line 406 of file processing.cpp.

References alpha, DCoffset_I, lpf_gain, sampleVminusDC_long, sumP_grid, and sumP_grid_overDL_Period.

Referenced by ISR().

Here is the caller graph for this function:

◆ processLatestContribution()

void processLatestContribution ( )
inline

Process the latest contribution after each new cycle.

This function calculates the real power and energy during the last whole mains cycle. It updates the energy bucket and prepares the system for the next cycle.

  • Calculates the average real power for the grid and diverted connections.
  • Adjusts the grid power to account for required export (useful for PV simulation).
  • Converts power to energy and updates the energy bucket.
  • Marks the start of a new cycle for the main code.

Definition at line 856 of file processing.cpp.

References absenceOfDivertedEnergyCountInMC, Shared::absenceOfDivertedEnergyCountInSeconds, antiCreepLimit_inIEUperMainsCycle, Shared::b_newCycle, Shared::copyOf_divertedEnergyTotal_Wh, displayShutdown_inMainsCycles, divertedEnergyRecent_IEU, divertedEnergyTotal_Wh, Shared::EDD_isActive, energyInBucket_long, IEU_per_Wh_diverted, perSecondCounter, realEnergy_diverted, realEnergy_grid, requiredExportPerMainsCycle_inIEU, sampleSetsDuringThisMainsCycle, sumP_diverted, sumP_grid, and SUPPLY_FREQUENCY.

Referenced by processPlusHalfCycle().

Here is the caller graph for this function:

◆ processMinusHalfCycle()

void processMinusHalfCycle ( )
inline

Process the start of a new -ve half cycle, just after the zero-crossing point.

This function handles the processing required at the start of a new negative half-cycle of the mains waveform. It updates the low-pass filter (LPF) for DC offset removal, ensures the LPF output remains within valid limits, and predicts the energy state at the end of the mains cycle.

  • Updates the low-pass filter (LPF) for DC offset removal using the cumulative voltage deltas.
  • Ensures the LPF output remains within the valid range to avoid signal drift.
  • Calculates the average power during the first half of the mains cycle.
  • Predicts the energy state at the end of the mains cycle based on the average power.

Definition at line 801 of file processing.cpp.

References cumVdeltasThisCycle_long, DCoffset_V_long, DCoffset_V_max, DCoffset_V_min, energyInBucket_long, energyInBucket_prediction, sampleSetsDuringThisMainsCycle, and sumP_grid.

Referenced by processRawSamples().

Here is the caller graph for this function:

◆ processPlusHalfCycle()

void processPlusHalfCycle ( )
inline

Process the start of a new +ve half cycle, just after the zero-crossing point.

This function handles the processing required at the start of a new positive half-cycle of the mains waveform. It updates performance metrics, processes the latest energy contributions, and resets accumulators for the new cycle.

  • Updates the lowest number of sample sets per mains cycle for performance monitoring.
  • Processes the latest energy contributions using processLatestContribution().
  • Handles data logging for the current cycle using processDataLogging().
  • Resets per-cycle accumulators for energy and sample sets.

Definition at line 772 of file processing.cpp.

References lowestNoOfSampleSetsPerMainsCycle, processDataLogging(), processLatestContribution(), and sampleSetsDuringThisMainsCycle.

Referenced by processRawSamples().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ processPolarity()

void processPolarity ( const int16_t rawSample)
inline

Processes the polarity of the current voltage sample.

This function determines the polarity of the voltage sample by removing the DC offset and comparing the adjusted value to zero. The polarity is then stored for use in zero-crossing detection and other processing steps.

  • Removes the DC offset from the raw voltage sample using a low-pass filter (LPF).
  • Determines the polarity of the adjusted voltage sample (positive or negative).
  • Updates the polarityOfMostRecentVsample variable with the determined polarity.
Parameters
rawSampleThe raw voltage sample from the ADC.

Definition at line 379 of file processing.cpp.

References DCoffset_V_long, NEGATIVE, polarityOfMostRecentVsample, POSITIVE, and sampleVminusDC_long.

Referenced by processVoltageRawSample().

Here is the caller graph for this function:

◆ processRawSamples()

void processRawSamples ( )
inline

This routine is called by the ISR when a pair of V & I samples becomes available.

This function processes raw voltage and current samples to determine the energy state and manage load control. It handles zero-crossing detection, energy bucket updates, and load state adjustments based on the energy level.

  • Detects the start of a new positive or negative half-cycle based on polarity.
  • Processes energy contributions for each half-cycle.
  • Updates the energy bucket and predicts the energy state at the end of the cycle.
  • Adjusts logical and physical load states to maintain energy levels within thresholds.
  • Updates the control ports for physical loads.
  • Handles energy diversion display updates and ensures stability during startup.

Definition at line 520 of file processing.cpp.

References absenceOfDivertedEnergyCountInMC, beyondStartUpPeriod, capacityOfEnergyBucket_long, Shared::EDD_isActive, energyInBucket_long, energyInBucket_prediction, loadPrioritiesAndState, loadStateOnBit, lowerEnergyThreshold, lowerThreshold_default, midPointOfEnergyBucket_long, NEGATIVE, polarityConfirmed, polarityConfirmedOfLastSampleV, POSITIVE, POST_TRANSITION_MAX_COUNT, POST_ZERO_CROSSING_MAX_COUNT, postTransitionCount, proceedHighEnergyLevel(), proceedLowEnergyLevel(), processMinusHalfCycle(), processPlusHalfCycle(), processStartNewCycle(), processStartUp(), recentTransition, refresh7SegDisplay(), sampleSetsDuringNegativeHalfOfMainsCycle, updatePhysicalLoadStates(), updatePortsStates(), upperEnergyThreshold, and upperThreshold_default.

Referenced by processVoltageRawSample().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ processStartNewCycle()

void processStartNewCycle ( )
inline

This code is executed once per 20ms, shortly after the start of each new mains cycle on phase 0.

This function manages the energy bucket and ensures that its level remains within the defined limits. It is responsible for maintaining system stability when conditions change, such as when energy import switches to export or vice versa.

  • Applies maximum and minimum limits to the energy bucket's level.
  • Ensures correct operation during transitions between energy import and export states.

Definition at line 736 of file processing.cpp.

References capacityOfEnergyBucket_long, energyInBucket_long, sampleSetsDuringNegativeHalfOfMainsCycle, sampleSetsDuringThisMainsCycle, sumP_diverted, and sumP_grid.

Referenced by processRawSamples().

Here is the caller graph for this function:

◆ processStartUp()

void processStartUp ( )
inline

Process the startup period for the router.

This function ensures that the system remains in a stable state during the startup period. It waits for the DC-blocking filters to settle and initializes key variables for energy and load management. Once the startup period is complete, the system transitions to normal operation.

  • Waits until the startup delay has elapsed, allowing filters to stabilize.
  • Resets energy and power accumulators for grid and diverted power.
  • Initializes counters for sample sets and load states.
  • Marks the end of the startup period by setting beyondStartUpPeriod to true.

Definition at line 704 of file processing.cpp.

References beyondStartUpPeriod, delayBeforeSerialStarts, lowestNoOfSampleSetsPerMainsCycle, sampleSetsDuringThisMainsCycle, startUpPeriod, sumP_diverted, sumP_diverted_overDL_Period, sumP_grid, and sumP_grid_overDL_Period.

Referenced by processRawSamples().

Here is the caller graph for this function:

◆ processVoltage()

void processVoltage ( )
inline

Process the calculation for the current voltage sample.

This function calculates the squared voltage value for the current sample and accumulates it for further processing. It also updates the DC offset and polarity information for the next cycle.

  • The voltage squared (V²) is calculated and accumulated for RMS calculations.
  • The low-pass filter is updated to remove the DC offset from the voltage signal.
  • The polarity of the last confirmed sample is stored for zero-crossing detection.
  • The number of samples during the current mains cycle is incremented.

Definition at line 643 of file processing.cpp.

References cumVdeltasThisCycle_long, l_sum_Vsquared, polarityConfirmed, polarityConfirmedOfLastSampleV, and sampleVminusDC_long.

Referenced by processVoltageRawSample().

Here is the caller graph for this function:

◆ processVoltageRawSample()

void processVoltageRawSample ( const int16_t rawSample)
inline

Process the current voltage raw sample.

This function processes the raw voltage sample by performing the following steps:

  • Determines the polarity of the raw voltage sample using processPolarity().
  • Confirms the polarity using confirmPolarity() to ensure stability in zero-crossing detection.
  • Processes raw samples for energy state and load control using processRawSamples().
  • Calculates the squared voltage value and accumulates it for RMS calculations using processVoltage().
  • Increments the sample set counter for the current datalogging period.
Parameters
rawSampleThe raw voltage sample from the ADC.

Definition at line 673 of file processing.cpp.

References confirmPolarity(), processPolarity(), processRawSamples(), processVoltage(), sampleSetsDuringThisDatalogPeriod, and sampleSetsDuringThisMainsCycle.

Referenced by ISR().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ updatePhysicalLoadStates()

void updatePhysicalLoadStates ( )

This function provides the link between the logical and physical loads.

This function maps the logical load states to the physical load states. It ensures that the physical loads are updated according to the logical priorities and states. The function also handles priority rotation if enabled.

The array, logicalLoadState[], contains the on/off state of all logical loads, with element 0 being for the one with the highest priority. The array, physicalLoadState[], contains the on/off state of all physical loads.

The lowest 7 bits of element is the load number as defined in 'physicalLoadState'. The highest bit of each 'loadPrioritiesAndState' determines if the load is ON or OFF. The order of each element in 'loadPrioritiesAndState' determines the load priority. 'loadPrioritiesAndState[i] & loadStateMask' will extract the load number at position 'i' 'loadPrioritiesAndState[i] & loadStateOnBit' will extract the load state at position 'i'

Any other mapping relationships could be configured here.

Definition at line 334 of file processing.cpp.

References Shared::b_diversionEnabled, Shared::b_overrideLoadOn, Shared::b_reOrderLoads, i, LOAD_OFF, LOAD_ON, loadPrioritiesAndState, loadStateMask, loadStateOnBit, NO_OF_DUMPLOADS, OFF, and physicalLoadState.

Referenced by initializeOldPCBPins(), and processRawSamples().

Here is the caller graph for this function:

◆ updatePortsStates()

void updatePortsStates ( )

Updates the control ports for each of the physical loads.

This function determines the ON/OFF state of each physical load and updates the corresponding control ports. It ensures that the correct pins are set to their respective states based on the load's current status.

  • If a load is OFF, its corresponding pin is added to the pinsOFF mask.
  • If a load is ON, its corresponding pin is added to the pinsON mask.
  • Finally, the pins are updated using setPinsOFF and setPinsON functions.

Definition at line 285 of file processing.cpp.

References countLoadON, i, LOAD_OFF, NO_OF_DUMPLOADS, physicalLoadPin, physicalLoadState, setPinsOFF(), and setPinsON().

Referenced by initializeOldPCBPins(), and processRawSamples().

Here is the call graph for this function:
Here is the caller graph for this function: