\chapter{Hardware design}
To realize the goals set in previous chapter, a suitable hardware platform is needed.
The choices made in this chapter have wide implications for the rest of the design.
For example, the choice of processor affects the kind of software it can run efficiently.
Higher performance processor can allow fast software development in a high-level language, but it will also have 
drawbacks in price, power usage and complexity.

Most important concerns in the hardware design are the manufacturability, cost and flexibility of the device.

For manufacturability, a premade platform would be optimal.
There exists a variety of embedded development platforms, some of which are also suitable for use in products.
Premade platforms have also a price advantage, as higher production volumes reduce the manufacturing costs.

On the other hand, maximum flexibility and suitability to the task is achieved with a custom platform.
In this way, every component choice can be tuned to achieve the optimal compromise between price and 
capabilities of the device.
The price is raised by the design costs and need for manufacturing resources.

\section{Design options}
The hardware design is necessarily a compromise between price and features.
There exists a very wide range of possible designs, but only a few can be investigated in depth.
To select the optimal design, a hierarchical approach is used: a high-level concept is decided first, after 
which the lower level options are explored.
This way the amount of options at each level is limited and manageable.

Figure \ref{fig_tree} illustrates the hierarchical decision process. The choices will be further explained in the following sections.

\begin{figure}[h]
\centering
\begin{tikzpicture} [every node/.style={align=center, minimum width=2cm},
    node distance=2cm]
\node (init) {Initial\\idea};
\node [right=of init, yshift=2cm] (usb) {USB\\peripheral};
\node [right=of init, yshift=0cm] (net) {Network\\device};
\node [right=of init, yshift=-2cm] (sa) {Stand-\\alone};
\node [right=of net, yshift=3cm] (pc) {Embedded\\PC};
\node [right=of net, yshift=1cm] (linux) {Linux\\platform};
\node [right=of net, yshift=-1cm] (mcu) {Micro-\\controller};
\node [right=of net, yshift=-3cm] (fpga) {FPGA SoC};
\node [right=of mcu, yshift=2cm, minimum width=2.5cm] (nxp) {NXP\\LPC4330};
\node [right=of mcu, yshift=0cm, minimum width=2.5cm] (st) {ST\\STM32F407};
\node [right=of mcu, yshift=-2cm, minimum width=2.5cm] (atmel) {Atmel\\ATSAM4S16};

\draw [->,thick] (init) -- (sa) node [midway, sloped, above, font=\footnotesize] {Most portable};
\draw [->,thick] (sa) -- (mcu) node [midway, sloped, above, font=\footnotesize] {Least cost};
\draw [->,thick] (mcu) -- (st) node [midway, sloped, above, yshift=-0.6cm, font=\footnotesize] {Best\\peripherals};

\draw [->,dashed] (init)--(usb);
\draw [->,dashed] (init)--(net);
\draw [->,dashed] (sa)--(pc);
\draw [->,dashed] (sa)--(linux);
\draw [->,dashed] (sa)--(fpga);
\draw [->,dashed] (mcu)--(nxp);
\draw [->,dashed] (mcu)--(atmel);

\node [below=of sa, yshift=0.5cm, font=\bf] {High-level\\concept};
\node [below=of fpga, yshift=1.2cm, font=\bf] {Processor\\class};
\node [below=of atmel, yshift=1.5cm, font=\bf] {Processor\\model};
\end{tikzpicture}
\caption{Decision tree of the design possibilities explored.}
\label{fig_tree}
\end{figure}

\subsection{High level concept}
At the beginning of the design process, three top-level design options were identified:

\begin{enumerate}
\item USB-connected device, which is operated from a control program running on a PC. This would be similar to 
the concept for previous versions.

\item Network connected device, which would be operated using a web browser. The user interface logic would run 
on the device itself, and the web browser would provide the display and control devices.

\item Completely stand-alone device, with its own touchscreen display and GUI running on it.
\end{enumerate}

Of these, 1. has the lowest requirements for the hardware, and would be consequently the most economical to 
implement.
At the other end of the spectrum, 3. requires display device and powerful enough platform to provide an user 
interface.
Option 2. avoids the need for display, but still requires a powerful processor and also network connectivity.

From the sales feedback, there was a slight preference for the stand-alone option 3.
A stand-alone device would be the easiest to demonstrate at sales events, and also is easiest to use in many of the use cases.
Portability of the device would be another advantage, as would the independence of PC operating system.
By including USB connectivity, the stand-alone device could also be controlled from a PC if necessary.

\subsection{Processor class}
To proceed with the design, the needed processing power must be evaluated and a suitable processor class has to be selected.
The exact model of the processor is not important at this stage, but the general performance class is selected.
The design choice of a stand-alone device with touchscreen display already precludes the lowest-end 
microcontrollers.
This leaves the following options:

\addglos{FPGA}{Field Programmable Gate Array, a microchip that can be programmed to implement logical circuits}
\addglos{USB}{Universal Serial Bus, an interface standard for connecting peripheral devices to computers}
\addglos{SoC}{System on Chip, a technique where the processor core and other necessary hardware components are integrated on a single microchip}

\begin{enumerate}
\item Embedded Windows PC, for example Intel Atom\cite{intel_atom} or AMD Geode\cite{amd_geode} based.
\item Embedded Linux platform, such as BeagleBone\cite{beaglebone} or Pandaboard\cite{pandaboard}.
\item High-end microcontroller, such as ARM Cortex-M4\cite{cortexm} based ones.
\item Custom system on a chip (SoC), implemented on an FPGA.
\end{enumerate}

Figure \ref{fig_classes} shows example products from each of these categories.
In practice, options 1. and 2. would be implemented using a premanufactured hardware platform, because the hardware complexity makes custom design prohibitively expensive.
Options 3. and 4. have simpler hardware design and could use either a premanufactured platform or a completely custom one.

It is important to notice that some of these options will not be sufficient by themselves.
The options 1. and 2. would not be able to fulfill the real-time needs of the system, due to overhead in high-level operating systems.
Therefore they would require an auxiliary microcontroller to handle the real-time processing.

\begin{figure}[ht]
\centering
\subfigure[][\nohyphens{Advantech ARK-3403\cite{ark}, an Intel Atom based embedded Windows PC.}]
{\includegraphics[width=8cm]{pictures/ark3403.jpg}}
\hspace{1cm}
\subfigure[][\nohyphens{BeagleBone\cite{beaglebone}, an ARM Cortex-A8 based embedded Linux platform.}]{\hspace{0.5cm}\includegraphics[width=4cm]{pictures/beaglebone.jpg}\hspace{0.5cm}}
\subfigure[][\nohyphens{STM32F4 Discovery\cite{discovery}, a development board for STM32F4xx series of ARM Cortex-M4 microcontrollers.}]{\hspace{3cm}\includegraphics[width=2cm]{pictures/stm32f4discovery.jpg}\hspace{3cm}}
\hspace{1cm}
\subfigure[][\nohyphens{Altera DE0-Nano\cite{de0}, a development board for Altera Cyclone~IV FPGA.}]{\hspace{0.5cm}\includegraphics[width=4cm]{pictures/de0.jpg}\hspace{0.5cm}}
\caption{A visual comparison of the processor class options. The photos are from the cited sources and are shown in approximate scale relative to each other.}
\label{fig_classes}
\end{figure}


Option 1. has a high cost, in the order of 1000-2000 EUR compared to the 100-200 EUR of the other options. It also lacks portability. Because it would still require a separate processor for all 
real-time tasks, it offers little advantage over just using a laptop and a USB-connected device.
Consequently, it is easy to rule out.

Option 4. would have the highest flexibility, as the complete processor system would be on a re-programmable logic device, in an approach called \emph{soft-core processor}.
The processor could for example be augmented with custom instructions for specific tasks.
However, the processing requirements would require a very high-performance FPGA.
Also, as design costs have to be kept low, it is unlikely that the processor would be heavily customized in this project.
Therefore using a soft-core processor would unnecessarily raise the price, as traditional processors in the same performance class are generally cheaper than an FPGA required to run one implemented in re-programmable logic.
Therefore custom SoC on FPGA is not the best option for this device.

The final two options 2. and 3. are both very good alternatives.
A Linux-based platform would allow using commonly available software development tools and libraries.
It would also have enough processing power to implement many signal processing algorithms, but with reduced 
real-time responsiveness.
Even though achieving the required timing resolution under a non-real-time operating system is difficult, it would only require a separate microcontroller or FPGA for the real-time tasks.
Such a separation could also make the software more structured, even though the required communication between processors would make it more complex.

Nevertheless, the processing requirements for the GUI are not exceedingly large.
Option 3. would easily handle the GUI, while also executing the real-time tasks at the same time.
Software development would be somewhat complicated, because there are not as many high-quality libraries 
available and the memory limitations must be considered at all times.
On the other hand, other parts of the software are simplified because there is no need to communicate between 
separate processors.
Also the hardware is simplified and power usage is reduced when everything is connected to a single processor,
and the closer connection to hardware allows more determinism in some measurement tasks.

The decisive factor is that option 3. is the simplest, lowest-cost design that can fulfill the requirements.

\subsection{Processor model}
The most common processor cores used in modern 32-bit microcontrollers are ARM Cortex-M series \cite{cortexm}, AVR32 \cite{avr32} and MIPS \cite{mips}.
Of these the ARM Cortex-M series has the widest array of associated manufacturers.
Consequently it also has the largest amount of available libraries and good tool support.
For example Texas Instruments TMS320 Delfino digital signal processors have very high performance, but their 
proprietary C28 processor core is not supported by many embedded operating systems.
Because the ARM Cortex-M processors have high performance, low cost and best software support, they are the most reasonable choice for this design.

ARM Cortex-M series includes M0, M3 and M4 models.
Of these, M4 has the highest performance and also includes a floating point unit in the M4F variant.
Because the price difference is negligible in small production volumes, choice is simple.
Highest performance processor will simplify the software development and allow larger flexibility in applications.

Manufacturers of high performance Cortex-M4 based microcontrollers include NXP Semiconductors, ST 
Microelectronics and Atmel.
Details of the available options are presented in Table \ref{comparison_m4}.

\addglos{FPU}{Floating Point Unit, a processor submodule that accelerates computations with floating point numbers}
\addglos{ADC}{Analog to Digital Converter, a device that allows conversion of analog voltage levels into numeric values}
\begin{table}[h]
\centering
\caption{Comparison of high-end Cortex-M4 microcontrollers from three manufacturers, as available for purchase in September 2012.
From each product series, the most suitable model was selected for the table.}
\label{comparison_m4}
\footnotesize
\begin{tabular}{>{\raggedright\arraybackslash}p{3.2cm}>{\raggedright\arraybackslash}p{3.3cm}>{\raggedright\arraybackslash}p{3.2cm}>{\raggedright\arraybackslash}p{3.2cm}}
\toprule
{\bf Manufacturer} 		& {\bf NXP} 				& {\bf ST} 		& {\bf Atmel} \\
Model 	     		& LPC4330FBD144 \cite{lpc4330}	& STM32F407ZG \cite{stm32f407}	& ATSAM4S16CA 
\cite{atsam4s} \\
Clock frequency & 204 MHz			& 168 MHz	& 120 MHz \\
Flash memory size 	& External			& 1 MiB		& 1 MiB \\
RAM size 		& 264 kiB			& 192 kiB	& 128 kiB \\
FPU			& Yes				& Yes		& No \\
ADC 			& 10 bit,			& 12 bit,	& 12 bit, \\
			& 8 channels,			& 24 channels,	& 16 channels, \\
			& 400 kS/s			& 3 $\times$ 2.4 MS/s & 1 MS/s \\
Other features 		& TFT controller, Cortex-M0 co-processor & & \\
Price for 1 unit	& 8.11 \euro & 12.75 \euro & 9.94 \euro \cite{digikey} \\
\bottomrule
\end{tabular}
\end{table}

The most important application requirement is high general purpose computing performance, including high amount of RAM.
For connecting different kinds of analog sensors, good analog capabilities are useful.
Finally, a relatively large amount of flash memory, atleast 1 MiB, is needed to give room for software extensions.

All of the microcontrollers in the table have high enough performance to run basic signal processing and user interface tasks.
However, the LPC4330 is clearly inferior in its analog capabilities, and also requires external flash memory which makes the circuit more complex.

Of the remaining two, the STM32F407 is slightly more powerful and has more memory.
The lack of a floating point unit also limits the performance of the ATSAM4S.
Combined with the superior analog capabilities of the STM32F407, this makes it the best option.

\section{Implementation of the main electronics}
With the processor chosen, the rest of the electronics can be designed around it.
These are quite straightforward design choices, as the only need is to provide the processor the necessary peripherals for interfacing the external world. Figure \ref{fig_hwa} shows the components and interconnections on the main board of the device.

\begin{figure}[h]
\centering
\includegraphics{pictures/hardware_architecture.pdf}
\caption{Overview of the hardware components of the system, and the interconnections between them.}
\label{fig_hwa}
\end{figure}

The following sections describe the subsystems in detail. All parts of the main electronics are mounted on the same circuit board, which was also designed as part of this work. The circuit board is shown in Figure \ref{fig_pcb}.

\begin{figure}[h]
\centering
\includegraphics[width=14cm]{pictures/pcb.jpg}
\caption{A hand-soldered prototype version of the main circuit board of the device.}
\label{fig_pcb}
\end{figure}

\subsection{Touchscreen}
\addglos{TFT}{Thin Film Transistor, a technology used in display panels}
\addglos{PCB}{Printed Circuit Board, usually a fiber glass board with etched copper conductors for mounting components}
The implementation of a touchscreen based user interface requires several parts: the display panel itself, a backlight, a TFT controller, touch screen film, touch screen controller, and finally the processor controlling the user interface. To reduce the design complexity, an integrated display module is desired. These usually contain all of the parts except for the main processor in a single module.

A significant challenge with the integrated modules is to ensure their continued availability.
Many modules are manufactured in small volumes and low profits, and consequently may be discontinued at any time.
Furthermore, there is no standard form factor for TFT modules, so changing the module type would involve a redesign of the main PCB as well as changes to the enclosure.

Displaytech is one prominent manufacturer of integrated TFT and touchscreen modules.
Their products are available from multiple distributors, providing good availability. The INT035TFT-TS module \cite{displaytech} was chosen for this project. It is a $320 \times 240$ screen with a resistive touchscreen film. While it is not comparable to modern smartphone displays in image quality, the availability in small quantities and simple hardware design make it a good choice for a design where production quantities are going to be small and low hardware development costs are important.

The INT035TFT-TS module integrates a SSD1963 TFT driver IC (Integrated Circuit). The driver IC has memory buffer for a single display frame, and automatically handles refreshing the display. The main microprocessor can write and read the screen contents using a 16-bit data bus. In this design, the TFT display is connected to the STM32F407 microcontroller's external memory bus to provide fast access.

The touchscreen controller in the display module is MAX11802, which uses a SPI serial bus to connect to the main processor. It also has a separate interrupt line, which can be configured to provide information about whether the display is currently being touched or not. The touchscreen controller manages the analog-to-digital conversions automatically, and provides numeric coordinates through the SPI bus.

Overall, the placement of the display determines a large part of the form factor of the device. The main electronics are placed on the other side of the main PCB, behind the display, in order to keep the size of the device small. This way the connections for the display could be routed directly from the processor to the display pins, while the external connectors are placed to the right of the display.

\subsection{Power management}
To make the device portable, a lithium-ion battery was chosen as the power supply. The battery will be charged through the USB connection. For safety purposes, a ready-made li-ion charger IC and a prepackaged battery with a protection circuit were selected for the design.

The operation on USB power places a constraint on the power usage of the device and the attached sensors. The maximum permitted current by the USB specification is 500~mA. In order to be able to also charge the battery simultaneously, the total power usage of the device should remain around 200-300~mA. The processor, at 100~mA, and the display module, at 150~mA, are the most power intensive devices on the main board. Fortunately, the total usage of them still leaves 250~mA leeway for external sensors and battery charging, which seems adequate.

The device is to be powered on and off by means of a slide switch. The switch could in the simplest case just cut the power supply to the device, but this would cause problems in practice. Because the device may be in the middle of a write operation to the memory card, it has to have control over the power-down. This is implemented using a MOSFET (Metal Oxide Semiconductor Field Effect Transistor), which allows the processor to control its own power supply independent of the power switch. This is used to force the power to stay on while important operations are in progress.

The components on the main board require a variety of supply voltages; Figure \ref{fig_power} shows an overview of this. Even though the number of separate supplies is large, most of them are implemented using one-chip linear regulators. Consequently the board area required by the power supply parts is relatively small.

The main supply voltage for the processor and display is +3.3~volts. This is easily produced from the nominal 3.7~V voltage of the li-ion battery using a low-dropout linear regulator (LDO). The regulator chosen operates at 150~mV dropout, which allows the supply voltage to remain stable until the battery voltage decreases to 3.5~V. At this point most of the energy in the battery has already been depleted.

The integrated color sensor and some of the planned external sensors require a +5~V supply voltage. This is generated from the battery voltage using a combination of a boost-type SMPS (Switching Mode Power Supply) and a linear regulator. The SMPS is necessary in order to be able to raise the voltage, but the switching action generates considerable noise in the output voltage. In order to make the output voltage stable enough for the sensors, the SMPS is configured to supply a +5.5~V output, which is then regulated down to +5~V using a LDO.

\begin{figure}[h]
\centering
\begin{tikzpicture}[node distance=0.5cm]
\tikzstyle{block} = [draw, align=center, minimum width=2.3cm, minimum height=1.3cm];
\tikzstyle{result} = [align=center];

\node [block, minimum height=3cm] (battery) {Li-ion battery\\3.5 -- 4.2~V};
\node [block, right=of battery] (switch) {Power switch};
\node [block, right=of switch, yshift=3cm] (rtc) {3.3~V low-power\\linear regulator};
\node [block, right=of switch, yshift=1.5cm] (adc) {3.3~V low-power\\linear regulator};
\node [block, right=of switch, yshift=0cm] (3v) {3.3~V linear\\regulator};
\node [block, right=of switch, yshift=-1.5cm] (1v2) {1.2~V linear\\regulator};
\node [block, right=of switch, yshift=-3cm] (5v5) {5.5~V boost\\SMPS};
\node [block, right=of 5v5] (5v) {5~V linear\\regulator};

\node [block, below=of battery] (charger) {Charger IC};
\node [block, below=of charger] (usb) {USB\\connector};

\node [block, right=of 5v] (color) {Internal\\color sensor};
\node [block, yshift=3cm, anchor=east] at (color.east) (mcu) {STM32F407\\microcontroller};
\node [block, yshift=1.5cm, anchor=east] at (color.east) (tft) {TFT display};

\draw [thick, ->] (battery) -- (switch);
\draw [thick, ->] (switch) -- (3v);
\draw [thick, ->] (switch) |- (1v2);
\draw [thick, ->] (switch) |- (5v5);
\draw [thick, ->] (switch) |- (adc);
\draw [thick, ->] (battery) |- (rtc);

\draw [thick, ->] (usb) -- (charger);
\draw [thick, ->] (charger) -- (battery);

\draw [thick, ->] (3v) -- +(3cm,0cm) |- ($(tft.west)+(0cm,0.4cm)$);
\draw [thick, ->] (1v2) -- +(3cm,0cm) |- (tft);
\draw [thick, ->] (3v) -- +(3cm,0cm) |- (mcu);
\draw [thick, ->] (5v5) -- (5v);
\draw [thick, ->] (5v) -- (color);
\draw [thick, ->] (adc) -| (mcu) node [midway, above, xshift=-1cm] {ADC};
\draw [thick, ->] (rtc) -| ($(mcu.north)+(0.4cm,0cm)$) node [midway, above, xshift=-1.4cm] {RTC};
\end{tikzpicture}
\caption{Diagram of the power supply scheme of the device.}
\label{fig_power}
\end{figure}

The display module also needs an additional +1.2~V supply for the display controller, which is also generated using a linear regulator. At a voltage difference this large, a SMPS could provide better efficiency in dropping the voltage. However, the power usage on the +1.2~V supply is low enough that it does not matter in this device.

Finally, there are also two separate +3.3~V supplies that are needed by the processor: a backup supply for the RTC (Real Time Clock), and a separate supply for the ADC (Analog-to-Digital Converter). These have a low current drain, and are generated using small linear regulators. The RTC supply is regulated directly from the battery voltage, before the power switch. This way the device can keep correct time also when switched off. The separate ADC supply is implemented only to reduce the noise in the measurements, and it is regulated similarly to the main +3.3~V supply.

\subsection{Data storage}
An internal non-volatile memory is required to save configuration settings and the measurement results. This memory can be accessed through the USB port, so it does not have to be removable. In order to provide enough storage space for the measurements, some of which can be many hours long and consist of millions of data points, at least a 128~MB memory is needed.

The most reasonable memory type is flash memory, which comes in various forms. Flash memories are available with both parallel and serial bus interfaces. While a parallel bus is faster, it is unnecessarily complex to layout on the PCB due to the large number of connections. Unfortunately, there are only few options of serial flash memory having capacity over about 8~MB.

Instead, a more common solution is to use microSD cards as a storage medium. They provide large capacities in a small form factor, and are available from many manufacturers. Due to the standardized interface, this also reduces the risk of the manufacture of an important part being discontinued later.

One potential problem of microSD cards is the unpredictable write latency. The card contains a built-in controller, which handles the erasure and allocation of memory areas for storage. If the controller has to relocate a large amount of data in order to free up a location, the write operation may stall for several hundred milliseconds. This is a problem if real-time measurement data is being saved to the card. However, in this design, the microcontroller has sufficiently high amount of RAM memory in order to buffer the data if a stall does occur.

\subsection{Built-in sensor}
The amount of built-in sensors to include on the main board was necessarily a compromise. Including a sensor on the main board simplifies the hardware and reduces the cost, as it can be assembled in the same step with the main board. However, including unnecessary sensors would increase both the cost and the risk of some sensor part becoming deprecated and unavailable in the future, requiring design changes.

The color sensor is central for the basic measurement situations, so its inclusion was justified. By having the color sensor built-in, the two external sensor connectors are available for other purposes.

\section{Extension capabilities}
To provide for the needs of any future measurement tasks, the device has to be extensible. Naturally, the choice of microcontroller and platform will limit the capabilities of the system, and any electrical device will be obsolete eventually as technology progresses. However, by bringing out as many as possible of the interfaces present on the microcontroller, we can make sure that anything that could have been added in the design phase, can also be added as an extension in the future.

Most important extension capability is the connectors for external sensors. These should accommodate many kinds of sensors with minimal interfacing. Therefore the connector has to provide both digital and analog interfaces, and suitable power supply for the sensors. Some ideas for sensors that have come up during the project are: sound input, sound output, second color sensor, RGB LED for light output.

In order to allow for higher speed peripherals, there is also an internal extension port. This provides a 16-bit extension bus, which will allow fast data transfer between the extension board and the main processor. This bus could allow for example connection of a camera, an external display or high-speed data storage.

\subsection{Sensor connectors}
The chosen microcontroller already contains a large range of useful peripherals for interfacing sensors: it has SPI, I2C and USART buses, ADC and DAC converters, timer inputs and outputs, and naturally also general-purpose IO pins. Any of these can be useful for some kind of a sensor or extension, but dedicating a pin for each function would lead to a large and cumbersome connector.

The microcontroller itself contains a partial solution to this: many of the functions share pins, and have software-configurable multiplexers that select which function is connected to each pin. Not all of the desired functions are available on any set of pins, but we can further combine pins electrically using resistors. In any case, a series resistor of about $50-100\;\Omega$ is appropriate for an external sensor bus, in order to act as series termination. The main benefit of the resistor is to reduce the electromagnetic emissions from the system.

However, the series resistor can serve a dual purpose: by connecting each connector pin to two microcontroller pins through separate resistors, we can double the amount of available functions on each pin. By configuring either of the two microcontroller pins as high-impedance input, the functions of the other pin can be used independently.

\begin{figure}[h]
\begin{tikzpicture}[circuit ee IEC]
\node [draw, minimum height=3cm, minimum width=1.5cm] (port) {};
\node [yshift=-0.5cm, right] at (port.north west) (pin1) {1};
\node [yshift=-0.5cm, left] at (port.north east) (pin2) {2};
\node [yshift=-1.0cm, right] at (port.north west) (pin3) {3};
\node [yshift=-1.0cm, left] at (port.north east) (pin4) {4};
\node [yshift=-1.5cm, right] at (port.north west) (pin5) {5};
\node [yshift=-1.5cm, left] at (port.north east) (pin6) {6};
\node [yshift=-2.0cm, right] at (port.north west) (pin7) {7};
\node [yshift=-2.0cm, left] at (port.north east) (pin8) {8};
\node [yshift=-2.5cm, right] at (port.north west) (pin9) {9};
\node [yshift=-2.5cm, left] at (port.north east) (pin10) {10};

\node [above=0mm] at (port.north) {J1};

\node [right, align=left] at ($(port.north west)+(7.5cm,+2cm)$) (pa7) {PA7: SPI1\_MOSI, \\TIM14\_CH1, ADC\_IN7};
\node [right, align=left] at ($(pa7.west)+(0cm,-1.5cm)$) (pb6) {PB6: I2C1\_SCL, \\USART1\_TX};

\draw (pin2) -| ($(pa7.west)-(3cm,0cm)$) to [resistor={ohm'=100, info={R1}}] (pa7);
\draw (pin2) -| ($(pb6.west)-(3cm,0cm)$) node [contact] {} to [resistor={ohm'=100, info={R2}}] (pb6);

\node (gnd) [ground, point down] at ($(port.south west)-(1cm,1cm)$) {};
\draw (pin1.west) -| (gnd);
\draw (pin5.west) -- +(-1cm,0cm) node [contact] {} -- (gnd);
\draw (pin9.west) -- +(-1cm,0cm) node [contact] {} -- (gnd);

\node (3v3) at ($(port.north west)+(-0.5cm,2.5cm)$) {+3.3V};
\draw (pin3.west) -| +(-0.5cm,1.5cm) to [resistor]
	node [midway, right=2mm, align=left] {F2\\150~mA} (3v3);
\draw (pin3.west) -| (3v3); % Fake the fuse line

\node (5v) at ($(port.north west)+(-1.5cm,2.5cm)$) {+5V};
\draw (pin7.west) -| +(-1.5cm,2.5cm) to [resistor]
	node [midway, left=2mm, align=right] {F1\\150~mA} (5v);
\draw (pin7.west) -| (5v); % Fake the fuse line

\draw (gnd) -- +(0cm,0.5cm) node [contact] {} -|
	($(port.south east)+(2.5cm,-0.5cm)$)
	node [contact] (j2) {}
    -- +(0cm,0.5cm)
    to [Zener diode={info'={D1}}]
    ($(pin2.east)+(2.5cm,0cm)$) node [contact] {};

\draw (pin4.east) -- +(1.5cm,0cm) [dashed];
\draw (pin6.east) -- +(1.5cm,0cm) [dashed];
\draw (pin8.east) -- +(1.5cm,0cm) [dashed];

\node [above right=0mm, inner sep=1mm] at (pin2.east) {IO 1};
\node [above right=0mm, inner sep=1mm] at (pin4.east) {IO 2};
\node [above right=0mm, inner sep=1mm] at (pin6.east) {IO 3};
\node [above right=0mm, inner sep=1mm] at (pin8.east) {IO 4};
\node [above right=0mm, inner sep=1mm] at (pin10.east) {ID};

\node [contact] at ($(pin10.east)+(4cm,0cm)$) (j10) {};
\draw (pin10.east) -- (j10);
\draw (j10) to [resistor] 
	node [midway, right=2mm, align=left] {R3\\2~k$\Omega$}
	($(j10)+(0cm,1.5cm)$) node [anchor=south] {+3.3V};
\draw (j10) to [capacitor]
	node [midway, right=2mm, align=left] {C1\\100~nF}
	($(j10)-(0cm,1cm)$) |- (j2);
\draw (j10) -- +(2cm, 0) node [anchor=west] (adc) {ADC input};

\draw (pa7.north east) -- (pa7.north west) -- (adc.south west) -- (adc.south east) -- +(2cm,0cm);
\node [below] at ($(adc.south west) + (2cm, 0cm)$) {IC1~~~STM32F407};

\end{tikzpicture}
\caption{Simplified electrical schematic of the external sensor connectors. The resistor arrangement for combining functions is shown for IO~1; the other three IO pins on the 10-pin connector are connected similarly.}
\label{fig_pinschema}
\end{figure}

% \addglos{ESD}{Electrostatic Discharge, the discharge of static electricity that can occur when a person touches a piece of metal. The high voltage involved can damage sensitive electrical parts.}

Figure \ref{fig_pinschema} shows a schematic of the sensor pin arrangement. The external sensor connects to the 10-pin connector J1. The resistors R1 and R2 are the series resistors that connect the two microcontroller pins to the sensor pin IO~1. The other three IO pins have same kind of connection, which is left out of the diagram for clarity.

Through careful selection of pins, it was possible to form two sets of 4 data pins so that each set containing the exactly same functions on each pin. This way the two external sensor connectors perform identically. Therefore any sensor can be connected to either connector. By providing appropriate abstraction in the software API, the sensor drivers do not even have to know which port the sensor is connected to.

To give the final touch of usability, each sensor should be automatically identifiable.
The simplest method of identifying the sensors is to simply have a pull-down resistor of a defined resistance on the pins. Combined with the R3 pull-up resistor in the device this forms a voltage divider. The analog input in the microcontroller can then be used to determine the voltage and identify the sensor. The capacitor C1 reduces the noise in the measurement.  A single resistor with 1~\% tolerance is enough to identify about 50 different kinds of sensors, and requires only a single pin on the connector.

Finally, the sensor connectors should be robust against normal use and occasional misconnections. Therefore each pin has its own electro-static discharge protection diode (D1 for IO~1) to protect against static electricity, and each power rail has a automatically resetting overcurrent fuse. The series resistors R1 and R2 included in the design provide further protection of the IO pins against overloading and short-circuits.

\subsection{Extension board connector}
The extension board connector allows insertion of another PCB inside the same device enclosure. It has especially been designed to be an efficient way to connect a FPGA as a co-processor to the main processor. Suitable tasks would be to capture signals from high-speed sensors, or equivalently provide high-speed data output.

The extension board connector provides access to the 16-bit external memory bus of the microcontroller. This bus is shared with the TFT display, and each device on the bus has a separate enable signal. The connector also provides the same +3.3~V and +5~V power supplies as are available on the main board. Finally, several general purpose IO signals and a synchronous serial port are provided in order to be able to load a configuration into an FPGA in runtime.

The design effort of an extension board is necessarily large, as the interface is not designed to be directly applicable for sensors. Whereas most sensor connections to the external sensor connectors consist only of a few discrete parts, an extension board will necessarily include an FPGA or a microcontroller. Therefore it is expected that most sensors will be connected through the sensor connectors.

However, the extension board connector provides an useful way to add even complex extra functionality in the future, without resorting to more intrusive hardware modifications. Because the connector is already designed in, even previously sold devices could be upgraded with an extension board.

\section{Enclosure}
The design of the enclosure posed some challenges in the project. Even though the scope of the thesis project did not necessarily include any enclosure at all, some solution was necessary in order to make the device usable and presentable for demos. For example, the optical fiber that connects into the color sensor would have been difficult to attach without an enclosure.

Furthermore, it was important to have some enclosure concept in mind when laying out the main board. For example, connectors had to be placed so that they could be brought easily to the sides of the enclosure, and the placement of the display also had to be reasonable.

In the prototype phase, low starting costs were essential for the enclosure design. It was very likely that several designs would have to be tried, so any starting costs such as mold making or CNC programming would quickly accumulate.

\addglos{CNC}{Computer Numerical Control, a class of machining tools that are used to cut and form metal according to a 3-dimensional model stored on a computer.}

For the prototyping phase, it was therefore important to have a flexible technology that allows affordable testing of many test models, with fast turn-around time. For the pilot production runs, it was also necessary to minimize the amount of manual labor.

\subsection{Options}
One way to keep costs low would be to use a pre-made standard enclosure. However, the need for openings for the connectors and especially the display would still have required custom machining of the enclosure. Another issue is that very few standard enclosures would match the dimensions of the display well.

Most commercial electronic devices use an enclosure made of injection molded plastic. For this product, even the estimated production runs are too small to warrant the cost of mold making. Even the inexpensive prototyping services have costs starting at thousands of euros per each run \cite{protomold}.

Some of the other devices manufactured by OptoFidelity Oy in the past have used a custom aluminum enclosure that has been milled using CNC machinery. This is a reasonable option, and allows the production of high-quality enclosures in small runs. The per-unit cost is high compared to most other options, but not unreasonable for the price range of these products. However, there are still significant non-recurring engineering costs charged by the supplier, for tasks such as processing the model and programming the tools.

Recently, the price of 3D printing has also become affordable for this kind of applications. The prime benefit of 3D printing is that there are no setup costs, and that very complex shapes can be created. It is therefore a good fit for the prototyping run, as various enclosure designs can be tried out at low expense.

\subsection{Implementation}
The prototype enclosures were ordered from ShapeWays, a company based in Netherlands that provides 3D-printing services \cite{shapeways}. ShapeWays uses high-precision industrial machinery for the purpose, which provide a good accuracy and surface quality in the end product. The material used was \emph{Polished Alumide}, which is a marketing name for polyamide mixed with fine aluminum powder, and then polished using glass beads after printing.

The 3D printed part and the complete enclosure are shown in Figure \ref{fig_enclosure}.
The main board, connectors and display fit readily in the apertures designed into the model, reducing the amount of manual assembly work. The size of the device is approximately $12\times8\times3$~cm.

\begin{figure}[h]
\centering
\subfigure[][3D printed part]{\includegraphics[width=7cm]{pictures/3dprint.jpg}}
\subfigure[][Assembled device]{\includegraphics[width=7cm]{pictures/enclosure.jpg}}
\caption{The 3D printed body and the assembled enclosure.}
\label{fig_enclosure}
\end{figure}

The front and back panels were ordered separately, laser-cut of acrylic sheet. This both reduces the amount of material that has to be printed, consequently reducing the price, and also makes the structure stronger. The laser cutting technology can also engrave the surface of the plastic, allowing the texts and markings to be added in the same step. The visibility of the engraved texts was not entirely satisfactory, but good enough for the pilot run.

Both the 3D printing process and the laser cutting are controlled by computer-based models. These were designed using the open source tools QCad \cite{qcad} and OpenScad \cite{openscad}. While they do not match the capabilities of commercial CAD packages, the amount of learning required is smaller and they allowed the quick production of models for this purpose.

