\chapter{Automatic Gearbox} \label{chap:automatic_gearbox}

\section{Solution Study} \label{sec:solution_study}

The original AtlasCar vehicle is equipped with a fully manual, five speed plus reverse transmission, which is still the most common type of transmission in Portugal. This system presents some important advantages for the driver. A manual transmission  allows the driver to have more control on the driving, improving the behaviour of the car during high speed turns, or even avoiding unexpected and dangerous situations. It is also known for making the driving process more efficient in what concerns the engine fuel consumption, even when compared against more modern, electronically controlled transmissions available in the market \cite{An Overview of Current Automatic}.

Although this system presents more advantages for a human driver, it brings some new challenges and problems when the control needs to be made by a computer or a machine. The ideal approach would be to use an automatic transmission system compatible with the current engine model. Unfortunately, this solution turned out to be impossible because there were no available automatic transmissions for the engine model currently installed in the AtlasCar prototype. Although an automatic transmission was available for the 1600 $cm^{3}$ engine, there was no such system compatible with the 1400 $cm^{3}$ engine, which is the one present in the AtlasCar vehicle. A drastic measure, like changing the engine itself, would also not be feasible because of all the changes and adaptations already made on the engine and mentioned in Section \ref{sec:the_atlas_project}, like the electronic accelerator or the second alternator. In order to keep the car as unchanged as possible, it was clear that the current fully manual transmission system should be used, with all the necessary adaptations to automatically actuate it. Given the situation, the most reasonable approach to use the current transmission would be to control the position of the gear lever, in the same manner a human driver controls it. A mechanical system, projected and built prior to the beginning of this work, was intended to do just this. This mechanism is represented in Figure \ref{figure:gear_selector_mechanism}.

\begin{figure}[h!]
\centering
\epsfig{file=Images/gear_selector_mechanism.eps,width=140mm}
\caption[Gear Selector Mechanism.]{Atlascar gear selector mechanism.}
\label{figure:gear_selector_mechanism}
\end{figure}

This gear selector mechanism had already been built several months earlier, and a first attempt to control it was made during the previous term. This first attempt resorted to limit switches placed at some key points in the mechanism, in order to determine the current position of the lever, and to drive it to the next. The system was driven by a Microchip PIC. The AtlasCar control PC would calculate the direction the gear should shift, and it would communicate this order, via TCP/IP, directly to the AtlasCar PLC. The PLC would then communicate with the PIC on the gearbox mechanism controller, and the micro-controller program would decide which movements to make in order to change to the requested gear.

This method has proven to be very prone to failure, and brought  some expected and unexpected problems. The PIC programming written using limit switches was made in a purely sequential mode. To make the system memorize every path possible from each point to the another would originate a rigid and complex code. Another problem is that the control type made using only limiting switches is a bang bang with dead band control, which is not the most indicated for high responsibility applications, such as a vehicle automatic gearbox, because the control system would not know the position of the gear lever at all times. The switches also presented some issues: they jammed frequently, got run over by the DC motors, they easily got out of their mounting places and the repetitive movements of the system caused the signal wires to break from their respective leads.

The electronic circuits used to drive the DC motors in this early version had also some issues. The system was divided into three separate printed circuit boards: two individual H-bridges to drive each one of the DC motors, and one signal board used to hold the Microchip PIC, and its auxiliary circuitry. The H-bridges power circuit often overheated, and turned out not being stable enough to mount permanently on the vehicle, where they would be subjected to both vibration and heat, in a much more heavy-duty environment than the laboratory.

Another main issue presented in this first system was its difficult tuning at the moment of being placed in the AtlasCar prototype. Mounting each one of the switches on its correct position would be difficult and very time consuming. Any recalibration of the system would also take hours of effort, and should be executed by someone very knowledgeable of both the mechanical system and its programming. Due to all these known issues, this solution was abandoned.

Most recently, some important changes took place in the AtlasCar project. The most important of these changes was the migration from the previous CARMEN based system, to the new ROS architecture, which simplified many of the complexities present in the previous and limited CARMEN system. ROS significantly improved and simplified the interprocess communication, and the constantly updated drivers and libraries, available on-line, are very helpful for those working with both hardware and software in the robotics field.

It was also decided to free the Programmable Logic Controller, a Siemens SIMATIC S7-1200 shown in Figure \ref{figure:plc_siemens}, which is AtlasCar's current Engine Control Unit (ECU), of some of its previous tasks. Any change on the PLC software is not easily made, because the Siemens TIA Portal proprietary software must be used. Another known issue associated with a big PLC code is the decreased TCP/IP communication frequency, which is currently performed at about 10 Hz.

According to the ROS philosophy, the big systems should be subdivided into many simpler subsystems, each one running their own simpler processes. All these subsystems should constantly exchange data between them via a solid interprocess communication system.

\begin{figure}[h!]
\centering
\epsfig{file=Images/SIEMENS_PLC_AtlasCar.eps,width=50mm}
\caption[Siemens SIMATIC S7-1200 PLC]{Siemens SIMATIC S7-1200, used as the AtlasCar Engine Control Unit (ECU) \cite{Siemens PLC}.}
\label{figure:plc_siemens}
\end{figure}

All these profound changes also affected the way in which a new gear selection system would be built. The most important change on the original project was the implementation of two multi-turn potentiometers to accurately measure the position of the lever in real-time, one for each motor. The other main change was the decision to use an \textit{Arduino} instead of a Microchip PIC, to handle all the control logic of the system. Although they are not as powerful as the Microchip PIC systems, the \textit{Arduino} boards are cheap, well tested and robust enough for this kind of simpler applications.

The high modularity of the \textit{Arduino} system also brings another advantage: with small and cheap hardware modifications, big changes in the communication system can be achieved. For example, the communication process between the \textit{Arduino} and the PC can be changed simply by replacing or adding a "Shield", and writing a few more code lines on the \textit{Arduino} code in order to use it. The fact that the \textit{Arduino} is already integrated in a board alongside with all its auxiliary circuitry, eliminates the need to design another new expensive PCB, print it, solder it and debug it, in order to have the platform for the micro-controller. Similarly to what happens in the case of ROS, there is also a very active, open source community constantly developing, using and testing software or hardware solutions and applications for the \textit{Arduino}. This constant development results in both helpful up-to-date libraries to handle specific hardware systems, and the on-line support to use them correctly.

Some communications changes were also implemented in this new gear system. Instead of a TCP/IP communication between the controlling PC and the PLC, and then a digitally coded message between the PLC and the gear selector mechanism PIC, the new communication process is made directly via TCP/IP with the \textit{Arduino} micro-controller, using an \textit{Arduino} Ethernet "Shield". A server is run on the Ethernet "Shield", while a client is running on a ROS node in the AtlasCar controlling PC. This client only needs to communicate to the \textit{Arduino} server the number of the new gear. The use of an Ethernet "Shield" is necessary because the AtlasCar prototype is a very electrically noisy environment, due to all the sensors, cameras and power actuators working at the same time. The \textit{Arduino} default communication port, a Serial USB port, is also not recommended for longer distances, such as the ones that will be required at the time of mounting the system on the vehicle.

In what concerns the power control of the DC motors, instead of using custom made H-bridges' printed circuit boards, a commercial automotive H-bridge integrated circuit is used. This simplifies the system because instead of a three custom made PCB system (one for each DC motor, and one for the controller), only one shield-like PCB would be used to drive both DC motors. The following Sections give a detailed description and explanation about each of the above subjects.

\section{Mechanical System} \label{sec:mechanical_system}

The original AtlasCar gear selector mechanical system, shown in Figure \ref{figure:gear_selector_mechanism} allows the movement of a metal ring in a two dimensional, horizontal plane. The gear lever is inserted in this metal ring, and the conjugation of vertical and horizontal movements allow it to drive the lever to the correct position, according to the gear desired.

The movement of the positioning ring is obtained using the combined movements of two 12 V DC motors. As the DC motors have a good rotational speed, but can not develop high torques by themselves, each one of these motors is mechanically connected to a 104:1 planetary gearbox, in order to achieve the necessary torque specifications required to move the gear lever.

The system also uses a set of toothed belts and pulleys, attached to their respective shafts. The use of toothed belts, instead of more rigid power transmission systems like worm gears, is justified to prevent the catastrophic situation of control loss over the motors. If the motors start, for some unexpected reason, moving uncontrollably, the belts will simply skip pulley teeth, and the car's transmission system, namely the lever and the vehicle's mechanism below it, will not suffer any relevant damage.

The only large modification made to this initial system was increasing the length of two of the shafts, in order to place multi-turn potentiometers. The potentiometers are coupled using two double aluminium screw couplers. Initially, a metal, possibly aluminium, potentiometers' fixation system was thought, but such rigid structure would not allow the potentiometer to perform small movements during the rotation of the shaft, in order to compensate possible misalignments between the shaft of the potentiometer and the pulley shafts, since this is an addition to the original project. The solution adopted was to use two acrylic potentiometer supports, bolted to the surface of the gear selector mechanism, which allows the fixation system to be more flexible, thus prolonging the lifetime of the potentiometers.

\section{Control System} \label{sec:control_system}

As referred at the beginning of this Chapter, in order to drive both DC motors in the gear selector mechanism, an \textit{Arduino} "Shield" was built. Actually, this "Shield" is responsible for handling the following four tasks:

\begin{itemize}
	\item Controlling the DC motors;
	\item Reading the analogue input from both multi-turn potentiometers;
	\item Reading the MAN/AUTO switches;
	\item Controlling the Seven Segment Display.
\end{itemize}

Each one of these subsystems will be described in detail in the following Subsections.

\subsection{DC Motor Controller} \label{subsec:dc_motor_controller}

The DC motor controller used for the purpose is a commercial fully integrated H-Bridge circuit, the VNH3SP30-E, which comes in a MultiPowerSO-30 package \cite{VNH3SP30-E}, as shown in Figure \ref{figure:VNH3SP30-E}. This H-bridge allows a maximum output current of 30 A and 40 V of maximum supply voltage. This integrated circuit also has integrated protection circuitry, making it easy to use and robust enough for automotive purposes, such as required for the task at hand. In order to drive each of these integrated circuits, the following signal pins must be connected to the \textit{Arduino}:

\begin{itemize}
	\item One Pulse Width Modulation (PWM) input for the duty cycle square wave;
	\item Two digital inputs for controlling the DC motor rotation sense;
	\item Two enable/diagnostic pins;
\end{itemize}

There is a big limitation on the number of available pins in the \textit{Arduino} UNO, specially if an Ethernet "Shield" is used. In order to save some \textit{Arduino} I/O pins, the two "enable/diagnostic" pins of each H-bridge can stay always active, thus always connected directly to the 5 V, since the motors can still be easily stopped if the duty cycle is set to 0\%. The motors can even be locked to Ground if both In$_{A}$ and In$_{B}$ are set to a LOW state. Both these measures would reduce the \textit{Arduino} pins needed to drive each H-bridge to only three: the PWM pin, and the two rotation sense pins. There is still the need for reducing the number of pins needed, in order for the \textit{Arduino} to perform all the above tasks.

\begin{figure}[h!]
\centering
\subfloat[]{\includegraphics[width=3cm]{Images/VNH_TOP.eps}}
\qquad
\qquad
\subfloat[]{\includegraphics[width=3cm]{Images/VNH_BOTTOM.eps}}
\caption[VNH3SP30-E Package]{VNH3SP30-E top (a) and bottom (b) view. Note the three heat slugs on the bottom view of the Integrated Circuit, used to conduct the high currents allowed by this Integrated Circuit.}
\label{figure:VNH3SP30-E}
\end{figure}

The solution found was to decode two of the \textit{Arduino} output pins, in order to control four bits, using a 1-of-4 decoder/demultiplexer. The use of this decoder is only possible because the motors only need to operate one at a time, since the trajectories travelled along the gear selector are always in vertical or horizontal straight lines.

\begin{figure}[h!]
\centering
\epsfig{file=Images/4555decoder.eps,width=40mm}
\caption[4555 Functional Diagram]{4555 Functional Diagram.}
\label{figure:4555functional}
\end{figure}

The decoder selected to decode the \textit{Arduino} pins, and consequently to select the direction in which the motors should turn was the HEF4555 \cite{4555B}. As shown in Figure \ref{figure:4555functional}, this decoder needs only three input bits to drive four output bits. In fact this integrated circuit has two 1-of-4 decoders included, but only half of the circuit is used in the scope of this work. The input pins are the normally closed $Enable$, the $A0$ and the $A1$. The four output pins are $Q3$, $Q2$, $Q1$ and $Q0$. The truth table for this particular decoder is represented in Table \ref{table:4555_truth_table}, where the output pins' response to input pins combinations can be observed.

\renewcommand{\arraystretch}{1.1}
\begin{table}[h!]
\centering
\begin{tabular}{|c|c|c|c|c|c|c|}
\hline
\multicolumn{3}{|c|}{\textbf{INPUTS}} & \multicolumn{4}{c|}{\textbf{OUTPUTS}} \\
\hline
\textbf{$\overline{\text{E}}$} & \textbf{A1} & \textbf{A0} & \textbf{Q3} & \textbf{Q2} & \textbf{Q1} & \textbf{Q0} \\ 
\hline
0 & 0 & 0 & 0 & 0 & 0 & 1 \\
\hline
0 & 0 & 1 & 0 & 0 & 1 & 0 \\
\hline
0 & 1 & 0 & 0 & 1 & 0 & 0 \\
\hline
0 & 1 & 1 & 1 & 0 & 0 & 0 \\
\hline
1 & X & X & 0 & 0 & 0 & 0 \\
\hline
\end{tabular}  
\caption{The 4555 decoder Truth Table.}
\label{table:4555_truth_table}
\end{table}
\renewcommand{\arraystretch}{1}

These measures reduce the number of \textit{Arduino} pins needed for driving both H-bridges to only five:

\begin{enumerate}
	\item One PWM output for the duty cycle wave of Motor 1;
	\item One PWM output for the duty cycle wave of Motor 2;
	\item One digital pin to drive the decoder pin A0;
	\item One digital pin to drive the decoder pin A1;
	\item One digital pin to enable the decoder.
\end{enumerate}

\subsection{Analogue value from the Potentiometers} \label{subsec:analogue_value_from_potentiometers}

As referred above, the \textit{Arduino} needs to read the analogue value from both two potentiometers. The potentiometers used in the system to read the axis angle are the wire-wound Model 533 from Vishay Spectrol \cite{Model 533}, depicted in Figure \ref{figure:multiturn_pot}. During the whole physically possible path of the gear selector system, the measured axis angle is of about $450^{\circ}$, so the use of a three turn potentiometer is enough for this purpose.

\begin{figure}[h!]
\centering
\epsfig{file=Images/multiturn_pot.eps,width=60mm}
\caption[Vishay Spectrol Mutiturn Wirewound Potentiometer]{Vishay Spectrol Mutiturn Wirewound Potentiometer \cite{RS Components}}
\label{figure:multiturn_pot}
\end{figure}

The \textit{Arduino}'s analogue input pins read values ranging from 0 to 1023, corresponding to a voltage level ranging from 0 V to 5 V, respectively. That would be the interval read from those inputs if the whole extent of the potentiometer's coil was used, which corresponds to $1080^{\circ}$ in the axis. As the angle is only of approximately $450^{\circ}$, the voltage interval perceived by the analogue inputs can easily be calculated, as shown in Equation \ref{eq:available_interval}:

\begin{equation}
\label{eq:available_interval}
Voltage\_Interval = \dfrac{450^{\circ}}{1080^{\circ}} \times 5 = 2.083(3) \hspace{5 mm} [\text{V}]
\end{equation}

From which the sensibility of the potentiometer system can also be calculated, as shown in Equation \ref{eq:pot_resolution}:

\begin{equation}
\label{eq:pot_resolution}
Sensibility=\dfrac{2.083(3)}{450^{\circ}} \approx 4.62 \hspace{5 mm} [\text{mV}/\circ]
\end{equation}

This means that variations of almost a degree are considered by the \textit{Arduino} analogue inputs, which is more than enough for the gear system.

In what concerns to the pins needed to read the two analogue values, each one of these potentiometers needs three independent connections:
\begin{itemize}
\item The 5 V pin;
\item The Groung (GND) pin;
\item The Output Signal pin;
\end{itemize}

Only the Output Signal pin is connected to the \textit{Arduino}, so both potentiometers occupy two analogue inputs.

\subsection{Manual/Automatic Switches} \label{subsec:manual_automatic_switches}

The system can be switched by the user from two available running modes:

\begin{itemize}
\item Manual Mode;
\item Automatic Mode.
\end{itemize}

Each one of these modes will be explained in detail on Sub-subsection \ref{subsec:manual_automatic_switches}. It consists of a three-button system of an adapted Renault M�gane audio pad:

\begin{itemize}
\item Gear UP Button: Sends a pulse to increment the current gear, when the system is running on Manual mode. This signal is ignored when the system is running on Automatic mode. This button is ignored when the system is moving from one gear to another.;
\item Gear DOWN Button: Sends a pulse to decrement the current gear, when the system is running on Manual mode. This signal is also ignored when the system is running on Automatic mode. This button is also ignored when the system is moving from one gear to another.;
\item Man/Auto Button: This signal changes the system's running mode, and is active both in Manual or Automatic modes. This button is also ignored when the system is moving from one gear to another.
\end{itemize}

\begin{figure}[h!]
\centering
\epsfig{file=Images/gear_pad.eps,width=100mm}
\caption[Renaul M�gane adapted audio pad.]{Renaul M�gane adapted audio pad.}
\label{figure:megane_gear_pad}
\end{figure}

Each one of these buttons uses an \textit{Arduino} pin, so it occupies three additional digital inputs.

\subsection{Seven Segment display} \label{subsec:seven_segment_display}

In order for the user to see the current gear the car is running on, a simple seven segment display was added to the system \cite{Vishay 7_Seg}. This seven segment display always represents the current gear, the car being on Automatic or Manual mode. As the number of \textit{Arduino} pins is very limited, a BCD to Seven Segment decoder was used, specifically the 7447 BCD to 7-Segment Decoder/Driver. This decoder uses four normally LOW input bits to drive seven output bits, used to directly drive the Seven Segment common anode display \cite{DM7447A}.

There is no need to use all the input combinations allowed by the decoder. In the AtlasCar gear system, there are only seven possible fixed positions, corresponding to the 6 gears and the neutral. Using only three of the BCD Driver's four input pins $a$, $b$ and $c$, it is possible to display the eight integer numbers from 0 to 7, as shown in Figure \ref{figure:sevensegmentdigits}. Table \ref{table:display_meanings} shows the meaning of each one of the numbers appearing in the Seven Segment display.

\begin{figure}[h!]
\centering
\begin{tikzpicture}[scale=0.75]
    \tikzstyle SSGOn=[red,line width=5pt]
    \tikzstyle SSGOff=[gray!20!white,line width=5pt]
    \foreach \x in{0,...,3} {
        \coordinate (L\x) at({(\x-0)*2.5} ,-3*1);
        \SSGNb{L\x}{\x}
    }
    \foreach \x in{4,...,7} {
        \coordinate (L\x) at({(\x-4)*2.5} ,-3*2);
        \SSGNb{L\x}{\x}
    }
\end{tikzpicture}
\caption{Seven Segment Display used digits.}
\label{figure:sevensegmentdigits}
\end{figure}

\begin{table}[h!]
\centering
\begin{tabular}{|c|c|}
\hline
\textbf{Display Digit} & \textbf{Meaning}\\
\hline
0 & Neutral\\
\hline
1 & First Gear\\
\hline
2 & Second Gear\\
\hline
3 & Third Gear\\
\hline
4 & Fourth Gear\\
\hline
5 & Fifth Gear\\
\hline
6 & Reverse Gear\\
\hline
7 & System in a moving state\\
\hline
\end{tabular}
\caption{Display Number Meanings}
\label{table:display_meanings}
\end{table}

The final 7-Segment display was assembled using a circuit prototyping board, and is depicted in Figure \ref{figure:7_segment_board}.

\begin{figure}[h!]
\centering
\epsfig{file=Images/7_Segment_Display.eps,width=95mm}
\caption[7-Segment Display Final Board.]{7-Segment Display final board.}
\label{figure:7_segment_board}
\end{figure}

\subsection{Printed Circuit Board} \label{subsec:printed_circuit_board}

After the definition of all the control board functions it is possible to precise the number of \textit{Arduino} input and output pins in order to build the final Control Printed Circuit Board. Table \ref{table:AvailablePins} shows all the final \textit{Arduino} pin functions, and Figure \ref{figure:arduino_uno_pins} shows the actual location and layout of these used pins in the \textit{Arduino} UNO board.

\begin{figure}[h!]
\centering
\epsfig{file=Images/arduino_uno_pins.eps,width=120mm}
\caption[\textit{Arduino} UNO]{\textit{Arduino} UNO and the available pins' functions used for this project.}
\label{figure:arduino_uno_pins}
\end{figure}

\begin{table}[h!]
\centering
\begin{tabular}{|c|c|c|c|c|c|}
\hline
  & Pins & \textit{Arduino} UNO & Ethernet "Shield" & Used For & I/O \\
\hline
\multirow{8}*{\rotatebox{90}{Digital IO}}
  & 0 & \textcolor{red}{RX}     & \textcolor{red}{RX}   & - & - \\
\cline{2-6}
  & 1 & \textcolor{red}{TX}     & \textcolor{red}{RX}   & - & - \\
\cline{2-6}
  & 2 & \textcolor{blue}{FREE}  & \textcolor{blue}{FREE} & Encoder Bit A0 & Output \\
\cline{2-6}
  & 4 & \textcolor{blue}{FREE}  & \textcolor{red}{SDCS}  & - & - \\
\cline{2-6}
  & 7 & \textcolor{blue}{FREE}  & \textcolor{blue}{FREE} & Encoder ENABLE & Output \\
\cline{2-6}
  & 8 & \textcolor{blue}{FREE}  & \textcolor{blue}{FREE} & MAN/AUTO Select & Input \\
\cline{2-6}
  & 12 & \textcolor{blue}{FREE} & \textcolor{red}{SPI}   & - & - \\
\cline{2-6}
  & 13 & \textcolor{blue}{FREE} & \textcolor{red}{SPI}   & - & - \\
\hline
\multirow{6}*{\rotatebox{90}{PWM}}
  & 3 & \textcolor{blue}{FREE}  & \textcolor{blue}{FREE} & Encoder Bit A1 & Output \\
\cline{2-6}
  & 5 & \textcolor{blue}{FREE}  & \textcolor{blue}{FREE} & PWM Motor 2 & Output \\
\cline{2-6}
  & 6 & \textcolor{blue}{FREE}  & \textcolor{blue}{FREE} & PWM Motor 1 & Output \\
\cline{2-6}
  & 9 & \textcolor{blue}{FREE}  & \textcolor{blue}{FREE} & MAN/AUTO Gear Up & Input \\
\cline{2-6}
  & 10 & \textcolor{blue}{FREE} & \textcolor{red}{ETHCS} & - & - \\
\cline{2-6}
  & 11 & \textcolor{blue}{FREE} & \textcolor{red}{ETHCS} & - & - \\
\hline
\multirow{6}*{\rotatebox{90}{Analogue Input}}
  & A0 & \textcolor{blue}{FREE} & \textcolor{blue}{FREE} & Potentiometer 1 & Input \\
\cline{2-6}
  & A1 & \textcolor{blue}{FREE} & \textcolor{blue}{FREE} & Potentiometer 2 & Input \\
\cline{2-6}
  & A2 & \textcolor{blue}{FREE} & \textcolor{blue}{FREE} & MAN/AUTO Gear Down & Input \\
\cline{2-6}
  & A3 & \textcolor{blue}{FREE} & \textcolor{blue}{FREE} & 7-Seg Bit A & Output \\
\cline{2-6}
  & A4 & \textcolor{blue}{FREE} & \textcolor{blue}{FREE} & 7-Seg Bit B & Output \\
\cline{2-6}
  & A5 & \textcolor{blue}{FREE} & \textcolor{blue}{FREE} & 7-Seg Bit C & Output \\
\hline
\end{tabular}
\caption{Available \textit{Arduino} Pins}
\label{table:AvailablePins}
\end{table}

The most important part of the printed circuit board is the power circuit, where the two H-bridges manage the electric current in order to drive the DC motors. According to the VNH3SP30-E H-bridge driver datasheet, some external protective circuitry should be used, in addition to the protective circuitry already included in the Integrated Circuit itself. The most important measure is the inclusion of a N-channel MOSFET connected to the Ground pin. This action protects the H-bridge against being connected in reverse to the car battery.

Other measure taken to prevent voltage peaks in the circuit, is the use of a zenner diode per H-bridge, so that the maximum voltage of the MOSFET gate pad is never exceeded.

An 8 A fuse is also used in the power source cables for the H-bridges. Because the circuit is directly connected to the AtlasCar vehicle battery, the fuse is used to prevent the circuit from possible high current peaks provoked by accidental short circuits.

The projected printed circuit board also contains a connection to an Emergency Stop, placed directly on the power source cables. This button allows the user to completely shut down the power part of the circuit, leaving only the signal systems still functioning.

Another common and recurrent problem in this kind of electronic applications is the electrical noise. In order to protect the circuit from the electrically noisy environment present in the AtlasCar vehicle, two capacitors were also added to filter the power voltage supply of the H-bridges:

\begin{itemize}
\item A 470\text{$\mu$}F electrolytic capacitor to withstand sudden voltage drops;
\item A 100nF ceramic capacitor to filter high frequency noise.
\end{itemize}

The signal coming from the potentiometers has been proven to be very stable. However, and due to the inevitable proximity between the potentiometers' analogue signal cables and the DC motors, a low-pass, first order, passive filter is also used in the analogue potentiometer input pins, to attenuate possible high frequency noise.

All the necessary pull-down or pull-up resistors were placed on the necessary digital input and output pins, to avoid problems with random fluctuations on the digital signals. All the vertical connectors, which allow the Printed Circuit Board to be inserted on the \textit{Arduino} are carefully aligned with its respective pins, to facilitate the coupling the DC motor control "Shield" and the \textit{Arduino}.

\begin{figure}[h!]
\centering
\epsfig{file=Images/PCB_3D_MODEL.eps,width=100mm}
\caption[Partial PCB 3D model]{Partial PCB 3D model, created using EAGLE 3D.}
\label{figure:pcb_3d_model}
\end{figure}

After considering all these details and electric protections, a circuit was projected using the EAGLE PCB Design software. Both layers of the final PCB drawing can be seen in Figure \ref{fig:top_bottom_pcb_layers}, and a full scale representation of each layer can be seen in the Annexes. The layout of the components in the Printed Circuit Board was carefully defined, with particular attention paid to the width of the pathways, given the considerably high currents passing through the circuit. EAGLE 3D was also used during the project process to obtain a partial representation of the final board, as depicted in Figure \ref{figure:pcb_3d_model}. The final printed circuit board, after the soldering of all its components, is represented in Figure \ref{figure:soldered_pcb}, and the complete system is represented in Figure \ref{figure:complete_system}.

\begin{figure}[h!]
\centering
\subfloat[]{\includegraphics[width=6cm]{Images/DC_MOTOR_CONTROLLER_TOP.eps}}
\subfloat[]{\includegraphics[width=6cm]{Images/DC_MOTOR_CONTROLLER_BOTTOM.eps}}
\caption[Printed Circuit Board]{Printed Circuit Board Top (a) and Bottom (b) layers. The image has been scaled to fit on the page, but the real scale image can be consulted on the Annexes.}
\label{fig:top_bottom_pcb_layers}
\end{figure}

\begin{figure}[h!]
\centering
\epsfig{file=Images/pcb_soldered.eps,width=100mm}
\caption[Final Motor Controller PCB.]{Final version of the Motor Controller Printed Circuit Board.}
\label{figure:soldered_pcb}
\end{figure}

\begin{figure}[h!]
\centering
\epsfig{file=Images/GENERAL_SYSTEM.eps,width=125mm}
\caption[Complete gear selector system]{Complete gear selector system. The second potentiometer is hidden below the metal surface. The \textit{Arduino}, and the respective Ethernet Shield are both positioned below the DC Motor Controller PCB.}
\label{figure:complete_system}
\end{figure}

\FloatBarrier

\section{Arduino Programming} \label{sec:arduino_programming}

The \textit{Arduino} has two types of internal cycles: the \textit{setup} and the \textit{loop}. The \textit{setup} cycle runs only once when the \textit{Arduino} resets, or each time a TCP/IP or Serial connection is successfully established. This cycle is used to set connection parameters and run some initial routines, prior to the main program itself. The \textit{loop} cycle runs in a continuous loop, and is where the main program is located. Both these cycles will be explained in the following Subsections.

\subsection{The \textit{Setup} Cycle} \label{subsec:the_setup_cycle}

The gearbox \textit{setup} cycle is used to start the communication processes, specifically the Ethernet Server which must be continuously running on the \textit{Arduino}. The \textit{setup} is also used to define the working mode of certain \textit{Arduino} pins, according to their function. For example, in order to use the ADC (Analogue to Digital Converter) which is available on the \textit{Arduino} to allow the use of certain analogue pins as digital ones, their mode must be defined here, in the \textit{setup} cycle.

This \textit{setup} cycle is also used to put the car in a neutral position. This is an extra safety measure to avoid any problems while starting up all the ATLASCAR systems, like the case of the clutch not being pressed at the time of the ignition. A representative flowchart of the described functions of the \textit{setup} cycle can be seen in Figure \ref{figure:setup_flowchart}.

% Define block styles
\tikzstyle{decision} = [diamond, draw, fill=white, text width=4.5em, text badly centered, node distance=5cm, inner sep=5pt]
\tikzstyle{block} = [rectangle, draw, fill=white, text width=10em, text centered, minimum height=3em,node distance=2.5cm]
\tikzstyle{line} = [draw, -latex']
\tikzstyle{cloud} = [draw, ellipse,fill=red!20, node distance=3cm, minimum height=2em]
\begin{figure}[h!]
\centering
\begin{tikzpicture}[node distance = 2cm, auto,scale=0.5]
    % Place nodes
    \node [block] (init) {Arduino Reset};
    \node [block, below of=init] (start_ethernet) {Start Ethernet};
    \node [block, below of=start_ethernet] (read_vertical) {Read Vertical Potentiometer Value};
    \node [block, below of=read_vertical] (move_vertical) {Move Vertical DC Motor};
    \node [decision, right of=move_vertical] (check_1) {Vertically Centered?};
    \node [block, below of=check_1] (read_horizontal) {Read Horizontal Potentiometer Value};
    \node [block, below of=read_horizontal] (move_horizontal) {Move Horizontal DC Motor};
    \node [decision, right of=move_horizontal] (check_2) {Horizontally Centered?};
    \node [block, below of=check_2] (loop) {Enter Loop};
    % Place Lines
    \path [line] (init) -- (start_ethernet);
    \path [line] (start_ethernet) -- (read_vertical);
    \path [line] (read_vertical) -- (move_vertical);
    \path [line] (move_vertical) -- (check_1);
    \path [line] (check_1) |- node [near start] {No} (read_vertical);
    \path [line] (check_1) -- node {Yes} (read_horizontal);
    \path [line] (read_horizontal) -- (move_horizontal);
    \path [line] (move_horizontal) -- (check_2);
    \path [line] (check_2) |- node [near start] {No} (read_horizontal);
    \path [line] (check_2) -- node {Yes} (loop);
\end{tikzpicture}
\caption[Flowchart for the $setup$ cycle.]{Flowchart for the $setup$ cycle.}
\label{figure:setup_flowchart}
\end{figure}

\subsection{The \textit{Loop} Cycle} \label{subsec:the_loop_cycle}

The \textit{Arduino loop} is used to run the \textit{Arduino} program that really controls the gear selector mechanism. During this cycle, the necessary \textit{Arduino} inputs and outputs are sequentially scanned and made active or inactive, according to the case at hand and the programmed orders.

As mentioned above, the AtlasCar gearbox is a common H-pattern transmission. To make the program as robust and flexible as possible, the use of a sequential gearbox is to be avoided, especially because the long shifting times inherent to the vehicle actuator's physical mechanism itself. In order to make this, the mechanism must compare the current gear with the gear asked by the control PC and, if necessary, execute the appropriate movements to obey and successfully execute that command.

Figure \ref{figure:gear_layout} represents the layout of the gear positions present in the AtlasCar.
% \matrix[column sep=20mm] {

\begin{figure}[h!]
\centering
\subfloat[]{
\begin{tikzpicture}[line width=3pt]]

% Define the points:
\path (0,0) node (P0_2) {$N$};
\path (-2cm,0) node (P0_1) {$N$};
\path (2cm,0) node (P0_3) {$N$};
\path (-2cm,2cm) node (P1) {$1^{st}$};
\path (-2cm,-2cm) node (P2) {$2^{nd}$};
\path (0cm,2cm) node (P3) {$3^{rd}$};
\path (0cm,-2cm) node (P4) {$4^{th}$};
\path (2cm,2cm) node (P5) {$5^{th}$};
\path (2cm,-2cm) node (PR) {$R$};
% Draw the system
\draw (P0_1) -- (P0_2) -- (P0_3);
\draw (P1) -- (P0_1) -- (P2);
\draw (P3) -- (P0_2) -- (P4);
\draw (P5) -- (P0_3) -- (PR);
\end{tikzpicture}
}

\subfloat[]{
\begin{tikzpicture}[line width=3pt]]
%\tikzstyle{every node}=[draw,shape=circle (1cm)]
\path (0,0) node (P0_2) {$5$} ;
\path (-2cm,0) node (P0_1) {$4$};
\path (2cm,0) node (P0_3) {$6$};
\path (-2cm,2cm) node (P1) {$1$};
\path (-2cm,-2cm) node (P2) {$7$};
\path (0cm,2cm) node (P3) {$2$};
\path (0cm,-2cm) node (P4) {$8$};
\path (2cm,2cm) node (P5) {$3$};
\path (2cm,-2cm) node (PR) {$9$};
% Draw the system
\draw (P0_1) -- (P0_2) -- (P0_3);
\draw (P1) -- (P0_1) -- (P2);
\draw (P3) -- (P0_2) -- (P4);
\draw (P5) -- (P0_3) -- (PR);
\end{tikzpicture}
}
\caption[Layout for the Gear positions.]{Layout for the Gear positions (a) and the respective numbering used for the \textit{Arduino} programming (b).}
\label{figure:gear_layout}
\end{figure}

In terms of control, there's the need to analyse this system to determine its interest points, as well as the possible paths to connect those points between them. A good way to get a mathematical model for the gear positions layout is to use some concepts of the graph theory. Although Figure \ref{figure:gear_layout} is already a graph by itself, the classic graph representative of the system is shown in Figure \ref{figure:system_graph}, which shows all the physically possible paths connecting each lever position.

At this point the system can be mathematically modelled, and a solution to determine the path needed to go from point A, which represents the current gear of the system, to point B, which represents the next gear, asked by the computer or the user, can be found.

There are several methods for computing and determining the solution for a problem which is commonly known as the                  "Shortest Path Problem".

\begin{figure}[h!]
\centering
\begin{tikzpicture}[scale=0.5]
	\tikzstyle{every node}=[draw,shape=circle]
	
  \node (n1) at (1,4)  {1};
  \node (n2) at (13,8) {2};
  \node (n3) at (17,8) {3};
  \node (n4) at (5,4)  {4};
  \node (n5) at (9,6)  {5};
  \node (n6) at (13,6) {6};
  \node (n7) at (9,2)  {7};
  \node (n8) at (13,4) {8};
  \node (n9) at (17,4) {9};

  \foreach \from/\to in {n1/n4,n4/n5,n4/n7,n5/n2,n5/n6,n5/n8,n6/n3,n6/n9}
    \draw (\from) -- (\to);

\end{tikzpicture}
\caption[Gear Positions Graph]{Graph representative of the gear positions and the physically possible paths between them.}
\label{figure:system_graph}
\end{figure}

In the situation at hand, the system goes under a particular case of the "Shortest Path Problem", which is called the single-source shortest path problem. The most commonly used algorithms to solve this particular case of the "Shortest Path Problem", and the ones that were considered in this work to solve it are:

\begin{itemize}
\item The Bellman-Ford algorithm;
\item The Dijkstra's algorithm;
\item The A* search algorithm.
\end{itemize}

All these algorithms are based on possible paths organized according to a pre-attributed weight, so that the algorithm can choose one path instead of another one, in the case there are several paths between two nodes belonging to the same graph.

The Bellman-Ford algorithm is used when these path weights can assume negative values. There is no need to use the Bellman-Ford algorithm, because the weights of each path of the gear system, used later to compute the shortest and most interesting path to follow, are never negative in the system at hand. Given the simplicity of the graph, and the need for a fast and simple method, capable of running efficiently on the limited processing capabilities of the \textit{Arduino}. There is also no need to use a more complex algorithm such as the A* search algorithm. This algorithm is an extension of the Dijkstra's algorithm, but it uses heuristic processes to achieve better performance, especially in what concerns to the computing time of large graph systems. These heuristic functions define the order in which the algorithm will compute each point. The system at hand is not complex enough to justify the use of this search algorithm.

Dijkstra's algorithm has shown to be the best candidate to solve this problem, and to do so in a fast way. The Dijkstra's algorithm requires the construction of a cost/adjacency matrix, representative of the graph, that the algorithm uses as a criteria to determine the shortest path between a given pair of points. For this particular system, the cost matrix M is shown in \ref{eq:cost_matrix}. The numbering used to build this matrix is the one present in Figure \ref{figure:gear_layout}, so the first column represents the first node, the second column represents the second node, and so on. The same happens with the numbering of the matrix rows.

\begin{equation}
M = \begin{bmatrix}
  5 & 5 & 5 & 1 & 5 & 5 & 5 & 5 & 5\\
  5 & 5 & 5 & 5 & 1 & 5 & 5 & 5 & 5\\
  5 & 5 & 5 & 5 & 5 & 1 & 5 & 5 & 5\\
  1 & 5 & 5 & 5 & 0 & 5 & 1 & 5 & 5\\
  5 & 1 & 5 & 0 & 5 & 0 & 5 & 1 & 5\\
  5 & 5 & 1 & 5 & 0 & 5 & 5 & 5 & 1\\
  5 & 5 & 5 & 1 & 5 & 5 & 5 & 5 & 5\\
  5 & 5 & 5 & 5 & 1 & 5 & 5 & 5 & 5\\
  5 & 5 & 5 & 5 & 5 & 1 & 5 & 5 & 5
\end{bmatrix}
\label{eq:cost_matrix}
\end{equation}


Each connected path assumes a cost of $1$ or $0$, respectively vertical or horizontal paths. This difference between the cost values is due to the necessity of distinguishing between vertical and horizontal paths, allowing this to be done using the same matrix to represent both the adjacency between nodes and the cost of the paths linking them. The longest path that can be travelled by the gear lever is from point 1 to point 9 and vice versa (which corresponds to the shifting from a first gear to a reverse), or the path from point 3 to point 7 and vice versa (which corresponds to the transition from a fifth gear to a second gear). The cost associated with the longest path is four, so every impossible path existing in the system will take a cost value greater than three(two paths with a 0 cost, and two paths with a 1 cost), so the impossible paths are set as being fives.

During the calibration process of the mechanism, a table is constructed with the horizontal potentiometer's values of the points 1, 2 and 3, and the vertical potentiometer's values of the points 1, 4 and 7. These values are defined at the beginning of the \textit{Arduino} code, so that the user can easily change them if necessary. The user can also define an admissible error interval for each one of the directions. These intervals are used to determine the current location of the gear lever, because the analogue values read from the potentiometers, and corresponding to a stationary position, have small fluctuations and vary overtime. When the lever is being positioned at a given point, the nominal values are used, but when determining the current gear lever position, both an $x$ and $y$ interval, in the vicinity of the nominal point, is considered admissible.

As soon as a new gear value is requested, and only if that value is in the interval $[0,6]$, the program checks its current position, and determines the corresponding point. Then it calculates the corresponding point of the requested gear. Next, the Dijkstra's algorithm, running in the \textit{Arduino}, takes as inputs the matrix M, the current point and the requested gear's point. The output of the function is a path vector containing all it's points, including the beginning and the end points.

Next, the system distinguishes vertical from horizontal paths, using the values from the matrix M. A value of 0 stands for horizontal paths, and 1 corresponds to vertical paths. The Dijkstra's algorithm function builds the transitions vector. If the path vector has $n$ elements, this transitions vector has $n-1$ elements. The transitions vector is the one responsible for determining which motor should move to execute the linear trajectory desired. Following this operation, a correction is made to both the path and the transitions vectors, so that the motor movements do not stop at each passing point.

The following example is useful to understand this problem. If the user asks a reduction from the 1$^{st}$ gear to the Reverse gear, the corresponding path vector would be the following, using the numeration from Figure \ref{figure:gear_layout}:

\begin{equation}
Path = \begin{bmatrix}
1 & 4 & 5 & 6 & 9
\end{bmatrix}
\label{eq:path_vector}
\end{equation}

And the corresponding Transitions vector is the following, admitting that the horizontal paths are represented by 0 and vertical paths are represented by 1, as referred above:

\begin{equation}
Transitions=\begin{bmatrix}
1 & 0 & 0 & 1
\end{bmatrix}
\label{eq:transitions_vector}
\end{equation}

If these vectors were used directly to drive the motors, the horizontal motor would stop when reaching the point number $5$, and then would accelerate again to reach point $6$. This would delay the mechanical system's response even more, because these stops are unnecessary. According to the referred correction, the corrected transition vector is:

\begin{equation}
Transitions_{corrected}=\begin{bmatrix}
1 & 0 & 1
\end{bmatrix}
\label{eq:transitions_corrected_vector}
\end{equation}

Then, the corrected path vector is calculated, and differs from the first one in point number $5$:

\begin{equation}
Path_{corrected}=\begin{bmatrix}
1 & 4 & 6 & 9
\end{bmatrix}
\label{eq:path_corrected_vector}
\end{equation}

At this stage, both vectors are ready to drive the motors. As depicted in Figure \ref{figure:motor_layout}, Motor 1 is responsible for the $y$ direction, and Motor 2 is responsible for the $x$ direction. The directions, represented by arrows in Figure \ref{figure:motor_layout}, show the positive increment of both potentiometer's values.

\begin{figure}[h!]
\centering
\epsfig{file=Images/orientationScheme.eps,width=120mm}
\caption[Orientation and Motor layout of the gear selector mechanism]{Orientation and layout of the gear selector mechanism.}
\label{figure:motor_layout}
\end{figure}

A \textit{for} cycle travels across the Transitions vector to determine which motor must move. Inside each cycle run, the system computes the direction in which the chosen motor must turn, using the values in the corrected Path vector. According to the numeration adopted, and depicted in Figure \ref{figure:gear_layout}, if the current point is greater than the next point, the motor must turn in one direction, and if the current point is smaller than the next point, the motor must turn in the opposite direction. This process becomes even simpler because each motor is represented by a C++ class, and this class already contains direct commands to make each motor turn clockwise or counter-clockwise, as desired.

An acceleration and deceleration ramp, similar to the one depicted in Figure \ref{figure:ramp_graphs} is also calculated according to the path each motor must travel. The function that calculates this ramp is given the starting and the ending potentiometer values, as well as the minimum and maximum PWM values. These PWM values are outputs from the \textit{Arduino}, and range from 0 to 255, which correspond to 0\% and 100\% motor duty cycle, respectively. The minimum, non-zero PWM value is necessary, because a zero starting value would lead the motors to a premature stop, prior to reaching the required position. Tests performed in laboratory on these DC motors showed that any duty cycle below 20\% was ineffective and the motors remained still. If the acceleration ramp began at zero, the system would assume that the motors were still in motion and it would continue indefinitely to impose the physically impossible interpolated PWM value.

\begin{figure}[h!]
\centering
\epsfig{file=Images/graph_ramps.eps,width=140mm}
\caption[Motor Acceleration and Deceleration Ramp]{Parametrizable acceleration and deceleration ramps for the motor PWM value.}
\label{figure:ramp_graphs}
\end{figure}

These ramps are necessary not just because they make the movements of the gear selector mechanism softer and more fluid, but because it is also a good practice to use this kind of approach to relieve the DC motors from current peaks and drastic accelerations, thus prolonging their lifetime.

After calculating the acceleration and deceleration ramps, the program enters a while cycle, in which the correspondent potentiometer analogue value is monitored, and the interpolated PWM value is imposed to the respective motor. This procedure is repeated until all the paths in the corrected Path vector are successfully travelled.

The process described above is common to both Automatic and Manual modes, but there are some differences between these two modes in what concerns to the behaviour of the mechanism. Sub-subsections \ref{subsubsec:the_manual_mode} and \ref{subsubsec:the_automatic_mode} describe in detail each one of these running modes.

\subsubsection{The Manual Mode} \label{subsubsec:the_manual_mode}

The Manual mode is implemented as a purely sequential gearbox mode, and is controlled directly by the \textit{Arduino} and the user. This control is possible using the \textit{Renault M�gane} adapted sound pad, presented in Figure \ref{figure:megane_gear_pad}. All the logic is controlled by the \textit{Arduino}, and the communication between the \textit{Arduino} and the PC is mono-directional; this means the \textit{Arduino} only communicates via TCP/IP the current gear of the car, and ignores any information coming from the control PC.

This sequential gearbox can only execute the shifting in the following order, without any possibility of skipping any of the steps, and without any possibility of going from the last position to the first ($5^{th}$ gear to $Reverse$) and vice-versa ($Reverse$ to $5^{th}$ gear):

\begin{center}
$ Reverse \longleftrightarrow Neutral \longleftrightarrow 1^{st} \longleftrightarrow 2^{nd} \longleftrightarrow 3^{rd} \longleftrightarrow 4^{th} \longleftrightarrow 5^{th} $
\end{center}

The $5^{th} \longleftrightarrow Reverse$ transition is not allowed in this mode, not only because it is a dangerous manoeuvre which makes no sense in normal car usage, but also because the AtlasCar gearbox does not mechanically allow this direct operation. The original manual gear system, currently installed in the car, is protected against this situation, since the user must at least bring the gear lever to a central $Neutral$ position before any attempt of forcing a $Reverse$, after a $5^{th}$ gear.

The user can also, and at any time while the mechanism is in a stationary state, change between modes using the MAN/AUTO switching button, also available on the described button pad.

\subsubsection{The Automatic Mode} \label{subsubsec:the_automatic_mode}

The Automatic mode is implemented in the form of a traditional H-pattern gearbox. The user has no direct control over the shifting process, and can only switch mode using the MAN/AUTO switching button, when the gear selector mechanism is at a stationary state. When in Automatic mode, the communication between the \textit{Arduino} and the PC is bidirectional: the \textit{Arduino} sends the current gear of the car to the controlling PC, and the PC can set the value of the next gear.

The Automatic mode is not sequential. The \textit{Arduino} constantly checks if a gear shifting is needed by comparing the current gear lever position with the gear asked by the PC, and it is able to calculate the next position from the previous one and execute it, using the methods described in Subsection \ref{subsec:the_loop_cycle}. The non-sequentiality can be useful during later project stages of the AtlasCar software and hardware development, widening the window of real world situations that could get an appropriate response from the gear selector mechanism.

\subsection{Communication Protocol} \label{subsec:communication_protocol}

The communication between the \textit{Arduino} and the PC is performed using an Ethernet \textit{Arduino} "Shield", similar to the one represented in Figure \ref{figure:eth_shield}. There is an Ethernet class available on the \textit{Arduino} website, which has available a complete set of useful communication functions to use the Ethernet "Shield".

\begin{figure}[h!]
\centering
\epsfig{file=Images/ArduinoEthernetShield.eps,width=80mm}
\caption[\textit{Arduino} Ethernet "Shield"]{\textit{Arduino} Ethernet "Shield" \cite{Arduino}.}
\label{figure:eth_shield}
\end{figure}

A simple, yet complete communication message system was defined to monitor the state or to set gears on the gear selector mechanism. The communication process with the \textit{Arduino} is an "Answer to Question" type, as the server running in the \textit{Arduino} only generates an answer if the client, running on the control PC, requests it. This communication process is used because it allows the higher level systems to constantly monitor the device, and take the necessary measures if, for some reason, the device stops responding to the commands sent. There are two main distinct message types:

\begin{itemize}
\item PC $\rightarrow$ \textit{Arduino}: This message is the simplest, and its only purpose is to set a car gear or to read the current state of the gear selector mechanism;
\item \textit{Arduino} $\rightarrow$ PC: This message is more complex, because it is able to give accurate and real-time information about the current state of the gear selector mechanism.
\end{itemize}

These message types will be described in detail in the next Sub-subsections.

\subsubsection{Pc to Arduino Messages} \label{subsubsec:pc_to_arduino_messages}

The message going from the control PC to the \textit{Arduino} has the following format:

\begin{center}
<STX> \textit{opcode} \textit{value} <ETX>
\end{center}

The possible \textit{opcode} strings coming on this message, and their corresponding meanings, are represented in Table \ref{table:comm_pc_arduino}. The \textit{opcode} is not case sensitive, and the valid \textit{value} is an integer number in the interval $[0,6]$.

\begin{table}[h!]
\centering
\begin{tabular}{|c|p{6cm}|}
\hline
\textbf{\emph{opcode} string} & \textbf{Message Meaning} \\ 
\hline
\emph{SG} & Sets a gear in the gear selector mechanism. The \emph{value} is not ignored in this case, and is used as the value of the gear to set. \\ 
\hline
\emph{GG} & Gets the value of the current gear of the car. The \emph{value} is ignored, if existent. \\
\hline
\end{tabular}  
\caption{Communication codes from the control PC to the \textit{Arduino}.}
\label{table:comm_pc_arduino}
\end{table}

\subsubsection{Arduino to Pc Messages} \label{subsubsec:arduinoto_pc_messages}

There are three main message types coming from the \textit{Arduino} to the PC:

\begin{itemize}
\item Answer to a "Set" command;
\item Answer to a "Get" command;
\item Unrecognised command message.
\end{itemize}

The first message type is used to answer to a "Set" message coming from the PC. The structure of this message is the following:

\begin{center}
<STX>a sg \textit{message\_code} <ETX>
\end{center}

The character "a" at the beginning of the message informs that it is an "Answer" message from the \textit{Arduino}. The "sg" string indicates that the answer is made to a "Set" command. These message elements are all separated by spaces, except the \textit{Start of Text} character and the "a", at the beginning of the message. Table \ref{table:comm_arduino_pc_stationary} shows the possible characters sent inside the \textit{message\_code} field, as well as their respective meanings.

\begin{table}[h!]
\centering
\begin{tabular}{|c|p{6cm}|}
\hline
\textbf{\emph{message\_code} character} & \textbf{Message Meaning} \\ 
\hline
\emph{i} & Indicates that the gear asked is invalid, i.e. not belonging to the integer interval $[0;6]$. For security reasons, the \textit{Arduino} always checks the validity of the gear sent by the PC. \\
\hline
\emph{m} & Indicates that the computer tries to set a gear while the system is in manual mode. The set operation is only allowed in automatic mode.\\
\hline
\emph{o} & Indicates that the system is already at the asked gear. The "o" stands for "OK". \\
\hline
\end{tabular}  
\caption[Communication codes from the \textit{Arduino} to the control PC]{Communication codes from the \textit{Arduino} to the control PC - Stationary State.}
\label{table:comm_arduino_pc_stationary}
\end{table}

The second message type is used to answer to a "Get" command sent from the control PC. This message has two different formats, which can be used to determine if the mechanism is moving or stopped at a certain gear. In the case the system is moving from a gear to another, the message has the following format:

\begin{center}
<STX>a gg c \textit{previous\_gear} - \textit{next\_gear} <ETX>
\end{center}

The "a" at the beginning of the message informs that it is an "Answer" message from the \textit{Arduino}. The "gg" string indicates that the answer is made to a "Get" command. The "c" character stands for "Changing". The \textit{previous\_gear} field indicates the gear from where the system is moving, and the \textit{next\_gear} field indicates the gear number the system is moving to. These message elements are all separated by spaces, except the \textit{Start of Text} character and the "a" at the beginning of the message. The purpose of this message is to let the computer or the higher level software know that the system is in motion and not in an error state.

If the system is currently stopped at a certain gear, the message sent to the control PC is the following:

\begin{center}
<STX>a gg a \textit{current\_gear} <ETX>
\end{center}

Similarly to what happens in the previous message, the "a" at the beginning of the message informs that it is an "Answer" message from the \textit{Arduino}, and the "gg" string indicates that the answer is made to a "Get" command. The "a" character, next to the "gg" string, stands for "Actual". The \textit{current\_gear} field contains the number of the selector system's current gear. All the message elements are separated by spaces, except the \textit{Start of Text} character and the first "a" character.

The last message type is an error message generated whenever a message arriving to the \textit{Arduino} is unrecognised, or written with a wrong syntax. This message presents the following format:

\begin{center}
<STX>a u <ETX>
\end{center}

Once again, the message starts with an "a" character, informing that it consists of an "Answer" message from the \textit{Arduino}. The "u" character stands for "Unrecognised".

\section{The Calibration Software} \label{subsec:the_calibration_software}

As said in Subsection \ref{sec:arduino_programming}, the gear selector mechanism needs to be calibrated prior to its usage, to make the firmware memorize the necessary potentiometers' values to define completely the points on the H-pattern, depicted in Figure \ref{figure:gear_layout}, and execute the desired gear changes effectively. This process normally consists on the following steps:

\begin{enumerate}
\item Connection between the \textit{Arduino} and the PC;
\item Compilation and transferring the calibration program into the \textit{Arduino};
\item Monitoring the Serial port and taking note of the \textit{x} and \textit{y} potentiometer's values for each necessary point;
\item Redefinition of each point on the \textit{Arduino} gear changing program, by direct code edition;
\item Compilation and transferring the gear changing program into the \textit{Arduino}.
\end{enumerate}

Although there has been the care to simplify this calibration process by defining these potentiometers' values in a very clear way at the beginning of the \textit{Arduino} code, along with the respective comments informing about the meaning of each value, some difficulties may still arise. A user less familiarized with the \textit{Arduino} programming language or some technical characteristics of the gear selector mechanism may not be able to calibrate it successfully, especially if an axis direction diagram, like the one depicted in Figure \ref{figure:motor_layout}, is not available. The above steps may also be of difficult execution at the time of mounting the gear selector mechanism in the car. Step number 2 is especially demanding in what concerns to the user attention and to the stability of the connection, both affected by the \textit{in-loco} calibration, as the mechanism needs to be on its final position on the car in order to perform the calibration correctly.

To allow the simplification of the calibration process described, a calibration software was created, along with a simple Graphical User Interface to use it. In what concerns to the calibrator programming, it is divided in two distinct processes that fork at the time the program is launched:

\begin{itemize}
\item The parent process, which is responsible for the Graphical User Interface;
\item The child process, which is responsible for the communications process.
\end{itemize}

The following Subsections explain in detail the operation of each of these processes.

\subsection{The Calibrator Graphical User Interface}

The calibrator parent process launches the Graphical User Interface and manages its button callbacks and the necessary functions. The Graphical User Interface used in this project was built using GLADE, which is a programming language-independent graphical user interface builder for GTK+ \cite{GTK}. All the code necessary for the handling of events, like clicking on a button or updating a text box, is written in this part of the program, as GLADE only produces a XML file containing the Graphical User Interface appearance. This file is loaded and the events are bound to its corresponding callback functions at the time of launching the program. The Calibrator Graphical User Interface can be seen in Figure \ref{figure:calibrator_gui}.

\begin{figure}[h!]
\centering
\epsfig{file=Images/calibrator_gui.eps,width=120mm}
\caption{Gear Selector Mechanism Calibrator GUI.}
\label{figure:calibrator_gui}
\end{figure}

Although the Graphical User Interface is very simple and self explanatory, the meaning of each of its fields and elements is explained in detail, according to the numeration in Figure \ref{figure:calibrator_gui}:

\begin{enumerate}
\item The \textit{Y VALUE} text box $\rightarrow$ This text box displays the current y-axis' potentiometer value. This value is constantly updated directly from the \textit{Arduino}, using the calibration software written for this purpose;
\item The \textit{X VALUE} text box $\rightarrow$ This text box displays the current x-axis' potentiometer value. This value is also constantly updated using direct information from the \textit{Arduino};
\item The \textit{Memorize Point} buttons $\rightarrow$ These buttons store the information on the text boxes inside internal variables when the user presses them. During the calibration process, the user must place the gear lever on the corresponding point position, and click on each of these buttons in order to memorize the necessary point;
\item The \textit{CALIBRATE} button $\rightarrow$ When clicked, this button automatically generates the \textit{Arduino} code, with the new calibrated values, in the same folder where the program is being executed;
\item The \textit{Points to Memorize} Figure $\rightarrow$ This figure is not interactive, and it is only placed on the calibrator program for the user to be aware of the equivalence between the point numbering used in the \textit{Arduino}, and its positions on the H-pattern used in the AtlasCar gear lever.
\end{enumerate}

When the calibration process is terminated, the calibrator program must be closed and the file recently created, named \textit{ARDUINO\_MOTOR\_CONTROLLER.pde}, must be transferred to the \textit{Arduino} in order to start the Gear Selector Mechanism program.

\subsection{The Calibrator Communication Process}

The child process, running in parallel to the Graphical User Interface is in charge of the communication process between the PC and the \textit{Arduino}. The communication protocol used to calibrate the \textit{Arduino} is the USB standard Serial communication. The USB communication is used during the calibration process because it is a maintenance operation, that needs to be done near the device. The calibration process also requires the user to consecutively transfer programs to the \textit{Arduino}, namely the calibration program followed by the calibrated gearbox firmware control code itself, which is not possible using the Ethernet communication due to the non-existence of the auto-reset necessary to the programmable integrated circuit reprogramming process.

The serial port defined in the program is the \textit{Arduino} default communication port, the "/dev/ttyACM0", and the baud-rate is also predefined to 9600, and should not be altered.

As soon as the calibrator \textit{Arduino} program is sent to the \textit{Arduino}, it starts sending a message via Serial communication with the following format:

\begin{center}
<STX>X<x\_pot\_value> Y<y\_pot\_value> <ETX>
\end{center}

The <x\_pot\_value> message field is the direct x-axis' potentiometer reading, thus an integer number between 0 and 1023, and the <y\_pot\_value> brings and equivalent reading but from the y-axis' potentiometer. The parallel communication process running on the PC is responsible for interpreting this message and sending both potentiometer's values to a shared memory between this process the Graphical User Interface one. These values appear on the interface text boxes, depicted in Figure \ref{figure:calibrator_gui}.

\subsection{The Calibration Process}

The simpler calibration process, executed using this calibration software, is comprised of the following steps:

\begin{enumerate}
\item Connect the \textit{Arduino} to the PC using the USB cable, and transfer of the \textit{Arduino} calibration firmware application;
\item Execute the Calibrator Software, and make it memorize all the five points, using the respective buttons;
\item When all the points are calibrated, the \textit{CALIBRATE} button is pressed, and the Gear Selector Mechanism control code is automatically generated and stored in the same folder where the Calibrator software is being executed in, with the name \textit{ARDUINO\_MOTOR\_CONTROLLER.pde};
\item Transfer of the \textit{ARDUINO\_MOTOR\_CONTROLLER.pde} to the \textit{Arduino}.
\end{enumerate}

\section{Integration with ROS} \label{subsec:integration_with_ros}

ROS (Robotis Operating System) is an open source software framework for robot software developers. Contrarily to the previous framework used in AtlasCar, CARMEN, ROS is based on a multitude of processes, or hosts, running in a peer-to-peer topology, instead of using a centralized server, like the CARMEN architecture \cite{article ROS}. ROS also allows the software development written in many different languages, such as:

\begin{itemize}
\item C++;
\item Python;
\item Octave;
\item LISP.
\end{itemize}

In order to achieve this cross-language development, ROS uses a simple language-neutral message definition system where the elements carried by each message and used by each process are defined.

Another important characteristic of ROS, is the large number of small tools that can be used to get or even set information about the processes or the messages being transferred between them. These tools allow the user to measure bandwidth utilization, visualize the current topology of the running processes, graphically plot data in a very easy way or auto-generate documentation.

ROS also supplies a large variety of useful drivers and libraries that allow the user to communicate with the sensors or hardware used within the project being developed. The fact that the ROS is an open-source project also enables a very active on-line community, constantly writing and using new software on the ROS project.

The ROS implementation is divided in four distinct concepts:

\begin{itemize}
\item Node;
\item Message;
\item Topic;
\item Service.
\end{itemize}

The Node is the name given to a certain process running within a ROS project. A project built using the ROS architecture is normally comprised of many Nodes working separately, and constantly communicating between them.

The ROS Nodes communicate with each other using Messages. A Message is an auto-generated data structure composed mainly of primitive types, and can include other Messages nested inside it.

The Topic is a string where a certain message is published, making its contents available to all the other ROS Nodes. When a Node, or a set of Nodes, needs to read the information contained inside a message published by another Node, it subscribes the corresponding Topic.

A Service is used when the topic-based publish-subscribe model is not advised for a certain Node that requires a synchronous communication with another Node. A Service is comprised of two distinct Messages, one user for the request, and the other used for the response.

In order to allow the future installation of the gearbox mechanism on the AtlasCar, and to integrate the system on the ROS based architecture currently being used, a ROS Node was created: the Gearbox Node. The main function of this Node is to implement the TCP/IP communication protocol, described in Subsection \ref{subsec:communication_protocol}, with the \textit{Arduino} firmware. The Node generates a Message and publishes it to a specific Topic, which is made available to any other Nodes in the AtlasCar. This node also subscribes another Topic, which contains the information about the gear that needs to be set on the gear changing mechanism. Note that it is not on the scope of this node to implement any gear logic on the AtlasCar, since the only purpose of the Node is to send orders to, or receive the status update from the gear selector mechanism's controller. Any gear shifting logic must be implemented on a higher level Node that communicates with this one, which is not the objective of this work. For this reason, the ROS Messages published and subscribed by this Node were intentionally kept as simple as possible.

The command message being subscribed by this Node has only one field, apart from the "priority" and the "lifetime" fields, that are required for ROS to make the automatic Topic and Message management. This field is called "gear", and is an unsigned 32 bits integer on the interval $[0,6]$, as said in Sub-subsection \ref{subsubsec:pc_to_arduino_messages}.

The status message being published by this Node is more complex, due to the fact that it needs to inform the controlling PC about the accurate status of the gear selector mechanism device. This Message has two fields: the "gear" and the "status". The gear field is an unsigned 32 bits integer and contains the current gear on the gear selector mechanism. If the device is moving, this integer corresponds to the last gear that was inserted by the device, thus the gear from where the mechanism left from. The "status" field is a string, interpreted by this Node according to the message read from the gear selector mechanism's control system. Table \ref{table:ros_status_field_strings} shows the possible strings that can appear on this Message field, as well as the respective meanings.

\begin{table}[h!]
\centering
\begin{tabular}{|c|p{8cm}|}
\hline
\textbf{\emph{status} string} & \textbf{Message Meaning} \\ 
\hline
\emph{manual mode} & Indicates that the control computer is trying to set a new gear on the gear selector mechanism while it is in manual mode, since the set operation is only allowed in automatic mode. To prevent or correct this situation, the MAN/AUTO button on the steering column gear pad selector must be pressed. \\
\hline
\emph{command invalid} & Indicates that the gear asked to the gear selector mechanism is invalid, i.e. not belonging to the integer interval $[0;6]$. This check is always made by the \textit{Arduino} firmware code. \\
\hline
\emph{changing to \textit{gear\_number}} & Indicates that the system is currently moving from one gear to another. The gear from where the system left is represented in the "gear" field, on the Node Message. The \textit{gear\_number} represents the gear to where the system is moving to. \\
\hline
\emph{ok} & Indicates that the system is currently stationary on the desired gear number. \\
\hline
\emph{unknown status} & Indicates that the Node could not interpret the message coming from the gear selector mechanism. This string indicates that something happened with the device, and security measures should be taken. \\
\hline
\end{tabular}  
\caption{Possible Strings being published by the ROS Node.}
\label{table:ros_status_field_strings}
\end{table}
