Internet PLC Forum
General => Technical support => Topic started by: pstiles on November 17, 2006, 05:13:56 PM
-
Can someone show me how I can sample a ADC input, and average the reading, then write to a DM location?
Thanks,
Paul Stiles
-
The following example is a custom function reads from ADC(1) and stores a 3 point moving average.
To prevent large initial error, you must fill up the 3 DM during 1st scan by calling this custom function 3 times.
-------------
The last 3 ADC data are stored in DM[101],DM[102] and DM[103]
' K is the index to keep track of the current ADC data
DM[101+K] = ADC(1) ' data are captured in the DM controlled by K
K = (K+1) mod 3 ' K will vary from 0,1,2
A = (DM[101]+DM[102]+DM[103])/3 ' A is the moving average of last 3
' reading.
A = (A+2)/4*4 ' This line is optional, to eliminate unreal precision
' in the intermediate value due to
' averaging. After this expr the
' result will be in increment of 4 only.
---------------
-
In the example below you state that I must call this custome function three times duriong the first scan. By doing this it reads the intial values into the DM, but does not update the value.
I have tried calling this in the first DM, plus in a second custom function, but I still can not get a steady value. The value from the temp sensor is rock steady.
Below is the code I am using in the custom function.
DM[101+K] = (168*(ADC(8)-261)/1376+32)
K = (K+1) mod 5
B=(DM[101]+DM[102]+DM[103]+DM[104]+DM[105]+DM[106])/5
B=(B+2)/4*4
DM[1]=B
-
The ADC input is subject to white noise due to the presence of digital switching signal in the system and typically the reading fluctuates between +/-3 LSB or +/- 12 when using ADC to read the analog input (due to 4x normalization). Moving average will help to even out the fluctuation. You should remove the B=(B+2)/4*4 statement since the reading in DM is already scaled.