update
[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={Factorial 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 Start = fst $ toMessages (OnInterval 500) (factorial 5) zero
38
39 //The output will be
40 //[MTSds 2 (BCValue 5), MTSds 1 (BCValue 1), MTTask (OnInterval 500) ...]
41 \end{lstlisting}
42
43 \begin{lstlisting}[label={lst:actualbc},%
44 caption={The resulting bytecode for the factorial function},language=C]
45 0-2 : BCSdsFetch 1
46 3-6 : BCPush (Int 1)
47 7 : BCLeq
48 8-9 : BCJmpF 16 //Jump to else
49 10-12: BCSdsPublish 2 ("result")
50 13 : BCReturn
51 14-15: BCJmp 37 //Jump to endif
52 16-18: BCSdsFetch 2 ("result") //Else label
53 19-21: BCSdsFetch 1
54 22 : BCMul
55 23-25: BCSdsStore 2 ("result")
56 26-28: BCSdsFetch 1
57 29-32: BCPush (Int 1)
58 33 : BCSub
59 34-36: BCSdsStore 1
60 37 : //Endif label
61 \end{lstlisting}