Showing posts with label Arduino. Show all posts
Showing posts with label Arduino. Show all posts

Saturday, July 09, 2022

Simple Arduino Leonardo USB Game Pad

Parts

Required Parts

Optional Parts

Hardware Assembly

  1. If using a case, place the Arduino Leonardo inside the case per the instructions provided with the case.
  2. Insert the Funduino Joystick Shield onto the Arduino Leonardo.

Software

  1. Download the latest v2 version of the Arduino Joystick Library from https://github.com/MHeironimus/ArduinoJoystickLibrary: https://github.com/MHeironimus/ArduinoJoystickLibrary/archive/refs/heads/version-2.0.zip.
  2. To install the library in the Arduino IDE, select Sketch > Include Library > Add .ZIP Library.... Browse to where the downloaded ZIP file is located and click Open. The Joystick library's examples will now appear under File > Examples > Joystick.
  3. Open the Funduino Joystick Shield example by selecting File > Examples > Joystick > FunduinoJoystickShield. Verify the correct Port is selected in the Arduino IDE and select Upload.
  4. On Microsoft Windows, the joystick can be tested using the “Game Controllers” dialog.

Saturday, January 08, 2022

Using GoogleTest to Unit Test Arduino Code

As Arduino projects get more complex, the need for unit testing becomes more apparent. Also, in order to utilize techniques like Test Driven Development (TDD), a fast and effecting unit testing strategy is needed. The following are some requirements I had for unit testing Arduino code:

  • Fast – Could be executed on the development machine, not the Arduino itself
  • Compatible – It supported the file structure required by the Arduino IDE
  • Easy – Something that is easy to install, setup, and use
  • Supportable – It is popular enough to have a plenty of on-line documentation and a sizable userbase

After evaluating several options, I settled on using GoogleTest (https://github.com/google/googletest) via Visual Studio 2022 (https://visualstudio.microsoft.com/vs). The following article describes how to install the software needed. This article assumes you already have the Arduino IDE installed.

Setup

Go to the Visual Studio website (https://visualstudio.microsoft.com/vs) and download and run the Visual Studio installer. The Community edition is free. Be sure to select the “Desktop development with C++” option.

This will cause the Test Adapter for Google Test to be installed.

Create Visual Studio Project

Run Visual Studio and select “Create a new project” when prompted.

Scroll down the list and select the “Google Test” project template.

Fill out the remaining fields and click Create. Be sure to give the project the same name as the Arduino Sketch file (i.e., *.ino). This allows both the Arduino IDE and Visual Studio to open the Sketch file. The default “Test Project Configuration” options will work for most projects.

A new project will be created that looks something like the following:

The new project will contain one sample unit test. The “Test Explorer” window can be used to execute the sample unit test. Click the “Run All Tests In View” button to build the project and run the sample unit test.

The results of running the sample unit test should look something like this:

Turning Off Precompiled Header

To allow both the Arduino IDE and Visual Studio to use the same source files, I recommend not using a precompiled header. Open the Project Properties dialog and select the “Configuration Properties – C/C++ - Precompiled Header” page. Select the “Not Using Precompiled Headers” for the “Precompiled Header” option.

Replace the following line at the top of the test.cpp file:

#include "pch.h"

With the following:

#include "gtest/gtest.h"

Then remove the pch.h and pch.cpp files from the project. Re-run the sample unit tests to verify things are still working.

Adding Arduino Code

The project is now ready for the Arduino code to be added. As long as the project was named the same as the Sketch file, the Sketch file should be able to be copied (and any additional files needed) into the project folder. Once the file has been added to the project folder, it will need to be added to the Visual Studio Project.

Separate Testable Code

Any Arduino code that will be tested should be pulled out of the Sketch file and moved into separate classes and/or functions. I tend to leave any logic that interacts directly with the Arduino hardware in the Sketch file and pull the rest of the logic into functions or classes that can be tested. In this example I pulled out all of the logic into a class called SystemState (i.e., sysstate.h and sysstate.cpp).

Writing Unit Tests

Unit tests can now be added to the project (either to the test.cpp provided by the template or by adding new files to the project).

GoogleTest Highlights

Setup and Teardown Functions

To write a series of unit tests that share the same setup and/or teardown code, create a new class that derives from ::testing::Test:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class SystemStateTest : public ::testing::Test {
protected:
    void SetUp() override {
        button_state[0] = 0;
        button_state[1] = 0;
        set_button_value_count[0] = 0;
        set_button_value_count[1] = 0;
        set_new_read_next_mock_value("");
        target = new SystemState(
            &button_press,
            &switch_change,
            &mock_read_next_byte,
            &set_button_value
        );
    }

    void TearDown() override {
        delete target;
    }

    SystemState* target;
};

Protected SetUp and TearDown functions can be defined that will run before and after each test. Unit tests that leverage the SetUp and TearDown functions are defined using the TEST_F macro:

1
2
3
4
5
6
TEST_F(SystemStateTest, UpdateStateButton0DownAndUp) {
    target->update_state(BUTTON_DOWN, BUTTON_UP, SWITCH_OFF);
    target->update_state(BUTTON_UP, BUTTON_UP, SWITCH_OFF);
    EXPECT_EQ(1, button_state[0]);
    EXPECT_EQ(0, button_state[1]);
}

Code Coverage

If you are fortunate enough to be using Visual Studio Enterprise, you can also view your unit test’s code coverage. This functionality can be accessed via the “Test – Analyze Code Coverage for All Tests” menu option.

Sample Results:

Conclusion

Software in embedded systems, like the Arduino, can have unit tests and be written using techniques like TDD. Tools like Visual Studio and GoogleTest can make writing and running unit test easier.

Friday, November 25, 2016

Arduino Joystick Library - Version 2.0

Introduction

Since I released the original Arduino Joystick Library (see http://mheironimus.blogspot.com/2015/11/arduino-joystick-library.html or http://www.instructables.com/id/Arduino-LeonardoMicro-as-Game-ControllerJoystick/ for more details) I have received numerous requests for enhancements. Most of these requests fall into the following two categories:

  • Increase the precision of the axes.
  • Make a version with only a specified set of features.
To accommodate these requests (and a few others) I have release Version 2.0 of the Arduino Joystick Library.

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 one or more generic Game Controllers or Joysticks. The Arduino Joystick Library Version 2.0 can be used with Arduino IDE 1.6.6 (or above) to add one or more joysticks (or gamepads) to the list of HID devices an Arduino Leonardo or Arduino Micro (or any Arduino clone that is based on the ATmega32u4) can support. This will not work with Arduino IDE 1.6.5 (or below) or with non-32u4 based Arduino devices (e.g. Arduino UNO, Arduino MEGA, etc.).

Features


The joystick or gamepad can have the following features:
  • Buttons (default: 32)
  • Up to 2 Hat Switches
  • X, Y, and/or Z Axis (up to 16-bit precision)
  • X, Y, and/or Z Axis Rotation (up to 16-bit precision)
  • Rudder (up to 16-bit precision)
  • Throttle (up to 16-bit precision)
  • Accelerator (up to 16-bit precision)
  • Brake (up to 16-bit precision)
  • Steering (up to 16-bit precision)
These features are configured using the Joystick_ class’s constructor.

Installation


The latest build of Version 2.0 of the Arduino Joystick Library can be downloaded from the following GitHub repository:
https://github.com/MHeironimus/ArduinoJoystickLibrary/tree/version-2.0

The library can also be downloaded directly using the following URL:
https://github.com/MHeironimus/ArduinoJoystickLibrary/archive/version-2.0.zip

Copy the Joystick folder to the Arduino Libraries folder (typically located at %userprofile%\Documents\Arduino\libraries on Microsoft Windows machines). On Microsoft Windows machines, only, this can be done by executing deploy.bat. The library should now appear in the Arduino IDE list of libraries.

Included Examples


The example Arduino sketch files listed below are included in this library. These will appear in the Arduino Example menu when the Arduino Joystick Library is installed.

Example Description
JoystickTest Simple test of the Joystick library. It exercises many of the Joystick library’s functions when pin A0 is grounded.
MultipleJoystickTest Creates 4 Joysticks using the library and exercises the first 16 buttons, the X axis, and the Y axis of each joystick when pin A0 is grounded.
JoystickButton Creates a Joystick and maps pin 9 to button 0 of the joystick, pin 10 to button 1, pin 11 to button 2, and pin 12 to button 3.
JoystickKeyboard Creates a Joystick and a Keyboard. Maps pin 9 to Joystick Button 0, pin 10 to Joystick Button 1, pin 11 to Keyboard key 1, and pin 12 to Keyboard key 2.
GamepadExample Creates a simple Gamepad with an Up, Down, Left, Right, and Fire button.
DrivingControllerTest Creates a Driving Controller and tests 4 buttons, the Steering, Brake, and Accelerator when pin A0 is grounded.
FlightControllerTest Creates a Flight Controller and tests 32 buttons, the X and Y axis, the Throttle, and the Rudder when pin A0 is grounded.
HatSwitchTest Creates a joystick with two hat switches. Grounding pins 4 - 11 cause the hat switches to change position.

Running the JoystickTest Example



The JoystickTest example sketch is included with the library. I recommend using this example to verify everything is working properly before beginning to write your own sketch files. Load, compile, and upload this example sketch file to an Arduino Leonardo or Micro using the Arduino IDE (version 1.6.6 or above).


Once you have uploaded the JoystickTest sketch file to the Arduino Leonardo or Micro, perform the following steps to verify everything is working properly. Note: the following steps are for Windows 10. If you have a different version of Windows or a different operating system, these steps may differ. Open the “Devices and Printers” window. This can be done by clicking the Start menu or pressing the Windows Key and typing “Devices and Printers”.

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


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, Y, and Z Axis Rotation

Simple Gamepad Example


Once the Arduino Leonardo or Micro has been tested using the JoystickTest example, I suggest making a simple gamepad controller. This controller will have five buttons: up, down, left, right, and fire.

Connecting the Buttons


Connect one end of each button to the ground pin. Connect the other end of each button as indicated below:

Arduino Pin Description
2
Up
3
Right
4
Down
5
Left
6
Fire

Sketch File


Upload the GamepadExample example sketch file to the Arduino Leonardo or Micro. This example is included with the Arduino Joystick Library.


Test


Open the game controller properties or use the joystick testing application of your choice to test the behavior of your gamepad.



Joystick Library API


The complete documentation for the Arduino Joystick Library can be found at https://github.com/MHeironimus/ArduinoJoystickLibrary/tree/version-2.0.



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.