add bigger mtask example
[msc-thesis1617.git] / mtaskext.examples.tex
1 As an example for the bytecode compilation the following listing shows the
2 thermostat example given in Listing~\ref{lst:exmtask} compiled to bytecode.
3 The left column indicates the position in the program memory.
4
5 \begin{lstlisting}[caption={Thermostat bytecode},language=c]
6 1-2 : BCAnalogRead (Analog A0)
7 3-6 : BCPush (Int 50)
8 7 : BCGre
9 8-9 : BCJmpF 17 //Jump to else
10 10-12: BCPush (Bool 1)
11 13-14: BCDigitalWrite (Digital D0)
12 15-16: BCJmp 21 //Jump to endif
13 17-19: BCPush (Bool 0) //Else label
14 20 : BCDigitalWrite (Digital D0)
15 21 : //Endif label
16 \end{lstlisting}
17
18 The factorial function can be expressed as an \gls{mTask}-\gls{Task} and uses
19 the \CI{sds} and the \CI{return} functionality. Typically this \gls{Task} is
20 called with the \CI{OnInterval} scheduling strategy and will calculate the
21 factorial after which is will return. The following listings shows the actual
22 \gls{mTask} and the generated messages followed by the actual bytecode in a
23 readable form.
24
25 \begin{lstlisting}[caption={Faculty as an \gls{mTask}-\gls{Task}}]
26 factorial :: Int -> Main (ByteCode () Stmt)
27 factorial i = sds \y=i In
28 namedsds \x=1 Named "result" In
29 {main =
30 IF (y <=. lit 1) (
31 pub x :. retrn
32 ) (
33 x =. x *. y :. y =. y -. lit 1
34 )}
35
36 //Generating the actual messages with:
37 //toMessages (OnInterval 500) (factorial 5) zero
38 //[MTSds 2 (BCValue 5), MTSds 1 (BCValue 1), MTTask (OnInterval 500) ...]
39 \end{lstlisting}
40
41 \begin{lstlisting}[label={lst:actualbc},%
42 caption={The resulting bytecode for the factorial function},language=c]
43 0-2 : BCSdsFetch 1
44 3-6 : BCPush i\d0\d1
45 7 : BCLeq
46 8-9 : BCJmpF 16 //Jump to else
47 10-12: BCSdsPublish 2 ("result")
48 13 : BCReturn
49 14-15: BCJmp 37 //Jump to endif
50 16-18: BCSdsFetch 2 ("result") //Else label
51 19-21: BCSdsFetch 1
52 22 : BCMul
53 23-25: BCSdsStore 2 ("result")
54 26-28: BCSdsFetch 1
55 29-32: BCPush i\d0\d1
56 33 : BCSub
57 34-36: BCSdsStore 1
58 37 : //Endif label
59 \end{lstlisting}