# Syntax for writing functions in function blocks

151 views

I would like to ask you about how to write functions in function blocks. The manual explains that it follows the C syntax. But it is not clear how.

I want to use a function block to calculate the angle between variables dq. I tried to write the function this way but it is not adequate. It divides by zero, and that is what I try to avoid by using relational and logical operators, but I do not know how to write it.

(abs(u[2]) > 0.01) * ((asin(u[1]/u[2])) * (180/pi))

Thanks

Juan

The syntax is C-like, but all the expressions are evaluated.  Therefore you will still get a divide by zero if the u[2] denominator is zero.  Therefore one has to correct the denominator of the function directly.

Since you're using an asin() function for variables in the DQ reference frame, then the denominator should be the magnitude u[2]=sqrt(d2 + q2), u[2] >= 0, and u[1] >= u[2].  Therefore, using a max() function would be appropriate here, per eq1 below.

However, there still could be some floating-point accuracy issues and the argument to asin(x) might be x>1 or x <-1 .  It would be even better to ensure that error does not happen, per eqn 2.

`eq1: (180/pi) * asin( u[1]/max(u[2],1e-6)  )`
`eq2: (180/pi) * asin( min(1, max(-1, u[1]/max(u[2],1e-6) )))`

answered Aug 16 by (2,023 points)
Thanks Bryan, very useful. Do you know if more operations can be added to the function? To make more complex operations, do I have to separate the operations with commas?
Thanks again,

Regards

Juan
You can always perform additional calculations by performing more arithmetic or inner terms to function calls.  The commas are there for min(x,y) functions, as noted in the component documentation.

For more complex calculations one can use additional blocks, cascade multiple function blocks, or use the C-Script block from the PLECS component library.
Thanks Bryan