%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
%% rtos-ws-example.tex = template for real-time Linux workshop papers
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\documentclass[10pt,a4paper]{article}
\usepackage[english]{babel}
\usepackage{multicol}
\usepackage{isolatin1}
\usepackage[dcucite]{harvard}
\usepackage{graphicx}

\setlength{\paperheight}{297mm}
\setlength{\paperwidth}{210mm}
\setlength{\voffset}{11mm}
\setlength{\topmargin}{0mm}
\setlength{\headsep}{0mm}
\setlength{\headheight}{0mm}
\setlength{\textheight}{235mm}
\setlength{\hoffset}{-4mm}
\setlength{\textwidth}{166mm}
\setlength{\oddsidemargin}{0mm}
\setlength{\evensidemargin}{0mm}
\setlength{\marginparwidth}{0mm}
\setlength{\marginparpush}{0mm}
\setlength{\columnsep}{6mm}
\setlength{\parindent}{0mm}


%% insert eps pictures
%% use as \epsin{epsfile}{width_in_mm}{label}{caption}
\usepackage{epsfig}
\newcounter{figcounter}
\def\epsin #1#2#3#4{
\refstepcounter{figcounter} \label{#3}
\[
\mbox{
  \epsfxsize=#2mm
  \epsffile{#1.eps}
}
\]
%\vspace{0mm}
\begin{center}
  \parbox{7cm}{{\bf FIGURE \arabic{figcounter}:}\quad {\it #4 } } \\
\end{center}
}

%% insert table
%% use as \tabin{size_in_mm}{label}{caption}{table_data}
\newcounter{tabcounter}
\def\tabin #1#2#3#4{
\refstepcounter{tabcounter} \label{#2}
\[ \makebox[#1mm][c]{#4} \]
%\vspace{0mm}
\begin{center}
  \parbox{7cm}{{\bf TABLE \arabic{tabcounter}:}\quad {\it #3 } } \\
\end{center}
}

\makeindex%

\begin{document}
\pagestyle{empty}
\begin{center}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% TITLE OF PAPER (REQUIRED)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

{\Large \bf Experimental platform for proving scheduling effects over control applications. \footnotemark \\} \vspace{10mm} 

\footnotetext{This work has been supported by the European Government 
 ......... under grant ..........}
{\large
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% AUTHOR (REQUIRED)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
{\bf  J.\ Vidal}\\
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% AFFILIATION (REQUIRED)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Department of Computer Engineering Universitat Polit\`ecnica de
Val\`encia,
\\
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% STREET ADDRESS (REQUIRED)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
14 Cam\'i de Vera,   Val\`encia E-46071, Spain\\
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% E-MAIL (REQUIRED)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\{jvidal\}$@$disca.upv.es \\ }
\end{center}

\vspace{10mm}

%\tableofcontents%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% ABSTRACT (REQUIRED)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\begin{abstract}
The purpose of this work is to build a real time platform where scheduling effects over control performances can be proved.
\newline 
\textbf{Keywords}:control applications, embedded systems, real-time operating systems, Linux based systems.
\end{abstract}



\vspace{10mm}

\begin{multicols}{2}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% SECTION (REQUIRED)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Introduction}
In a previous work  \cite{Val:98}, the closed architecture of the robot arm was opened by changing the robot's computer by a PC plus some data acquisition cards, like the jr3 force sensor, an encoders reader, A/D and D/A converters. All of this was done following the electrical specifications. The architecture was transformed so the control algorithm could be changed and external sensors could be used.
But still the architecture was closed since the operating system used was Windows NT. The main disadvantages of this operating system were:

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% FIGURES ARE HANDLED LIKE THIS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\epsin{images/robot}{70}{f1}{Robot arm.}

\epsin{images/robothand}{70}{f2}{Robot arm hand.}


\begin{itemize}         
\item Very poor real time performance.
\item the scheduling policy was difficult to change.
\item There was no way of seeing what was happening in the system, i.e. tasks activations and compute time.
\end{itemize}
So, we decided to move to RT-Linux \cite{Bar:96}. Now we got completely control over the entire process from the point of view of control and real time. So, it has been built a platform where it can be tested the strong relations between real time theory and control theory. In order to show the capabilities of the system, as a control example, it has been developed an application to make the robot arm play chess.
In this hard rtos, it has been implemented the control of a robot arm, and some useful tools to investigate the effects of scheduling in control applications.
To prove the platform, a real time application has been developped. This application combines pattern recognition techniques (voice recogniton and image processing) and real time ones to make the robot arm play chess.


\section{RT-Linux in detail}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% FIGURES ARE HANDLED LIKE THIS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\epsin{images/rt-arch}{70}{f3}{RT-Linux architecture.}

The way that rtlinux achieves hard real time is through of one idea  born 
from the MERT OS implementation paradigm.The strategy was not to introduce 
changes in the in the architecture of an operating system, but to make 
coexist them .This obtaining a good performance for real time task and all 
the power of an operating system of general purpose in the same machine. 
Rtlinux takes the control over the system by building  a virtual machine 
between the hardware and Linux, emmulating the interrupts and runs Linux as 
the lowest priority thread.This  capability of running special realtime tasks 
and interrupt handlers and a standard Linux with all the power that SO same 
machine is something that we cannot avoid.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% FIGURES ARE HANDLED LIKE THIS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\epsin{images/rtlinux}{70}{f4}{RT-Linux architecture.}

 In such a way that for linux will be imposible to take control over hardware interrupts or prevent itself from being preempted, depending on rtlinux for managing it.
\subsection{Real-time tasks, Memory protection \& context switching}

In Rtlinux all threads runs in the kernel address space,that is the reason why they can accede to all the variables and functions of the kernel and calls to the linux sistems are forbidden, also run supervisor mode , what means that can execute any processor instruction and  they have access to all the I/O ports . This allows too avoid the overhead of protection level changes, improving performances and making switching easier. However,when such protection is disabled, a possible bug can appear hanging the whole system up.

As Yodaiken assert the  RT kernel does not request memory, share spin-locks, or synchronize on any
data  structures except in tightly controlled situations, being the functional design the quite robust enough  to give a suitable real time operation.

\subsection{Scheduling}
Rtlinux has an efficient, flexible, modular and compact priority-based preemptive scheduler. All the code is located mainly in two files (include\/rtl\_sched.h and schedulers\/rtl\_sched.c. The scheduling policy is as follows.the user define, through a function,  a unique priority. When   several tasks  are ready, the task with the highest priority is executed,but the first time that is execute in arrival order .A task with high priority always preempt a minor priority task  whenever it  becomes ready . Each task is supposed to relinquish the CPU voluntarily.

\subsection{Timing}

Rtlinux achieves an accurate and efficient timing, using a programmable interval timer to interrupt the CPU only when needed. The Intel 8354 timer chip present in some form in all IBM PC compatible computers is set into the interrupt-on-terminal-count mode. Using this mode, an interrupt can be scheduled with approximately 1 microsecond precision. In this scheme the overhead of interrupt processing is minimal while the timer resolution is high. However, reprogramming the 8354 timer on PCs takes a long time because the timer is not on the processor chip. Fortunately, most modern CPUs, e. g., Pentiums [ref], have timers on-chip in addition to the 8354.

\subsection{Developing control applications in RT-Linux}
Developing control applications in RT-Linux usually requires splitting the
application into two parts. Both parts can be communicated using a special
device called RT-fifos.
\begin{description}
\item Tasks with hard real-time constraints: they are programmed and executed
  as RT-tasks at kernel level.
\item Tasks with soft or no real-time constraints: they are executed as
  "conventional" Linux user processes. Unlike RT-tasks, the graphical system
  and the networking support are available for these tasks, so those parts
  of an application that need these resources have to be executed as Linux
  processes.
\end{description}
%Both parts of an application can communicate using a special device called RT-fifos. 
The execution of RT-tasks is done using the Linux facility to
dynamically load new kernel modules. RT-tasks are dynamic kernel modules. Even
RT-Linux is a set of kernel modules (scheduler, fifos, ?) that need to be
dynamically loaded.

\section{Robot arm chess player}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% the figure will be in file rt-tux.eps and will occupy 75mm on the page
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\epsin{images/rpick}{70}{f4}{Robot arm picking a piece.}

\subsection{How it works}
The basic application consists in a tcl/tk gui which controls the applications setting (reference type, controller periods, etc...) and launch a chess board so the user can make moves by picking pieces. This board communicates to the real time application side via fifos. Every time the board sends a move, a thread generates a reference for the move and other thread implementing the controller will make that the robot arm follows the reference. 
This basic application, has been completed so the user can play chess by giving oral orders. For this purpose a voice recognition application has been embedded in a biscuit PC, using RTLEAST and some voice recognition tools based in hidden markov moddels devolopped by the group of PRHLT of UPV.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% the figure will be in file rt-tux.eps and will occupy 75mm on the page
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\epsin{images/guichess}{40}{f5}{Chess GUI.}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% the figure will be in file rt-tux.eps and will occupy 75mm on the page
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\epsin{images/gui}{70}{f6}{GUI.}

\subsection{Application files distribution}
Next, the necessary files of the basic applications are listed, explaining it's function.
\begin{itemize}
\item \textit{ \textbf{robotgui.tcl}} : Application user interface developped in TCL/TK.
        \item There is one directory for each DAC, with the developed drivers \& example programs:
                \begin{itemize}
                        \item \textit{ \textbf{812}}: A/D converter.
                        \item \textit{ \textbf{833}}: Encoders.
                        \item \textit{ \textbf{6208}}: D/A converter.
                        \item \textit{ \textbf{jr3}}: Force sensor.
                \end{itemize}
\item \textit{ \textbf{rt\_to\_6208}}: User space program that allows kernel modules use 6208 Linux driver. 
\item real time modules for controlling the robot:
\begin{itemize}
\item \textit{ \textbf{controller.c}}: Controller's module having all the controllers implementations, PIDs, PIs, etc...
\item \textit{ \textbf{moves.c}}: Module containing all the different robot arm moves and trajectory generation for them.

\item \textit{ \textbf{util.c}}: module containing all the auxiliary function implementations.   
\item\textit{ \textbf{drivers.o}}: Linking real time drivers of data acquisition cards  833/833drive.o 812/pcl812.o jr3/jr3ft.o into one module.
\item\textit{ \textbf{robot.c}}: Main application module. It is listening from a FIFO user orders like moving the robot arm,switching reference type, changing controllers period or sending debugging information thorough a FIFO.
\item \textit{ \textbf{robot\_module.o}}: Final loadable application module. Composed by robot.o util.o controller.o moves.o drivers.o      

\end{itemize}
\item \textit{ \textbf{ send\_command.c}}: User space program that allows to send orders to real-time modules (robot.c) like  moving the robot arm,switching reference type, changing controllers period or debugging the application.
\item \textit{ \textbf{ debug\_controllers.c}}:User space program that allows to read information about reference, motors speeds, robot arm position, force sensor values and control actions from the real time modules.
\item \textit{ \textbf{ rtl\_sched.c}}: Modified version of the rtlinux scheduler, so it inform about task activations and execution times.     
\item \textit{ \textbf{ reader.c}}: Program that read from a fifo schedule events sent by the scheduler.
\end{itemize}
\subsection{A quick glance around the source code.}
\subsubsection{Building the drivers}
In order to make drivers in rtlinux there is a nice library, called COMEDI, with a lot of cards supported. But here, it has been programmed the driver without using COMEDI library. The reason was that it wasn't needed all the functionality of a driver and there was the source code of the two cards from others operating systems. So, we only need an automatically way of porting it to rtlinux.
\begin{itemize}
\item \textit{ \textbf{ 812}}: This is a very known and easy A/D converter. I just need some function to write voltages to the robot's motors. So the source code looks like this:
\begin{verbatim}
#include "./pcl812.h"
#include <asm/io.h>

int pcl_read_polled(
        int channel, 
        unsigned char *higher,
        unsigned char *lower
        )
{
   if ( channel < 16)
    {
      /* Read analog input */
      // Select input channel.  
      outb(channel,BASE+10); 
      /* Start an ADC conversion 
      and wait for ready */
      /* Any value causes trigger */
      outb(5,BASE+12); 
      /* Wait until data is ready */
      while((inb(BASE+5)&0x10) != 0)
           {};

      if((*higher=(inb(BASE+5)))>=16)
        /* Nothing readen */
         return (-EINVAL); 
 
      *lower=inb(BASE+4);
     }
  else if (channel==18)
    {
      /* read LSB */
      *lower=inb(BASE+6);
      /* and add the MSB */ 
      *higher=inb(BASE+7);     
    }
  else return(-ENODEV);
 
  return 0;
 
}                   
\end{verbatim}
\item \textit{ \textbf{833}}: The DOS source code for this driver is supplied by the manufacturer. So, it is only needed to port it to rtlinux. This can be done easily by adding this lines:
\begin{verbatim}
//used to adapt the driver code to LINUX.
#define  outportb(a,b) outb(b,a)
#define  inportb(a)    inb(a)    
\end{verbatim}
\item \textit{ \textbf{jr3}}:The DOS/Windows NT source code for this driver was found so we adapt it by adding the same lines and removing some O.S. specific operating system calls. 
\begin{verbatim}
//used to adapt the driver code to LINUX.
#define outpw(a,b) outw(b,a)
#define inpw(a) inw(a)
#include <asm/io.h>   
\end{verbatim}


\end{itemize}

\subsubsection{Application source code.}
The main real time application file is robot.c. In this file, it can be found
the two application threads, move\_robot and controller. The first thread is listening from a fifo. Every time the user sends a move command, the thread generates the correct references in order to make it. The second thread runs the controller that tries to achieve references established by the first thread(move\_robot\_thread).
Let's take a look to two main functions needed to move the robot: the trajectory generator and the PID controller.
\begin{itemize}
\item  \textit{ \textbf{Trajectory setting up}}:
According to the reference type (ramp, spline,scale), a different 
trajectory is generated. As a example of one of the implemented controllers, the source code the PID is listed. The fuction that implements the PID recieves as parameter the position generated each time by the trajectory generator in order to make the robot move, expressed in encoder counts for each axis. First, what is done is to initialize PID parameters and period. Next, the robot's position, speed and force is read. Then the PID equation is applied. Finally the control action is sended to the motors axis as a voltage.
\begin{verbatim}
/**********************************/
/* 
  Force sensor controller.
*/
/**********************************/
void *controller4(void *param)  
{ 
   .....
  
  // initialize PID parameters.  
  fKp_x=0.004;
  fKp_y=0.004;
  fKp_z=0.004;
  fKd_x=0.001;
  fKd_y=0.001;
  fKd_z=0.001;
  fKi_x=0.04;
  fKi_y=0.04;
  fKi_z=0.04;
  
  fKf=0.006;
  f=0.05;

  pos=*((position *)param);
  
  // initializa variables.
  Posdesitjada_X=pos.posX;
  Posdesitjada_Y=pos.posY;
  Posdesitjada_Z=pos.posZ;
  
  fPos_x=readEncoder(1);
  fPos_y=readEncoder(2);
  fPos_z=readEncoder(3);

  fVel_x=readSpeed(1);
  fVel_y=readSpeed(2);
  fVel_z=readSpeed(3);
  fFor_z=read_fs_z();

  fError_x=Posdesitjada_X-fPos_x;
  fError_y=Posdesitjada_Y-fPos_y;
  fError_z=Posdesitjada_Z-fPos_z;

  fErrAnt_x=fError_x;
  fErrAnt_y=fError_y;
  fErrAnt_z=fError_z;
  
  if (Posdesitjada_Z>0)
    {
     fTau_x=fKp_x*fError_x-fKd_x*
            fVel_x+fKi_x*
            (((fError_x+fErrAnt_x)/2)*f);
     fTau_y=fKp_y*fError_y-fKd_y*
            fVel_y+fKi_y*
            (((fError_y+fErrAnt_y)/2)*f);
     fTau_z=fKp_z*
            fError_z-fKd_z*
            fVel_z+fKi_z*
            (((fError_z+fErrAnt_z)/2)*f);
      
      fErrAnt_x=fError_x;
      fErrAnt_y=fError_y;
      fErrAnt_z=fError_z;
      
    } 
  else 
    { 
      fTau_x=fKp_x*fError_x-fKd_x*
             fVel_x+fKi_x*
             (((fError_x+fErrAnt_x)/2)*f);
      fTau_y=fKp_y*fError_y-fKd_y*
             fVel_y+fKi_y*
             (((fError_y+fErrAnt_y)/2)*f);
      fTau_z=fKf*(Posdesitjada_Z-fFor_z);
          
      fErrAnt_x=fError_x;
      fErrAnt_y=fError_y;
      fErrAnt_z=fError_z;

    }

// Control action.    
  writeTau(0,fTau_x);
  writeTau(1,fTau_y);
  writeTau(2,fTau_z);
 
   ..........

 }
\end{verbatim}
\end{itemize}
\subsection{Embedded voice recognition}
In order to make play chess by giving oral orders, an embedded voice recognition system has been developped. The software used was developped by the group of pattern recognition and human language translation at UPV. This people and it's software can be reached at \{ajuan,rparedes,evidal\}@iti.upv.es or prhlt.iti.es. 
When the application was finished, RT-LEAST was used to embed the software in a biscuit PC.
\subsubsection{Voice recognition software brief description}
More information about the software and  how to use it can be found at the above site.
\begin{itemize}
\item \textbf{aumix}: It's a basic linux mixer. It comes in most linux distributions.
\item \textbf{rawtobf:} It's a simple programm for adquiring and\/or parametrizing voice.
\item \textbf{bf2str}: This is a vectorial quantification program for parametrized voice.
\item \textbf{strclass}: This is a string classification program based in Hidden Markof Models
\end{itemize}
\subsubsection{Training}
\begin{verbatim}
#!/bin/bash

export PATH=$PATH:/usr/speech/

ITERS="0 1 2 3 4 5 6 7 8 9"

#Obtaining data; ten repetitions of each digit.
echo ``Obtaining data."
for d in $ITERS; do 
    for r in $ITERS; do
        echo $d$r
        ./raw2bf -be 0 -ee 0 
                ./mydata/DIG/$d/$d$r.raw > 
                ./mydata/DIG/$d/$d$r.bf 
done ;  done

#Obtaining a codebook of 32 codewords.
echo "Obtaining a codebook of 32 codewords."
cat ./mydata/DIG/?/??.bf | 
./bf2str -C 32 > DIG.cdbk

#Vectorial quantification.
echo "Vectorial quantification."
for d in $ITERS; do 
    for r in $ITERS; do
        echo $d$r 
        ./bf2str -c DIG.cdbk -l $d 
                 ./mydata/DIG/$d/$d$r.bf > 
                 ./mydata/DIG/$d/$d$r.str;
done ; 
    done 
        

#Training
echo "Training."
cat ./mydata/DIG/?/??.str | 
./strclass -n 20 > DIG.hmm
\end{verbatim}
\subsubsection{Classification}
\begin{verbatim}
#!/bin/bash

export PATH=$PATH:/usr/speech

#adquire a number
./raw2bf -be 25 -ee 150 -n 1 -raw aux.raw >
         /dev/null
#transform from  raw to bf.
./raw2bf -be 0 -ee 0 aux.raw > aux.bf 
#Vectorial quantification
#with the built codebook.
./bf2str -c DIG.cdbk aux.bf > aux.str 
#Classification
n=`/bin/cat aux.str | ./strclass -m DIG.hmm`
echo $n
\end{verbatim}

\section{Real time, control and embedded capabilites}
In order to experiment with the effects of scheduling over the control applications some tools has been developed. In the control side the following things has been done:
\begin{itemize}
\item Generate reference trajectories for each move.
\item Several controllers for the robot's position and force.
\item Allowing to change the reference type of the trajectory (stair,ramp or cubic spline), controller's type and period on the fly.
\item Allowing to mesure the robot's position, sensor  force, motors speed, position errors,...
\end{itemize}
\subsection{Task descomposition}
     Real time control system are usually build in two phases:
     In the first one, the regulator is designed by characterising the process and it is expected to obtain a desired response.
     In the second, the regulator is implemented in a RTOS. It may happen that the real response doesn’t match with the desired.
  
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% FIGURES ARE HANDLED LIKE THIS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\end{multicols}
\epsin{images/control}{150}{f7}{Regulator design phases.}
\begin{multicols}{2}
The reason for this, can be found in the variable delays. They produce that the control actions can't be send at equal periods of time.
 There are several  things that causes variable delays like:
\begin{itemize}
   \item  Delays in control system.
   \item  Delays due to sampling.
   \item  Delays due to the use of computational resources. Caused either by tasks computing time and high priority task interference.
\end{itemize}
A task partitioning scheme for improve the control performances reducing the variable delay (Crespo et al., 1999) . This scheme splits system priorities into three bands:
\begin{itemize}
\item The final band with the highest system priorities. 
\item The initial band with the intermediate system priorities. 
\item The main band with the lowest priorities. 
\end{itemize}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% FIGURES ARE HANDLED LIKE THIS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\epsin{images/imf}{70}{f9}{Task decomposition.}

 Following this scheme a periodic job can be split into three tasks: initial, main and final assigning a priority to each part in a the corresponding priority band. 
 Graphically, observe that for the final part an offset is added in order to execute it at same distance from activation.
 The problem with this scheme is that increases notably the tasks in the system.
 In order to solve the drawback before commented, two servers were proposed for initial and final bands with the following characteristics:
\begin{enumerate} 
\item Have a multiperiod resulting of all the tasks periods in a band
\item Execute the activities of a singular task in each activation
\item Apply the first come first served scheduling policy.
\end{enumerate} 

\subsection{Seeing what is happening: Task activation, execution times and CPU usage.}
The way in which the mesures are token is the following: Every time the scheduler makes a context switch, the time at the new process enters is annotated and the time at the old process exits from the CPU is recorded. Next, a message is sended thorough a rtlinux FIFO, indicating the thread id, the time at it reaches the CPU and the time at the thread left it. In a similar way the resume time of tasks is reported. At the other side, in user space, a user process is listening from that fifo, reading the scheduler messages. Finally a graphicall tool interprets the messages and builts a chronogram.
In a similar way, the tasks CPU usage during an interval of time is reported to the system. Bellow the scheduler code added is showed:
\epsin{images/measures}{70}{f10}{Taking measures of the tasks activation and resume times.}
\end{multicols}
\begin{verbatim} 
int rtl_schedule (void)
{
                      ..........

        for (t = sched->rtl_tasks; t; t = t->next) {
                /* expire timers */
                if (test_bit(RTL_THREAD_TIMERARMED, &t->threadflags)) {
                        if (now >= t->resume_time) {
                                clear_bit(RTL_THREAD_TIMERARMED, &t->threadflags);
                                rtl_sigaddset (&t->pending, RTL_SIGNAL_TIMER);
                                if (t->period != 0) { /* periodic */
                                        t->resume_time += t->period;
#ifdef __CPU_TRACER
                                        if (t != &sched->rtl_linux_task)
                                            rt_print_request(events,t,0,FIFO);
                                        else
                                            rt_print_request(events,t,7,FIFO);
#endif
                      ...........
                                }

                        }
                }
                
                /* and find highest priority runnable task */
                if ((t->pending & ~t->blocked) && (!new_task ||
                        (t->sched_param.sched_priority > new_task->sched_param.sched_priority))) {
                                new_task = t;
                }
        }

                      ............

        if (new_task != sched->rtl_current) { /* switch out old, switch in new */
                if (new_task ==  &sched->rtl_linux_task) {
                        rtl_make_rt_system_idle();

                } else {
                        rtl_make_rt_system_active(); 
                }

                rtl_trace2 (RTL_TRACE_SCHED_CTX_SWITCH, (long) new_task);

#ifdef __CPU_TRACER
        write_activ(sched,events,ini_time,now,FIFO);
#endif
#ifdef __CPU_USAGE
        t_u_counter[(int)sched->rtl_current->user[0]]+=now-ini_time;
#endif
#ifdef __CPU_USAGE
                {
                  int i=0;
                  hrtime_t time_diff=now-last_sample;
                  if (time_diff>=PERIOD){
                    for (i=0; i<ntasks; i++) 
                      {
                        t_usage[i]=(((t_u_counter[i]-last_t_u_counter[i])*UNIT)/time_diff); 
                        last_t_u_counter[i]=t_u_counter[i];
                      }// end for.
                    last_sample=now;
                    usage_window[sample%window_size]=t_usage[0];
                    sample++;
                  }
                }// end embedded code.
#endif
        
#ifdef __CPU_TRACER
                ini_time=now;
#endif
                rtl_switch_to(&sched->rtl_current, new_task);
                 ..........
}

\end{verbatim}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% NEXT SUBSECTION (OPTIONAL)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Embedding the voice recognition software with RTLEAST}
The RT-LEAST (Real-Time Linux Embedded \& Autonomous System
Tailoring) tool  \cite{Jos:01} has been developed in order to solve all the
issues involved in setting up of an embedded system. RT-LEAST is a
graphical tool able to tailoring a large set of embedded systems
in an easy manner. There are three basic steps involved in setting
up an embedded system:
\begin{itemize}
        \item Building the execution support.
           \begin{itemize}
            \item Customizing a kernel.
            \item Building the root file system.
           \end{itemize}        
        \item Configuring  the root file system and boot devices.
        \item  Set-up of the embedded PC.
\end{itemize}

\subsubsection{Building a file system}
The idea of profiles allows developing the system
in a modular and flexible way. The main goal is to create a file
system made up of modules. Depending on the services needed, different
packages can be installed. In order to run the embedded voice recognition applications
are needed the minimum profile for booting and basic execution support and the network profile to allow redirecting the user interface to another HOST and provide telnet access to the embedded PC. 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% FIGURES ARE HANDLED LIKE THIS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\epsin{images/prof}{70}{f14}{Combining profiles incrementally.}

In table 1 there are shown the required profiles according to the
application needs. 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% TABLES ARE FORMATTED LIKE THIS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\tabin{75}{tbl:t1}{Embedded system requirements.}{}
\begin{small}
\begin{tabular}{||l|l||}
\hline
\hline
\bf{Processor} & 386 or up * \\
\hline
\hline
\bf{RAM} & 4 Mb or up \\
\hline
\hline
\multicolumn{2}{||l||}{\bf{Boot device} (one of the next)} \\
\hline 
\hline
\multicolumn{2}{||l||}{Network card with bootp } \\
\hline
\multicolumn{2}{||l||}{temporal connection floppy disk  } \\
\hline
\multicolumn{2}{||l||}{No volatile memory } \\
\hline
\multicolumn{2}{||l||}{(Serial port)} \\
\hline
\hline
\multicolumn{2}{||c||}{\bf{File system capacity} } \\
\hline
\hline
Minimal real time execution support & 114 Kb \\
\hline
\hline
Modular real time execution support & (+) 600 Kb \\
\hline
Network & (+) 430 Kb \\
\hline
On site admin-utilities & (+) 600 Kb \\
\hline
On site debugging  & (+)  3.3 Mb \\
\hline
Java 2 Micro-edition & (+)     2 Mb \\
\hline
Java standard & (+)   25 Mb \\
\hline
\hline
\end{tabular}
\end{small}
\subsubsection{Configuring  the root file system and boot devices}
The embedded PC that make the voice recognition can be configured so it boots using the bootp protocol and places the run-time environment into the RAM memory. To do that, the RT-LEAST tool will configure the host machine so it acts as a boot server for the embedded machine. Next, it will adapt the root file system so it works in RAM disk and will patch the kernel so it uses the RAM disk as the root file system. Finally, it will construct a file that contains the run-time environment, i.e.: the kernel plus the root file system. This file will be transferred through the network when the embedded machine boots, thus providing a quickly and hardware independent way of installing the root-time environment to the embedded system, as shown in fig. 7.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% FIGURES ARE HANDLED LIKE THIS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% the figure will be in file rt-tux.eps and will occupy 75mm on the page
\begin{figure}
%\vspace*{5cm}
\centering \epsfig{file=./images/netboot, width=7cm}
%\epsfig{file=netboot, width=70mm}
%\includegraphics{netboot}
\caption{Network booting.}
\label{f1}
\end{figure}

\subsubsection{Set-up of the embedded PC.}
Once the voice recognition application has been developed it is compressed into a tar+gzip file. This compressed file will contain a script that will make the necessary actions to configure and load the application. Then, it will be customized the embedded PC operating system image according to our example using the RT-LEAST tool. First it will be chosen the precompiled kernel offered by RT-LEAST that supports RT-Linux, the bootp protocol and ram-disk file system. Second the file system will be tailored using the minimum and network's profiles plus the control application.
Next the RT-LEAST tool will configure the embedded operating system image so
it boots from network with the bootp  protocol and for allocating the file
system on RAM. Also RT-LEAST will configure the HOST so it acts as a bootp
server for our embedded machine (fig. 8). Finally the embedded machine is powered on and the operating system image will be transferred from the HOST to the
embedded machine by the tftp protocol. When the operating system image is
loaded the control application is launch and will begin the voice recognition. The operator will receive information of what it happens on the HOST by
redirecting the user interface and the monitoring application. 

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% FIGURES ARE HANDLED LIKE THIS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\epsin{images/netbootdisk}{60}{f15}{ Set-up of the embedded PC with RT-LEAST.}

\section{Results}
\subsection{Task decomposition}
 In order to show the improvems in control applications introduced by the task decomposition, the Z axis position error while the robot arm is picking a piece has been test following three approaches: 
\begin{enumerate}
\item  Desired response in design phase ( Experiment 1, blue line). 
\item  Real response with variable delays in implementation phase ( Experiment 2, red line). 
\item  Integration phase: IMF  task decomposition applied to the set of task ( Experiment 3, green line).
\end {enumerate}
The results are showed in figure 11. In this plot, it can observed that the IMF decomposition is the approach that most follows the desired response, reducing the position error. While the real response without applaing the task decomposition increases the position error.


\epsin{images/imfplot}{70}{f16}{Task decomposition improvements.}

\subsection{Controlling the use of CPU by rtlinux threads.}
\epsin{images/usage2}{70}{f16}{Task CPU usage measure.}
\begin{verbatim}
void usage_PI_ctrl(long long usage,unsigned long ref, int ntasks,pthread_t threads[],hrtime_t t_usage[]){
                      .............  
  if (iter>15)
    {
  // calculate error.
  E=(double)((ref-usage)/100*1000);
  
  // PI.
  U=(double)(U_bef+ (double)(1.1*E) - (double)(0.99*E_bef));

  period=(long long)(((double)((6*100*1000)/U))*1000*1000);

  // Apply new periods.
  for (i=1;i<ntasks;i++)
    if (period>1*1000*1000) threads[i]->period= period;

  //finally actualize U_bef and E_bef.
  E_bef=E;
  U_bef=usage;
    }
  iter++;
}
\end{verbatim}
\begin{multicols}{2}

\subsection{Embedding industrial applications.}     
It has been shown rtlinux as a free, portable, powerful, tailor-able, open source platform in order to implement industrial applications on embedded systems. 
It has been tailored Linux to fit it in embedded system, developing useful tools and techniques for control applications. The control of a robot arm via voice recognition been implemented to expose with an example the possibilities of Linux/rtlinux in embedded systems. 
 Finally, RT-LEAST tool has been developed in order to deal with all the installation issues. This tool makes easy configuring and setting up an embedded system, automatically tailoring Linux to a great variety of embedded devices and making an efficient use of the available resources.


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% REFERENCES (REQUIRED)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


\bibliography{paper}
\bibliographystyle{plain}

\end{multicols}
\end{document}
 
