SoMachine / Machine Expert Basic - Mean / average

If you can hold off for a bit, I will post an even simpler approach that eliminates the mean/average calculation entirely while still giving identical results. @Peter Nachtwey knows what that approach is already, but graciously chose to not steal my thunder (thanks, Pete!).
 
What @drbitboy calls discretization noise I call quantizing noise but we are saying the same thing. This "noise" is a common problem and is solved/reduced by using higher resolution encoders or by having more teeth. It is made worse by reducing the sample interval.
TL;DR - gentlemen, start your popcorn, its geek-out time!

I chose "discretization" noise here rather than "quantization noise*" because I think of the latter more as a property of A/D converters.

That said, it's a fuzzy line, and I agree we are definitely saying the same thing.

* also called shot noise in CCDs, IIRC
 
... I will post an even simpler approach that eliminates the mean/average calculation entirely while still giving identical results. ...
See the attached PDF file. Simulated testing yields functionally indistinguishable results from across all three approaches:

  1. LAD 3 - averaging algorithm using ten delta-tooth values in a shifting FIFO: 6 rungs; 18 instructions
  2. LAD 4 - no-average algorithm using ten sampled counter accumulator values in a shifting FIFO: 5 rungs; 9 instructions
  3. LAD 5 - no-average algorithm using ten sampled counter accumulator values in a fixed, non-shifting FIFO: 5 rungs; 12 instructions

LAD 5 answers OP's earlier query:
So I'm not following when you're saying that I don't need to shift the data within the array. I'm thinking that you mean to manage it by writing to specific location in the array instead of moving the data in the array? [the answer is yes]
 

Attachments

  • counting_teeth.pdf
    305.3 KB · Views: 9
So in case it is not yet clear, here is the deal:

Background

  • Post #1 of this thread is asking about averaging the elements of a SoMachine table, i.e. array, of values
  • We eventually found out that the values were the HSC-generated counts, presumably of the rising edges some prox sensor input pointed at, and detecting each tooth of a toothed wheel (gear)
  • the counts are discrete samples taken at 250ms intervals
  • the number of teeth that triggers the prox input per interval is the difference between the HSC accumulator values at the start and end of the interval
  • The HSC is reset at each sample interval,
    • the choice to reset the HSC accumulator value was made to avoid mathematical problems with the difference when the accumulator rolls over, either from +32767 back to -32768 or from 65535 back to 0.
    • so the accumulator value is assumed to be 0 at interval start, and
  • the HSC accumulator value at the end of the interval is then the number of teeth counted per interval
    • because subracting the 0 from the start of the interval yields the same value
  • the ten most recent interval's differences are kept in a table/array FIFO
    • and averaged to attenuate discretization/quantization errors,
      • which are apparent when using a single interval's count to calculate the tooth rate
    • at each interval,
      • the oldest difference in the FIFO is discarded (FO - First Out) from, and
      • the newest difference is added to, the FIFO,
    • so only the then most recent differences are used in the average calculation at each interval

So there are a few improvements that can be made here

#1 the HSC accumulator does not need to be reset
  • moving the accumulator values into a float (with 24 bits of resolution) or into a signed long integer (with 32 bits of resolution)
    • will cause the initially-calculated difference across an interval when the accumulator rolls over to be a value slightly greater than -65536
      • which value can be detected and offset by adding +65536 to the difference to get the actual number of teeth counted over that interval
  • this actually gives better results because eliminating the HSC reset also eliminates inaccuracies in the measured tooth count
  • This is what was done in the algorithm implemented in the LAD 3 subroutine of my code
    • N.B. this refactor also allows further improvements; see below

#2 the calculation of individual per-interval differences is unnecessary once the HSC reset is eliminated
  • Let's call the eleven HSC accumulator values (not the difference value)used to calculate the last ten differences are
    • accFIFO[0] - 2500ms ago
    • accFIFO[1] - 2250ms ago
    • accFIFO[2] - 2000ms ago
    • ...
    • accFIFO[9]
    • accNOW - current accumulator value
  • Which means the ten difference values in the difference FIFO would be the result of the following difference formulas
    • accFIFO[1] - accFIFO[0]
    • accFIFO[2] - accFIFO[1]
    • accFIFO[3] - accFIFO[2]
    • ...
    • accFIFO[9] - accFIFO[8]
    • accNOW - accFIFO[9]
  • To get the arithmetic average of the differences requires adding all of the difference values together
    • and dividing the resulting sum by 10
  • But what should be apparent by inspection is that, in adding all of those difference formulasabove together,
    • the HSC accumulator value accFIFO[1] is added in the first difference, and subtracted in the second, so it cancels out
    • and the same is true for all subsequent HSC accumulator values, accFIFO[2] through accFIFO[9]
    • which leaves the formula accNOW - accFIFO[0]as a much simpler way to calculate the exact same sum of the 10 individual differences,
      • again with a correction for overflow when required, and
    • which sum will be divided by 10 to get the average difference value per interval.
  • Only the current (newest) and oldest accumulator values, accNOW and accFIFO[0], are needed at each sample interval.
    • where those accumulator values (not the differences) are kept in a FIFO table/array,
      • with accFIFO[0] popped off the array bottom, and
      • accFiFO[1] through accFIFO[9] shifted (ROL_ARRAY'ed) down to arrFIFO[0] through arrFIFO[8],
      • and accNOW pushed onto the array top (accFIFO[9]),
      • at each sample interval
  • This is what was done in the LAD 4 subroutine of my code

#3 the shift/ROL_ARRAY of the FIFO is unnecessary
  • in #2 above, it was shown that only the newest and oldest accumulator values are required at each sample interval
    • the newest accumulator value is always available because it is read directly from the HSC
      • caveat: in the case of an HSC counting asynchronously with the evaluation of ladder logic,
        • that newest value should be moved to a local value exactly once per scan cycle in the code,
          • because if it is read more than once in a scan cycle,
            • then it is possible that it could change between the two readings
    • the oldest accumulator value was in accFIFO[0]in #2 above,
      • because the FIFO values were shifted/ROL_ARRAY'ed down
      • and the newest accumulator value was pushed/place at the top of the FIFO
  • It is possible to instead leave the accumulator values fixed in the FIFO array where they are placed, and
    • to keep track of array index of the oldest accumulator value with an integer, oldNewINDEX, and
    • use that index value to make the difference calculation (accNOW - accFIFO[oldNewINDEX]), and
    • then to write over the oldest value with the newest value accNOW into accFIFO[oldNewINDEX], and
    • finally increment oldNewINDEX by 1, with a rollover back to 0 when it increments from 9 to 10
  • This is what was done in the LAD 5 subroutine of my code
 
See the attached PDF file. Simulated testing yields functionally indistinguishable results from across all three approaches:

  1. LAD 3 - averaging algorithm using ten delta-tooth values in a shifting FIFO: 4 rungs; 11 instructions 6 rungs; 18 instructions
  2. LAD 4 - no-average algorithm using ten sampled counter accumulator values in a shifting FIFO: 5 rungs; 9 instructions
  3. LAD 5 - no-average algorithm using ten sampled counter accumulator values in a fixed, non-shifting FIFO: 5 rungs; 12 instructions
I realized I was not fair to the averaging algorithm, because three of the rungs and eight of the instructions are dedicated to calculating the averaging on my system, and that can be done with 1 rung and 1 averaging instruction in SoMachine.
 
I just confirmed that the counter in "recirculating", so that's good.

I'm keeping the counter running now, so I'm at an almost steady 73 counts / 4 Hz, which would be off in real life, but I'm running it on a cheap function generator so that may be that, I really wish it's that. WIth the reset that was 71-72, so that will surely helps.

Next step will be to manage the re-circulation between 65535 back to almost 0. Just need to make sure that the M221 understands the instruction correctly.

Then 1-3 beer(s) then straight to bed.

Then I'll add the averaging when I'm happy with the first part after I beat the code for a while.
 
Next step will be to manage the re-circulation between 65535 back to almost 0. Just need to make sure that the M221 understands the instruction correctly.
you may be able to manually place a large value like 65000 into to counter accumulator, so you don't have to wait several minutes to see the rollover.
 
I'm moving it quickly putting a 1kHz signal from the signal generator, but that's still a 1-shot deal.

I'll figure that out tomorrow, I'm beat.
 
So.

What "worked".

I'm keeping the counter running at all time and I'm dealing with the 65535 gap when it happens, works great from your example.

I'm scanning at 100 ms now, so I'm counting teeth each 100 ms, this adds stability.

First averaging:

I'm placing a reading each 100 ms in an array of 11. Each 100 ms, I'm subtracting the earliest value from the latest and divide by 10, which gives me a "dynamic" average that refreshes every 100 ms. That mostly does the job.

Second averaging:

I then place the value from previous averaging and (that's funny, I'm thinking in English to write to you guys and still my fingers types french words at random times even if I'm reciting my sentence in English, I wrote "et" instead of "and". Anyway) do a MEAN / average on the last 10 values in an array, which brings a really nice stability.

Basically, I can now get "fractions of tooth" and the multiplication won't give me large gaps anymore. It's steady enough that customer may think that the screen has frozen.

Also, going from 0 to 100 % (I mean when I push RUN at nominal on my function generator) only slows the process by less that 2 seconds, so that's decent enough since these units can take a couple minutes to many minutes to go from low to high and high to low (0-100%). This is reactive enough, that would catch an overspeed quicky enough.

But that brought other considerations. When I'm at nominal speed, or whatever speed, I still won't reach the nominal value. The reason is not known completely right now. That may be hardware, that may be the accuracy from the signal generator, that may be the scan time, that may be the fact that this is a cheap ass PLC.

Since the offset is very linear, what I did is adding a gain to adjust the speed when we reach nominal speed. That does the trick. I was something like 7% offset. Problem here is that I have auxiliaries that rely on the speed to act, that could prove tricky at some point on the first run.

That should not happen, it's just counting, but it looks like it's missing some tooth at some point.

PLC scan time was executing below 500 us and had a x gain. Then, I added in the output logic that was missing, bringing the execution time a little over 800 us. The gain wasn't right anymore, even if I'm scanning 100 times + slower than the execution time. So I readjusted the gain and it fixed the thing. So what to know here is if that even if I'm running way inside the execution time, it looks like the PLC is missing some teeth once in a while, or something sketchy is happening. This is not cool.

Then, something more came across.

I was beating the code and while doing so, I just disabled one of the probes (when both probes are enabled, I do an average between both of them). That renders 1 rung false and another true. That's it. But in that M221, that changes the execution time for whatever reason. And getting a little slower was dropping the speed by something like 1%, which is not good for an operator to see. So, execution time changing = speed is changing, which is kinda weird.

So what I did is to move the high speed counter block and the cycle timer into a periodic 1ms task, and that fixed what I was seeing. Moving all the speed detection logic in there wasn't helping though.

So now I have something decent, but I don't like having a gain to deal with since it's physics, that shouldn't do that.

Then I put in some parameters for another upcoming project where the tooth wheel has 24 teeth at the same RPM, and I'm back to jumpy again, so it's not over, not sure we'll be able to build a speed switch that does all under a M221. I could still add a feedback average when I'm around nominal but I really don't like that.

R&D budget it will be, I hope.

But thanks for the help guys!
 
I know that you probably solved your issue by now but something that could help is instead of using a timer for your sampling interval, you could create a dedicated cyclic task for that and in that task, you read the value of your high speed counter. The timing of a cyclic task is a lot more accurate than a timer that is affected by the scan of its task. That task would need to have a "higher" priority (0 is high priority 31 is low priority) to interrupt the main task.
In that task you could read the high speed counter by a function called EXPERTGetImmediateValue that refresh the counter value without waiting for the typical IO refresh cycle.

Another way to do it that would also remove the cycle time inaccuracy could be to put a setpoint to the high-speed counter and then trigger a task once that setpoint is reached. You configure the task as External and the External event would be like HSC0_TH0 for high-speed counter 0 threshold 0. Then, in that task, you only capture the timestamp with SysTimeGetUs (microsecond) or SysTimeGetNs (Nanosecond). In your normal task you could calculate the time difference between the 2 and filter it or average it.

Another way to do it is to use the high speed counter as a frequency meter:
 
I'm using a 1 ms periodic task for the counter and the cycle timer since I had problems with the PLC execution time changing when disabling / enabling stuff, while also changing the speed for whatever reason. That fixed this particular problem.

This is a M221 with Machine Expert Basic, not the same capabilities. Frequency meter @ 1 ms don't have decimal places in the reading, it's 0 Hz or 1 Hz, nothing in between.

We should be moving to a MC80 soon enough.
 
And just a side note to @dalporto , the thread seems to have shifted from Machine Expert Basic on the M221 to Machine Expert on the M241 and up.

On EcoStruxure Machine Expert Basic, some operators work on Tables (arrays). In the EcoStruxure Machine Expert - Basic online help (or PDF version) , There is the Generic Functions Library Guide. There's a chapter on Instructions on Object Tables. There are many more advanced processing that you can do with tables, indexed addressing (indirect addressing / pointer) and user-defined function/function blocks.

Regarding your initial question, here is how the MEAN function in Machine Expert Basic works:
In M221, when you have an operator with
%MF5 := MEAN(%MF10:3)
The result is written to %MF5 Floating point memory.
The average (mean) is calculate from a table of 3 elements ( :3) starting at %MF10. So it means that %MF10 , %MF12 and %MF14 are used. You can try it in the Animation table (watch table). If you type %MF10:3 , it will add %MF10, 12 and 14 to the table.

1758318756714.png
 

Similar Topics

Hi folks, I am having an issue with Schneider Electric Machine Expert (PLC: M241), I am trying to use a ST method as part of CFC (related to the...
0
Replies
1,069
Views
Buenas tardes, Necesito hacer una modificación para un proyecto existente y requiero la versión V4.4.1 de SoMachine Motion. Lamentablemente, no...
3
Replies
505
Views
Hello every body. I want to onlie with M258 plc from schneider . I have uploaded program from it with the version that program has been written ...
2
Replies
1,341
Views
Hello Everybody Anybody knows where I can get this version of SoMachine? The new machine expert version won't open my project saying there is a...
2
Replies
1,232
Views
I am trying to connect with a Schneider plc which has a firmware version only available in Somachine v4.2. In Machine expert After taking upload...
0
Replies
864
Views
Top