Skip to main content

PWM Light Control - Ver. 2

Loading...

Here is another version of the PWM Light Control Project. It does exactly the same thing as the one in the previous effort. The difference is in the use of the Custom Function block. The block may contain multiple lines of formulas and other code.

To view the code, click the Custom Function block to open its properties. To do this with more comfort, click the Expand icon:

pwm_light_icon

Here is the code:

pwm_light_function_code

The code inside the Custom Function block must be written in Tibbo BASIC. What you are editing here is the body of a Tibbo BASIC function. You are even supposed to give this function a name.

Since Tibbo BASIC is very similar to other versions of the BASIC language, and since most Tibbo BASIC math formulas look completely "natural," it will be easy for you to learn how to pack complex calculations into custom functions. Here is what the output Tibbo BASIC code looks like:

function pwm_calculation() as float
time_point_distance=time2-time1
if time_point_distance<0 then time_point_distance= time_point_distance+86400
traveled_distance=current_time-time1
if traveled_distance<0 then traveled_distance=traveled_distance+86400
pwm_calculation=level1+(traveled_distance/time_point_distance)*(level2-level1)
end function

In the above "printout," only the first and last lines are auto-generated. The user is responsible for all the code inside the function. The name of the function is explicitly defined by the user, and the function type is determined automatically from the type of the variable the result is assigned to. For example, in this project, the assignment is x=pwm_calculation(), where x is a number (float). Based on this, the system determines that the function shall also return a number (float).

The Custom Function block allows you to further reduce the total number of blocks in the project. Compared to the previous version, which required 25 blocks (17 if you excluded Debug Print blocks), this new incarnation only takes 12 blocks (11 if we disregard printing). Small flow diagrams often look better than large ones!

To be fair, the block count reduction in this project wasn't achieved solely through Custom Functions. Another decluttering step was to print all items within a single Debug Print block. Check out the block contents to see how this was done.