Building a Superflight Controller

Building a controller for Superflight with Arduino, PySerial, and a Wii Nunchuk.

Superflight_1

A few months ago, I downloaded Superflight on Steam.  It’s an awesome game.

I thought it might be fun to play with a a joystick, but I didn’t have one… so I hacked one together with an Arduino Mega, an old Wii Nunchuk, and PySerial.  The controller works by using the Arduino as an interface between the Nunchuk and computer (via USB) which allows our Python code to read & interpret the Nunchuk data and simulate keystrokes in the game.  The entire hardware configuration and most of the code I needed was already generously available from Gabriel Bianconi’s Makezine article and Chris Kiehl’s Virtual Keystroke project.

The only real hardware change I made was the Arduino pin locations.  For me on an Arduino Mega 2560, this was SDA: Pin 20 and SCL: Pin 21.

In the Arduino code from Bianconi’s article, I modified the Baud rate from 19200 to 9600.  This seemed to be more stable for me, but I’m not sure if it was entirely necessary.  Regardless of what rate you select, make sure the Baud rate matches in the Arduino and Python code.

I pruned a lot of the Nunchuk gyroscopic readings out of Bianconi’s Python code.  Then I added the VK_CODE dictionary (partial) and “press” function from Chris Kiehls’ project which takes advantage of the win32api to simulate keystrokes on a Windows machine.  Finally, I modified some of the existing logic to “press” the arrow keys when the Wii joystick was moved in the corresponding direction.  My python code ended up looking like this:

"""
Building a Superflight Controller with a Wii Nunchuk

Note: Must run with Python 2.
"""

# Import the required libraries for this script
import string, time, serial, win32api, win32con

#Dictonary to hold key name and VK value
VK_CODE = {'left_arrow':0x25,
           'up_arrow':0x26,
           'right_arrow':0x27,
           'down_arrow':0x28,}

#press keys
def press(*args):
    '''
    one press, one release.
    accepts as many arguments as you want. e.g. press('left_arrow', 'a','b').
    '''
    for i in args:
        win32api.keybd_event(VK_CODE[i], 0,0,0)
        time.sleep(.001)
        win32api.keybd_event(VK_CODE[i],0 ,win32con.KEYEVENTF_KEYUP ,0)

# The port to which your Arduino board is connected
port = 'COM3'

# Invert y-axis (True/False)
invertY = False

# The cursor speed
cursorSpeed = 20

# The baudrate of the Arduino program
baudrate = 9600

# Variables indicating whether the mouse buttons are pressed or not
leftDown = False
rightDown = False

# Variables indicating the center position (no movement) of the controller
midAnalogY = 130
midAnalogX = 125

if port == 'arduino_port':
    print('Please set up the Arduino port.')
    while 1:
        time.sleep(1)

# Connect to the serial port
ser = serial.Serial(port, baudrate, timeout = 1)

# Wait 5s for things to stabilize
time.sleep(5)

# While the serial port is open
while ser.isOpen():

    # Read one line
    line = ser.readline()

    # Strip the ending (\r\n)
    line = string.strip(line, '\r\n')

    # Split the string into an array containing the data from the Wii Nunchuk
    line = string.split(line, ' ')

    print(line)

    # Set variables for each of the values
    analogX = int(line[0])
    analogY = int(line[1])
    zButton = int(line[5])

    threshold=25

    # If the analog stick is not centered
    if((analogY-midAnalogY)>threshold):
        press('up_arrow')
    elif((analogY-midAnalogY)threshold):
        press('right_arrow')
    elif((analogX-midAnalogX):
        press('left_arrow')

# After the program is over, close the serial port connection
ser.close()

To summarize, the overall process looks something like this:

  1. Connect the Wii Nunchuk to the Arduino as shown in the Makezine article.  Make sure you wire the Nunchuk to your SDA and SCL pins – these might be different that what’s shown in the article depending on what Arduino model you have.
  2. Connect the Arduino to your computer through USB and upload Bianconi’s Arduino sketches.  Take note of what baud rate you’re using.
  3. Save the python code (shown above) to your local machine.  Update the baud rate as needed – make sure it’s the same as what is listed in your Arduino code.  Make sure you have all python library dependencies installed.
  4. Open a terminal.  CD to whatever directory you saved the python code to.  Run the .py file using Python 2.  If you attempt to run it with Python 3, it probably won’t work.
  5. Open Superflight and have fun.

A few closing thoughts:

  • The overall setup is still a little bit unstable.  The python code seems to crash after a few minutes.  A few parameters to troubleshoot with are the threshold variable, the sleep duration, and the baud rate.
  • A definite improvement would be to make the Nunchuk trigger buttons work in the menu for a more complete controller.  But the keyboard still works.
  • Another big improvement would be to re-write the python code to use a variable rate of virtual button-pressing based on how far from the origin the controller is.
  • For a more long-term hardware design, we could design & 3D-print an enclosure that houses an ATtiny which runs the Arduino code.  From the outside, it would just look like a Nunchuk-to-USB cable.
  • Maybe it would have been more interesting to use the Wii Gyro data instead of the joystick?

 

Find McMaster Details with AutoHotkey

Using AutoHotkey to open a URL.

AutoHotkey script for re-assigning the F6 function key to look up a selected part number on McMaster-Carr.

As you can see below, we’re able to highlight a McMaster part number with and then hit F6 which opens up the appropriate webpage.

McMaster

Prerequisites:

  • Google Chrome installed
  • AutoHotkey installed
  • AHK Script is running

Save the follow script as a .ahk file and execute it.  If you want your .ahk scripts to run immediately on system startup, create shortcuts to the .ahk files in your systems startup directory.  For me on Windows 7, this is in C:\Users\Craig\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup.


F6:: ; Open McMaster based on selected part number
 Clipboard =
 Send ^c
 ClipWait ;wait for clipboard to have content
 Run, chrome.exe https://www.mcmaster.com/#%clipboard%/

Thanks to Tom Sherman, McMaster now also supports OpenSearch!

Web Scraping for Engineers

Scrape 3D models from McMaster-Carr with Python & Selenium.

Here is a script for fetching 3D models from McMaster-Carr using Selenium.

Make sure Chromedriver is in the same directory as your .py file.  The 3D models will be downloaded to your default Downloads directory.

# -*- coding: utf-8 -*-
"""
Scrape 3D models from McMaster-Carr.

Requirements: Chromedriver.exe is in the same folder as this script.
"""
from selenium import webdriver
import time

test_part_numbers=['98173A200', '7529K105', '93250A440']

def fetch_model(part_numbers, delay=3):
    if type(part_numbers) is str:
        part_numbers=[part_numbers]
    
    #Start browser
    options = webdriver.ChromeOptions()
    driver = webdriver.Chrome(chrome_options=options)
    
    #For each part number
    for part_number in part_numbers:
        driver.get('https://www.mcmaster.com/#' + str(part_number) + '/')
        #Pause for page to load
        time.sleep(delay)    
        #Find and Click submit button
        try:
            try:
                submit_button=driver.find_element_by_class_name("button-save--sidebyside")
            except:
                submit_button=driver.find_element_by_class_name("button-save--stacked")
            finally:
                submit_button.click()
        except:
            print('No button found or other error occured')
        finally:
            time.sleep(delay)
            
    driver.close()
    driver.quit
    
fetch_model(test_part_numbers)

Create Folder Structure with a Batch Script

Generate uniform folder hierarchies using a simple batch file.

Take for example, the folder hierarchy shown below. This is our default starting point for any new project.
FolderHierarchy
Using a batch file to create directories for a new project is an easy way of making sure that we’re maintaining consistent structure.

Save the following text as a .BAT file and run it anytime a new project needs to be created. The script prompts the user for a project name and will create all directories as shown above.

@echo off
set /p project="Enter Project Name: "

MkDir "C:\Engineering\%project%\Documents\"
MkDir "C:\Engineering\%project%\Documents\Assembly Procedures\"
MkDir "C:\Engineering\%project%\Documents\Design Requirements\"
MkDir "C:\Engineering\%project%\Documents\Test Procedures\"

MkDir "C:\Engineering\%project%\Drawings\"
MkDir "C:\Engineering\%project%\Drawings\Assembly Drawings\"
MkDir "C:\Engineering\%project%\Drawings\Part Drawings\"

MkDir "C:\Engineering\%project%\3D Models\"
MkDir "C:\Engineering\%project%\3D Models\3D Printer\"

Check if file exists with VBA

UDF for checking if a file exists.

As mentioned in the title, the code below is for checking if a file exists in a certain directory. I find this function useful for monitoring if drawings have been created and are ready for production.

Public Function InFolder(Folderpath As String, Filename As String, FileExtension As String) As Boolean
'Infolder returns TRUE if a file is found in the specified folderpath

'Add backslash (\) to end of folderpath if there isn't one
If Right(Folderpath, 1) <> "\" Then
Folderpath = Folderpath & "\"
End If

'Add period (.) to front of file extension if there isn't one
If Left(FileExtension, 1) <> "." Then
FileExtension = "." & FileExtension
End If

'Create filepath from input arguments
Filepath = Folderpath & Filename & FileExtension

'Check if file exists
If Dir(Filepath) <> "" Then
InFolder = True
Else
InFolder = False
End If

End Function

You can either save this directly in your current workbook or if you’d like the function available in all workbooks, save it to a AddIn file (.xlam) in the default folder and enable the AddIn through File>Options>AddIns>Go.

If you are typing arguments in directly, then you will need quotes. However, if you are referencing other cells as input, quotes are unnecessary.

Find and Zip All .py Files

Create a Zip folder including all .py files on your computer.

This is a program for finding all .py files in a directory and zipping them into a single folder.  We can substitute any file extension (.doc, .xlsx, .dxf, etc.) that we’d like to search for, but in our example we’ll use .py

To find all of the files in a given directory, we’ll import and use functionality from the FolderHierarchy script.  Be sure to save this file in the same directory as the script below.

Next, we’ll filter our FolderHierarchy results to include just the .py files.  Then we simply loop through the filtered DataFrame and add each file to a zip folder using the zipfile module.

# -*- coding: utf-8 -*-
"""
Purpose: Copy all files of a given filetype within a folder, zip them,
         and save.

Input: 1. A folderpath to search in.
       2. File type/File Extension to search for.
Output: A zip file containing all of the files with the specified file extension
        that were folder in the specified input folder.
"""
import pandas as pd
import zipfile
import FolderHierarchy

#Define what filetype to search for
extension=".py"

#Execute 'FolderHierarchy' program (in same directory)
FolderHierarchy
results=FolderHierarchy.all_levels

#Filtering for just files with the defined file extension
found_files=pd.concat([results[level][results[level]['Path'].str.contains(extension,
                                  regex=False)] for level in results])

#Copy and zip all of the files found.
new_zip=zipfile.ZipFile('all_'+extension+ '_files'+'.zip',mode='w')

#Writing to zip (https://pymotw.com/2/zipfile/)
for file in found_files['Path']:
    new_zip.write(file,arcname=file.split('\\')[-1])
new_zip.close()

print('Found '+str(len(found_files))+' '+extension+' files.')