This example demonstrates how to create a running average in scripting to smooth out data that may fluctuate above and below the actual value. An example of this would be fuel level on a marine vessel or mobile equipment.
This example uses a List which is essentially an array to store the latest x number of data values then calculate a running average of the data set. The list is displayed in a List Widget for demonstration purposes but is not needed for the actual calculations. Each Script Event is manually fired from button presses to demonstrate the actions required and their sequence, in a actual application these would need to be fired by a recurring timer or similar.
This works fine for small data sets and makes it easy to view on the screen however a much more efficient method would use an array declared in the script and just a counter to continually populate the array from the top down. This method only touches one array location each time through the loop rather than having to shuffle all the data each time.
The data used in the script comes from J1939 Fuel Level PGN 65276 SPN 96. Send different values of fuel level then select the add button to see how the data is pushed through the list. Select the Calculate button to get the average of the data.
Note: J1939 fuel level data will be an integer on the CAN bus however when it is received and the scaling of 0.4 is applied to it, the system variable created in Powervision will be a double data type. It is important to keep data types consistent throughout this process.
- Create the List and assign the length to the maximum entries (rows) needed and one column for your data. Create any other variables used in the process on the configuration side.
- At Power up initialize the List with nominal data in each row. When first powered up the list is empty and only the Add library function will work however the Set function will be needed to populate the list with latest data.
- Update the list with the latest data at the top of the list and discard the oldest data at the end of the list
- Add all the data in the list and calculate the average.
See the notes located in the Running Average Script for specific details.
Download the Example for a PV700 (Can be used on any M2/G1e display) created in version 4.797