Quick though: the power of encoding

Wo Meijer
3 min readJun 3, 2019

I am working on a fun little electronics project: a DIY mouse that is really a test bed for developing BLE applications with the ESP32 while I am riding around on the train. And one of the main input devices is a little joystick taken from a PSP (found here on Adafruit).

More info on this bad boy later!

It’s a lot of fun to play with, but one of the main things I want to do is to play games. So, I need to take the analog output and convert it to 8 directions.

The traditional method: lots of “if”s

I’m too lazy to color correct, but at least my bad hand writing will make up for it

My first thought was to just check the direction of both sticks independently and then use a bunch of if conditions to check which of the 9 states the joystick is in. However, this does not feel like elegant, and quite frankly I care more about that than copy-pasting an if statement a few times.

The question becomes: what now?

Well, I started thinking about how to store both states in one single number. So that you check the directions in X and Y and boom, you are done. How can you do that? Let’s try throwing around some numbers!

Uh ohhhh

First, let’s start by just assigning numbers in order starting from X pointing left. As you see above you, everything is fine for the four base directions! However, things start to go wrong when you point between them and add the X and Y values together. So, we just need to find some numbers that are no necessarily prime, but are “sum prime”, as in, the sum of any of the two numbers does not equal any of the other numbers we choose.

It’s pretty easy!

We can keep 1 and 2, but for the X+ direction let’s use 4 so we don’t confuse it with 1+2. Now, we also cannot use 5 (4+1, would not naturally happen, but let’s avoid it), 6 (4+2). Thus we are left with 7 as our final number! As you can see above this all works.

Does this actually save any processing power?

Well, we’ve encoded the 2 directions into 9 possible numbers simpler than using a bunch of if conditionals sure. However, if we need to know what this number stands for, we have to look it up in a dictionary (or just use all of the if statements that we tried to avoid).

Why should I care?

I agree, this isn’t the most revolutionary idea in the world, however, I have helped a lot of people who struggle with messy code and getting lost in a cascade of if’s. This is an example of how encoding makes life easier for everyone.

--

--