• No results found

Joystick Radar Control : Implementing joystick control of a radar rig using single board micro-controllers by emulating generic mouse and keyboard commands

N/A
N/A
Protected

Academic year: 2021

Share "Joystick Radar Control : Implementing joystick control of a radar rig using single board micro-controllers by emulating generic mouse and keyboard commands"

Copied!
83
0
0

Loading.... (view fulltext now)

Full text

(1)

Bachelor of Science Thesis in Electrical Engineering

Department of Electrical Engineering, Linköping University, 2021

Joystick Radar Control

Implementing joystick control of a radar rig

using single board micro-controllers by

emulating generic mouse and keyboard

commands

(2)

Bachelor of Science Thesis in Electrical Engineering

Joystick Radar Control: Implementing joystick control of a radar rig using single board micro-controllers by emulating generic mouse and keyboard

commands

Swedish title:

Joystickstyrning av radar: Implementering av joystickstyrning på en radarrigg med hjälp av enkortsdatorer

Christopher Gustafsson LiTH-ISY-EX-ET–21/0502–SE Supervisor: Göran Sällberg

Försvares Materielverk

Examiner: Michael Josefsson

isy, Linköpings universitet

Division of Computer Engineering Department of Electrical Engineering

Linköping University SE-581 83 Linköping, Sweden Copyright © 2021 Christopher Gustafsson

(3)

Sammanfattning

Försvarets materielverk tillhandahåller test och evaluering av militära flygsystem. De tillhandahåller även tjänster rörande militära övningar såsom belysning av flygplan med en radar för att öva piloter. Denna radar är monterad i en container och kontrolleras av en styrdator som kör operativsystemet Windows 2000. Denna dator styrs med hjälp av en mus och tangentbord. I denna rapport kommer ett sy-stem designas som kan förbättra användarupplevelsen av denna dator samtidigt som förändringar av hårdvara eller mjukvara i styrdatorn undviks.

Resultatet av rapporten var ett system bestående av en kommersiellt tillgäng-lig joystick och två microkontrollers i kombination med ett grafiskt användar-gränssnitt som omvandlar knapptryck och styrutslag från joysticken till mus och tangentbords kommandon i styrdatorn.

(4)
(5)

Abstract

The Swedish Defence Materiel Administration provides tests and evaluations of military Aircrafts and their systems as well as provide services in connection with military exercises. Testing aircraft against a radar antenna and training crews with this radar is part of that offering. The radar is deployed in a container rig and controlled by a computer running Windows 2000. The current option to control this computer is a mouse and keyboard. In this thesis, a system will be designed that is able to improve the ease of use of this rig while minimizing any need to modify the radar rig’s already established hardware and software.

The resulting system designed used a commercially available joystick and off the shelf single board micro-controllers in combination with a graphical user in-terface to supply the radar rig with a converted input from the joystick in the form of mouse and keyboard commands, simplifying the end-user experience.

(6)
(7)

Acknowledgments

I would like to thank FMV for the opportunity to work with this thesis. I would also like to thank my girlfriend for all the support during this time.

Linköping, March 2021 Christopher Gustafsson

(8)
(9)

Contents

List of Figures xi

List of Tables xii

List of Code xiii

Notation xv 1 Introduction 1 1.1 Motivation . . . 1 1.2 Purpuse . . . 2 1.3 Problem statements . . . 2 1.4 Research Limitations . . . 2 2 Background 3 2.1 The radar rig – “TRACKE” . . . 3

2.2 The control computer . . . 4

2.3 Conclusions . . . 4

3 Theory 5 3.1 Universal Serial Bus . . . 5

3.1.1 USB - Overview . . . 6

3.1.2 Data Flow . . . 8

3.1.3 Endpoints and Pipes . . . 9

3.1.4 Types of Transfers . . . 10

3.1.5 Packets . . . 11

3.1.6 Transactions . . . 15

3.1.7 Descriptors . . . 17

3.1.8 The standard device requests . . . 19

3.1.9 From plug-in to an established connection . . . 22

3.1.10 usb device classes . . . 23

3.1.11 usb On-The-Go and Embedded Hosts . . . 26

3.2 Serial Peripheral Interface . . . 26

(10)

3.3 Single-Board Microcontrollers . . . 27

3.3.1 Arduino Due . . . 27

3.3.2 Arduino Micro . . . 27

3.3.3 Logic-level Converter . . . 28

3.4 Hands-on Throttle and Stick & Joysticks . . . 28

3.4.1 Logitech Extreme 3D Pro . . . 29

4 Method 31 4.1 Introduction . . . 31

4.2 Pre-study . . . 32

4.3 Implementation . . . 32

4.4 Deciding on a programming method . . . 33

4.4.1 Implementing spi . . . 33

4.4.2 Implementing USB Host . . . 36

4.4.3 Implementing usb Client and Mouse/Keyboard emulation 37 4.4.4 Tying it all together . . . 40

4.4.5 Implementing the GUI . . . 41

5 Results 45 5.1 Pre-study . . . 45

5.2 The platform . . . 45

5.3 The Graphical User Interface . . . 46

5.4 Using the system with the Radar rig . . . 47

6 Discussion 49 6.1 Results . . . 49 6.2 Method . . . 50 6.3 Reliability of sources . . . 51 7 Ethical Aspects 53 8 Conclusions 55 8.1 Further work . . . 55

A Capture of usb packets 59 A.1 hid Report . . . 59

(11)

LIST OF FIGURES xi

List of Figures

2.1 Schematic over the TRACKE radar rig based on original provided by FMV. . . 3 3.1 Topology of a usb bus. . . 6 3.2 At the top an unaltered data stream, in the middle an nrzi

end-coded stream and at the bottom an nrzi enend-coded stream with bit stuffing. . . 7 3.3 A simple visualization of a connection between a host and a device. 8 3.4 The three different logical communications layers on the usb bus. 8 3.5 The physical or real communication flow on the usb bus. . . 9 3.6 A connection of host to device through a pipe. . . 9 3.7 The different fields for IN-, OUT -, SET UP -, and SOF- packets. . 11 3.8 Flow of a packet from sender through crc and bit stuffing to the

receiver. . . 12 3.9 Data fields and number of bits for each field in a token packet. lsb

and msb is shown for the payload of the packet. . . 13 3.10 Data fields and number of bits for each field in a start-of-frame

packet. lsb and msb is shown for the payload of the packet. . . 13 3.11 Data fields and number of bits for each field in a data packet. lsb

and msb is shown for the payload of the packet. . . 14 3.12 Data fields and number of bits for each field in a handshake packet.

lsband msb is shown for the payload of the packet. . . . 15 3.13 Typical flow for a control transfer. . . 17 3.14 Typical transaction flow during an interrupt transfer. . . 17 3.15 Common USB-plugs, from left to right, a Standard A-plug, a

Stan-dard B-plug, and a Micro-B plug. . . 26 3.16 To the left a USB Micro-AB receptacle and to the right a Micro-B. . 26 3.17 A simple block diagram presenting an SPI connection between a

master and a slave device. . . 27 3.18 An Arduino Due, Atmel SAM3X chip in the middle with native

usbMicro-AB port on top-left side and programming usb Micro-B port below it. . . 28 3.19 Arduino Micro, ATmega32U4 chip in the middle of the board and

(12)

3.20 A logic-level converter from sparkfun, high voltage side on the top

and low voltage side at the bottom. . . 29

3.21 A Logitech Extreme 3D Pro joystick. . . 30

4.1 A block schematic representation of the demand specification. . . 32

4.2 The inheritance uml chart for the HotasSerial class with subclasses. 34 4.3 Schematic demonstrating the SPI connection of the Arduino Due and the Arduino Micro using the logic level converter. . . 35

4.4 uml inheritance diagram of the usb implementation. . . 38

4.5 Inheritance uml diagram for the H otasCommand class. . . . 41

4.6 Call graph for the state machine in the RecieveCommand class. . . 42

5.1 The resulting platform with the Arduino boards connected using the logic converter and the usb cables hooked up to the two boards. 46 5.2 The gui that was implemented to control which commands differ-ent buttons on the joystick will result in on the computer. . . 47

List of Tables

3.1 usb transfer types. . . 10

3.2 Packet identifier types for token packets. . . 13

3.3 Packet identifier types for start-of-frame packets. . . 14

3.4 Packet identifier types for data packets. . . 14

3.5 Packet identifier types for handshake packets. . . 15

3.6 Beginning field for all descriptors. . . 18

3.7 Device descriptor format. . . 19

3.8 Configuration descriptor format. . . 20

3.9 Interface descriptor format. . . 20

3.10 Endpoint descriptor format. . . 21

3.11 Format of setup data. . . 21

3.12 The standard requests. . . 22

3.13 The hid class-specific requests. . . 24

3.14 Format of the hid descriptor. . . 25

(13)

List of Code

3.1 Report descriptor from a Logitech 3D joystick captured using Wire-shark. . . 25 4.1 Configuring the SPI settings. . . 33 4.2 Initialization of spi on the Master device. . . 34 4.3 The configuration of the Arduino Micro in Slave mode. Modified

code from original written by Nick Gammon. . . 35 4.4 Code for receiving a byte, the code copies the received byte from

the buffer to a supplied uint8_t pointer. Modified code from origi-nal written by Nick Gammon . . . 36 4.5 Code for sending and performing an IN transaction with a device. 39 4.6 The code for initializing the Logitech USB joystick. . . 40 4.7 The main program of the Arduino Micro board. . . 43 4.8 The main loop of the Arduino Due with the relevant code relating

to the joystick implementation. . . 44 A.1 The full hid report captured with Wireshark. . . 59

(14)
(15)
(16)

xvi Notation

Notation

Abbreviations

Abbreviation Explanation

bcd Binary Coded Decimal, binary encoding of a decimal number where each decimal is represented by a num-ber of bits.

csv Comma Separated Values, a file format to store data, the data-points are typically separated with commas. eot End Of Transmission, a non-printable character used

to indicate the end of a transmission.

fmv Försvarets Materielverk, the Swedish Defence Mate-rial Administration

gui Graphical User Interface, a computer program that has a graphical interface, in contrast to a program that uses a command line.

hotas Hands On Throttle and Stick, a term used for flight controls where the pilot can control the aircraft with-out moving the hands off the flight controls.

ide Integrated Development Environment, Software used to develop software, provides functionalities such as compilers and text editor.

nil Nothing In Line, indicates that the a space in the text is intentionally left blank.

nrzi Non Return to Zero Inverted, a way to encode a data stream where a zero-bit on the bus would lead to a transition of the level of the encoded stream.

otg On The Go, an addition to the USB protocol to allow devices to switch Host and Client roles.

pcb Printed Circuit Board, a board where electronic com-ponents can be mounted.

risc Reduced Instruction Set Computer, a computer proces-sor that uses a reduced set of instructions compared with a complex instruction set computer.

spi Serial Peripheral Interface, protocol for serial commu-nication between electronic devices

uml Unified Modeling Language, is a modelling language to visualize computer code.

url Uniform Resource Locator, a reference to a network location, typically web-addresses.

usb Universal Serial Bus, common bus used by peripheral devices.

(17)

1

Introduction

The Swedish Defence Material Administration (fmv) is a Swedish governmental agency responsible for procurement of and providing services in connection with, defence equipment and systems for the Swedish armed forces [1].

The work contained within this thesis was performed at fmv ’s “Testing and Evaluation Division” in Linköping, Sweden, where testing of different aeronauti-cal systems takes place as part of the service offering of fmv.

One of the test and evaluation offerings that fmv has is the testing of an air-craft’s radar warning and protection capability. For this purpose, fmv has a rig that enables the illumination of an aircraft with a radar beam. The radar rig is also used during training and military exercises.

This radar rig is currently controlled using a mouse and a keyboard on a com-puter, this is a rather slow process where the operator of the computer has to switch back and forth between windows on the computer screen. Therefore, fmv has the interest to improve the responsiveness and the ease of use of the control of this rig by implementing a solution wherein the computer can be controlled in a fashion more similar to that of a radar mounted in an aircraft.

1.1

Motivation

The view of the possibility of external threats to the Kingdom of Sweden has shifted in the recent decade from a view of there being a very low possibility of a military conflict to one where the possibility is higher, as can be seen by a recent study of different threat scenarios produced by the Swedish Civil Contingencies Agency written by L. Holm at Uppsala University [2].

This has resulted in a greater frequency of military exercises and exercises on a greater scale in Sweden, for example, the exercise Aurora 17 in 2017 which was the largest military exercise in Sweden in over 20 years [3].

(18)

2 1 Introduction

In this context, the ability to deliver qualitative and close to real-life scenar-ios by fmv ’s service offering is increasingly important. By implementing a way wherein the computer controlling the radar rig can be controlled using a joystick with buttons on it which has the ability to perform different actions, called a hands-on-throttle-and-stick (hotas) solution in aircraft terms, would enable the radar rig to be controlled in a way more similar to the way radar is controlled in an aircraft and in part facilitate the goal of achieving more realism in the services provided by fmv using this rig.

1.2

Purpuse

The goal of this thesis is developing a system wherein the controls of the radar rig computer can be switched from the current solution of mouse and keyboard to a solution wherein the operator of the computer instead can use a joystick to perform the same actions, without the need for the operator to release his or her hands from the joystick during use. The buttons of the joystick should also be easily configurable by the operator.

The developed system should also facilitate the possibility to expand it so that different types of hotas solutions can be implemented in the future, for example, flight-sticks from older types of aircraft.

1.3

Problem statements

The questions this thesis will answer is:

• Can a system be designed so that a commercially available joystick, having USB as its output, could be used to improve the ease of controlling the radar rig?

• Is it possible to achieve this ease of control without modifying the hardware and software of the radar rig?

• Is it possible to design that system so that it has the possibility to use out-puts from a flight-stick previously used in an aircraft as input?

These questions will be discussed and answered throughout this thesis.

1.4

Research Limitations

Due to the limited time of the project and the desires of fmv, the focus of this thesis will not be on constructing a specific PCB for the solution, instead, the focus will be on development boards available on the market.

A specific design implementation for used aircraft joysticks will not be devel-oped due to the fact that there was no working aircraft joystick on hand to be analyzed, instead, the system should have the possibility to be expanded in this regard.

(19)

2

Background

This chapter will briefly describe the radar rig that the aim of this thesis is to develop a joystick control for.

2.1

The radar rig – “TRACKE”

In Linköping, Sweden FMV has a test site for validation and testing of different aircraft systems. To test, validate and verify aircraft systems ability to detect radar signals FMV uses a container-based solution they call “TRACKE”. It con-sists of a radar of type PS46 mounted in the container, this radar is of the same type that was once installed in aircrafts of type SAAB 37 Viggen [4], the necessary support systems for the radar and a computer that controls it, a basic schematic of TRACKE can be seen in Figure 2.1. The container also has a second computer which the user uses while the rig is in operation.

Figure 2.1:Schematic over the TRACKE radar rig based on original provided by FMV.

(20)

4 2 Background

2.2

The control computer

The computer controlling TRACKE consists of a normal personal computer run-ning the Windows 2000 operating system. This computer has software and hard-ware for controlling the radar.

The software contains two parts, each running in its own window, which the user has to switch between to control the radar.

2.3

Conclusions

The design of TRACKE provides some constraints to the solution provided in this thesis. The solution must work in a Windows 2000 operating system envi-ronment. Changes to the hardware or software of the computer are not feasible for a project like this thesis due to the limited time of the project so the solution has to adapt to these constraints.

(21)

3

Theory

In this chapter, the theory behind the protocols and hardware used in this the-sis will be discussed. First, the Universal Serial Bus protocol will be discussed, secondly, single-board microcontrollers, thirdly the Serial Peripheral Interface protocol and lastly the joystick used.

3.1

Universal Serial Bus

In this section, a brief history of the standard will be discussed followed by a description of usb. Much could be written on this subject and this is by all means not a complete description of usb, some parts will be discussed briefly, such as usbphysical connectors and power management, as these subjects are outside the scope of this thesis and the main focus will be of usb in terms of the specification for version 2.0.

Universal Serial Bus or usb as it is commonly abbreviated is an industry-standard developed to connect a computer with all manners of peripheral devices such as keyboards, thumb-drives and many more.

The Universal Serial Bus was first introduced in 1995, it was created by a group consisting of American technology companies with the aim to create a stan-dardized peripheral interface for computers [5]. This group of companies later formed the usb Implementers Forum (usb-if) which is a non-profit organization to promote and advance usb implementation and technology [6].

The usb-if also provides compliance certification with the standard and the Vendor ID that is used in the device descriptor all usb devices provides, this descriptor will be further discussed in section 3.1.7.

Since its introduction, the usb standard specifications has undergone numer-ous revisions, most notably the usb 1.0, 2.0, 3.0 and the usb 4 specification.

(22)

6 3 Theory

3.1.1

USB - Overview

The usb 2.0 specification describes a device as a “logical or physical entity that performs a function” [7] this function provides the host with some functionality, for example, a printer, a storage device or a keyboard. The specification also allows one device to implement several functions, this is then called a compound device.

In the usb bus each peripheral device connects to a host creating a star topol-ogy, this includes usb hubs where the user can connect additional devices to the bus, thus, each hub has its own particular star topology, as illustrated in Figure 3.1, creating a tiered star topology for the bus as a whole with up to 127 devices connected [8]. The specification allows for up to seven tiers within the bus i.e between a device and the host there can be up to five hubs in between, this is not, however, applicable to compound devices since a compound device in itself is comprised of two tiers limiting the allowed amount of tiers in between the compound device and the host [7].

Figure 3.1:Topology of a usb bus.

The Host

In a usb bus, there is one host that controls the bus. It consists of a root hub and a host controller. The implementation of the host controller varies [9] from one with more of a software-oriented implementation to one with more of a hardware-oriented implementation [10], nevertheless, the host controller provides power and data management services, and monitoring of devices activity on the bus for the host.

(23)

3.1 Universal Serial Bus 7

The Device

There are several different standardized classes for devices such as Human Inter-face Devices (hid), printers and the hub class. A device class describes a group of devices sharing the same functionality and the class allows a host to communi-cate with a device in a generic way reducing the need for specialized software for every device [11].

Devices are required to detect when a host intends to start communications and are required to respond in a way compliant with the usb standard upon receiving a standard request, such as a reset request [7].

Physical Characteristics

A usb device is connected to a host (or hub) using a four-wire cable [7] consisting of a ground wire, V BU S wire and two signal wires D+ and D−. The data in the usbbus is differentially transmitted together with a non-return-to-zero inverted (nrzi) encoded clock [7].

In the nrzi encoding that the usb bus employs a zero bit indicates a transition from one level to another on the bus. Thus, if a long series of zeroes would be sent onto the bus the level of the bus would go from either high to low or low to high continuously and reversely if a long series of ones would be sent the bus would stay at the same level for the duration of the one bits. To ensure synchronization between devices on the bus usb employs bit-stuffing, where after six repeated ones sent on the bus a zero will be inserted which will force the nrzi encoded stream to shift from the current level to the other [7]. When the receiver recognizes a stuffed bit, it removes that bit. All bits on the bus are sent out with the least significant bit (lsb) first and ending with the most significant bit (msb). See Figure 3.2 for an illustration of the bitstream on the bus, the nrzi encoded stream and the stream with bit stuffing.

Figure 3.2:At the top an unaltered data stream, in the middle an nrzi end-coded stream and at the bottom an nrzi enend-coded stream with bit stuffing.

(24)

8 3 Theory

3.1.2

Data Flow

Figure 3.3:A simple visualization of a connection between a host and a de-vice.

In Figure 3.3 we can see a simplified view of the connection between a host and a peripheral device. This view can be further broken down, as shown in Figure 3.4, into three different layers, the bus interface level, the device layer and the function layer.

Figure 3.4:The three different logical communications layers on the usb bus. The bus interface layer handles the physical connection between the host and the device while the device layer handles basic functionality and the function layer handles higher-order capabilities used by the client software.

In each of these layers, there is no physical direct communication between host and device, as shown in Figure 3.5, but there is a logical communication flow between them and the device layer and function layer uses the interface level to achieve this communication [7].

(25)

3.1 Universal Serial Bus 9

Figure 3.5:The physical or real communication flow on the usb bus.

3.1.3

Endpoints and Pipes

All communication in the usb bus is done through what is called pipes, it is a representation of the connection between a memory buffer on the host side and an endpoint on a device [7], endpoints are the point where the communication between host and device is terminated. Figure 3.6 shows a visual representation of a device connected to a host through a pipe. It should be noted that a device has multiple endpoints which all have their unique address and a pipe related to it.

Figure 3.6:A connection of host to device through a pipe.

Endpoints

An endpoint is a buffer that is typically a register (or other memory) on the device [8]. This buffer serves as the endpoint and termination of communication from the host, it can, however, store both incoming and outgoing data from the device. An endpoint is still called an endpoint no matter which way the data-direction is.

The data direction of the endpoint is defined from the hosts perspective, thus an I N endpoint is intended for sending data to the host while an OU T endpoint is intended for storing data received from the host [8].

All endpoints have an address consisting of a number and the data direction of the endpoint, for example, 1 I N which would represent endpoint 1 with a data direction of sending to host.

There is one special endpoint that all devices must have, endpoint zero, it is intended for control transfers and must be configured as a control endpoint that transfers data in both directions, thus this endpoint has the address 0 I N and 0

(26)

10 3 Theory

Pipes

As noted earlier it is the host that is in control of the bus and the host is the one who will establish a pipe to each endpoint it wants to communicate with, and the host can request new pipes or remove already established ones. Since every device has an endpoint zero there will also always be a pipe associated with it [8]. The pipes are established during a process called enumeration, this is an on-going activity that detects when devices connect or disconnect from the bus. If the host during enumeration detects a new device it assigns an address to that device [7].

Pipes also have a few other parameters associated with them aside from the endpoint and data direction, these include allocated bandwidth, maximum packet size and type of transfers, which will be further discussed in section 3.1.4.

3.1.4

Types of Transfers

This section will discuss the four types of transfers on the Universal Serial Bus, control transfers, bulk transfers, interrupt transfers and isochronous transfers. Table 3.1 provides some brief examples of usage for each type of transfer.

Table 3.1:Typical uses for each type of transfer [7], [8]. Type of transfer Typical use

Control Command/Status operations Bulk

Large data that can be delayed until sufficient bandwidth is available such as drives, print-ers etc.

Interrupt Communication requiring bounded latency such as keyboards and mice.

Isochronous Time-relevant information such as streaming audio/video.

Control Transfers

The control transfer type is used to configure the device, with proper support from drivers it can also be used for other device-specific purposes [7], [8].

This type of transfers all usb devices must support since without it the host cannot properly configure the device.

Bulk Transfers

This type of transfer is intended for large sequential data transfers where the rate of transfer is not critical such as accessing a drive. On an idle bus, the bulk transfer is the fastest type, but if the bus is busy the transfer of data has to wait [8].

(27)

3.1 Universal Serial Bus 11

Interrupt Transfers

This type of transfer is intended for applications where there is a requirement for low latency or when the host needs to be polled periodically. This transfer type is typically used by for example keyboards to send keypresses [7], [8].

Isochronous/Stream Transfers

Data transferred using this type have a steady rate for receiving and transmit-ting and is intended for data that is created and consumed in real-time such as streamed audio or video. When using this type of transfer one must take into consideration that there is no error-correcting in this type [8].

3.1.5

Packets

There are three types of packets used in usb: • Token packets

• Data packets • Handshake packets

Each of these packet types has, in itself, different types which will be further discussed in the following sections. A usb transaction typically follows this se-quence, a token packet followed by an optional data-payload packet ending with a handshake packet.

Common fields for all packets

This section will discuss data fields that are common to all packet types.

The sync field All packets start with a sync field, this field ensures that there will be edge transitions on the bus, it is used for synchronization of the data transfer with the local clock of the device. As seen in figure 3.7, the sync field is typically eight bit long and ends with two bits used to identify the end of the sync field [7].

(28)

12 3 Theory

The packet identifier field After the sync field follows the packet identifier field which also consists of eight bits. These bits are divided into one four-bit packet type field and one four-bit check field. The type field indicates the type of packet being sent and the check field consist of one’s complement of the type field used to ensure proper decoding of the whole packet identifier field i.e. if the first half of the field is not complemented to the other and vice versa some error has occurred and the remainder of the packet is discarded [7].

The address field This field indicates the destination device for the packet, it consists of seven bits which would give 128 different devices being able to con-nect to the bus, however, since all devices must respond on the default address zero this gives the maximum allowable devices of 127 on the bus. To be able to address a specific endpoint on a device there’s also an endpoint address field consisting of four bits [7].

The frame number field The frame number field is only sent in start-of-frame tokens and consists of 11-bits. The value of these bits are incremented by each frame sent on the bus up to a value of 7FFH, at that point the value is rolled over to zero [7].

Cyclic redundancy checks Cyclic redundancy checks (crc) are performed on data and token packets. On token packets, the packet identifier field is excluded from the crc-check and on data packets, it’s the data field that is included.

As seen in Figure 3.8 the generation of the crc is done before the bit stuffing and it’s not decoded before the stuffed bit is removed on the receiving end.

Figure 3.8:Flow of a packet from sender through crc and bit stuffing to the receiver.

The crc field of token packets are five bits and the generator polynomial for this is stated in equation 3.1.

G(X) = X5+ X3+ 1 (3.1) The crc field of a data packet is 16-bits and the generator polynomial for this is stated in equation 3.2.

G(X) = X16+ X15+ X2+ 1 (3.2)

End-of-packet End-of-packet (eop) is signalled by driving the voltage of the D− and D+ lines below the maximum allowed voltage of 0.3 V for a low output state

(29)

3.1 Universal Serial Bus 13 during two bits time and then transitioning to a differential “0” for a low-speed bus or a differential “1” for a high-speed bus [7].

Token Packets

Figure 3.9: Data fields and number of bits for each field in a token packet. lsband msb is shown for the payload of the packet.

A token packet is a packet that only the host is allowed to issue, it consists of a sync field (common to all packets) followed by a packet identifier (pid), an address (ADDR), an endpoint address (EN DP ), a cyclic redundancy checksum (CRC5) and ending with an end-of-packet signal (eop) [7]. Figure 3.9 shows the structure of a token packet.

There are three types of packet identifiers for a token packet, I N , OU T , and

SET U P [7], for further details refer to Table 3.2, it should be noted that the bit

value for the packet identifier is four bits, the rest of the eight-bit fields consist of the one’s compliment check field.

Table 3.2:Packet identifier types for a token packet, their corresponding bit values and where the ADDR and EN DP fields should point to [7].

Packet identifier Value ADDR & EN DP point to

IN 1001 Endpoint transmitting packet

OUT 0001 Reciever of packet

SETUP 1101 Reciever of packet

Start of Frame Packets

Figure 3.10:Data fields and number of bits for each field in a start-of-frame packet. lsb and msb is shown for the payload of the packet.

Figure 3.10 shows the structure of a start-of-frame (sof) packet. Start of frame packets are sent by the host to indicate the start of a new frame and delivers timing information to the device. These packets are sent at a rate of once per

(30)

14 3 Theory

1 ms ± 0.0005 ms for a full-speed bus [7]. Table 3.3 list the types of identifier and the corresponding value for the pid field.

Table 3.3:Packet identifier types for a start-of-frame packet and correspond-ing bit values [7].

Packet identifier Value

SOF 0101

Data Packets

Figure 3.11: Data fields and number of bits for each field in a data packet. lsband msb is shown for the payload of the packet.

There are four different types of data packets, DAT A0, DAT A1, DAT A2, and

MDAT A, the type is indicated by the pid field of the packet (refer to Figure 3.11).

The DAT A2 and MDAT A types are only used for high-speed isochronous trans-missions. Either a DAT A0 or a DAT A1 packet are sent for every transfer as an error checking system, if two packets of the same type are received sequentially the receiver will discard the last packet [7]. Table 3.4 shows the different types of packet identifiers for the data packets along with their corresponding values and use.

Table 3.4:Packet identifier types for data packets, corresponding bit values and use [7].

Packet identifier Value Use

DATA0 0011 For even packets

DATA1 1011 For odd packets

DATA2 0111 Isochronous transactions MDATA 1111 Isochronous transactions

Handshake Packets

A handshake packet is shown in Figure 3.12. There are three types of handshake packets common to all usb speeds and two additional types that are limited to high-speed transmissions. Handshake packets are used to report the status of a transaction, i.e. if it for example was successful or not. It consists only of the

(31)

3.1 Universal Serial Bus 15

Figure 3.12: Data fields and number of bits for each field in a handshake packet. lsb and msb is shown for the payload of the packet.

sync signal, a packet identifier and an end-of-packet. In Table 3.5 each handshake packet type is described along with its use.

Table 3.5:Packet identifiers for handshake packets, their corresponding val-ues and use [7].

Packet identifier Value Use

ACK 0010 Receiving device has received an error-free data packet and accepted it.

NAK 1010

Receiving device received a data packet with some error and cannot accept the packet or the device has no data to transmit.

STALL 1110 Indicates that inability to transmit or receive data or an unsupported control pipe request. NYET 0110 No response from the receiver.

ERR 1100 Split transaction error.

3.1.6

Transactions

In this section transactions in usb will be described concerning typical control and interrupt transfers, bulk and isochronous transfers will not be discussed to limit the scope of this section, for further reading see the Universal Serial Bus specification revision 2.0.

There are three basic transaction types in usb, each consisting of three packets. These types are I N -transactions, OU T -transactions and SET U P -transactions [12].

TheI N -Transaction

This is a transaction from the device to the host. The host initiates the transac-tion with a token packet of the I N type, this is followed by a response from the device with one or more data packets ending with the host acknowledging the transaction with a handshake packet.

(32)

16 3 Theory

If the device is not ready to send data to the host, the device will reply to the hosts IN packet with a N AK handshake packet.

TheOU T -transaction

This is a transaction from the host to the device. The host initiates the transac-tion with an OU T packet, this is followed by one or more data packet from the host to the device ending with the device acknowledging the transaction with a handshake packet.

TheSET U P -transaction

This is a transaction from the host to the device. The host initiates the transac-tion with a SET U P token-packet, this is followed by an 8 byte long data packet of type DAT A0 ending with the device acknowledging the transaction with a handshake packet.

Transactions during a control transfer

Control transactions are used to control and configure devices, they are always sent to the default control pipe 0 on the device. A control transfer can have up to three stages, the Setup Stage, the Data Stage and the Handshake stage.

The setup stage always starts with a SET U P -transaction where the data packet consists of a descriptor of the type of request.

Depending on the type of request the optional data stage then one or more

I N - or OU T -transaction.

The status stage then follows where the device reports on the status of the re-quest. This stage consists of one I N - or one OU T -transaction with a data packet of type DAT A0 of zero length. Figure 3.13 shows a typical flow for a complete control transfer.

Transactions during an interrupt transfer

Interrupt transfers are used to regularly receive data from a device or send data from the host although the former is more common. One use could, for example, be reviewing coordinates from a mouse, keypresses from a keyboard or values from a joystick.

The interval at which the host will request a transfer is specified in the end-point descriptor, which will be further discussed in section 3.1.7. This interval specifies the guaranteed longest interval between a request, but the host may choose to request a transfer more often.

The packet size of interrupt transfers varies with the speed of the bus, from 8

bytes for a low-speed bus to 1024 bytes for a high-speed bus.

For an I N -type transaction, the host will poll the device with I N -token pack-ets, if the device has data queued it will then send it to the host, otherwise it will send a N AK-handshake packet. Figure 3.14 shows typical behaviour in both of these cases.

(33)

3.1 Universal Serial Bus 17

Figure 3.13:Typical flow for a control transfer.

Figure 3.14:Typical transaction flow during an interrupt transfer.

3.1.7

Descriptors

Descriptors are pre-defined data structures that provide information about the device to the host. This section will discuss the most common standard

(34)

descrip-18 3 Theory

tors, the device descriptor, the configuration descriptor, the interface descriptor and the endpoint descriptor. For a more in-depth report of these and the other standard descriptors, see the usb Specification revision 2.0 chapter 9.6, it is worth mentioning string descriptors, however, since they will be mentioned in this sec-tion.

String descriptors are optional, but they contain a string containing informa-tion about something concerning the device in string form, for further reading refer to chapter 9.6.7 of the usb Specification revision 2.0. There are also device class-specific descriptors, the hid device-class specific ones will be discussed in section 3.1.10.

All descriptors begin with the two same fields, the first contains the size of the descriptor in the number of bytes, and the second one contains an identifier for the type of descriptor, see Table 3.6.

Table 3.6:The beginning fields for all descriptors [7].

Offset Field Size (bytes) Use

0 bLength 1 Size in bytes

1 bDescriptorType 2 Descriptor type

n . . . Parameters for descriptor

The device descriptor

The device descriptor is usually the first descriptor that the host request from the device. It contains general information about the device that the host uses to fur-ther configure and set-up the device, as such, fur-there is only one device descriptor on each device [7], [8]. Table 3.7 contains the format of the device descriptor.

The configuration descriptor

The configuration descriptor contains information for the host on how to config-ure the device, for example, how much power the device needs, thus each device has at least one configuration descriptor. Each configuration descriptor contains one or several interface and endpoint descriptors which are returned along with the configuration descriptor when the host requests a configuration descriptor from the device [7], [8]. Table 3.8 contains the format of the configuration de-scriptor.

The interface descriptor

A device configuration can have one or several interfaces associated with it, the interface descriptor provides information about what features one of those inter-faces implement. Each interface can have one or more settings, although only one can be active at a time. As noted in section 3.1.7 this descriptor is returned together with the configuration descriptor. Table 3.9 contains the format of the interface descriptor.

(35)

3.1 Universal Serial Bus 19

Table 3.7: Format of the device descriptor. Note that the Vendor ID is pro-vided by the usb Implementers forum [7], [8].

Offset Field Size (bytes) Use

0 bLength 1 Size in bytes

1 bDescriptorType 2 Descriptor type

2 bcdUSB 2

Highest supported USB revision of the device

4 bDeviceClass 1 Class code

5 bDeviceSubClass 1 SubClass code

6 bDeviceProtocol 1 Protocol Code

7 bMaxPacketSize0 1

Maximum

allow-able packetsize for endpoint zero

8 idVendor 2 Vendor ID

10 idProduct 2 Product ID

12 bcdDevice 2 Device release number

14 iManufacturer 1 Index for the

manufac-turer string descriptor

15 iProduct 1 Index for the product

string descriptor

16 iSerialNumber 1

Index for the serial number string descrip-tor

17 bNumConfigurations 1

Number of possible configurations of the device

The endpoint descriptor

The endpoint descriptor is used by the host to find out the requirements of each endpoint, for example, what types of transfers it accepts, what packet sizes it ac-cepts and how often it expects to be polled. The endpoint descriptor is returned alongside the interface descriptors and configuration descriptor as stated in sec-tion 3.1.7, it should be noted that there is no endpoint descriptor for endpoint zero, since it is predefined as a control endpoint. Table 3.10 contains the format of the endpoint descriptor.

3.1.8

The standard device requests

Device request is control transfers initiated by the host sent as an 8 byte SET U P -packet which contains the specific request, request type and direction of data, refer to Table 3.11.

(36)

20 3 Theory

Table 3.8:Format of the configuration descriptor [7], [8].

Offset Field Size (bytes) Use

0 bLength 1 Size in bytes

1 bDescriptorType 2 Descriptor type

2 wTotalLength 2

Total size in bytes of the descriptors re-turned when request-ing the configuration descriptor

4 bNumInterfaces 1 Number of interfaces

5 bConfigurationValue 1

Value to use as an argu-ment when requesting this configuration

6 iConfiguration 1

Index for the string de-scriptor with a descrip-tion of this configura-tion

7 bmAttributes 1 Power and wake-up

settings

8 bMaxPower 1

Maximum power con-sumption, in number of 2 mA units

Table 3.9:Format of the interface descriptor [7], [8].

Offset Field Size (bytes) Use

0 bLength 1 Size in bytes

1 bDescriptorType 2 Descriptor type

2 bInterfaceNumber 1 Number for identifica-tion of this interface 4 bAlternateSetting 1 Value to use to select

an alternate setting

5 bNumEndpoint 1

Number of endpoints associated with this in-terface

6 bInterfaceClass 1 Class Code

7 bInterfaceSubClass 1 SubClass Code

8 bInterfaceProtocol 1 Protocol Code

9 iInterface 1

Index for the string de-scriptor with a descrip-tion of this interface

(37)

3.1 Universal Serial Bus 21

Table 3.10:Format of the endpoint descriptor [7], [8].

Offset Field Size (bytes) Use

0 bLength 1 Size in bytes

1 bDescriptorType 2 Descriptor type

2 bEndpointAddress 1

The number for the endpoint and its direc-tion

3 bmAttributes 1

Transfer type, synchro-nisation type and us-age type

4 wMaxpacketSize 2

Maximum packet size this endpoint can re-ceive or send.

6 bInterval 1

Interval for polling the endpoint, for example, interrupt transfers

Table 3.11:Format of the setup data [7], [8]. Offset Field Size (bytes) Use

0 bmRequestType 1

Bitmap containing in-formation about the type of request, data direction and who is the recipient of the re-quest.

1 bRequest 1 The request made.

2 wValue 2 Value depends on

re-quest.

4 wIndex 2 Most often used topass an offset or index. 5 wLength 2 Size of data to be sentif any.

are class-specific, the standard request will be further described below and the class used in this thesis, the Human Interface Device (hid) class, will be further discussed in section 3.1.10. The standard requests provide functions to the host such as requesting and setting descriptors, features and configuration as well as requesting the status of the device. Refer to Table 3.12 for a brief overview of all the standard request or the usb Specification revision 2.0 chapter 9.4 for more detail.

(38)

22 3 Theory

Table 3.12: The standard requests and their corresponding bitmaps and value, if several bitmaps are stated they depend on the recipient (device, interface or endpoint) [7], [8].

bmRequestType bRequest bRequest Value Use

10000000b 10000001b 10000010b

GET _STATUS 0x00

Returns status of the recipient of the re-quest.

00000000b 00000001b 00000010b

CLEAR _FEATURE 0x01 Disables a feature.

00000000b 00000001b 00000010b

SET _FEATURE 0x03 Enables a specific fea-ture on the recipient.

00000000b SET _ADDRESS 0x05

Sets the address used by future request for a device.

10000000b GET _DESCRIPTOR 0x06 Returns the specific

descriptor requested.

00000000b SET _DESCRIPTOR 0x07 Adds new descriptor

or sets an existing one.

10000000b GET _CONFIGURATION 0x08

Returns the current configuration value of the device.

00000000b SET _CONFIGURATION 0x09 Sets the configuration of a device.

10000001b GET _INTERFACE 0x10

Returns the currently alternate setting of an interface.

00000001b SET _INTERFACE 0x11 Selects an alternate set-ting on an interface.

10000010b SYNCH _FRAME 0x12

Sets and reports an endpoints synchro-nization frame.

3.1.9

From plug-in to an established connection

The process wherein a host detects and configures a newly attached device is called enumeration [8]. When a user connects a usb device into a hub it allows the device to draw up to 100 mA from the hub and this, in turn, sets the device in the attached state. After detecting a voltage of at least 0.8 V on the V BU S line a device is required to bring the pull-up line to a high state (this is one of the signal lines, either the D+ or D− line depending on the speed of the device). After this, the hub will report the event to the host which will, in turn, send a Get Port Status request which will return the status of the port to the host. The host

(39)

3.1 Universal Serial Bus 23

then resets the device by setting both the D+ and D− signal line to a low state for a minimum of 10 ms. After the reset, the device will be in the default state with its registers reset and being able to respond to requests at default endpoint zero. Now the host can send a GET _DESCRI P T OR request which will inform the host of the maximum packet size for the device endpoint zero and will, de-pending on implementation, reset the device once again. The host then sends a SET _ADDRESS request and assigns a new address for further communica-tion with the device. Now the host will request addicommunica-tional informacommunica-tion from the device by sending GET _DESCRI P T OR request on the newly assigned ad-dress, this information is then used to load an appropriate driver for the host which will then lastly set an appropriate configuration of the device using a

SET _CON FI GU RAT I ON request. The device is now in a configured state and

allowed to draw as much power as it has specified in its configuration from the

V BU S. The device is now ready to be used by the user.

3.1.10

USB

device classes

Universal Serial Bus devices are segmented into different classes that provide similar functionality or have similar data transmission needs, a single physical device can consist of several different usb classes, for example, a joystick with force-feedback functionality could be part of both the Human Interface Device (hid) class for the basic joystick functions and the Physical Interface Device (pid) class for the force-feedback functionality.

There are currently 22 different class codes defined and the device class is specified in the interface descriptor or device descriptor depending on the type of class, although most use the interface descriptor (only 2 of the defined classes only use the device descriptor, the hub and billboard device classes). To indicate to the host that there is a device class specified in the one or more interface de-scriptors the device must use class code 00H in its device descriptor [13]. The hidclass will be discussed further in the section below since that class has the most impact on this thesis.

TheHIDdevice class

The usb Human Interface Device class is designed mainly for devices that interact with humans, such as keyboards or mice, but it’s not limited to only such devices and even such unlikely things as exercise machines [14] could use the hid class.

hidclass devices typically require a low delay in regards to for example key-presses because of this control transfers can not be used due to the possibility of them being delayed on a busy bus, thus interrupt transfers are used in the hid class in addition to control transfers, because of this all devices complying with the hid class needs to, in addition to the default control endpoint zero, have at least one I N interrupt endpoint, with a possibility to add one OU T interrupt endpoint as well. As noted in section 3.1.4, interrupt transfers give a guaran-teed timing between transfers ensuring low latency. Due to the unpredictable behaviour of human interaction the host needs to poll the device continuously

(40)

24 3 Theory

for changes.

HID specific requests There are six different types of requests that are

class-specific to the hid class, which are used to get or set reports (the data structure used in hid class transfers), get or set idle which can be used to suppress a specific report and get or set protocol which is used for boot devices such as keyboards and mice, for further details refer to Table 3.13 and the Device Class Defenition for hid [15].

Table 3.13: The six different hid class-specific request, their request type bitmap, request hexadecimal value and their use [8], [15].

bmRequestType bRequest bRequest Value Use

10100001b GET _REPORT 00

Returns a report to the host over the control pipe..

10100001b GET _IDLE 01 Returns the idle rate to

the host.

10100001b GET _PROTOCOL 03

Returns zero in the wValue field if boot protocol is active or one if report protocol is active.

nil nil 04 - 08 Reserved

00100001b SET _REPORT 09 Sends a report to the

device.

00100001b SET _IDLE 0A

Inhibits a particular re-port until the values in the report changes or a time-limit are reached.

00100001b SET _PROTOCOL 0B

Switches between the boot and the report protocol.

TheHIDDescriptor The hid descriptor provides the host with basic information on how to communicate with the device such as the size of the report descriptor and if the device can be used even if the host drivers are not loaded, such as during boot. Refer to Table 3.14 and the Device Class Definition for hid for a more detailed description of the hid descriptor [15].

HIDReports All data transfers in the hid class use reports, reports are a fixed-length data form that is defined in the devices Report descriptor, it informs the host what kind of data is to be expected from the device and the format of the

(41)

3.1 Universal Serial Bus 25

Table 3.14:Format of the hid descriptor [8], [15].

Offset Field Size (bytes) Use

0 bLength 1 Size in bytes.

1 bDescriptorType 1 Descriptor type.

2 bcdHID 2

Number in binary-coded decimal (bcd) indicating hid release number.

4 bCountryCode 1

Used to indicate local or language-specific hardware, such as a Swedish keyboard.

5 bNumDescriptors 1

Represents the num-ber of class descrip-tors.

6 bDescriptorType 1 Represents the class

descriptor type

7 wDescriptorLength 2 Size of the report de-scriptor.

data [8], [15]. In Listing 3.1 parts of a Report descriptor from a Logitech Extreme 3D Pro joystick is presented, the information contained in this descriptor is for example what is the intended usage of the device or the kind of inputs it pro-vides, as seen in the example the device reports that it has a logical interface with two reports of a size of 10 bits that provides an X and a Y value between 0 and 1023. The data in the figure has been modified from its original form to improve readability. See Appendix A for the original capture.

Listing 3.1: Report descriptor from a Logitech 3D joystick captured using Wireshark.

HID Report

Usage Page: Generic Desktop Controls Usage: Joystick Collection: Application Collection: Logical Report count: 2 Report size: 10 Logical minimum: 0 Logical maximum: 1023 Physical minimum: 0 Physical maximum: 1023 Usage: X Usage: Y

(42)

26 3 Theory

3.1.11

USB

On-The-Go and Embedded Hosts

usbOn-The-Go (otg) and Embedded Hosts is a supplement to the normal usb 2.0 standard that allows devices to act as hosts without the need of being as ca-pable as a normal PC. The documentation defines these devices that support a specific set of peripherals as Targeted Hosts. The main difference between a de-vice using usb otg or acting as an Embedded Host is that the usb otg dede-vice support role-swapping on a single port while the Embedded Host has dedicated host-ports, this also means that the usb otg device can only be either host or device at one single time while the Embedded Host device might be both, de-pending on the design of the device. [8], [16]

An usb otg device always has one, and only one, usb Micro-AB receptacle while the Embedded host might have one or more usb Standard-A or Micro-AB receptacles, it might also have separate receptacles providing device ports such as Standard-B, Mini-B or Micro-B. [8]

In Figure 3.15 is three common usb connectors, Standard-A, Standard-B and Micro-B and in Figure 3.16 a Micro-AB receptacle, as well as a Micro-B receptacle, can be observed.

Figure 3.15: Common USB-plugs, from left to right, a Standard A-plug, a Standard B-plug, and a Micro-B plug.

Figure 3.16:To the left a USB AB receptacle and to the right a Micro-B.

3.2

Serial Peripheral Interface

Serial Peripheral Interface (spi) is a protocol for communication between inte-grated circuits. Similar to the Universal Serial Bus there is one device that con-trols the bus, in spi this is called the Master and the other devices on the bus

(43)

3.3 Single-Board Microcontrollers 27

is called Slaves. As seen in figure 3.17 spi uses four signal lines, one carrying a clock signal from the master to the slaves, one slave select (SSn) which the

mas-ter pulls to low to select which slave to communicate with, one data line in the direction from master to slave (MOSI) and one data line with the direction slave to master (MI SO). There is however no real standard or specification on spi and implementation can differ from different microcontrollers and applications. [17]

Figure 3.17:A simple block diagram presenting an SPI connection between a master and a slave device.

3.3

Single-Board Microcontrollers

A Single-Board Microcontroller is a circuit board with a microcontroller that also has all the necessary I/O, clocks, and memory to be able to use it straight out of the box. Today many components are integrated into the main microcontroller circuit such as in the Atmel AVR microcontroller. This section will further dis-cuss the single-board microcontrollers used in this thesis.

3.3.1

Arduino Due

Arduino Due, pictured in Figure 3.18, is a single-board microcontroller based on the 32-bit Atmel Cortex-M3 risc processor, the chip used in the Arduino Due is called the Atmel SMART SAM3X which features an 84 MH z clock, a High-Speed usb otg port, 512 K B flash memory and 96 K B SRAM. The Arduino Due board features one native usb port connected to the SAM3X (the top left usb Micro port in Figure 3.18). On the board there is also an Atmel ATmega16U2 microcontroller, this controller is connected to the second usb Micro port and is used to provide power and to program the SAM3X microcontroller. The board offers several I/O possibilities and includes a dedicated spi-header. Unlike most Arduino boards the Arduino Due runs on a voltage of 3.3 V this is an important factor to have in mind when connecting it to other peripherals running on 5 V . [18], [19]

3.3.2

Arduino Micro

Arduino Micro, pictured in Figure 3.19, is a single-board microcontroller based on the 8-bit ATmega32U4 risc chip, it has a 16 MH z clock, 32 K B of flash

(44)

mem-28 3 Theory

Figure 3.18: An Arduino Due, Atmel SAM3X chip in the middle with na-tive usb Micro-AB port on top-left side and programming usb Micro-B port below it.

ory, 2.5 K B of SRAM and 1 K B EEPROM. The Arduino Micro offers several I/O possibilities including a usb-port with possibilities to emulate a mouse and key-board to a connected PC. [20], [21]

Figure 3.19: Arduino Micro, ATmega32U4 chip in the middle of the board and USB Micro-B port to the left.

3.3.3

Logic-level Converter

A logic level converter is used to convert logic levels between systems that have different logic levels [22]. In Figure 3.20 an example of a logic level converter is presented, it is based on a BSS138 N-Channel Logic Level Enhancement Mode Field Effect Transistor. The converter is bi-directional and able to convert 3.3 V to 5 V and the reverse at the same time. It has four signal input and output pins for both the high- and low- voltage sides, as well as ground and voltage pins for both sides. [23], [24]

3.4

Hands-on Throttle and Stick & Joysticks

The Hands-on Throttle And Stick concept were first introduced with the British “English Electric Lightning” fighter aircraft in the 1950s [25]. The Swedish Saab

(45)

3.4 Hands-on Throttle and Stick & Joysticks 29

Figure 3.20:A logic-level converter from sparkfun, high voltage side on the top and low voltage side at the bottom.

35 Draken from the same time period also incorporated similar design elements. In the 1970s the F/A-18 was the first aircraft in the US Navy and Marine Corps that used the concept [26].

The concept localizes all the controls a pilot needs during combat to the flight stick and throttle so that pilots do not have to move their hands from them [26].

The modern gaming joystick has evolved from another ancestor, namely the controller for Atari’s Pong game in the 1970s which later evolved into the Atari Joystick released in 1977 [27]. One can however easily see the similarities be-tween the two different concepts.

3.4.1

Logitech Extreme 3D Pro

In Figure 3.21 the Logitech Extreme 3D Pro is pictured, it’s a joystick with 12 buttons, a hat-switch, throttle, and twist function. It connects to a PC via a usb connection. [28]

(46)

30 3 Theory

(47)

4

Method

The following chapter will describe the steps taken to design and construct the system.

4.1

Introduction

At the beginning of the study, a demand specification was developed together with the client. It was at this stage determined that modifying the existing radar control system should preferably be kept to a minimum. Since the software in the control system was using a normal mouse and keyboard as inputs, including key-board shortcuts, a solution based on simulating mouse and keykey-board commands was decided on. Based on this, four demands on the solution were formed:

1. The system should have a joystick as input

2. The signals from the joystick should be converted by the device and pre-sented to the computer as keyboard and mouse commands through a usb connection

3. There should be a graphical user interface (gui) to enable the user to change what commands the device sends to the computer

4. There should be a possibility in the future to add a flight stick from the SAAB 37 Viggen as an input

A visual representation of these demands can be seen in figure 4.1. The dashed lines of the Viggen HOTAS box indicates that there should be a possibility to implement that functionality in the future.

(48)

32 4 Method

Figure 4.1:A block schematic representation of the demand specification.

4.2

Pre-study

Based on the previously stated demands a pre-study was performed to find out how to best solve the problem in the given timeframe.

To reduce the chance that system overheads would impact the response of the device the focus fell on various microcontroller solutions instead of single-board computers such as a Raspberry Pi. The microcontroller had to be readily available due to the time constraints and to meet the requirements listed in section 4.1 i.e. act as both a usb host and client at the same time. While no microcontroller meeting these criteria in itself was found, two single-board microcontrollers that met either the host or client requirement and the availability criteria was, the Arduino Micro and Arduino Due.

To reduce development time it was decided to use publicly available code libraries where applicable.

To connect the two boards some form of communication was needed, the choice fell on spi due to its simplicity and speed.

The pre-study then continued with the studying of datasheets for the respec-tive microcontroller, and the study of usb specifications.

4.3

Implementation

After the pre-study components were ordered and plans for a simple gui appli-cation was formed.

To program the two microcontrollers the Integrated Development Environ-ment (ide) PlatformIO was used, it is an extension to the VSCode code editor from Microsoft containing all that is needed to program an Arduino in one

(49)

pack-4.4 Deciding on a programming method 33

age. The programming languages that were used were C/C++ for the program-ming of the Arduino devices. For the programprogram-ming of the gui, the language Kotlin was used in combination with the IntelliJ IDEA ide.

The following sections will describe each step taken during the implementa-tion and programming of the device. The programming code will not be gone through in detail since the whole program covers thousands of lines of code, it will instead be discussed more broadly with examples of important parts of the code.

4.4

Deciding on a programming method

Before starting to program the Arduino boards a brief composition of the in-tended code structure was formed. An Object-Oriented approach was decided on due to the author’s prior knowledge of the model and industry practice. The brief composition consisted of dividing different functionality between different classes, one class to handle spi communication between the boards, one to han-dle the usb host functionalities and one to hanhan-dle the communication with the computer in the Radar rig.

4.4.1

Implementing

SPI

The spi was implemented in a class called “HotasSerial” with two subclasses called “SerialMaster” and “SerialSlave”. The uml inheritance graph is shown in Figure 4.2. The rest of the section will further describe some of the functional-ities in this class.

The Arduino boards have a library for implementing spi functionality with the Arduino as a master device this library was used to implement the “Serial-Master” subclass. Listing 4.1 shows the settings used, a 2 MH z clock, sending the Most Significant Bit (msb) first and using spi Mode 0, i.e. clock idle low and sampling of data on the rising edge of the clock [29].

Listing 4.1:Configuring the SPI settings.

SPISettings settingsSlave(2000000, MSBFIRST, SPI_MODE0);

The Master device is then rather straight forward to set up, the Slave Select (SS) pin on the Master device is set to act as an output and then brought high to ensure its state. After that, the library can be enabled with the SP I.begin() command. This setup of spi can be seen in Listing 4.2.

A caveat with using the spi library from Arduino is that it assumes that the Arduino device is intended to be the Master. In this case, the Arduino Micro is intended to be the Slave device. This requires some modification of the code from the earlier case, we cannot use the prebuilt library. Instead, the Slave will be configured using the registers of the microcontroller manually. In Listing 4.3 we can see that the Master Input Slave Output (MI SO) pin is configured as an

(50)

34 4 Method

Figure 4.2: The inheritance uml chart for the HotasSerial class with sub-classes.

Listing 4.2:Initialization of spi on the Master device.

void SerialMaster::init(){ #ifdef DUE_BOARD

// Enable output on Slave select pin: pinMode(SS, OUTPUT);

// Ensure Slave Select stays high at startup: digitalWrite(SS, HIGH);

//Turn on SPI SPI.begin (); #endif }

output, the spi Enable (SP E) bit and the spi Interrupt Enable (SP I E) is set and lastly, the Master/Slave Select bit is cleared to ensure that Slave Mode is selected. Now the Arduino Micro can receive data from the Master Arduino Due. It uses an interrupt routine to store the data received from the Due in a buffer.

An example of the code for receiving data from the Due is seen in Listing 4.4. First, there is a busy wait for the receive interrupt routine to complete. Then there is a check that the eot character is in the buffer, after that it ensures that the buffer ends with a zero and the eot character is stripped from the buffer. The

(51)

4.4 Deciding on a programming method 35

Listing 4.3:The configuration of the Arduino Micro in Slave mode. Modified code from original written by Nick Gammon, http://www.gammon.com.au/ [30]. License: https://creativecommons.org/licenses/by/3.0/au/

void SerialSlave::init(){ #ifdef MICRO_BOARD

// Have to send on Master Input, ie slave output pinMode(MISO, OUTPUT);

// Turn on SPI: SPCR |= bit(SPE); // Turn on interrupts: SPCR |= bit(SPIE);

// Make sure MSTR bit is zero: bitClear(SPCR, MSTR);

pos = 0;

process_it = false; #endif

}

buffer is then copied to the supplied character pointer and then cleared.

Logic level conversion

As noted in section 3.3.1 and 3.3.3 one should take care when connecting two systems that use different logic levels. This is the case with the Arduino Due and Arduino Micro which uses 3.3 V and 5 V respectively. To ensure a safe connection between the devices when implementing spi a logic level converter was used. The logic level converter was connected as an intermediary between each of the Clock, Master Output Slave Input, Master Input Slave Output, Slave Select, Voltage and Ground wires.

Figure 4.3 demonstrates the SPI connection of the Arduino Due and the Ar-duino Micro. On the right side of the figure, one can note the high voltage of 5 V from the Arduino Micro and on the left side the lower voltage of 3.3 V from the Arduino Due.

Figure 4.3:Schematic demonstrating the SPI connection of the Arduino Due and the Arduino Micro using the logic level converter.

(52)

36 4 Method

Listing 4.4: Code for receiving a byte, the code copies the received byte from the buffer to a supplied uint8_t pointer. Modified code from origi-nal written by Nick Gammon, http://www.gammon.com.au/ [30]. License: https://creativecommons.org/licenses/by/3.0/au/

void SerialSlave::recieve(char* out){ //Wait for data to be availible

while (!process_it){}

//Sanity check that EOT character is in the buffer

if (memchr(buf, EOT, sizeof(buf))) {

//Sets the last carachter the //buffer points to to null buf [pos] = 0;

//Remove the EOT character from string. buf [pos -1] = ’\0’;

//Resets the position of the buffer "pointer" pos = 0;

memcpy(out, buf, sizeof(buf)); memset(buf,(char)0, sizeof(buf) ); #ifdef MICRO_BOARD SPDR = (char)0; #endif process_it = false; }else{ memset(buf,(char)0, sizeof(buf) ); memcpy(out, buf, sizeof(buf)); process_it = false;

} }

4.4.2

Implementing USB Host

Atmel offers a C library for implementing large parts of the low-level code for the usb otg interface of the Cortex-M3. It provides functions for the clearing, setting and receiving of values from usb related registers in the processor in a more human-readable format.

The functionality was implemented with the intent to be able to implement further usb devices in the future with less effort. Therefore a layered tree of a class with subclasses with different responsibilities was created, the whole inher-itance diagram between the classes can be seen in Figure 4.4. The highest class created, at the top of the aforementioned diagram was called H otasU SBCore it implements common functionality between USB devices such as the layout of a SET U P packet and different types of descriptors as structs in the C++

References

Related documents

stage. It is definitely more focused on the pursuit of a new style and attractiveness to the customer due to its totally different appearance comparing to the products that exist

Denys Calvaert, Amor and Psyche, 1568, oil on canvas, copyright Stockholm University, 2020, X-ray image.. Denys Calvaert, Amor and Psyche, 1568 oil on canvas, cm 75 x cm 59, copyright

The bond graph will, after a completed bicausal algorithm, show all possible causal paths, particularly a path in an algebraic loop or between two dependent storage elements..

We have in Section 3.3 presented an initialization algorithm for modes with derivative causality at one storage element and shown that the algorithm yields initial values for the

Projektledaren Lena Johansson beskrev att kulturmiljö kan vara en resurs för attraktivitet på flera sätt; för turism och besöksnäring, för människors livskvalitet men också

As one of the aims of this study was to look closer at what context the lexical words were put in, the example in this case being asexual, as it is unique to the community,

Thanks to the pose estimate in the layout map, the robot can find accurate associations between corners and walls of the layout and sensor maps: the number of incorrect associations

In a number of examples we show how to stabilize the zero dynamics of dierent systems by switching between dierent output zeroing controllers, where no continuous stabilizing