YouTube Red Play Button: The LED Live Subscriber Counter

I’ve always been interested in my YouTube analytics. Looking at dynamic data is always exciting, so I wanted this to be my next idea. So for my latest project (which I’ve wanted to do for a while), I’ve decided to make an LED YouTube Live Subscriber Counter display that just sits on my desk or office and lets me know how many subscribers I’ve got at any moment! I’ve decided to share the process so you can make one yourself! This was inspired by getting 100,000 YouTube subscribers, so I wanted to make myself a RED YouTube play button.

You can find all the details at the links above.

IMG_9812

WhatWorkouts: A Workout Generator

Over the past couple of months, I’ve been spending my free time (that I have left) programming a website. This website is called WhatWorkouts.

What workout should I do today?

WhatWorkouts was was inspired by the lack of variety in my gym routine. Now don’t get me wrong, I’m a strong advocate for committing to a program for best results in the gym, but I wasn’t satisfied with the online workout idea-generator-inspirer-type things.

I made some features that I think might be useful to my following gym-goers:

  • Workout suggestion: on the main page is just a random workout session that’s generated with sets and reps. Refreshing the page refreshes the workout.
  • Workout generator: you can choose multiple muscle groups and the page will load a workout that targets those muscles/muscle groups specifically.
  • Workout builder: a form in which you can submit custom workouts to share or save.
  • There are also a bunch of videos that demonstrate how to do certain exercises.

I’m fairly proud of it, because I did it all from scratch. The back end, database, URL re-writing, CSS, HTML and javascript. I implemented a user logon feature where users can save their workouts and link them, or browse other users’ submitted workouts – with the idea of making training in the gym social. I think it will be one of those projects that doesn’t really ever die, but it’s been lots of fun and I’ve learnt so much about web development in the last 8 weeks or so.

Making a Facebook Meme-bot with Raspberry Pi

It’s been a while since I last posted…but I can explain. Over the last 6 months, I’ve finished my engineering honours thesis, graduated with first class honours in engineering, managed to grab a degree in Information Technology along the way, gone on a cruise, lined up a job for 2017 and caught up on my social life.

So as my downtime has increased, so has wasting my time on social media, particularly looking at funny images and gifs of cats and goats.

I noticed that lots of content on Facebook is ‘procured’ from other sites (i.e recycled) which makes it popular, as it’s already been socially approved on an external site.

For example, take reddit.com, which is a user-submitted content site. Lots of the memes, videos and images I’ve seen on Facebook appear a week later after I’ve seen them on Reddit. You know your audience will like it on Facebook as it’s been heavily liked (upvoted on Reddit). I decided that I also want to join in on the spam, so I started looking into APIs for Reddit.com

The goal I wanted to achieve was to make an autonomous bot, that took something popular from Reddit and posted it to Facebook, on regular intervals, indefinitely.

2016-12-21 15.09.03.jpg

The Memebot: Wifi module + 5V PSU makes it super portable.

After discovering PRAW: The Python Reddit API Wrapper, and making a developer account with Facebook, it wasn’t too difficult to search, filter, select, download, upload the content that I wanted. As this was done in Python, I thought running it off dedicated hardware (Raspberry Pi) would be a good idea as this would enable me to keep it running 24/7 just with a USB cord and a wall outlet.

Of course, there were lots of small issues along the way. Some of them (off the top of my head) were:

  • Filtering posts just for images
    • Gifs really screwed up my downloading and uploading flow. So I had to make some special cases (try…catch) in order to only get images through.
  • Availability of reddit.com
    • At peak times, reddit is down a lot. This messed up the behind-the-scene python fetching with the lower-level HTTP calls. So, again, I had to insert some code to check whether it was all operational. If, for example, the internet connection did not work for any given reason, it would wait 30 mins and try again.
  • Resilience of the bot
    • Pulling the power cord out obviously kills the bot, but what happens when you plug the power back in? In order to auto-run my bot script, I actually had to make a bash script to run my python code on startup. Doing this, I made the machine very durable.
  • Duplication of content
    • Often, content wouldn’t refresh as fast as I wanted, or I couldn’t loop through content I knew I had already posted. To overcome this, I made a log (a text file) that simply wrote a unique string per image in it. It’s this easy:

# Check if we’ve looked at this post before.
duplicate = False
# If the file doesn’t exist, move on.
if os.path.isfile(logfile):
log = open(logfile, ‘r+’)
for line in log:
if line.strip() == submission.id:
print (‘Duplicate detected: ‘ + submission.id)
duplicate = True;
break
log.close()
if duplicate:
continue

I also made the Raspi have SSH activated, so I could remotely access the logs, images, etc.

Capture.PNG

2 Posts from the Meme-bot.

Note: this post is an extremely high over-view of this project. I combined some usage of Python, with Raspi hardware and some bash scripting (and lots of error handling, something I learnt lots about) with Facebook developer API to create a potential Facebook personality.

Filtering Spam from your Google Analytics

Capture

If you use Google Analytics for your clients or for your own sites, you no-doubt receive spam referrals which can skew or distort the data you want to capture.

Below is a quick-and-dirty filter I’ve made to get rid of spam in analytics. It is based on regular expressions which you can look up if you’re interested. (Regular expressions are a powerful way to quickly filter out the sources you don’t want in your data, or use in any other applications.)

On Google Analytics go to:

  • Aquisition > All traffic > Source/medium.
  • Click on the advanced button.
  • Put ‘exclude’. Change ‘containing’ to ‘Matching RegExp’.
  • Paste in the following line:
^[0-9A-Za-z-]*.xyz|^(с.)|^[0-9A-Za-z-]*seo

This is broken into 3 filters. The first matches any source that has any numbers and letters and dashes then ‘.xyz’ which should strip all .xyz domains. The ‘|’ ORs the conditions together to join them. ‘^’ means starting with.

The next is a filter for the с.новым.годом.рф domain.

The last is the same as xyz but any domain containing ‘seo’.

To test if this is working, Put ‘include’ on and then it should show all the spam sources it picks up.

Capture

You can setup the spam filter to do this automatically under Admin > Filters, of course, this treats the symptom and not the cure. To prevent clicks from spam, you’ll have to muck around with access files on the server. With this filter (as an example) in place, you can see more legitimate traffic to your site.

 

 

 

11 tips for getting the maximum out of your (engineering) degree

2015-12-20 18.58.18

As 2015 comes to a close, it brings comfort to some and anxiety to others. We all understand that 2016 brings a fresh year and a fresh start, but it also wipes the momentum from successes we had in 2015 and reminds us that we can’t be complacent.

2016 carries me into my final year of my Engineering and Information Technology studies here at ANU. I know this year will be the biggest challenge of all five, with a major group project and my final honours thesis. I’m writing this post to try and give the insight I’ve gained through my already-completed 4 years that I think you might find helpful. These are based on my experiences and are definitely not exclusive to engineering students.

1. Make friends

1006312_501210433304395_336328234_n

Source: ANUESA Facebook

I’d say this is definitely more important for the IT side because the amount of panic you can fall into when your code doesn’t work is very high/10, but it certainly applies to engineering students. Making friends is not only great for your social life, but it will definitely help in academic terms too. You’ll have back up and much deeper levels of confidence knowing you can talk to someone about your troubles so I definitely encourage you to talk to new people and make friends.

2. Go to lectures

12088320_912462095512558_4437260634910539423_n

Source: ANUESA Facebook

This goes without saying. BUT, you’ll be surprised at how many students don’t go to lectures, especially when you have to opportunity to watch the recording or scroll through the slides later on. I stress to you, however, that you attend as many as you can. You WILL feel lazy and not want to go, but don’t give in. This will not only stop you forming lazy habits, but it will give you a chance to meet other people and ask the lecturer questions live.

3. Study smart AND study hard

Screenshot 2015-12-20 18.46.10.png

Past exams – Best stuff

Studying hard is a given. The more you study, the more likely you’ll do better. It should be said, though, that studying smart is probably even more important. Talk to older students, find tips on courses. Lots of lecturers use similar questions in exams. Find past exams. They are the best study tool in my experience. Use tools like wolframalpha, that can make your life easy, because it’s going to be hard enough. Find out all the free software your institution has and get all of the things you need.

4. Join clubs and societies

10421122_736889773069792_7665875489310697443_n

Source: ANUESA Facebook

Going with the social route, get amongst the college/university vibe. You’ll be here once in your life, so maximise your immersion. Join all the clubs and societies you want to, the more the better. My personal favourite was the Engineering Student’s Association, and they made uni life much more pleasant for myself and a lot of people I know. These sorts of things give colour to your experience and glues everything together.

5. Go to the gym

2013-09-27 08.46.11

In America, they have this thing called the Freshman 15. Don’t be that person. Your health is the most important thing to you, so don’t neglect it. Personally, grabbing a gym membership was probably one of the best decisions of my life. I got it cheap because it was the campus one, but I also made a boat-load of friends through it and I look and feel much better. I understand not everyone will be into this, but I highly, highly recommend it, even just for a try. If you go for a month and you like it, you’ll be there for the rest of your degree and beyond. With study, you can’t really measure your intellectual gains, but with the gym, the physical gains are tangible and give you confidence in all areas of your life. Oh yeah, eat as best as you can, and sleep as much as you can too.

6. Get internships – grow your professional side

It’s not the grades you make, but the hands you shake. – Someone

This is the most important point out for this blog. Getting into the industry, or getting work experience even tangentially related to your major is invaluable. Constantly be on the lookout for job opportunities and intern opportunities. I’m lucky enough to be in my 2nd and I am not concerned about my job prospects in a year, let me tell you that. You may not get all the ones you apply for, but every interview helps, and every contact you make matters.

Along with this, build a strong LinkedIn page. Attend networking events. Join committees. Make a super strong resume, format it nicely in LaTeX (google for templates). Get your name out there, you need to prove yourself before you’re given any opportunity to choose. All these things put you a head and shoulders above the rest, and everyone needs that boost.

7. Be social

11816098_882532825172152_6094877838369690957_o

Source: ANUESA Facebook

This is also heavily overlooked. It’s fine to keep your head in the books and make good grades, but don’t pay the price by losing some of the most valuable years of your life. Go out for drinks, do things with clubs, meet new people. What good is it if you’re having no fun? At the end of the day, your quality of life is the only thing that really matters.

8. Do side projects, have hobbies

PERSONAsmooth

Much like building your professional side, you need to try and develop a character of depth. Much like this blog I have, try to have a creative or constructive outlet that others can see. This will make you a more interesting person in general, but it will also increase your employability aspects substantially. Build things with electronics, make websites, write code for open-source projects, do something that shows your passion.

9. Use cloud storage

You every-so-often hear of someone crying about losing their USB drive with their thesis on it, or hear about how someone’s computer dies and all their work is lost. THIS IS TOTALLY AVOIDABLE. Get Dropbox, or google drive or any other cloud storage service and save your work in there. My personal favourite is Dropbox, it syncs my photos, documents, etc. and I can share any document with a simple link. I can access ALL my files from ANY computer with internet, and I can access older versions of documents, it’s an absolute dream. If you’re concerned about privacy issues, there are lots of other private alternatives you can host yourself, just use google. This is one of the biggest confidence boosters and peace-of-mind bringers ever invented. You don’t have to haul USBs around anymore, and you don’t have to remember to email yourself things anymore.

10. Be organised

Organisation is one of the foundations to a smoother success. Things I own and highly recommend:

  1. Whiteboard
    1. Write reminders, equations, schedules, anything you like. It’s out in the open and in your mind constantly.
  2. Calendar
    1. I setup my timetable in my calendar which syncs through my phone and computer so I’m always in the loop.
  3. Pre reading
    1. If you’re up for it, reading the text book chapter before the actual class makes things much more comprehensible in class and gives you time to listen to the lecturer, and not just worry about getting down all the content.

11. Keep your eye on the prize

You might fail. You might get a bad score.  You might have to do supplementary exams. It doesn’t matter. In 5 years you’ll look back and nothing of it will matter because you’re in a great job that you like and it gives you big $$$. So don’t worry about the small stuff because a 15% assignment that’s stressing you out is nothing at the end of the day. Lots of people don’t realise this. Don’t spend 30 hours on a 5% assignment. Prioritise your time, and know when to cut your losses.I wish more people would understand this, it’s just a matter of perspective.

 

My First PC Build

As my 5th year of university rolls around, it’s time to drop my current desktop (HP pavilion ≈5 years old, actually a laptop connected to a monitor) and upgrade to something with a little more beef, especially with a very demanding year ahead.

So I did some research online and I found that there were lots of resources for computer buying and building. I decided to build a computer as it would not only be fun, but also rewarding and more bang for the buck. What I found most helpful were the people over at /r/buildapc and Carey Holzman on YouTube. These two resources were the only ones I needed in choosing my parts, and putting them together respectively. Coming from absolutely no experience with putting computers together, I consider this a very successful build as it worked the very first try but I’d like to give credit to these sources as they were extremely helpful.

There are generally 8 key parts to building a computer. These are:

  1. CPU (central processing unit)
    1. Brain of the computer
  2. CPU cooler
  3. Motherboard
    1. Holds everything together, the interface between all components.
  4. Memory (RAM)
  5. Storage
    1. Where you store all your documents, music, operating system, etc.
  6. Video Card
    1. Primary used for gaming, higher end graphics.
  7. Case
    1. The enclosure of the entire PC.
  8. PSU (Power supply)
    1. Converts the wall power into DC for the computer to use.

Summary

Item Part Cost (AUD $)
CPU Intel i7 6700 449
PSU Corsair CS450M 107
Memory 16GB Corsair Vengeance LPX 3000Mhz 159.83
Storage Samsung Evo 250GB 118.91
Case Corsair Carbide Series 200R 84
Motherboard ASUS Z170M Plus 199
Total 1117.74

Higher quality images can be found here.

My parts:

CPU

The CPU I chose for my build was the Intel (Skylake) i7 6700. While I absolutely didn’t need this CPU, I can definitely justify buying it. I wanted a Skylake CPU anyway, as this is Intel’s latest release and is more powerful and power efficient than any other [gave me slight future-proofing]. I didn’t go the AMD route as my laptop was AMD based, and I wanted a change. I decided to choose the i7 version over the i5 as it has hyper-threading capabilities (more logical cores) which will benefit me in occasional video rendering, simulations and multitasking workloads. I did not purchase the k version (unlocked, overclock-able) as I saw no need for it, and I’d rather operation inside Intel’s rated conditions. Following Mr Holzman’s many video tutorials, installing this into the motherboard was a piece of cake (albeit a very anxious and careful piece).

A CPU cooler was also not purchased as the i7 6700 came with a heatsink/fan.

The CPU cost me $449 from CPL, Australia in November 2015.

Motherboard

The motherboard I purchased was the ASUS Z170M-PLUS. I didn’t have too many choices in the motherboard as it had to be support LGA1151 (Skylake) processors. However, ASUS is a reputable motherboard brand. Some will question my choice of an overclock-able motherboard, and I respond by saying that it leaves room for upgrades, as well as having more peripherals and RAM speed capabilities. The installation of this was probably the most annoying out of the whole build. The IO shield was fiddle to begin with, and I noticed later that some metal from the IO shield was obstructing the USB and other slots so I had to reinstall it.

The motherboard cost me $199 from CPL, Australia in November 2015.

Memory

The memory I purchased was 16GB (2×8) of DDR4 Corsair Vengeance LPX. DDR4 is marginally more expensive, but fit the motherboard/cpu. I also wanted 16GB to ensure no bottlenecking with large application use, etc. I was also lucky to get it at the price I did.

The RAM cost me $159.83 after all expenses from Newegg, USA in November 2015. Given I received it at this price after a large exchange rate and international shipping and it being $50 cheaper than the Australian alternative just demonstrates the crazy prices Australians pay for tech.

Storage

I purchased a 250GB Samsung 850 evo SSD. I upgraded my laptop’s storage to SSD years ago, and this really made me learn that SSD’s are the only way to go with storage. This is the essential computer component for daily pleasure working on your computer. I didn’t purchase a larger internal HDD after some debate, as I have some larger external drives that I can utilise if I need that space (I’m not much of a data hoarder). I can also buy an internal storage HDD if needed in the future.

The storage cost me $118.91 from Amazon, USA in November 2015.

Video Card

I did not buy a video card. I do not play games, and the i7 contains some graphics capabilities on it anyway. However, I can buy one anytime if needed.

Case

I bought the Corsair 200R. Not much to say here, but I bought this because of great reviews, as well as a nice low profile appearance.

The case cost me $84 from CPL, Australia in November 2015.

Power Supply

For this build I decided to buy a Corsair CS450M PSU. This review by Anandtech sealed my PSU purchase’s fate and I decided to spend a little more for a little more quality. I also didn’t need more power for this build. Once again, installation was easy because of YouTube demos by CZ.

The case cost me $107 from CPL, Australia in November 2015.

BIOS

I must say, I was extremely impressed with the ASUS BIOS. I was used to the 80’s style blue screens, but this was a very nice graphical interface that made some early configuration easy.

Installation Shots

Below are some photos I’ve taken of putting the whole thing together. It was a fun process and I will do it again.

Figure 1 – All parts (except SSD, damn you post office)

Figure 2 – BAM. PSU in.

Figure 3 – New shiny. Motherboard looks nice.

Figure 4 – Another shot of the motherboard.

Figure 5 – This is where skynet rises up.

Figure 6 – 1151 pins. Don’t touch this. Don’t even look at it.

Figure 7 – 1151 Pads. Engineering at its finest!

Figure 8 – Skynet is online

Figure 9 – CPU installed into motherboard

Figure 10 – Ram installed into motherboard.

Figure 11 – CPU fan/heatsink fitted on the mothership, Carey Holzman style

Figure 12 – Most pieces in the case!

Figure 13 – Boots first go! YES. All the ram shows up, and the CPU is fine.

Figure 14 – The BIOS UI makes me feel smart

Figure 15 – Picked up SSD next day, thanks post office

Figure 16 – SSD installed.

Figure 17 – The best cable management I could do.

Figure 18 – Putting it back in my room and installing Win10

Figure 19 – Thanks for the free stapler CPL.

Screenshot 2015-11-25 01.23.03

SSD quick check – Yep it’s fast.

 

Screenshot 2015-11-25 01.33.09

Performing a quick bench on MATLAB

 

Capture

Using CPU-Z to look at the CPU.

 

Detecting DTMF Tones

This is just a brief post about part of a project I completed last semester for discrete-time signal processing course. If you’re unfamiliar with DTMF tones, have a look here.

The basic idea is to transmit information by using 2 frequencies together, then decoding them to find the transmitted information. For example, if I press ‘1’ on the old-style keypad, a 697Hz and 1209Hz tone will play simultaneously. You must obviously know what tones they are on the other end to find out what button was pressed, and this is done by a Fourier Transform (in this case).

For this part of the project, I had to detect the DTMF tones present in audio files, and collect some data about them.

I developed a function called decodeDTMF which did the following:

  1. Finds the ‘start’ of the signal and trims any non signal.
  2. Finds the ‘end’ of the signal and trims any non signal. Now the rest of the processing is on the signal itself.
  3. Runs a Fast Fourier Transform on the signal.
  4. Finds the frequency(ies) closest to the signal present. (DTMF tones are 1209, 1336, 1477, 1633, 697, 770, 852, 941) Hz.The sampling may show a signal of 1206Hz for example, which should be 1209Hz. I did this simply by smallest difference.

I then made some wrapper-code to test and extract all the information about the tones.
Here are the files, the FFT output, and my analysis output of the files:

File 1

1

File 2

2

File 3

3

File 4

4

File 5

5

File 6

6

File 7

7

File 8

8

Some of the above files should sound similar to the keypad found here.

This was the output from my analysis:

File Duration of actual DTMF tone (s) Number of samples for FFT Sample Freq. (Hz) FFT resolution (Hz) DTMF Symbol
File01 0.539571 3777 7000 1.853323 5
File02 0.250048 5251 21000 3.999238 0
File03 1.099769 14297 13000 0.909282 A
File04 0.850000 6800 8000 1.176471 *
File05 2.200000 9020 4100 0.454545 6
File06 0.860089 8674 10085 1.162670 3
File07 3.100055 28412 9165 0.322575 D
File08 0.690004 26127 37865 1.449267 8

If you listen to the wikipedia tones, they pretty much match the corresponding tones I’ve tabled here. For extra verification, this site also provided some nice peace of mind, which also backed up my analysis quite well.

Controlling RGB LEDs with Music

I’ve always wanted to do create something audio/visual like a laser show, or audio processing.  After finally getting some spare time to sit down and play around, I decided that making some lighting that responded to music was a great way to get something up and running fairly fast. My vision was to have music playing, and the lights in my room change based on the beat. After some research, it was clear that there was lots of material about getting an Arduino to change the RGB LED lighting that you can get from many sources. So I bought a 5m LED strip off the internet and started putting things together. There were many ways I could’ve gone about controlling the LED strip. These were:

  1. Through the IR remote that came with the control.
    1. I wanted this to happen because of the wireless aspect. However, it would be difficult to get the Arduino to send the right IR sequences to the receiver without an oscilloscope to debug and deconstruct the initial IR code. Also (after more digging), this would limit the output to the preset 16 colours on the remote, something not that desirable.
  2. Through a microphone.
    1. This is the ideal way in my opinion. The Arduino listening and responding to make the LEDs change from any audio source.
  3. Through an AUX cable.
    1. This was the way I used to design and test it. It’s easy to get started, but it limits my wireless capability and it’s difficult to get an audio source playing through both AUX and the main speaker (need splitter, etc).

I decided to break down the strip system into 4 modules. These were Audio source, amplifier, controller and LED lighting (with external power supply).

2015-03-15 12.17.03

  1. Audio Source
    1. This was easy enough. To start, I used an aux cable plugged into my ipod, which split the signal to headphones so I could listen to the music, as well as to the amplifier itself.
  2. Amplifier
    1. I built an (inverting) amplifier using an op-amp circuit I modified from this post. However, I note that with sampling, there would be several issues relating to the signal. The signal is not rectified (but Arduino can’t read -ve voltages anyway, so this is fine)  but, as I was using a change-LED-on-amplitude approach (as opposed to FFT or something else), the waveform (sinusoid shape) gets small before going negative. This is a problem because if sampled at this time, while the music may be loud and have a large amplitude, it would be shown to be deceptively small (seen in image).AM_signalThis can be solved with a circuit piece consisting of a single diode and capacitor (smooth + rectify) known as an ‘envelope detector’, which  is exactly what I needed: this keeps the voltage like a changing DC voltage rather than total analog AC. Unfortunately, late into my design I found this great website detailing a circuit design that I almost could’ve totally used for this module. It has given me good ideas for the future though (I revised and learnt a lot about electronics in this project).
  3. Controller
    1. This is the Arduino. It takes the analog amplified signal and processes it to output a PWM signal to 3 output pins, R, G and B. PWM is used to change the intensity of the colour. An issue I also encountered designing the code for this was the actual colour transition, how would I transition from red (low) to blue (loud) while crossing total green in the middle somewhere? I found out that there are many, many ways to do this, but I used a method that is a sort of piece-wise step function that I adapted from the ones shown here. The code that I used was fairly simple and can be found at the bottom of this post. As the LED strips needed currents way higher than what the Arduino could tolerate, I needed to create some ‘isolation’ between the Arduino outputs and the LED inputs, this was done with the MOSFET circuit shown here. (Lots of this has been done before, that post is great!)

As of yet, the whole system works great. I’ve only tested it with music and a 15cm LED strip, but I’m sure it will work with a larger one. Overall, this was a great project that had me looking at lots of aspects of electronics, going back to basics on some things, and using knowledge fresh in my head on others.


/* Converting sound to changes in an RGB LED strip */
// Josip Simunic
// Colour wheel based on the second image at http://academe.co.uk/225512/2554/arduino-cycling-through-colours-of-the-rainbow/

#define sensorPin A0 
#define red 11 
#define green 10
#define blue 9

int maximum = 845; // Used for calibration
int volume;
int minimum = 5;

/* Seperating the volume into 6 levels and adjusting RGB based on this */
int level6 = maximum; // This is the highest reading the Arduino can read through analog.
int level5 = minimum + (level6/6*5);
int level4 = minimum + (level6/6*4);
int level3 = minimum + (level6/6*3);
int level2 = minimum + (level6/6*2);
int level1 = minimum + (level6/6);

void setup() {
 pinMode(red, OUTPUT); 
 pinMode(green, OUTPUT); 
 pinMode(blue, OUTPUT);
 Serial.begin(9600);
}

/* Note that the pins are inverted - They're HIGH when they're off and LOW when they're on */

void loop() {
 /* Read the music volume. Note, this is an analog reading from 0-1023. Based on a reading of 0-5V*/
 volume = analogRead(sensorPin);
 if (volume > maximum){
 maximum = volume;
 }
 if (volume > minimum){
 Serial.println(volume);
 Serial.println(maximum);
 Serial.println();
 }
 
 /* Mapping the volume to suitable RGB colours, starting at RED and ending at BLUE with GREEN in the middle */
 if (volume < minimum){
 // DO nothing
 } else if (volume <= level1){
 analogWrite(red, map(volume, minimum, level1, 255, 0)); // red rises
 analogWrite(green, 0); // no green
 analogWrite(blue, 0); // no blue
 } else if (volume <= level2){
 analogWrite(red, 255); // max red
 analogWrite(green, map(volume, level1, level2, 255, 0)); // green rises
 analogWrite(blue, 0); // no blue
 } else if (volume <= level3){ 
 analogWrite(red, map(volume, level3, level2, 255, 0)); // red falls
 analogWrite(green, 255); // max green
 analogWrite(blue, 0); // no blue
 } else if (volume <= level4){
 analogWrite(red, 0); // no red
 analogWrite(green, 255); // max green
 analogWrite(blue, map(volume, level3, level4, 255, 0)); // blue rises
 } else if (volume <= level5){
 analogWrite(red, 0); // no red
 analogWrite(green, map(volume, level5, level4, 255, 0)); // green falls
 analogWrite(blue, 255); // max blue
 } else {
 analogWrite(red, 0); // no red
 analogWrite(green, 0); // no green
 analogWrite(blue, 255); // max blue
 }
 
}

Analysing Facebook Chat Data

Bar charts + transparency + a short time frame are the nicest ways to show this data visually.

Bar charts + transparency + a short time frame are the nicest ways to show this data visually.

I’ve always been interested in data. Logging, automation, data use, data management etc. play a huge role the digital environments that we are all apart of, and companies like Google and Facebook hold onto a lot of it.

PERSONB

Here’s a sample of patch conversation with someone. (Note, I wasn’t talking to myself, the red is behind the blue 😉 )

I was inspired to make this post by some forum posts I saw online of people analysing their messenger conversations and SMS threads. Of course, you could look at any sort of logged information and start filling in spreadsheets, but this conversation information is particularly interesting. Conversation information is usually logged multiple times per day and changes based on the relationship of the parties involved (I found some intriguing trends within my conversations) and so it can show data graphically in a very meaningful way.

There are multiple ways about obtaining Facebook Chat conversations and data. I’ve seen a few examples online that use scripting (which works nicely) but for this example I simply downloaded my bulk Facebook information. To do this, go to Privacy Shortcuts (top right) -> See More Settings -> General -> Download a copy of your Facebook data -> Start my Archive. After you press this, Facebook starts aggregating everything about you and collects it into a neat little zip file, and they’ll email you when it’s ready. Once this is downloaded, it contains all the videos, photos, messages, etc that you’ve had linked to your Facebook history. If you prod around, you’ll find everything in that zip file, including a HTML file that contains your entire Facebook Chat history.

Now you have the message data, you need to extract the meaningful things you want. Naturally, I’ll be using MATLAB, but scripting would be great (or any HTML processing software, regular expressions, etc). After inspecting the format of the file, I concluded that there are several key elements to the structure of Facebook Chat. These are threads and messages. Threads seem to contain a chunk of conversation with a given person. I initially thought that a thread contained all the conversations with you and that person, but that is not the case, there may be multiple threads. Messages contain information about the actual content of the message, as well as the sender and a time stamp of the message. After learning this structure of the HTML file, it wasn’t hard to get the things I wanted out of it.

An example of consistent contact with a friend.

An example of consistent contact with a friend.

10 day running average with PERSON A.

10 day running average with PERSON A.

As a conversation with you and another person can have multiple threads, I had to scan the start of each thread to check if the person I wanted chat information with was the correct person. After this, I looked through each message and simply extracted each timestamp and appended it to an array (expensive). After this process, I had all the received and sent timestamps in two separate matrices. Now what was required was some quick formatting of the timestamps to match MATLAB’s internal time format, I could plot a histogram of each sent and received matrix, and overlay them also. This double-overlayed histogram (with days as buckets) shows dates along the x axis and the number of messages sent/received along the y axis. Showing the data like this immediately identifies periods of intense conversation, or lulls in a relationship, and these are quite obviously identified.


<div class="thread">Person 2, Person 1(You)<div class...

This is an example of a thread format in the HTML file.


<div class="message_header"><span class="user">Person's Name Here</span><span class="meta">Saturday, January 10, 2015 at 3:21pm UTC+11</span></div></div><p>Oh hey! How are you?</p>

This is an example of the format for a message.

A thread contains a single thread tag, followed by many messages in succession, then ends with the start of another thread with another person. Developing a way to neatly cut away the waste wasn’t difficult, it just took some trial and error with string trimming and delimiters.

This all worked well and displayed exactly what I wanted it to, but it was slow. I initially didn’t think of a nice way to glean the data on the fly, and ended up concatenating each found item to the array that it belonged to, and then processing the array at the end of the entire run.

Initially, I had the time of day included in the processing, but I soon figured this was just a waste of time as I was never going to use a resolution less than a day, so I scrapped this. Upon ‘Run and Time’ing the code, I noticed that string splits are also quite expensive, along with the matrix concatenation that I mentioned earlier. Hence instead of the concatenation, I simply incremented an array that corresponded to each day in the range, then plotted that at the end.

After some profiling and testing, I managed to speed my code up by 26.8x! This occurred because MATLAB has great internal timing tools. What was a particular bottleneck was the function datenum which converted a date string into a double for plotting. I managed to instead piece together custom lines of code from the internet to do this function myself, and it paid off. The initial timing for PERSON A was 120s, and after all improvements was around 4.5s. Using regular expressions instead of string splitting also helped with this, as well as smarter array accessing.

I might come back to this and add some message statistics, such as average length (in characters) of a message sent/received, avg. sent/received a week, maximums, minimums, etc. but I’m currently busy with a full-time internship. Some of this data could be quite interesting to read over.

You can download the files I’ve made and use them yourself here.

 

Using Arduino with an 8×80 LED Display

2014-11-23 22.56.40

I bought a larger LED display some months ago, and haven’t really had time to muck around with it until now. Previously though, I used this display and fiddled around with a Raspberry Pi and used the code and guide you can see here. I decided that i’d like to use and manipulate the display from scratch, and naturally I used Arduino this time around.

Here is there data sheet for the display, as well as a location you can purchase one. There are several great features of this display that I’d like to highlight:

  • Each pixel (LED) can be lit as red, green or orange.
  • The display is shift-register based. So only  (9) minimal pins are needed to operate all 640 pixels.
  • It’s fairly low powered. I can run it straight from the Arduino pins. You can also power it independently.

The data sheet specified certain combinations of A, B, C and D to activate 16 rows, but you can ignore this and only use 8. I personally found the trickiest part of playing with this was hooking it up properly.

2014-11-23 21.54.12

Here, I simply used a continuity check on the ribbon cable to see how it worked before putting the cables into the Arduino pins and the ribbon cable itself. Be sure to insert the pins in the correct orientation (In the perspective of looking down) as to get it up and running properly.

For convenience purposes, I converted some Raspberry Pi code (Python) and converted it to Arduino compatible code (C). After this was done, It was simply a matter of managing the way I wrote data to the display. For my following examples, I used a 8×80 2D array (as 1s and 0s) and wrote the data to the screen, but did other computations on this seperately. I did three examples to see how well the display could operate, these were the Game of Life, a general text display and a ‘bouncing balls’ container. In the end they all worked quite well, and you can see me demonstrating this in the video.

What I didn’t mention in this video is that I could obviously vary the speed of all the transitions. I also adapted some pixel bitmaps from various other projects as to not write all ascii characters out by hand.

Here is the code for the game of life I made:

/* 
- Game Of Life -
Josip Simunic 
I basically re-wrote some parts from Pete Goss'
http://www.raspberrypi.org/forums/viewtopic.php?f=41&t=67520 
Python to C.
*/

#define A 13
#define B 12
#define C 11
#define D 10
#define enable 9
#define latch 8
#define shift 7
#define green 6 // Active low
#define red 5 // Active low
#define orange 4 // unused
long startTime = 0; // Used for timing.
long endTime = 0;

/* Make map bigger by a byte in each direction for ease of neighbour computations */
byte gameOfLifeBefore[10][82];
byte gameOfLifeAfter[10][82];

void setup() {
 //Serial.begin(9600);
 pinMode(A, OUTPUT); pinMode(B, OUTPUT); pinMode(C, OUTPUT); pinMode(D, OUTPUT);
 pinMode(enable, OUTPUT);
 pinMode(latch, OUTPUT);
 pinMode(shift, OUTPUT);
 pinMode(green, OUTPUT);
 pinMode(red, OUTPUT);
 // Initialise pins.
 digitalWrite(red, HIGH);
 digitalWrite(green, HIGH);
 digitalWrite(shift, HIGH);
 digitalWrite(latch, LOW);
 digitalWrite(enable, LOW);
 clear();
 /* Starting randomisation */
 randomSeed(analogRead(0));
 /* Initialising the maps to 0 */
 for (int row = 0; row < 10; row++) {
 for (int col = 0; col < 82; col++) {
 gameOfLifeBefore[row][col] = 0;
 gameOfLifeAfter[row][col] = 0;
 }
 }
 /* Glider */
 //gameOfLifeAfter[3][1] = 1; gameOfLifeAfter[3][2] = 1;gameOfLifeAfter[3][3] = 1; gameOfLifeAfter[2][3] = 1; gameOfLifeAfter[1][2] = 1;
 /* Oscillator */
 //gameOfLifeBefore[7][10] = 1; gameOfLifeBefore[7][11] = 1;gameOfLifeBefore[7][12] = 1;
 /* Toad */
 //gameOfLifeBefore[5][20] = 1; gameOfLifeBefore[5][21] = 1; gameOfLifeBefore[5][22] = 1;
 //gameOfLifeBefore[4][21] = 1; gameOfLifeBefore[4][22] = 1; gameOfLifeBefore[4][23] = 1;
 /* Die hard */
 //gameOfLifeAfter[1][1] = 1; gameOfLifeAfter[1][2] = 1;gameOfLifeAfter[2][2] = 1;
 //gameOfLifeAfter[2][6] = 1; gameOfLifeAfter[2][7] = 1;gameOfLifeAfter[2][8] = 1; gameOfLifeAfter[1][7] = 1;
 /* Line oscillator */
 //gameOfLifeAfter[4][36] = 1; gameOfLifeAfter[4][37] = 1; gameOfLifeAfter[4][38] = 1; gameOfLifeAfter[4][39] = 1; gameOfLifeAfter[4][40] = 1;
 //gameOfLifeAfter[4][41] = 1; gameOfLifeAfter[4][42] = 1; gameOfLifeAfter[4][43] = 1; gameOfLifeAfter[4][44] = 1; gameOfLifeAfter[4][45] = 1;
 
 //gameOfLifeAfter[4][16] = 1; gameOfLifeAfter[4][17] = 1; gameOfLifeAfter[4][18] = 1; gameOfLifeAfter[4][19] = 1; gameOfLifeAfter[4][20] = 1;
 //gameOfLifeAfter[4][21] = 1; gameOfLifeAfter[4][22] = 1; gameOfLifeAfter[4][23] = 1; gameOfLifeAfter[4][24] = 1; gameOfLifeAfter[4][25] = 1;
 
 //gameOfLifeAfter[4][56] = 1; gameOfLifeAfter[4][57] = 1; gameOfLifeAfter[4][58] = 1; gameOfLifeAfter[4][59] = 1; gameOfLifeAfter[4][60] = 1;
 //gameOfLifeAfter[4][61] = 1; gameOfLifeAfter[4][62] = 1; gameOfLifeAfter[4][63] = 1; gameOfLifeAfter[4][64] = 1; gameOfLifeAfter[4][65] = 1;
}

int index = 0;
void loop() {
 /* Only do this every second */
 if (isEmpty(gameOfLifeAfter)) {
 seed(gameOfLifeAfter);
 }
 startTime = millis();
 if ((startTime - endTime) > 500) {
 nextStepOfLife(gameOfLifeBefore, gameOfLifeAfter);
 copyMap(gameOfLifeAfter, gameOfLifeBefore);
 endTime = startTime;
 }
 for (int i = 0; i < 8; i++) {
 for (int j = 0; j < 80; j++) {
 if (gameOfLifeAfter[i + 1][j + 1]) {
 insert(4 + random(3)); // Inserts a random colour everytime.
 } else {
 shiftIT();
 }
 }
 showRow(i);
 delay(1);
 clear();
 }
}

/* Shifts the LED info */
void shiftIT() {
 digitalWrite(shift, HIGH);
 digitalWrite(shift, LOW);
 digitalWrite(shift, HIGH);
}

/* Clears the selected row */
void clear() {
 digitalWrite(red, HIGH);
 digitalWrite(green, HIGH);
 for (int i = 0; i < 80; i++) {
 shiftIT();
 }
}

/* Illuminates a selected row of LEDS */
void showRow(int n) {
 switch (n) {
 case 0:
 digitalWrite(A, LOW); digitalWrite(B, LOW); digitalWrite(C, LOW); digitalWrite(D, LOW); break;
 case 1:
 digitalWrite(A, HIGH); digitalWrite(B, LOW); digitalWrite(C, LOW); digitalWrite(D, LOW); break;
 case 2:
 digitalWrite(A, LOW); digitalWrite(B, HIGH); digitalWrite(C, LOW); digitalWrite(D, LOW); break;
 case 3:
 digitalWrite(A, HIGH); digitalWrite(B, HIGH); digitalWrite(C, LOW); digitalWrite(D, LOW); break;
 case 4:
 digitalWrite(A, LOW); digitalWrite(B, LOW); digitalWrite(C, HIGH); digitalWrite(D, LOW); break;
 case 5:
 digitalWrite(A, HIGH); digitalWrite(B, LOW); digitalWrite(C, HIGH); digitalWrite(D, LOW); break;
 case 6:
 digitalWrite(A, LOW); digitalWrite(B, HIGH); digitalWrite(C, HIGH); digitalWrite(D, LOW); break;
 case 7:
 digitalWrite(A, HIGH); digitalWrite(B, HIGH); digitalWrite(C, HIGH); digitalWrite(D, LOW); break;
 case 8:
 digitalWrite(A, LOW); digitalWrite(B, LOW); digitalWrite(C, LOW); digitalWrite(D, HIGH); break;
 default:
 digitalWrite(A, LOW); digitalWrite(B, LOW); digitalWrite(C, LOW); digitalWrite(D, LOW); break;
 }
 /* Latches the data */
 digitalWrite(latch, HIGH); digitalWrite(latch, LOW);
 /* Displays the data */
 digitalWrite(enable, HIGH);
}

/* Shifts a given colour into the display */
void insert(int colour) {
 if (colour == orange) {
 digitalWrite(red, LOW); digitalWrite(green, LOW);
 shiftIT();
 digitalWrite(red, HIGH); digitalWrite(green, HIGH);
 } else if ((colour == red) || (colour == green)) {
 digitalWrite(colour, LOW);
 shiftIT();
 digitalWrite(colour, HIGH);
 } else {
 shiftIT();
 }
}

void copyMap(byte oldArray[][82], byte newArray[][82]) {
 for (int row = 0; row < 10; row++) {
 for (int col = 0; col < 82; col++) {
 newArray[row][col] = oldArray[row][col];
 }
 }
}

/* Creates the next transition of life from */
void nextStepOfLife(byte oldArray[][82], byte newArray[][82]) {
 for (int row = 1; row < 9; row++) {
 for (int col = 1; col < 81; col++) {
 /* Check the neighbours of a cell */
 int liveNeighbours = oldArray[row - 1][col - 1] + oldArray[row - 1][col] + oldArray[row - 1][col + 1] + \
 oldArray[row][col - 1] + /*This is my cell */ + oldArray[row][col + 1] + \
 oldArray[row + 1][col - 1] + oldArray[row + 1][col] + oldArray[row + 1][col + 1];
 if (oldArray[row][col]) { // If we're currently alive.
 if (liveNeighbours < 2) newArray[row][col] = 0; // Dies from under population.
 if ((liveNeighbours == 2) || (liveNeighbours == 3)) newArray[row][col] = 1; // Lives on.
 if (liveNeighbours > 3) newArray[row][col] = 0; // Dies from voer crowding.
 } else { // If we're dead.
 if (liveNeighbours == 3)newArray[row][col] = 1; // We come alive.
 }
 }
 }
}

int isEmpty(byte oldArray[][82]) {
 for (int row = 1; row < 9; row++) {
 for (int col = 1; col < 81; col++) {
 if (oldArray[row][col] != 0) {
 return 0;
 }
 }
 }
 return 1;
}

void seed(byte oldArray[][82]) {
 for (int i = 0; i < 100; i ++) {
 oldArray[1 + random(8)][1 + random(80)] = 1;
 }
}