notesToSelf 1.0

Things to keep handy

Author: richardpeter3

Retro NES Projector Console

This post describes how to re-purpose a NES console into a self-contained console with integrated Projector and games using a Raspberry Pi.

After seeing many very cool retro gaming ideas on Pinterest I decided to try and make one. Management wouldn’t approve a full size gaming cabinet as they had already approved a retro console in the yet-to-be-built breakfast bar. Instead, while I waited for the kitchen to become a reality, I forged ahead with a mini project using my favourite beloved childhood console the Nintendo Entertainment System. With the very cool NES30 controllers from 8BitDo I wondered whether a standalone NES could be integrated with a projector to play 8BIT on epic scales…

 

  1. Source a broken NES
  2. Bleach it back to grey
  3. Parts and Tools
  4. Projector
  5. Power
  6. BUILD
  7. Final Touch – the happy red LED
  8. To-Do

 

Sourcing a NES

I knew that Making a NES projector would be destructive, and couldn’t bring myself to destroy a working relic of history so began searching for a ‘spares or repairs’ NES that was going cheap… It turns out good people earn good money repairing NESs so getting one is still not the 10 quid I thought it would be. Eventually I found a NES that was not listed as working (so my conscience is half-clear) and ponied up 20 quid to buy it.

The Bleach

Sadly when it arrived it looked like a special edition ZELDA Nes so I researched restoring the colour and discovered some hair bleach, clingfilm and sunlight could work. It turns out that NESs turn a gold colour with age – due to a fire retardant chemical in the plastic apparently.

The internet instructions suggested buying 40vol (12%) hair bleach and applying liberally before covering in clingfilm to ensure it stays moist and finally leaving for 3 hours in the Arizona sun. I initially tried a full day in overcast London, but after washing off the bleach only a little progress had been made. I decided to go for broke and applied copious bleach secured with clingfilm and left it outside for a week through several sunny but cool days in direct sunlight. (I left it for a week because I kind of forgot about it!)

After removing the clingfilm  Voila! a Grey NES! There appeared to be a slightly uneven shading to the grey, but I couldn’t be bothered to spend any more time at this stage.

Parts and Tools

Bits and Materials

Tools

  • Hacksaw blade
  • Glue Gun
  • Screwdriver
  • Drill
  • Half-round file or drill to fit projector lens
  • Gaffa Tape
  • Soldering Iron (Optional)

Connectivity and Bits

  • Short, flexible HDMI Cable (~20cm)
  • HDMI Splitter (Optional)
  • If you want the option of using a normal TV without dismantling the Console.
  • 2X Short Micro USB cables for Power.
  • 15cm Steel Ruler and small pebble
  • 330 Ohm resistor and connector leads (Optional)

Projector

Next I did some hunting on cheap projectors and settled for one from Gearbest that looked reasonable. I thought resolution would not be an issue given the low resolution of the games. (While this is true, it later turned out the menu and prompt like a higher resolution.)

I then realised I’d have to find a way of powering a projector, PI and speaker without having 3 very un-cool plugs coming out the back. A lot of googling and nothing had come up and I thought I was scuppered… but then I noticed that while the projector comes with a power lead it also has a micro USB port that can power it!

It also turned out that the projector comes with a small internal speaker so I would not need to have a separate one.

Power Adaptor

I’d already planned to have 3 micro USB ports by this stage so opted for the 4-port adapter from Anker as it seemed to be the only one that offered a 3A power supply that the pi would need to operate reliably without the lightning symbol in the corner forever being illuminated.

Controllers

Next was controllers – there really was only ever one option, and probably it was the 8BitDo famicom controllers that inspired me to build a NES Projector in the first place. Yes they are expensive, but you cant put a price on happiness and seeing my old friend (with a couple extra buttons) wireless and free still makes me smile…

 

 

The Build

Reflect on simpler days – remove the heart

Open your beloved console and remove the heart. Note you can see an extension port on the base that never got used… Cool. Note the size and simplicity of everything compared to todays microelectronics and the retro-coloured cables going to the power/reset buttons… Shibui.

Once reflection is over its time to figure out where everything is going to go. I wanted to be able to use the original controller ports for access when the controllers needed charging or if a keyboard was needed for any reason. Luckily the Pi can be positioned to line up perfectly with these once the plastic pegs to hold the body are removed. The best way I found to remove these (keep them as you need to reuse them later) was with a hacksaw blade removed from the hacksaw. It can be forced to bend close to the base of the NES to remove as much as possible.

Several attempts at removing as little of the original casing as possible but still being able to get a good connection and keep the chamfered corner look.

Projector

Next was the projector. Luckily on this model the tripod mount aligned PERFECTLY with the raised channel on the base so with a trimmed down bolt I could easily and securely affix it while keeping the NES able to sit flat on a table. (Very lucky).

To cut a hole in the casing in the right place, I found an olive oil cap that was the size of the projector lens. (Alternatively you could draw round it on a piece of card/paper and cut it out). Then place the template (cap) on the outside of the case, aligned with the visible bit of the lens and draw round it for where you need to cut.

template

Find or make an appropriate sized template

If you are lucky enough to have a drill the size of the projector lens, you can just use it to drill and make the correct size hole. However, I did not own this drill and didn’t want to go out and buy one. In my woodworking days I’d have been told to use a coping saw to cut the curved line, however I don’t have one of these either… Instead I drilled lots of small holes around the marked line and with my trusty hacksaw blade joined the dots to remove most of the plastic. Then CAREFULLY use the half-round file to smooth back the hole. I was not patient enough here and ended up making a slightly imperfect hole 🙁   .

Power

While i’d have loved to be able to re-use the original power ports, the Anker adapter sat  snugly (very and probaly a little too snugly) beside the PI with the power cable input over the original AV out ports. This was close enough… It served to secure the PI as well as meaning no new holes in the pi. Plus they would be hidden at the back so no harm done:

To help support it, take some of the removed plastic moulding cone things and cut to size so that the adaptor can rest on them with the port at a hight so that the cable can be pushed through the AV ports. I wasn’t originally too happy with just gluing the power adapter but I’ve learned to admire the glue gun in this project. The rubbery, tacky filling substance also adds a little shock absorbtion too. plus I can’t be bothered making brackets and screwing/gluing them in place when it’s 5 minutes with a glue gun.

Accessing the power button of the Projector

Unfortunately, unlike the PI, you have to turn on the projector separately. To do this I rigged a steel ruler with a tiny pebble from the garden and some gaffa tape. This acted like a cantilever that could be accessed through the original game flap beside the HDMI splitter if you fitted one of these.

Something’s missing…

You’ve powered up your beautiful NES and basked in the glory of it being fully loaded with all NES games, fast-forwarded into the future with SNES and  even cross-pollinated with the retro goodness of both the Sega Master Sytem and Megadrive. But something’s missing… The little happy square red LED that you associated with your happy childhood memories… It has to be on.

Looking online I found that you can direct power an LED from the PI (thats how most people start playing) but BEWARE if you’re directly powering the LED, be sure to include a couple of resistors.

Warning – I don’t know electronics and was getting bored by this point. I didn’t use connectors I just soldered the wires together and taped them up. Follow this at your own risk (and the risk of your Pi)!!!

I trust this guide and it’s great diagrams more than my own advice!

Take a female connector cable from a raspberry Pi starter kit and attach it to pin 6 (Ground).  Attach inline the 330 Ohm resistor (I crudely soldered the two together and insulated with tape). Connect another female connector to pin 8 (TXD). Connect the other side of the resistor and the Second (pin 8) connector to the diode terminals (Orange and White).

 

There… Much better 🙂

 

Happy Gaming

 

 

To-Do…

To take the project further, it would be super cool to see if a fully stand-alone battery powered console could be created. Not for any practical reason other than it might be cool to take camping and use on the inside of a tent to annoy the other campers!

It would also be good to create a custom 8-BIT style menu for game selection (Ideally with the original artwork!) so that the projector can handle the menu better.

It would also be good to put a HDMI extender in the box so that a TV can be connected through the back or perhaps the original ports?

Finally it would be cool to put a smaller projector in there to see if the controllers could be stored inside through the original game flap so the whole thing can be put in a bag and taken to your friends place or perhaps a fine establishment that serves beer?

 

Time to upgrade from Java2 to Java8

 

I’m using Storm at work (a bank, using An Apache 1.0 Project?). I like the sound of it because I can write python, but really why bother figuring out how to mix Java with python (the rest of the IT team when I can just learn Java?)… Well the hand-me-down book I originally learned Java from was Sams Teach yourself Java 2 in 21 days fourth edition, first printed 2004! Time for an upgrade…

This was a very enthusiastic and humourous presentation of the benefits of Java8, well worth a watch.

Down to Foyles tomorrow to Pick up something more current… Then get storm working.

An observation by a colleague, C++ by training but now knee deep in Java, said that Java code is always telling something else what to do. I agree, all I ever see are methods that call other methods. Luckily the Functional programming seems to get rid of (some of?) that and distills it down to the real meat.

Presently ploughing through Storm Applied from Manning.

Installing openCV for Python

Some smart chap has installed opencv on a mac and explained how to do it here

brew tap homebrew/science

Then for the information type:

brew info opencv

I used the options with-ffmpeg (because I want mpg4?) and without-numpy (I already have it)
brew install opencv --with-ffmpeg --without-numpy

 

10 minutes and 30seconds later. it was built…

As I’m using anaconda I navigated to my root packages…
cd /anaconda/anaconda/lib/python2.7/site-packages

made a new directory

mkdir opencv

enetered it:

cd opencv

then navigated to where my brew python libs should have been and checked they were there (they were)

cd /usr/local/Cellar/opencv/2.4.13/lib/python2.7/site-packages/
ls

then I got the full directory with

pwd

and pasted the below into the terminal window that was still in the /anaconda/anaconda/lib/python2.7/site-packages/opencv folder and ran:

ln -s /usr/local/Cellar/opencv/2.4.13/lib/python2.7/site-packages/cv.py cv.py
ln -s /usr/local/Cellar/opencv/2.4.13/lib/python2.7/site-packages/cv2.so cv2.so
TO-DO: Tell anaconda it’s there – (not showing in conda list)

Setting up python to process videos… FPV HUD stage1

So a micro-project is to generate HUDs for FPV Drone Racing… The coolest thing since sliced bread to uubergeeks

Truth is I honestly don’t know how i managed to get this working.. I had some pretty strange errors along the way but I’ve managed to do it so I wanted to note down how in case my laptop dies, is stolen or someone else wants to try.

What I want to do for phase 1:

  • Import a video file into Python (.mp4)
  • Convert to numpy array
  • Laplace filter it to detect edges.

Phase 1 was always going to be the hardest.

The first googling turned up this:

http://docs.scipy.org/doc/scipy/reference/tutorial/ndimage.html

 

That’s great but nor very user-friendly.

next search was this:

http://stackoverflow.com/questions/29718238/how-to-read-mp4-video-to-be-processed-by-scikit-image

More my level of skills (Thanks to the really bright people who can actually write libraries…), so this gives two options

  1. pylabs/imageio (imageio is the workhorse as pylabs was not referenced in the example)
  2. scikit-video

I’m using Anaconda for my python environment so i tried the usual
conda install imageio

But no luck, then I actually read the documentation (sorry!) and tried:
conda install -c pyzo imageio

That didn’t work, so i tried the PIP install method on the same page
pip install imageio

This should have done it but when I tried to restart the kernel in my ipython notebook and import it, it was not found in my packages…

Some faffing with my conda Environment (I had not set up an environment and was using root) gave more strange errors- even the example (conda create --name snowflakes biopython) would not work as a previously cocked up version of this command meant it kept looking for a package that did not exist (the name of my new environment videoedit)

Eventually after much faff I managed to make a new environment (not my exporting to txt as a lot of my packages were clashing (due to a recent numpy upgrade)
Richards-MBP:~ richardpeter$ conda create --name videoed --clone root
Source: /anaconda/anaconda
Destination: /anaconda/anaconda/envs/videoed
The following packages cannot be cloned out of the root environment:
- conda-4.1.6-py27_0
- conda-build-1.19.0-py27_0
Packages: 184
Files: 444
Linking packages ...
[ COMPLETE ]|###################################################| 100%
#
# To activate this environment, use:
# $ source activate videoed
#
# To deactivate this environment, use:
# $ source deactivate
#

Success! ?

Looking in my environment I could in fact see the imageio in there with <PIP> as the version… which meant it was in fact in my root so should have been in my jupyteer/ipython notebook all along! (!!!!?)

Anyway, I killed my current ipython session, did NOT enter my videoed environment and just ran the below in the terminal:

ipython notebook

It worked….  I don’t know why but it did.

 

2: Convert to numpy array:

After trying to edit one of my own mp4 files to a manageable 30s without success I downloaded this small, low res 1mb file from here.

A few lines of python later I’d flattened the image to a greyscale and plotted it:

 

Screen Shot 2016-07-10 at 20.51.54

 

3) Laplace Filter

Following the documentation  here a few more lines of python code give us a Laplace Filter:

from scipy.ndimage import correlate1d
from scipy.ndimage import generic_laplace

def d2(input, axis, output, mode, cval):
return correlate1d(input, [1, -2, 1], axis, output, mode, cval, 0)

a = np.zeros((3, 3))
a[1, 1] = 1
lf = generic_laplace(a, d2)

lf
array([[ 0., 1., 0.],
[ 1., -4., 1.],
[ 0., 1., 0.]])
Cool. And we can apply this to our image with a few more lines of python:

from scipy.ndimage import correlate
plt.imshow(correlate(img_grey, lf),cmap=’Greys_r’)

Screen Shot 2016-07-10 at 22.23.36

Somewhere in here you can vaguely see the outline of the scene.. but not quite what I was after… Perhaps a Sobel Filter instead? (And looking at the docs prewitt while we;re at it…)

from scipy.ndimage.filters import sobel, prewitt
plt.imshow(sobel(img_grey),cmap='Greys_r')

Screen Shot 2016-07-10 at 22.33.18

plt.imshow(prewitt(img_grey),cmap='Greys_r')

Screen Shot 2016-07-10 at 22.33.58

Hurrah! … But still not enough to be able to spot a competing drone…

Let’s try to make it more black/white… I wonder…

sob = sobel(img_grey)

sob.min(), sob.max()

(-560.66666666666663, 480.66666666666669)

Hmm…

To Dosob[sob>0] = sob[sob>0]*-1
plt.imshow(sob,cmap=’Greys_r’)

Screen Shot 2016-07-10 at 22.41.47

Better… but perhaps still not enough to identify a drone..

Googling edge detection in Python – looks like someone has been here before: https://en.wikipedia.org/wiki/Canny_edge_detector

And what I want is likely in openCV…

Tomorrow’s work…

 

Calculating the percentage of intersection between two shapefiles: ZIPCODES and Community Areas

iPython note:

ZIP-communityWeights

 

This was a favour for the lovely missus – She needed to look at census data , provided by ZIP code, but was working with an organisation that was interested in community areas.

Census data can be obtained in the form of Population/unemployment/Ethnic minority in each zipcode.

To translate this to Community area, we can make an approximation by weighting each zipcode by the portion of it’s Area in each Community area.

This is not a perfect mapping, for example, in zipcode 60101 there may be a part that overlaps Community Area ‘LOOP’.   in this case nobody from 60101 would live in the LOOP, but you would assign some of the unemployed population to that Community area.

Anyway, it’s a first approximation and that’s all we need for now.

Shapefiles for Community Areas are here:

https://data.cityofchicago.org/Facilities-Geographic-Boundaries/Boundaries-Community-Areas-current-/cauq-8yn6

Shapefiles for ZIPs are here:

https://data.cityofchicago.org/Facilities-Geographic-Boundaries/Boundaries-ZIP-Codes/gdcf-axmw

 

Code Highlights osgeo package and Pandas (of course)
from osgeo import ogr
import os
import pandas as pd #My favourite Package!

 

Import a shapefile downloaded from the cityofchicago.org:

driver = ogr.GetDriverByName('ESRI Shapefile')
daShapefile = r"yourCommunitiesFile1.shp"
Communities = driver.Open(daShapefile, 0)
# 0 means read-only. 1 means writeable.

# Check to see if shapefile is found.
if Communities is None:
print 'Could not open %s' % (daShapefile)
else:
print 'Opened %s' % (daShapefile)
com_layer = Communities.GetLayer()
featureCount = com_layer.GetFeatureCount()
print "Number of features in %s: %d" % (os.path.basename(daShapefile),featureCount)

daShapefile2 = r"yourZIPShapeFile1.shp"
ZIP = driver.Open(daShapefile2, 0)
# 0 means read-only. 1 means writeable.
if ZIP is None:
print 'Could not open %s' % (daShapefile2)
else:
print 'Opened %s' % (daShapefile2)
z_layer = ZIP.GetLayer()
featureCount = z_layer.GetFeatureCount()
print "Number of features in %s: %d" % (os.path.basename(daShapefile2),featureCount)

z_layer = ZIP.GetLayer()
c_layer = Communities.GetLayer()

Create a dictionary:

wt = {}
for z_lyr in [z_layer.GetFeature(i) for i in range(z_layer.GetFeatureCount())]:
z = z_lyr.zip
zg = z_lyr.geometry()
wt[z]=[]
    for c_lyr in [c_layer.GetFeature(j) for j in range(c_layer.GetFeatureCount())]:
cg = c_lyr.geometry()
intersection = cg.Intersection(zg)
wt[z].append(intersection.Area()/zg.Area())

Create a list of the communities:

communities = []
for c_lyr in [c_layer.GetFeature(j) for j in range(c_layer.GetFeatureCount())]:
communities.append(c_lyr.community)

 

Create a pandas DataFrame and export to excel:

tbl = pd.DataFrame(wt).T
tbl.columns=communities
tbl.to_excel('zip-community weights.xls')
ZIP-communityWeights

Hello world!

Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!

© 2017 notesToSelf 1.0

Theme by Anders NorenUp ↑