Monday, December 28, 2015

Ultimate Classic Game Console Joystick to USB Adapter

Background

Original Classic Joystick to USB AdaptorBack in September of 2014 I posted an article (Arduino: Classic Joystick to USB Adaptor) explaining how to use an Arduino Leonardo or Arduino Micro to create an adapter that would allow a classic game console controller/joystick (e.g. Atari 2600, ColecoVision, and possibly others) to work on a modern computer (e.g. Windows PC, Mac, or Linux). This adapter mapped the various joystick actions (Up, Down, Left, Right, Fire Button, etc.) to keyboard keystrokes. I used the keystrokes used by the ADAMEm (http://www.komkon.org/~dekogel/adamem.html) ColecoVision / Coleco ADAM emulator, but any keystroke mapping could be used.

Throughout 2015 I have been posting the following articles that explain how to make an Arduino Leonardo or Arduino Micro appear as a USB Game Controller:

All of these articles have been building up to this article which will explain how to create the “ultimate” classic game console joystick to USB adapter.

Overview

Final VersionThis article describes how to use an Arduino Leonardo or Arduino Micro to make up to three classic console joysticks (e.g. Atari 2600, ColecoVision, and possibly others) available to a modern computer (e.g. Windows PC, Mac, or Linux). This adapter can be placed into one of the following modes:

  • Joystick Mode
    Each of the three classic console joysticks appear as a Game Controller.
  • ADAMEm Mode
    Configured for use with the ADAMEm emulator. Joystick 1’s direction and fire buttons are mapped to a Game Controller and the keypad is mapped to the keyboard’s numeric keypad keys. Joystick 2 is mapped to keyboard keys (e.g. up arrow key, down arrow key, etc.). This allows ADAMEm to support two player games. Joystick 3 is not used in this mode.
  • MAME Mode
    Configured for use with the MAME emulator. All three joysticks’ direction and fire buttons are mapped to the three Game Controllers. The numeric keys on all three joysticks are mapped to keyboard keys.

Classic Console Joysticks

Atari 2600 Joysticks

Atari-2600-Joystick The Atari 2600 joysticks are the simplest of the controllers supported by this adaptor. They have a D-Subminiature Female 9 Position connector. The following table describes the function of each pin:
DSUB9-Pinout
Pin Number Description
1 Up
2 Down
3 Left
4 Right
6 Fire
8 Ground

ColecoVision Controllers

ColecoVision-Joystick ADAM-Joystick

ColecoVision Controller

ADAM Controller

ColecoVision-Super-Action-Controller  

ColecoVision Super Action Controller

 

The ColecoVision and ADAM joysticks are much more complicated. In addition to the four direction control stick, they have two fire buttons (or 4 in the case of the Super Action Controller) and a 12 button keypad. Like the Atari 2600 joystick, they have a D-Subminiature Female 9 Position connector, but the pin outs have two different modes. When pin 8 is grounded, pins 1-4 are the four directions and pin 6 is the left fire button. When pin 5 is grounded, pins 1-4 are a keypad scan code and pin 6 is the right fire button. The table below lists the pin outs for the ColecoVision and ADAM controllers.

Pin Number Pin 8 Grounded Pin 5 Grounded
1 Up Bit 0
2 Down Bit 2
3 Left Bit 3
4 Right Bit 1
5 Keypad Mode Keypad Mode
6 Left Fire Right Fire
7 Spinner Spinner
8 Control Stick Mode Control Stick Mode
9 Spinner Spinner

The keypad scan codes are listed below:

Keypad Value
Bit 3 / Pin 3
Bit 2 / Pin 2
Bit 1 / Pin 4
Bit 0 / Pin 1
Decimal Value
Hex Value
1
0
0
1
0
2
2
2
1
0
0
0
8
8
3
0
0
1
1
3
3
4
1
1
0
1
13
D
5
1
1
0
0
12
C
6
0
0
0
1
1
1
7
1
0
1
0
10
A
8
1
1
1
0
14
E
9
0
1
0
0
4
4
0
0
1
0
1
5
5
*
0
1
1
0
6
6
#
1
0
0
1
9
9
Purple Fire Button
0
1
1
1
7
7
Blue Fire Button
1
0
1
1
11
B

The solution I have developed will support Atari 2600 joysticks, ColecoVision and ADAM controllers, and most of the ColecoVision Super Action Controllers’ functions. This solution does not currently support the Spinner located below the keypad on the Super Action Controllers.

Parts List

Required Parts

Quantity Item
1 Arduino Leonardo - http://arduino.cc/en/Main/ArduinoBoardLeonardo
or
Arduino Micro - http://arduino.cc/en/Main/ArduinoBoardMicro
3 D-Subminiature Male 9 Position Connector
For example: http://www.jameco.com/webapp/wcs/stores/servlet/Product_10001_10001_12504_-1, http://www.jameco.com/webapp/wcs/stores/servlet/Product_10001_10001_1975029_-1, etc.
3 LEDs (any color(s) you want)
3 330 Ohm Resistors (or whatever is appropriate for the LEDs chosen)
1 Momentary Push Button
1 - 3 Classic Console Joysticks
1 Solderless Plugin Breadboard or Solderable PC Breadboard

Optional Parts

Quantity Item
1Project Box

Hardware

D-Sub Male 9 Position Connector Preparation

DSUB-Prep-1

Depending on the type of D-Sub Male 9 Position connector you use, you may need to do some work to get the connector ready to use. In my case I used a connector and a SparkFun Serial DB9 Breakout (https://www.sparkfun.com/products/retired/8552), so I needed to do a little soldering to get it ready to use.

DSUB-Prep-2

Momentary Push Button Preparation

Depending on what type of momentary push button you use, you many need to solder some wires to the push button so it can be connected to the Arduino.

Momentary-Push-Button-Prep

LED Preparation

Depending on the type of LED you use and how you plan to package the final device, you many need to solder some wires to the LEDs so they can be connected to the Arduino.

Solderable PC Breadboard Preparation

For my project I used an Arduino Micro (http://arduino.cc/en/Main/ArduinoBoardMicro) which I soldered to a solderable PC breadboard. I wanted to make sure I had good connections between my Arduino Micro and my joystick lines, so I threaded very small wires through the breadboard to act as the conductive traces.

Arduino-Prep

Arduino-Prep-Back

Wiring Diagram

The following diagram shows how to connect the Arduino Leonardo or Arduino Micro to the three, D-Subminiature male 9-pin connectors, resistors, LEDs, and momentary switch.

Classic Controller to USB Adapter

The following table describes how the pins of the Arduino are connected to the Joystick’s D-Subminiature pins.

Arduino Description Joystick 1 Joystick 2 Joystick 3
0 RX – Reserved for serial communication      
1 TX – Reserved for serial communication      
2 UP / Data 0 1 1 1
3 DOWN / Data2 2 2 2
4 LEFT / Data 3 3 3 3
5 RIGHT / Data 1 4 4 4
6 FIRE 6 6 6
7 Spinner A 7 7 7
8 Spinner B 9 9 9
9 Emulation Mode Toggle Pin – Connect one end of momentary switch to this pin and connect the other end to ground      
10 ADAMEm Mode Indicator – connect to 330 Ohm resistor, 330 Ohm resistor is then connected to LED, which is connected to ground      
11 MAME Mode Indicator – connect to 330 Ohm resistor, 330 Ohm resistor is then connected to LED, which is connected to ground      
12 Joystick Mode Indicator – connect to 330 Ohm resistor, 330 Ohm resistor is then connected to LED, which is connected to ground      
13 Fire Monitor Pin – on-board led      
A0 Joystick 1 Keypad Mode 5    
A1 Joystick 1 Control Stick Mode 8    
A2 Joystick 2 Keypad Mode   5  
A3 Joystick 2 Control Stick Mode   8  
A4 Joystick 3 Keypad Mode     5
A5 Joystick 3 Control Stick Mode     8

Wiring-top   Wiring-back

Enclosure

So the final product would look nice (and I would not worry about my kids breaking any of the wires) I put the adapter into a project box. I had to drill holes for the momentary switch, the LEDs, and the d-subminiature connectors.

Enclosure-Front-Switch   Enclosure-back-switch   Enclosure-half   Enclosure-top-off-side   Enclosure-top-off-top   Enclosure-top-on-side

To finish it up I put some labels on the connectors and on the LED mode indicators.

Enclosure-labels

Software

Arduino made a major change to how they implemented the USB HID functionality in Arduino IDE Version 1.6.6, so I have two different sets of instructions depending on which version of the Arduino IDE you are using. I recommend using Version 1.6.6 or above if you can, because it is much simpler.

Arduino Version 1.6.5 and Below

  1. Follow the instructions provided in the following article to add 3 USB Game Controllers to the Arduino Leonardo or Arduino Micro: Add Up To 3 USB Game Controllers to Arduino Leonardo or Micro.
  2. Download and install the ClassicController library from the Arduino-1.6.5 branch of the MHeironimus/ClassicJoystickAdaptor GitHub repository. This library can be installed by copying it to the Arduino libraries folder (typically %userprofile%\Documents\Arduino\libraries).
  3. Download the ClassicJoystickAdaptor.ino sketch file from the Arduino-1.6.5 branch of the folder of the MHeironimus/ClassicJoystickAdaptor GitHub repository and open it in the Arduino IDE.
  4. Compile and upload the sketch file to the Arduino Leonardo or Arduino Micro.
  5. The adapter can be testing using the “Game Controllers” dialog in Microsoft Windows. See “Add Up To 3 USB Game Controllers to Arduino Leonardo or Micro” (http://mheironimus.blogspot.com/2015/04/add-up-to-3-usb-game-controllers-to.html) for more details on testing the adapter.

Arduino version 1.6.6 and Above

  1. Download and install the Arduino Joystick Library from the MHeironimus/ArduinoJoystickLibrary GitHub repository. This library can be installed by copying it to the Arduino libraries folder (typically %userprofile%\Documents\Arduino\libraries). For more information on how to install this library, see the following article: Arduino Joystick Library.
  2. Download and install the ClassicController library from the master branch of the MHeironimus/ClassicJoystickAdaptor GitHub repository. This library can be installed by copying it to the Arduino libraries folder (typically %userprofile%\Documents\Arduino\libraries).
  3. Download the ClassicJoystickAdaptor.ino sketch file from the master branch of the folder of the MHeironimus/ClassicJoystickAdaptor GitHub repository and open it in the Arduino IDE.
  4. Compile and upload the sketch file to the Arduino Leonardo or Arduino Micro.
  5. The adapter can be testing using the “Game Controllers” dialog in Microsoft Windows. See “Arduino Joystick Library” (http://mheironimus.blogspot.com/2015/11/arduino-joystick-library.html) for more details on testing the adapter.

Final Product

Final VersionI have tested this “ultimate” classic game console joystick to USB adapter on Windows 7, Windows 10, and Raspbian on the Raspberry Pi Model B. To work properly on the Raspberry Pi (or any other linux devices), see Linux Support for Arduino Leonardo / Micro USB Game Controllers.

Thursday, November 19, 2015

Arduino Joystick Library

IMPORTANT NOTE: This article is for Arduino IDE version 1.6.6 (or above). To add a USB Game Controller to an Arduino Leonardo or Micro using Arduino IDE version 1.6.5 (or below) see the following postings: Add USB Game Controller to Arduino Leonardo or Micro and Add Up To 3 USB Game Controllers to Arduino Leonardo or Micro.

Introduction

Out of the box the Arduino Leonardo and the Arduino Micro appear to the host computer as a generic keyboard and mouse. This article discusses how the Arduino Leonardo and the Arduino Micro can also appear as a generic Game Controller or Joystick. This project will only work with Arduino products based on the ATmega32u4 microcontroller (i.e. the Arduino Leonardo and the Arduino Micro). It will not work with the Arduino UNO, because it is based on the ATmega328 microcontroller.

The Arduino generic Game Controller provides the following:
  • X, Y, and Z axis
  • 32 buttons
  • X, Y, and Z axis rotation
  • Rudder
  • Throttle
  • 2 Point of View Hat Switches

Installing the Library

The latest version of the Arduino library that allows the Arduino Leonardo and Micro to appear as a Game Controller can be downloaded from the following GitHub repository:

https://github.com/MHeironimus/ArduinoJoystickLibrary/tree/version-1.0

This GitHub repository actually contains three different versions of the Arduino Joystick Library:

  • Joystick - Causes the Arduino to appear as single Game Controller
  • Joystick2 - Causes the Arduino to appear as two, simple Game Controllers
  • Joystick3 - Causes the Arduino to appear as three, simple Game Controllers

Copy the Joystick (and/or Joystick2 and/or Joystick3) folder from GitHub to the Arduino Libraries folder (typically located at %userprofile%\Documents\Arduino\libraries). The library (or libraries) should now appear in the Arduino IDE list of libraries.

Running the Test Sketch

Included in the library is a test sketch, called UsbJoystickTest.ino (or UsbJoystick2Test.ino or UsbJoystick3Test.ino). This sketch should be loaded, compiled, and uploaded to the Arduino Leonardo or Micro using the Arduino IDE (version 1.6.6 or above).

The following steps are for Windows 7. If you have a different version of Windows or a different operating system, these steps may differ.

Go to the Windows Control Panel and select “Hardware and Sound”.

Then select “Devices and Printers”.

The Arduino Leonardo or Arduino Micro should appear in the list of devices.

Next right mouse click on the Arduino Leonardo or Arduino Micro to display the settings menu.

Select “Game controller settings” to get to the “Game Controllers” dialog.

The Arduino Leonardo or Micro should appear in the list of installed game controllers. Select the Arduino Leonardo or Micro and click the Properties button to display the game controller test dialog.

While this dialog has focus, ground pin A0 on the Arduino to activate the test script. The test script will test the game controller functionality in the following order:

  • 32 buttons
  • throttle and rudder
  • X and Y Axis
  • Z Axis
  • 2 Hat Switches
  • X and Y Axis Rotation

Joystick Library API

Now that the Joystick library is available to the Arduino IDE, an Arduino Leonardo or Arduino Micro can be used for custom game controller projects. The following describes the complete Joystick library. The simpler library that is used for the Joystick2 and Joystick3 libraries is documented at the end of this posting.

Joystick.begin(bool initAutoSendState)

Starts emulating a game controller connected to a computer. By default all methods update the game controller state immediately. If initAutoSendState is set to false, the Joystick.sendState method must be called to update the game controller state.

Joystick.end()

Stops the game controller emulation to a connected computer.

Joystick.setXAxis(byte value)

Sets the X axis value. Range -127 to 127 (0 is center).

Joystick.setYAxis(byte value)

Sets the Y axis value. Range -127 to 127 (0 is center).

Joystick.setZAxis(byte value)

Sets the Z axis value. Range -127 to 127 (0 is center).

Joystick.setXAxisRotation(int value)

Sets the X axis rotation value. Range 0° to 360°.

Joystick.setyAxisRotation(int value)

Sets the Y axis rotation value. Range 0° to 360°.

Joystick.setZAxisRotation(int value)

Sets the Z axis rotation value. Range 0° to 360°.

Joystick.setButton(byte button, byte value)

Sets the state (0 or 1) of the specified button (0 - 31). The button is the 0-based button number (i.e. button #1 is 0, button #2 is 1, etc.). The value is 1 if the button is pressed and 0 if the button is released.

Joystick.pressButton(byte button)

Press the indicated button (0 - 31). The button is the 0-based button number (i.e. button #1 is 0, button #2 is 1, etc.).

Joystick.releaseButton(byte button)

Release the indicated button (0 - 31). The button is the 0-based button number (i.e. button #1 is 0, button #2 is 1, etc.).

Joystick.setThrottle(byte value)

Sets the throttle value. Range 0 to 255.

Joystick.setRudder(byte value)

Sets the rudder value. Range 0 to 255.

Joystick.setHatSwitch(byte hatSwitch, int value)

Sets the value of the specified hat switch. The hatSwitch is 0-based (i.e. hat switch #1 is 0 and hat switch #2 is 1). The value is from 0° to 360°, but in 45° increments. Any value less than 45° will be rounded down (i.e. 44° is rounded down to 0°, 89° is rounded down to 45°, etc.).

Joystick.sendState()

Sends the updated joystick state to the host computer. Only needs to be called if AutoSendState is false (see Joystick.begin for more details).


Joystick2 and Joystick3 Library API

The joystickIndex is 0-based (i.e. the first game controller has a joystickIndex of 0, the second has a joystickIndex of 1, and the third has a joystickIndex of 2).

Joystick[joystickIndex].begin(bool initAutoSendState)

Starts emulating a game controller connected to a computer. By default all methods update the game controller state immediately. If initAutoSendState is set to false, the Joystick[joystickIndex].sendState method must be called to update the game controller state.

Joystick[joystickIndex].end()

Stops the game controller emulation to a connected computer.

Joystick[joystickIndex].setXAxis(byte value)

Sets the X axis value. Range -127 to 127 (0 is center).

Joystick[joystickIndex].setYAxis(byte value)

Sets the Y axis value. Range -127 to 127 (0 is center).

Joystick[joystickIndex].setButton(byte button, byte value)

Sets the state (0 or 1) of the specified button (0 - 15). The button is the 0-based button number (i.e. button #1 is 0, button #2 is 1, etc.). The value is 1 if the button is pressed and 0 if the button is released.

Joystick[joystickIndex].pressButton(byte button)

Press the indicated button (0 - 15). The button is the 0-based button number (i.e. button #1 is 0, button #2 is 1, etc.).

Joystick[joystickIndex].releaseButton(byte button)

Release the indicated button (0 - 15). The button is the 0-based button number (i.e. button #1 is 0, button #2 is 1, etc.).

Joystick[joystickIndex].sendState()

Sends the updated joystick state to the host computer. Only needs to be called if AutoSendState is false (see Joystick[joystickIndex].begin for more details).

Saturday, November 14, 2015

2015 St. Louis Days of .NET: Arduino Programming with Visual Studio 2015

2015 St. Louis Days of .NET

Arduino Programming with Visual Studio 2015

I just want to thank everyone who attended the talk I gave at this year’s St. Louis Days of .NET (which is being renamed to "dev up") event on Saturday, November 14, 2015 titled “Arduino Programming with Visual Studio 2015”.


The source code that was used in my talk and the slide deck can be downloaded from GitHub at https://github.com/MHeironimus/ArduinoWithVisualStudioSamples.

Monday, October 19, 2015

Explanation of the GetPropertyName Function

I was recently asked how a particular GetPropertyName function my team was using worked. This is what I said:

Usage Example

C#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
static void Main(string[] args)
{
    var demoClass = new Demo();
    Console.WriteLine("demoClass.{0}: {1}", 
        Utilities.GetPropertyName(() => demoClass.TestProperty),
        demoClass.TestProperty);
    Console.WriteLine("demoClass.{0}: {1}", 
        Utilities.GetPropertyName(() => demoClass.TestNumber),
        demoClass.TestNumber);
}

VB.NET

1
2
3
4
5
6
7
8
9
Sub Main()
    Dim demoClass As New Demo()
    Console.WriteLine("demoClass.{0}: {1}",
                      GetPropertyName(Function() demoClass.TestProperty),
                      demoClass.TestProperty)
    Console.WriteLine("demoClass.{0}: {1}",
                      GetPropertyName(Function() demoClass.TestNumber),
                      demoClass.TestNumber)
End Sub

Usage Explanation

The first line prints of the method prints the name of the demoClass’s TestProperty property and its value. The second line prints the name of the demoClass’s TestNumber property and its value.

GetPropertyName Function Overview

The GetPropertyName function returns a string.

The GetPropertyName function takes a single input argument which must be a lambda expression. The lambda expression must be a function. The function must contain a single statement that returns the value of one of the object’s properties.

The GetPropertyName function uses built-in .NET framework functionality to get the name of the property that was accessed by the lambda expression and returns that property name as a string.

More information about lambda expressions:

GetPropertyName Code

C#

1
2
3
4
public static string GetPropertyName<T>(Expression<Func<T>> expression)
{
    return ((MemberExpression)expression.Body).Member.Name;
}
  • The <T> in GetPropertyName<T> is used to genericize the class that is used in the lambda expression.
  • The Expression<Func<T>> in (Expression<Func<T>> expression) indicates the input argument to the GetPropertyName function must be a lambda expression that is a function that uses an object of type “T”. Expression is a special .NET Framework datatype that causes the compiler to create and populate a data structure that contains details about the code inside a lambda expression. More information about this data type can be found at http://msdn.microsoft.com/en-us/library/Bb335710.aspx https://docs.microsoft.com/en-us/dotnet/api/system.linq.expressions.expression-1.
  • expression.Body gets the body of the lambda expression.
  • ((MemberExpression)expression.Body) casts the body of the lambda expression to a MemberExpression. A MemberExpression is a datatype that represents a class’ property being accessed. If the lambda expression passed into the GetPropertyName function is not a single line of code that accesses a class property, an InvalidCastException will be thrown at runtime.
  • The Member property of the MemberExpression datatype represents the property being accessed. It is of type MemberInfo.
  • The Name property of the MemberInfo type returns the name of the property as a string.

VB.NET

1
2
3
Public Function GetPropertyName(Of T)(expression As Expression(Of Func(Of T))) As String
    Return DirectCast(expression.Body, MemberExpression).Member.Name
End Function
  • The (Of T) in GetPropertyName(Of T) is used to genericize the class that is used in the lambda expression.
  • The Expression(Of Func(Of T)) in (expression As Expression(Of Func(Of T))) indicates the input argument to the GetPropertyName function must be a lambda expression that is a function that uses an object of type “T”. Expression is a special .NET Framework datatype that causes the compiler to create and populate a data structure that contains details about the code inside a lambda expression. More information about this data type can be found at http://msdn.microsoft.com/en-us/library/Bb335710.aspx https://docs.microsoft.com/en-us/dotnet/api/system.linq.expressions.expression-1.
  • expression.Body gets the body of the lambda expression.
  • DirectCast(expression.Body, MemberExpression) casts the body of the lambda expression to a MemberExpression. A MemberExpression is a datatype that represents a class’ property being accessed. If the lambda expression passed into the GetPropertyName function is not a single line of code that accesses a class property, an InvalidCastException will be thrown at runtime.
  • The Member property of the MemberExpression datatype represents the property being accessed. It is of type MemberInfo.
  • The Name property of the MemberInfo type returns the name of the property as a string.

Why are we using GetPropertyName?

So why do we use GetPropertyName instead of just passing in a string constant (see alternate code below)?

C#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
static void AlternateVersion()
{
    var demoClass = new Demo();
    Console.WriteLine("demoClass.{0}: {1}",
        "TestProperty",
        demoClass.TestProperty);
    Console.WriteLine("demoClass.{0}: {1}",
        "TestNumber",
        demoClass.TestNumber);
}

VB.NET

1
2
3
4
5
6
7
8
9
Sub AlternateVersion()
    Dim demoClass As New Demo()
    Console.WriteLine("demoClass.{0}: {1}",
                      "TestProperty",
                      demoClass.TestProperty)
    Console.WriteLine("demoClass.{0}: {1}",
                      "TestNumber",
                      demoClass.TestNumber)
End Sub

If the name of a demoClass’s property changes, the developer needs to remember to update the code to use the new name. The string is not tied to the class at all. One alternative would be to add readonly properties to the class that returned the name of the properties (e.g. Demo.TestPropertyName or something like that), but the developer would still need to remember to update that property’s name if its associated property’s name changed.

By using the GetPropertyName function, if a property is renamed, Resharper can automatically rename our GetPropertyName lambda expressions. If we are not using Resharper and we rename a property, we will get a compiler error if we forget to update the property's name wherever it is used.

Monday, September 07, 2015

Linux Support for Arduino Leonardo / Micro USB Game Controllers

A few months ago I posted an article that described how 3 USB game controllers could be added to the Arduino Leonardo and the Arduino Micro. Out of the box, they look like a USB serial port, keyboard, and mouse to the host computer, but with these modifications they can also look like 3 game controllers. This works great on Microsoft Windows (I have tested it on 7, 8.1, and 10), but it does not work on Linux.

If you plug the modified Arduino Leonardo or Arduino Micro into a machine running Linux and do a listing on the input devices, you will see the Arduino mouse, but not the joysticks.

Before Plugging in the Arduino Leonardo or Micro

BeforePluggingIn

After Plugging in the Arduino Leonardo

LeonardoBeforeConfigurationChange

After Plugging in the Arduino Micro

MicroBeforeConfigurationChangeCropped

To get this to work on Linux, you need to adjust a setting on the usbhid driver. This can be done by editing the /boot/cmdline.txt file. Add the following string to the end of the line of text in this file (there should only be one line of text in this file):

For the Arduino Leonardo

usbhid.quirks=0x2341:0x8036:0x040

For the Arduino Micro

usbhid.quirks=0x2341:0x8037:0x040

Explanation

0x2341 is the Vendor ID for Arduino
0x8036 is the Product ID for the Leonardo
0x8037 is the Product ID for the Micro
0x040 indicates the Multiple Input “quirk” should be used (i.e. HID_QUIRK_MULTI_INPUT)

Example

cmdline.txt_Update

After changing the /boot/cmdline.txt file the Linux machine will need to be rebooted. You will need to have root privileges to edit the /boot/cmdline.txt file. Now when the modified Arduino Leonardo or Arduino Micro is plugged in, three new joysticks will appear.

After Applying Setting – Arduino Leonardo

LeonardoAfterConfigurationChange

After Applying Setting – Arduino Micro

MicroAfterConfigurationChangeCropped

Wednesday, July 15, 2015

Introduction to Domain-Driven Design

The article “An Introduction to Domain-Driven Design” by David Laribee (https://msdn.microsoft.com/en-us/magazine/dd419654.aspx) provides a great introduction to Domain-Driven Design (DDD). The definitive book for this topic, “Domain-Drive Design: Tackling Complexity in the Heart of Software”, by Eric Evans, can be a bit overwhelming (especially if one has never been exposed to DDD before), but this article is a great starting point for people wanting to learn more about Domain-Driven Design. The author himself describes this article as a “gentle introduction to designing and evolving rich domain models”. The following is a brief summary of the topics covered in this article.

Model-Driven Design

The software we write is just a model of the system or business process we are automating. The model in everyone’s head and the model that gets implemented in software is never exactly the same. The concept of modifying software over time to more closely match the true model is model-driven design.

Ubiquitous Language

Terminology used by experts in any domain to describe concepts in that domain is called the Ubiquitous Language. Class names, variable names, etc. in the software should use terms from this Ubiquitous Language. Both the business experts and the programmers should be using the same language to describe the business.

Bounded Context

Most enterprise systems have course-grained areas of responsibility. In DDD these areas are called Bounded Contexts. A context map is used to diagram the Bounded Contexts and describe how they relate to one another. Each Bounded Context can have its own unique Ubiquitous Language.

Anti-Corruption Layers

An Anti-Corruption Layer is a DDD pattern that is used to prevent non-domain concepts from leaking into a model. A repository or data access layer is an example of an Anti-Corruption Layer. They keep SQL or other persistence details out of your model.

Entities

An Entity is a noun (i.e. a person, place, or thing) that has both an identity and a lifecycle. For example, a person has a name, a car has a VIN, a city has a name, etc. Also, a person has a birthday and eventually a day they died, a car has a manufacture date, etc.

Value Objects

Value Objects are descriptors or properties that do not have an identity, they simply describe something about an entity. Value Objects are also immutable (i.e. they do not change value once they are created). An object representing the value $35.75 USD is an example of a Value Object (i.e. a decimal value 35.75 and an indicator the value is in US dollars).

Aggregate Roots

An Aggregate is a cluster of associated objects (e.g. entities, value objects, etc.) that are treated as a unit. An Aggregate Root is the single, specific entity in the Aggregate that objects outside the scope of the Aggregate are allowed to hold a reference to. Objects inside the Aggregate are allowed to refer to each other, but objects outside of the Aggregate must go through the Aggregate Root to access objects in the Aggregate.

Domain Services

Domain Services are classes use to represent operations or processes that do not have an identity or lifecycle in the domain. They are typically named after verbs or business activities defined in the Ubiquitous Language. A “funds transfer” service that withdraws money from one account and deposits it into another account is an example of a Domain Service.

Repositories

Repositories are used to retrieve and store entities. They prevent database or persistence concepts (e.g. SQL statements, stored procedures, etc.) from getting in the model. They are an example of an Anti-Corruption Layer.

DDD Resources

DDD combines many good object-oriented programming principles, design patterns, software development practices, techniques, and philosophies. The following resources are good places to learn more about DDD:

Sunday, June 28, 2015

.NET web.config Style Transformations for app.config Files

Visual Studio 2010 added a useful feature that allowed a web.config file to be transformed during the build processes. This made it possible to have different settings for development, test, and production environments without having to manually edit web.config files after a project has been built. This feature would also be useful other types of .NET applications (i.e. applications that use app.config files), but unfortunately Microsoft does not current support transforming app.config files (as of Visual Studio 2013).

Fortunately Golan Avraham has created a Visual Studio extension, called Configuration Transform, that makes it easy to do web.config style transformations on app.config files. This extension can be downloaded from https://visualstudiogallery.msdn.microsoft.com/579d3a78-3bdd-497c-bc21-aa6e6abbc859. This extension works with Visual Studio 2010, 2012, and 2013.

The really nice thing about this extension is it works with TFS Build servers without having to install the extension on the TFS Build server itself. It only need to be installed on the machine where you plan to setup the transformation.

More information the web.config transformation syntax can be found at https://docs.microsoft.com/en-us/previous-versions/aspnet/dd465326(v=vs.110).

Tuesday, May 05, 2015

Adding Touch Keyboard Support to a WPF Desktop Application

Touch enabled devices are increasingly becoming more common. Microsoft has released its own line of Surface tablets and there are quite a few hybrid or convertible laptops available today (e.g. Lenovo Yoga, Dell Inspiron Series 2-in-1, etc.). Today many laptops even include touch screens. When developing a new Microsoft Windows application that needs to provide a good user experience on a touch screen, using the new Universal Windows App template in Visual Studio 2015 is a good choice, but these applications can only run on Windows 8.1 and Windows 10. If the application also needs to run on Windows 7, a traditional desktop application must be used. That, however, does not mean the application cannot provide a good user experience on touch enabled devices. This article describes how to add touch keyboard support to a traditional WPF desktop application.

Avoid Keyboard Data Entry

Typing on a virtual touch keyboard is not an ideal user experience. Whenever possible it is best to avoid requiring the user to use the keyboard. There are numerous ways to get information from users without using a textbox (e.g. dropdown lists, radio buttons, checkboxes, etc.). Unfortunately sometimes there is no way around requiring keyboard data entry.

Showing and Hiding the Touch Keyboard

The following TouchKeyboardProvider class contains a ShowTouchKeyboard and a HideTouchKeyboard method that can be used to show or hide the touch keyboard:

public class TouchKeyboardProvider : ITouchKeyboardProvider
{
#region Private: Fields

private readonly string _virtualKeyboardPath;
private readonly bool _hasTouchScreen;

#endregion

#region ITouchKeyboardProvider Methods

public TouchKeyboardProvider()
{
_hasTouchScreen = HasTouchInput();

_virtualKeyboardPath = System.IO.Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles),
@"Microsoft Shared\ink\TabTip.exe");
}

public void ShowTouchKeyboard()
{
if (!_hasTouchScreen) return;

try
{
Process.Start(_virtualKeyboardPath);
}
catch (Exception ex)
{
// TODO: Log error.
Debug.WriteLine(ex.ToString());
}
}

public void HideTouchKeyboard()
{
if (!_hasTouchScreen) return;

var nullIntPtr = new IntPtr(0);
const uint wmSyscommand = 0x0112;
var scClose = new IntPtr(0xF060);

var keyboardWnd = FindWindow("IPTip_Main_Window", null);
if (keyboardWnd != nullIntPtr)
{
SendMessage(keyboardWnd, wmSyscommand, scClose, nullIntPtr);
}
}

#endregion

#region Private: Win32 API Methods

[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr FindWindow(string sClassName, string sAppName);

[DllImport("user32.dll", EntryPoint = "SendMessage", SetLastError = true)]
private static extern IntPtr SendMessage(IntPtr hWnd, uint uMsg, IntPtr wParam, IntPtr lParam);

#endregion

#region Private: Methods

private static bool HasTouchInput()
{
return Tablet.TabletDevices.Cast<TabletDevice>().Any(
tabletDevice => tabletDevice.Type == TabletDeviceType.Touch);
}

#endregion
}



The ShowTouchKeyboard method shows the touch keyboard by telling Windows to start the TabTip.exe executable. The HideTouchKeyboard method hides the touch keyboard by telling the IPTip_Main_Window window (i.e. the touch keyboard window) to close.

Both of these methods check to see if the device has a touch screen before attempting to show or hide the touch keyboard. Since some users may be on a laptop with a touch screen, but want to use the physical keyboard rather than the touch keyboard, consider having an application setting that prevents the touch keyboard from appearing even if the device supports touch.


Alternate Technique for Showing and Hiding the Touch Keyboard


Another technique for showing and hiding the touch keyboard in a desktop application is described in detail at http://brianlagunas.com/showing-windows-8-touch-keyboard-wpf/, but at the time this article was written there was a bug in .NET Framework 4.5.2 that causes applications that use this technique to stop responding to the user. Microsoft has released hotfix 3026376 (https://support.microsoft.com/en-us/kb/3026376) to address this issue, but the hotfix must be downloaded directly from Microsoft as it is not yet available in Windows Update.


Showing and Hiding the Touch Keyboard on GotFocus Events


Different techniques can be used to call the ShowTouchKeyboard and HideTouchKeyboard methods described above, but the technique I found works the best is to call the methods in the GotFocus event handlers. For framework elements that should have the touch keyboard visible (e.g. TextBox, RichTextBox, etc.), call the ShowTouchKeyboard method in their GotFocus event handlers. For other framework elements that should not have the touch keyboard visible (e.g. ComboBox, RadioButton, CheckBox, etc.), call the HideTouchKeyboard method in their GotFocus event handlers.



private readonly ITouchKeyboardProvider _touchKeyboardProvider = new TouchKeyboardProvider();

private void ShowTouchKeyboard(object sender, RoutedEventArgs e)
{
_touchKeyboardProvider.ShowTouchKeyboard();
}

private void HideTouchKeyboard(object sender, RoutedEventArgs e)
{
_touchKeyboardProvider.HideTouchKeyboard();
}


Controlling Which Touch Keyboard Is Displayed


The touch keyboard layout Windows uses is determined by the framework element’s InputScope property (https://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.inputscope.aspx https://docs.microsoft.com/en-us/dotnet/api/system.windows.frameworkelement.inputscope?view=netframework-4.8). The complete list of InputScope options is available at https://msdn.microsoft.com/en-us/library/system.windows.input.inputscopenamevalue.aspx https://docs.microsoft.com/en-us/dotnet/api/system.windows.input.inputscopenamevalue?view=netframework-4.8. The following are some of the more common touch keyboard layouts on Windows 8.1:


InputScope="Default"


DefaultKeyboard


InputScope="Url"


UrlKeyboard


InputScope="EmailSmtpAddress"


EmailKeyboard


InputScope="Number"


NumericKeyboard



Dealing With Controls Hidden By the Touch Keyboard


Microsoft Windows will automatically resize the desktop when the touch keyboard appears (assuming the touch keyboard in in “docked” mode). This will cause the application to move or resize to accommodate the new desktop size. Often when this resizing occurs, the framework element that has focus will no longer be visible. The following code can be used in the main application window’s SizeChanged event to cause the framework element that has focus to scroll back into view if the window gets smaller (e.g. the touch keyboard appeared).



private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
{
// When the main window resizes (often caused by the touch keyboard
// being displayed), attempt to bring the element that has focus
// into view.
var elementWithFocus = Keyboard.FocusedElement as FrameworkElement;

if ((elementWithFocus != null) && ((e.PreviousSize.Height > e.NewSize.Height)))
{
elementWithFocus.BringIntoView();
}
}


The BringIntoView method typically causes the element to appear at the bottom of the scrollable area. The BringIntoView method can be replaced with the following BringIntoTopOfView extension method to cause the element to appear at the top of the scrollable area instead:



public static void BringIntoTopOfView(this FrameworkElement frameworkElement)
{
if (frameworkElement == null)
{
throw new ArgumentNullException("frameworkElement");
}

var parentScrollViewer = frameworkElement.FindParent<ScrollViewer>();
if (parentScrollViewer != null)
{
parentScrollViewer.ScrollToBottom();
frameworkElement.BringIntoView();
}
}


The BringIntoTopOfView extension method makes use of the following FindParent extension method, which can be used to find a specific parent of the element by type:



public static T FindParent<T>(this DependencyObject dependencyObject) where T : DependencyObject
{
if (dependencyObject == null)
{
throw new ArgumentNullException("dependencyObject");
}

T parent;

do
{
dependencyObject = VisualTreeHelper.GetParent(dependencyObject);

if (dependencyObject == null) return null;

parent = dependencyObject as T;

} while (parent == null);

return parent;
}


Summary


Although it takes extra work, a Microsoft Windows desktop application can provide a user on a touch device with an experience similar to that of a Windows Store or Windows Universal App. All of the example code shown in this article can be downloaded at https://static.heironimus.info/blog/codesamples/TouchKeyboardSample.zip.