From Zero to Circuits Part 3: The Flippy Switch

As a reminder, all of the supply links I provide are just there to help. If you have something on hand, or pick out something cheaper, that is perfectly fine. That said, things you’ll want on hand for this part:

  • Your circuit so far
  • Some sort of flippy switch
  • Your soldering iron
  • Some solder
  • Wire strippers

Now, this time we will be modifying our circuit by adding this switch. Our new circuit will match the circuit diagram below.

“Wait! But there are TWO circuits!” you cry. Yes, yes there are. If you look at them carefully, the only difference between the two is whether the switch is connected to the battery’s positive or negative terminal. In practice, and for safety with higher voltage and current, you would connect the switch to the battery’s positive terminal, so that you don’t accidentally become the grounding component in your circuit.

However! These are floating ground on a very low power system, so in practice, for our purposes, it does not matter which side you connect your switch to. I will reiterate though: for safety, the best practice is to connect your switch to the positive terminal on your battery.

Now that that is out of the way, you may be wondering why both of these circuits could be treated as being the same. The correct answer is in the picture itself! The image for a switch is an open or closed line of wire (showing it’s default “safe” state). Since the purpose of a switch is to “break the loop” that means that it will break the loop in either position, and since current wont draw to an open end, the LED wont get power, and the circuit will be “off”.

So! On to the practical exercise! First and foremost: Remove your battery. I know that seems obvious, but getting a spark will definitely make you jump, and with larger circuits can be dangerous! Even if your battery has run out of juice, please, please remove it. It’s a good practice to get into.

Once you’ve de-powered your circuit, we’ll move on to incorporating the switch! If you were smart and labeled the positive and negative wires on your circuit, then now is the time to cut the positive wire in the middle. (If you don’t have them labeled, that’s alright! As we just saw, this will work no matter which side you connect, so pick one of your wires and cut it.)

Strip the now open ends and solder them to the leads on your switch like so:

Note: If your switch has three leads instead of two, this means your switch is what’s called an ON-ON switch rather than an ON-OFF switch. This is okay, it just means you will have an unused lead in this situation. Flip the switch to the “on” state you want, and then insert your battery into the holder. Then, just like when we were looking at battery leads, carefully touch each wire end to a different lead until your LED lights up. When the LED lights up, you know you have the correct pair of leads. Label them, then REMOVE THE BATTERY before soldering the wires to the lead pair.

Does it matter which wire you solder to which lead in the pair? Not for this scenario, and not for an ON-OFF switch. It basically functions the same as you physically tapping your wire to the battery when in the ON state, and removing it when in the OFF state. If you have an ON-ON switch like discussed above, and wanted to connect something (say… A different color LED) to that third lead, THEN it would matter which wire is connected to each lead, but that’s beyond the scope of this tutorial.

Once all is said and done, you should have something that looks kinda like this:

Perfect! Stick your battery in and flip the switch to “ON” aaaand…

Ta-da! There is light once more! Be proud of yourself, because you have functionally made a flash light, and honestly? You should be proud! You’ve gone from zero circuit knowledge to building your own flashlight! You’re now armed and dangerous, and from here the sky is the limit!

I will be making a couple more follow-up tutorials of more complex circuits, but consider yourself armed with the basics, and at this point you have all the skills you need to start making a LOT of different electronic projects.

From Zero to Circuits Part 2: Adding Some Heat

As a reminder, all of the supply links I provide are just there to help. If you have something on hand, or pick out something cheaper, that is perfectly fine. That said, things you’ll want on hand for this part:

This step involves a soldering iron and some solder. The heck is a soldering iron and solder, you ask? Why, they are these!

A soldering iron is basically a heat source with a metal pokey bit at the end that heats up. The solder is a bit of metal that is designed to melt at a lower temperature so you can combine metal components without melting them as well. For the moment, you just need to make sure you have these on hand.

We’re not doing anything fancy, so you can grab the cheapest versions of these tools and you’ll still be fine. My personal tools are this iron and some Radioshack brand solder which… Doesn’t exist anymore! So, maybe try this one. Don’t stress brand too much, as long as it says electrical on it and not plumbing you’ll be fine.

Again, there are a lot of fancier solder and soldering irons you could pick up, and they have benefits… But we don’t care! Right now all we need is some conductive metal to melt and a thing to melt it with. That’s a-okay for this process.

To make a looonger circuit, we’ll also need some wire. There are lots of wire options to choose from, but again, for our purposes we don’t really care. I tend to go with this because it’s easy to strip the plastic and easy to solder. If you get a larger or smaller gage (20-26 is perfectly fine range) or get stranded instead of solid is a-okay. Get what’s cheap and plentiful and call it a day.

You’ll also want a couple more tools. They are by no means necessary, but they make everything way easier, and they’re basic good to have on hand tools.

  • Wire cutters
  • Needle nose pliers
  • Wire strippers (designed to strip 20-24 gage wire)

If you don’t have them, no worries! As long as you have some way to cut away plastic and cut a section of wire you’ll be fine. (I used an x-acto or box cutter in the past to strip the plastic insulation on the wire. It’s a pain but totally doable.)

So! To start off you’ll want to cut two equal lengths of wire, with clippers if you have them, and whatever else if you don’t.

Next you strip some plastic from the ends with your wire strippers (or carefully cut it away with a knife). Your wires should look something like this at the end.

Don’t stress how much plastic you cut off. We want just enough gone that we can solder more metal in the ends of the wire, so if you cut too much it’s okay. If you cut too little you can always cut a bit more.

Next you grab your LED, and you’re soldering your wires to the metal leads. A good practice to make strong bonds is to ‘splice’ the wires like so:

But! If you don’t want to or can’t, it’s not a big deal. For what we’re doing it’s really not necessary.

Next up is the soldering itself. If the wires are spliced it makes this step a bit easier, but again, no big deal. Your goal is to melt your solder between the wire and LED lead so you have a good electrical contact.

Soldering is a bit of an art, but even an ugly melt will still do the job for our stuff.

Place the tip of your heated soldering iron where the LED lead and wire are contacting, and give it a little bit to warm the metal. Then stick your solder on the wire (not the soldering iron) and hold until it starts melting. Then just add until the connection is pretty well covered. Then take away the solder and iron and let it cool.

If by any chance you have electrical tape, wrap the joint in that. If not, eh, it’s fine, just make sure none of the metal from wire-lead A touches wire-lead B. If you wanna know what happens, it’ll spark! Wanna see? Take a wire and touch one end to the.plus side.of your coincell.and. the other to the minus side. Zzzzap! That’s a short circuit, and can muck up more complex circuits pretty badly.

Okay! You soldered the first wire lead like so, now solder your second wire to the other lead. Awesome! Now what?

Take the loose ends and tape them to your coin cell. Hey look! You made a circuit again!

Okay, okay, you want a non-tape version. For a non-tape circuit, you get a plastic coin cell holder like this.

It also has some leads on it, so now instead of tape you solder the leads on the holder to the other ends of your wires. This is where you need to start remembering the polarity (positive or negative) of your wires and the battery. I would recommend touching your wires to the battery holder leads (with battery inside) to confirm you’ve got it connected correctly, and then label them so you don’t mix it up when you solder the connection!

The final soldered holder should look something like this:

Voila! You made a circuit! No tape, all solder and fancy. You have your very own LED circuit!

Oh, you want to turn it on or off without taking out the battery? Well, that’s the next step!

(An aside: If you’re wondering why there were no circuit diagrams in this part, it’s because we made no changes to the circuit. Physically we did, but as far as the mathematical model, nothing really changed.)

Unity Mini-Tutorial #4 – Unity Cameras to MATLAB Images

Unity Version: 2018.3.0f2

OK, so you have camera frames spewing out of Unity into the ether. Let’s say you want to do some processing on these images in MATLAB. That is what this installment of the Unity mini tuts is all about. We will be picking up where Unity Mini-Tutorial #3 left off and adding the MATLAB code needed to read the frames from Unity.

This should be pretty easy, right? MATLAB can read from TCP/IP sockets and display images right? All we have to do is convert the data from the socket into a m x n x 3 matrix. Let’s get that a try:

% CameraCapture_Bad.m 
clc
clear all
tcpipServer = tcpip('0.0.0.0',55000,'NetworkRole','Server', 'INPUT', 1000000);
fopen(tcpipServer);
try
while(1)
imageDataLength = fread(tcpipServer, 1, 'uint32');
imageData = uint8(fread(tcpipServer, imageDataLength, 'uint8'));
imageData = reshape(imageData, 640, 480, 3);
imshow(imageData);
end
catch e
fprintf("%d -", e.identifier);
fprintf("\n %s", e.message);
end
fclose(tcpipServer);

Now, if you run the Unity code and then run the above MATLAB code you get something like this:

Fail!

Hmm… that is not quite right… and this is what Reakain came to me with after he scoured the Internets high and low and could not find a solution. I love a challenge and so I pounced at the change to solve this coding riddle.

The problem here is in the difference in the way that Unity stores RGB color data in images and how MATLAB does it. Unity stores the each pixel’s color components one right after the other: RGB RGB RGB RGB MATLAB on the other hand stores the colors like this: RRRR GGGG BBBB

This is not immediately obvious in either the Unity or MATLAB documentation.

OK, let’s try this again… we need to rearrange the image data so that MATLAB likes it.

% CameraCapture.m 
clc
clear all
tcpipServer = tcpip('0.0.0.0',55000,'NetworkRole','Server', 'INPUT', 1000000);
fopen(tcpipServer);
try
while(1)
imageDataLength = fread(tcpipServer, 1, 'uint32');
imageData = uint8(fread(tcpipServer, imageDataLength, 'uint8'));
imageData = reshape(imageData, 3, []);
imageData = imageData.';
imageData = reshape(imageData, 640, 480, []);
imageData = imrotate(imageData, 90);
imshow(imageData);
end
catch e
fprintf("%d -", e.identifier);
fprintf("\n %s", e.message);
end
fclose(tcpipServer);

That’s more like it!

Success!

You can read more about how Unity handles images and how MATLAB handles images if you want to really dig into the details. Otherwise, grab the code and enjoy the pretty pictures!

The full Unity package for this is at our GitHub here. So take a look or ping us if you have any difficulties.

Unity Mini-Tutorials #3 – Piping Camera Streams Out

Unity Version: 2018.3.0f2

There’s lots of guides to pipe camera data into Unity, but a lot less on piping out. Or at least, there’s a lot of old information on piping camera information from Unity.

This tutorial builds off the TCP connections information in Tutorial 2. The TCPSendPipe.cs file from it gets very heavily modified, but if you’re comfortable with sending TCP data from Unity already, then good! I’m not covering it again.

This tutorial covers the camera specific part of actually getting your camera renders as a 2D texture.

using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
using System.Runtime.InteropServices;
using System.Collections.Generic;

namespace UnityTutorial
{
    public class CameraPipe : MonoBehaviour
    {
        // Use this for initialization
        public int resolutionWidth = 640;
        public int resolutionHeight = 480;
        public String Host = "localhost";
        public Int32 Port = 55000;
        public bool writefile = false;

        const int SEND_RECEIVE_COUNT = 4;
        private Texture2D texture2D;
        private Rect rect;
        TcpClient mySocket = null;
        NetworkStream theStream = null;
        StreamWriter theWriter = null;
        Camera controlCam;

        void Start()
        {
            Application.runInBackground = true;
            controlCam = this.GetComponent<Camera>();

            mySocket = new TcpClient();
            InitializeGameObject();

            if (SetupSocket())
            {
                Debug.Log("socket is set up");
            }

            Camera.onPostRender += SendRenderedCamera;
        }

        // Update is called once per frame
        void Update()
        {
            if (!mySocket.Connected)
            {
                SetupSocket();
            }
        }

        public bool SetupSocket()
        {
            try
            {
                mySocket.Connect(Host, Port);
                theStream = mySocket.GetStream();
                theWriter = new StreamWriter(theStream);
                return true;
            }
            catch (Exception e)
            {
                Debug.Log("Socket error: " + e);
                return false;
            }
        }

        private void InitializeGameObject()
        {
            texture2D = new Texture2D(resolutionWidth, resolutionHeight, TextureFormat.RGB24, false);
            rect = new Rect(0, 0, resolutionWidth, resolutionHeight);
            controlCam.targetTexture = new RenderTexture(resolutionWidth, resolutionHeight, 24);
        }

        //Converts the data size to byte array and put result to the fullBytes array
        void byteLengthToFrameByteArray(int byteLength, byte[] fullBytes)
        {
            //Clear old data
            Array.Clear(fullBytes, 0, fullBytes.Length);
            //Convert int to bytes
            byte[] bytesToSendCount = BitConverter.GetBytes(byteLength);
            //Copy result to fullBytes
            bytesToSendCount.CopyTo(fullBytes, 0);
        }

        public void SendRenderedCamera(Camera _camera)
        {
            if (mySocket == null || _camera != controlCam)
            {
                return;
            }

            if (texture2D != null)
            {
                texture2D.ReadPixels(rect, 0, 0);
                Texture2D t2d = texture2D;

                byte[] imgBytes = t2d.GetRawTextureData();

                // Test line to write to file
                if (writefile)
                {
                    string temp = Application.dataPath + @"/../" + controlCam.name + DateTime.Now.Ticks.ToString() + @".png";
                    Debug.Log("Writing camera frame to: " + temp);
                    File.WriteAllBytes(temp, texture2D.EncodeToPNG());
                }

                //Fill header info
                byte[] camHeaderbyte = new byte[SEND_RECEIVE_COUNT];
                byteLengthToFrameByteArray(imgBytes.Length, camHeaderbyte);

                try
                {
                    //Send Header info first
                    if (mySocket.Connected)
                    {
                        theStream.Write(camHeaderbyte, 0, camHeaderbyte.Length);
                        Debug.Log("Sent header byte Length: " + camHeaderbyte.Length);
                    }

                    //Send the image bytes
                    if (mySocket.Connected)
                    {
                        theStream.Write(imgBytes, 0, imgBytes.Length);
                        Debug.Log("Sent image frame");
                    }
                }
                catch (Exception e)
                {
                    Debug.Log("Socket error: " + e);
                }
            }
        }

        private void OnApplicationQuit()
        {
            Camera.onPostRender -= SendRenderedCamera;
            if (mySocket != null && mySocket.Connected)
                mySocket.Close();
        }
    }
}

Very first thing is to create a Texture2D and a Rect object. Then set your control camera’s target texture as a new Render texture that matches the width and height and color spectrum.

This process hinges on the inbuilt Camera signal “onPostRender”. We attach a custom function to that signal which is the SendRenderedCamera function. It first checks if the rendered camera is one we want to send, and if not it exits the function.

If it is the camera we want, we read the render texture pixels to our 2D texture. Then we convert it into raw byte data (or encoded byte data if that’s your jam). (We can also write it out from here to a static image, which you can see if we set writefile to true.)

Next we send whatever header information on the image ahead of the image, so the output knows how many bytes we’re looking for. This is also where you would put any other data that you want to send on the image.

Once the header info is sent, we send the image bytes themselves, and presto! This script will fire and send every time the camera renders.

The full Unity package for this is at our github here. So take a look or ping us if you have any difficulties.

Unity Mini-Tutorials #2 – TCP Client and Server Connections

Unity Version: 2018.3.0f2

A first point of note: Large swaths of this code is used from information found on this Matlab forum thread. I used this setup as part of a master’s capstone project. (I’m the only one on the team that’s really comfortable with Unity/C#).

A second point of note: I have so far failed to be able to talk between a server and client within a single Unity application, probably because I’m port blocking myself. So I’ve added both python and Matlab client and server scripts for testing.

It’s basically just C#, but slapped together into the Unity MonoBehaviour scripting framework to run them in a scene.

TCP Server

The TCP server/listener is in the TCPListenPipe.cs script. You feed it your address and port, and it sits there listening for clients that want to talk to it.

TCPListenPipe.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using UnityEngine;

namespace UnityTutorial
{
    public class TCPListenPipe : MonoBehaviour
    {
        public String Host = "localhost";
        public Int32 Port = 55000;

        private TcpListener listener = null;
        private TcpClient client = null;
        private NetworkStream ns = null;
        string msg;

        // Start is called before the first frame update
        void Awake()
        {
            listener = new TcpListener(Dns.GetHostEntry(Host).AddressList[1], Port);
            listener.Start();
            Debug.Log("is listening");

            if (listener.Pending())
            {
                client = listener.AcceptTcpClient();
                Debug.Log("Connected");
            }
        }

        // Update is called once per frame
        void Update()
        {
            if (client == null)
            {
                if (listener.Pending())
                {
                    client = listener.AcceptTcpClient();
                    Debug.Log("Connected");
                }
                else
                {
                    return;
                }
            }

            ns = client.GetStream();

            if ((ns != null) && (ns.DataAvailable))
            {
                StreamReader reader = new StreamReader(ns);
                msg = reader.ReadToEnd();
                Debug.Log(msg);
            }
        }

        private void OnApplicationQuit()
        {
            if (listener != null)
                listener.Stop();
        }
    }
}

A lot of this script is simply error handling so it doesn’t hang or miss seeing the client. To start, when it starts up it kicks off the listener and starts listening. If a client is already trying to make a connection then it accepts the client and it’s connected. If no one is trying to connect, it doesn’t hang up your Unity program over it, however.

Instead, in the update loop it checks if you have a client. If you don’t it checks if there’s a client asking to connect, if there is, it connects and continues on. If there’s not, then it exits the update loop and skips all attempts to read from a client (as there is no client connected!).

Once it connects to a client, then every update frame is gets new data, reads the stream, and then spits the data out in a way we can check it. (In this instance, via the Debug Log.)

TCP Client

TCPSendPipe.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using UnityEngine;

namespace UnityTutorial
{
    public class TCPSendPipe : MonoBehaviour
    {
        public String Host = "localhost";
        public Int32 Port = 55000;

        TcpClient mySocket = null;
        NetworkStream theStream = null;
        StreamWriter theWriter = null;

        // Start is called before the first frame update
        void Start()
        {
            mySocket = new TcpClient();

            if (SetupSocket())
            {
                Debug.Log("socket is set up");
            }
        }

        // Update is called once per frame
        void Update()
        {
            if (!mySocket.Connected)
            {
                SetupSocket();
            }
        }

        public bool SetupSocket()
        {
            try
            {
                mySocket.Connect(Host, Port);
                theStream = mySocket.GetStream();
                theWriter = new StreamWriter(theStream);
                Byte[] sendBytes = System.Text.Encoding.UTF8.GetBytes("yah!! it works");
                mySocket.GetStream().Write(sendBytes, 0, sendBytes.Length);
                Debug.Log("socket is sent");
                return true;
            }
            catch (Exception e)
            {
                Debug.Log("Socket error: " + e);
                return false;
            }
        }

        private void OnApplicationQuit()
        {
            if (mySocket != null && mySocket.Connected)
                mySocket.Close();
        }
    }
}

A lot of this is also intended for error handling and good practices, so we’ll quickly jump through the different pieces.

Starting with the class variables:

Host and port are self explanatory, make sure they match so your servers and clients find each other. The socket, stream, and stream writer are the workhorses, where the socket is your actual connection, the network stream is the data feed between the client and server, and the writer takes your data, and injects it into the stream between the two.

Start and Update are just handling trying to connect to the server no matter which order you run your server and client in. The OnApplicationQuit is simply intended as cleanup of any remaining open sockets.

SetupSocket it the part we care about, which attempts to connect to the host, then gets the stream, turns our message into bytes, and then writes our stream to the socket. If it fails it lets you know it failed in the Debug Log.

Python and Matlab

As I noted earlier, both Python and Matlab client/server scripts have been provided for testing. I’m not going to go over them, because the other side of the connection is a bit out of scope for this tutorial. However, they are listed in their respective folders in the tutorial repository.

pythonReceive.py

#!/usr/bin/env python

import socket


TCP_IP = '127.0.0.1'
TCP_PORT = 55000
BUFFER_SIZE = 20  # Normally 1024, but we want fast response

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)

conn, addr = s.accept()
print 'Connection address:', addr
while 1:
    data = conn.recv(BUFFER_SIZE)
    if not data: break
    print "received data:", data
conn.close()

pythonSend.py

#!/usr/bin/env python

import socket


TCP_IP = '127.0.0.1'
TCP_PORT = 55000
MESSAGE = "Hello, World!"

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(MESSAGE)
s.close()

matlabReceive.m

clc
clear all
tcpipServer = tcpip('0.0.0.0',55000,'NetworkRole','Server');
while(1)
data = membrane(1);
fopen(tcpipServer);
rawData = fread(tcpipServer,14,'char');
for i=1:14 rawwData(i)= char(rawData(i));
end
fclose(tcpipServer);
end

matlabSend.m

clc
clear all
tcpipClient = tcpip('127.0.0.1',55000,'NetworkRole','Client');
set(tcpipClient,'Timeout',30);
fopen(tcpipClient);
a='yah!! we could make it';
fwrite(tcpipClient,a);
fclose(tcpipClient);

The full Unity package for this tutorial is at our github here. So take a look or ping us if you have any difficulties.

Unity Mini-Tutorials #1 – Json Files

Unity Version: 2018.3.0f2

For Unity, a great way to store item, stat, etc info is in dictionaries, and everyone loves a good JSON dictionary. Or, rather, JSON dictionaries are a great way to store game data.

So, let’s start with a sample JSON file. This ones for an item database.

{
	"items": [
		{
			"name": "name01",
			"desc": "item description",
			"sprite": "item image in inventory",
			"action": "what the item does"
		},
		
		{
			"name": "name02",
			"desc": "item description",
			"sprite": "item image in inventory",
			"action": "what the item does"
		}
	]
}

Simple enough, right? We’ve got an array object “items” where each object in the array is an “item” with a name, description, sprite, and action. In this case we have an array of 2 items for our example.

The next part to look at is your C# scripts for reading the data in. For this example I have to script files. We’ll start by looking at Item.cs

using UnityEngine;
using System.Collections;
using UnityEngine.Serialization;
using System;

/// Scripts for loading and storing and reading json data for items
namespace UnityTutorials
{
	[Serializable]
    public class ItemDatabase
    {
        public Item[] items;
        public static ItemDatabase CreateFromJSON(string jsonString)
        {
        	return JsonUtility.FromJson(jsonString);
        }
    }
    
	[Serializable]
    public class Item
    {
        public string name = "";
        public string desc = "";
        public string sprite = "";
        public string action = "";
    }
}

Alright, what are we looking at. Item.cs has two classes. Let’s look at the second class first, the “Item” class. It has variables that correspond with the different objects within an individual item from the JSON file. So, you see name, desc, sprite, and action again. This tells the JSON parser what exactly it’s looking at when it pops open the JSON file.

Looking now at the ItemDatabase class, this class is one level up. So, one level up from your item in the JSON file has only one field “items” which is an array of Item. So, for this class we put in that variable so it can fill it out, and we make a static function to create an ItemDatabase from the JSON file.

The key pieces in here is to make sure our variable names match the names we define in the JSON file, and the static function that calls Unity’s inbuilt JSON parser.

The final piece is a script that actual generates an ItemDatabase class. I’ve labeled my script InventoryMonitor.cs and attached it to a gameobject in my example scene.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace UnityTutorials
{
    public class InventoryMonitor : MonoBehaviour
    {     
        [Header("Usables")]
        public string[] usableItemNames;
             
        [Header("Item References")]
        public TextAsset usableItems;

        private ItemDatabase usables;

        void Awake()
        {
            usables = ItemDatabase.CreateFromJSON(usableItems.text);   // Read in our Json file
            usableItemNames = new string[usables.items.Length];        // Instantiate our names array
            // Iterates through our items and populates the names array with the name of each item
            for (int i = 0; i < usables.items.Length; i++)
            {
                usableItemNames[i] = usables.items[i].name;
            }
        }
    }
}

Whew! This has a lot of pieces, so starting from the top! The usableItemNames string array is purely for us to see that our code is working. The TextAsset field is where we assign our JSON file, and the ItemDatabase variable is where we put the data from the JSON file.

From there, we call our static ItemDatabase function with the text from our JSON file, which populates the item database. From there it’s just a matter of using it to fill our names array to prove it worked.

What we see in the object inspector with our attached script. Right now the Item Names is 0, as we haven’t parsed the data from our JSON file.
And once we hit the play button, we see the Item Names is populated with the data from the JSON file. Voila! It worked!

Shabam! Success! The full Unity package for this is at our github here. So take a look or ping us if you have any difficulties. I listed a version up top, but based on content, this one is likely pretty version insensitive.

Unity Mini-Tutorials Intro

There’s a LOT of things you can do with Unity, and they have done a LOT of changes to their architecture. Searches on how to do little things tend to be out of date or not exist to begin with.

So! This is going to he an on going series of not-quite tutorials made of sample code and a listing of which version of Unity it was tested on. The goal being just to… Keep track of these things.

Maybe also do a page with a directory of them all. I dunno, we’ll see. It will keep developing as we keep writing in Unity.

From Zero to Circuits Part 1: Let There Be Light!

So! You want lights for a prop project and want to venture into basic circuits! That’s great! I’m gonna walk you through some absolute minimum steps for making an LED circuit. There’s lots of info on electronics on the web, and if you know anything about circuits this probably is not a tutorial for you. We’re going from zero circuit knowledge to making an LED light up to further refining and explaining what these different components really are.

Part 1 – Your First Circuit

Things you’ll need for this part:

  • Some tape (Anything you have on hand)

So! Let’s start simple and look at our LED! An LED is a light source commonly used in circuit boards and also commonly used in costumes and props.

LEDs can be purchased in different colors from places like AdaFruit or SparkFun. The ones we generally use for hobby projects look like this! (This particular one pictured is a blue LED)

image6

Important to note is that your LED has a short lead and a long lead. This represents a plus side and a minus side, also called polarity. We’ll get into this with more detail a little later. There are other types and details, but I’ll address that info later. For now, you have an LED.

Next thing we need is a battery. For this I’m using a coincell battery type CR-2032. You can go look them up, or grab this lovely five pack for less than three dollars here

image3

Now we put them together, with the plus side on your coincell battery touching the long lead, and the minus side touching the short and…

Voila! You made a circuit. The circuit diagram for this would look something like this (with a couple more numbers and less descriptive names tacked on):

image4

But that was easy! Circuits aren’t that easy! I promise that was a real circuit. If you wrap some tape around your coincell lead connections and stick it in your costume or wherever you want the LED, no one will be the wiser. Glue gun glue is also a perfectly acceptable adhesion method.

image8

If you want to go a liiiittle more complex, that’s going to be our next step! For now, rejoice in your victory over electrons, and cherish your new light friend.

Smartphone Controlled Timelapse Camera Using Raspberry Pi

So! SDCC is a great opportunity to show people just how MASSIVE nonprofit fan events can be. I wanted to show some friends what I couldn’t accurately describe in words or still shots. To do this in a function way I decided to make a timelapse body cam to see what I see when I walk around con. It needed to have on off control so I could stop recording if I decided to go to a panel. So the plan was to cobble something together from what I already have. In this case: A Pi Zero W, Pi mini camera, and external battery pack. The whole setup would be controlled by my phone on a wireless access point generated by the Raspberry Pi.

(Quick note: This means the RPi is generating a wireless signal that other devices can connect to. In this case a wpa secured connection my phone can hook into to control the pi and camera.)

Of course I decided this… The day before I was set to fly. Bonus points: I wasn’t taking my laptop because it’s heavy and I’m lazy. So, I had a night to pack and put together what should have been a simple project.

Spoiler: It was not and I was wrong. What followed instead was of course a comedy of errors which I’ll detail, and then follow up with what ACTUALLY worked out so you can hopefully replicate the end success without the chaos.

So! My friend got real hype about getting body cam timelapse, so he pulled out some quick links he thought might make it a trivial task!

They are as follows:

https://learn.adafruit.com/digital-free-library/configure-access-point

https://www.raspberrypi.org/blog/piui-control-your-pi-with-your-phone/

https://computers.tutsplus.com/tutorials/creating-time-lapse-photography-with-a-raspberry-pi–cms-20794

I want to preface by saying there is nothing WRONG with these articles. In truth I never made it to article three, and the first two – while useful primers on wireless access points – are out of date.

First hilarious failure: You can control an RPi through any network it’s connected to without needing a monitor and keyboard on the RPi. A Zero W has a built in wireless port, and no other connection. I would have to turn this OFF in order to change it to an access point. A Zero also does not have a full size HDMI port and I don’t own an adapter.

Cue Rea frantically dissecting his 3D printer’s brain because it was an RPi3. An RPi3 is bigger, but it has two networking ports and a full hdmi port. This meant I could control it while the wireless port on it was turned off.

From the photos, you can tell the big Pi 3B has an ethernet port on it, which is necessary for the initial setup. It also has two ribbon cable ports, one marked camera, and one marked display. The Pi Zero W has on the other hand, no ethernet port and one ribbon cable slot. Both have wi-fi chips on them though, so both can make a wireless access point, and all pieces are the same, so you can swap an SD card image between the two with no real problems for hardware that’s common between both boards.

Great! Now to follow my guides! Except… they’re outdated and don’t work. And suddenly the system isn’t even acknowledging it has a wireless port. My first instinct is that I royally fucked something. So! RPis are a nice platform because you can wipe the OS and start again in about ten minutes.

So I wipe the SD card and re-image an OS onto the system. Then I… try again and it does it again. I can’t figure out why it’s doing this, and between the two attempts and cobbling everything together it’s now almost nine. So I call in the big guns.

The big guns are my brother in trash and owner of possumtrash.com . He is FAR more competent on network stuff, so I ping him. Over text he can’t really diagnose the system, so he wants to set up the Pi to SSH in.

(Note: SSH is a secure shell connection routine to let you access and control one computer through another. I had already been locally using ssh to set up the system through the RPi3s second network port.)

Now! A local SSH is easy. Local meaning everything is on the same network/wifi. However, he lives about thirty minutes away with his lovely wife and three cats and two dogs. This means more work is required. I’ve never set up a non-local ssh. It is spooky and a whole new undertaking on its own.

A network ssh involves opening up ports on your router to the greater internet. It is generally not a good idea, because the internet is full of scripts constantly trying to ping on open ports. Port 22 is especially spooky because that is a general computer data port for ssh. IF you open something for SSH it’s important to have the proper security measures in place.

Have nonstandard login info for the computer system and router, as well as ssh access keys. In this instance, I was opening ssh for one particular system, the RPi. So I gave it a set address and made a second user for nonlocal ssh.

This is where we get into access keys. Access keys are a handshake of sorts to prevent randos from getting into your system. You make a private and public key. The server – in this case the RPi – gets the public key, and he uses the private key to show he can get in. Sorta like in prohibition movies how they flash their lapel pin to get into the speakeasy.

So! I get the key, put it in the new user folder .ssh and forward port 22 to the RPi, effectively opening it up for the spooks of the internet.

It doesn’t work. Hilariously I forgot I had masked the house internet to stupid extremes, half by accident and half on purpose. The original house owners I’m renting from have a router, but it is Bad, so I hardlined my router into it so I could do RPi networking more easily.

However I hadn’t forwarded port 22 from the other router, so it never even made it to my router. So I went into the spooky basement and hard swapped some cables so there router didn’t block me.

It still didn’t work.

He talks to my system by talking to my external IP address. Unbeknownst to me, taking out the old router changed my IP. So I get him the new router IP.

Success! It is now ten o’clock and he begins troubleshooting. I sit on my thumbs and then start packing.

At nearly eleven he loses ssh connection. I lose ssh connection. Neither of us can talk to the RPi and we don’t know why. We both have work the next morning, so he calls it a night. I contemplate flashing a clean OS again.

Instead I rip up my playstation hdmi cable and plug the thing into my TV, as it is my only other monitor. It boots up, fails to load the wifi server, but it IS trying. A little more poking shows that following the guide was shutting off ALL network ports, not just the wireless one we were trying to turn into an access point.

At nearly midnight my buddy (who should have been sleeping) sends me a link for a different networking guide. I have been ripping up and slowly repairing the systems that were failing, and also re-enabled network ports. The link he sent is:

Final Tutorial Used

This is the one that ultimately works, but at the time I couldn’t make it work either. In the middle I had installed a camera control web interface to take care of the timelapse portion:

Camera Web Interface

Which created a web interface. The web interface worked, but wouldn’t show the camera feed. I gave up about 2 AM and went to bed.

The next morning I take my packed bags for con and a mass of RPi testing gear and cables to work with me. I mentioned the RPi to other coworkers, who got real excited and decided to take a look. They spent a good hour futzing with it before realizing the issue was… A typo in the config file. They introduced another typo while fixing mine and took another half hour to figure that out.

The camera still doesn’t work, but the access point does! At this point my buddy gets into work, and I share the pain by gifting it to him to figure out the camera. I then proceed to send him about five links to possible fixes and ten suppositions of what the error is.

Another hour goes by and he realizes… We were putting it in the wrong ribbon cable slot. There were no software issues with the camera.

About five of us stand around for a bit feeling very dumb.

Time to move everything from the RPi3 to the Zero W! This part is relatively painless. The entire system memory and operating system is on a microSD card, so I take the card from the RPi3 and plug it into the Zero. The camera we were testing with is bigger than the one I wanted to use, but should be compatible from a driver perspective, so I hook the smaller one into the Zero camera ribbon cable port.

Turn it on and…

SUCCESS

There are no compatibility issues and the system plays perfectly! Of course, I flew with it without a proper case, so I cobbled something together out of a base 3D printed case I had on hand and scotch tape and receipts…

If you want your own, simpler instructions and a parts list is below. Feel free to ask if you have any questions, cause as you can see, even folks that are paid for this kinda stuff make an absolute mess of it.

Parts List

  • Raspberry Pi Zero W or Raspberry Pi 3
  • Raspberry Pi camera (I used this one)
  • microSD card with at least 8GB
  • External battery (like this)

This quick guide is for peeps who want to be a little more hands on and get into the system guts. To start with, for these tutorials I recommend having a monitor and keyboard to plug into your Pi, or else is gets a little hairy.

First thing is first, initial Pi Setup. First you download the Raspbian Stretch Lite image from here. And use an SD card imager like Win32DiskImager to flash the image to an SD card. This will erase everything on the card currently, so make sure there’s nothing you still want on it. Once that’s done, you need to go into the boot drive it shows up as. (Don’t mind the disk size discrepancy, the SD card partitioned into two drives. One that’s the readable boot, and one that Windows thinks it has to format.)

Go into the boot file and add a blank file called ssh with no file extension on it. You might need to turn on file extension visibility if you haven’t ever done that before. This just turns on ssh, which you’ll want anyway and is a default step whenever I make a new RPi SD card. Take that SD card and stick it in the Pi.

At this point you take your lovely camera and its ribbon cable (if your camera has a USB plug in, you have the wrong camera) and hook it into the Raspberry Pi camera port. An RPi3 has two ribbon ports, so make sure you put it in the right one (it’s labeled camera).

Now you can hook it up to power, a monitor, and a keyboard and you can watch the system boot up. It will ask for login info. Standard login is username: pi password: raspberry. I’d recommend changing that for security reasons. At this point you’re in the pi and ready to follow the Web Interface Tutorial.

Web Interface and Timelapse Tutorial

Once you got that working happy and good to go, you follow the Access Point tutorial.

Wireless Access Point Tutorial

Wambam you have made your very own system! If you get hung up somewhere or feel lost, feel free to ping me. My hope is to help total Pi noobs start playing with them, so really don’t be afraid to ask!