Best Terminal theme for Mac OS X Yosemite

The white version of Terminal isn’t everyones cup of tea, definitely not mine.

Like on Mavericks, Yosemite’s Terminal is white by default (and is pretty ugly).

  1. Download monokai.terminal
  2. As the instructions on GitHub say, open the “Monokai.terminal” file

    Finder showing Monokai.terminal

    Finder showing Monokai.terminal

  3. You’ll be greeted with something like this

    Monokai.terminal file opened

    Monokai.terminal file opened

  4. However, to make this theme default you do need to open up the preferences for Terminal: Click Terminal in the menu bar, click Preferences and when the window opens hit the Profiles tab.
  5. Now, on the left menu you’ll see a list of system themes. Monokai should be in there. You’ll then want to click the Default button. You should have something like this

    Default Monokai

    Default Monokai

That’s all there is to it. All my thanks definitely goes to Stephen Way for creating this in the first place. It’s definitely my favourite theme.

Netflix captions not working

If you’re on OS X and you’re having trouble with displaying the best feature Netflix has, closed captioning, for movies check what language your computer is set to.

Mine’s been set to Māori (so I can do that cool ā) and that was when it clicked. As soon as I turned it back to “U.S” and refreshed my browser, captions displayed instantly.

See the following two screenshots from a scene in Team America:

Captions not working on Netflix

Captions not working on Netflix

Working captions on Netflix

Working captions on Netflix

All I did was switch between the following in the top right hand corner of my screen, to “U.S” and then refreshed my screen to get the captions, as this image shows:

Keyboard Input Source

Keyboard Input Source

If you do not have the above on your computer, just have a look in System Preferences for Input Sources, which is located under Keyboard.

This has never been a problem in the past, only very recently — when Microsoft Silverlight updated I think.

This post is for all you frustrated Netflix fans who’ve been having problems with captions. It’s also perhaps worth looking into, if you work for Netflix etc it doesn’t seem very user friendly. :-)

EDIT

I’ve been told Windows users are experiencing the same problem! Try changing your “Country region” to the US too. Try following this: http://windows.microsoft.com/en-nz/windows/change-country-region-setting#1TC=windows-7

Reading a websites contents using PHP and XPath

Following on from my previous post Scraping data with PHP and cURL today I’m going to show you about reading a websites contents using PHP and XPath.

One of the biggest problems I have faced when dealing with a scraped web page (read: block of HTML) is how to go about getting specific text elements out of it. Several years ago I would’ve gone with regex. This was a hassle to me and I’ve still yet to get my head around how it correctly works. These days though, I have discovered a useful little thing called XPath.

Basically, how it works is, you put the HTML in a DOMDocument and then you can use XPath to navigate through elements and attributes of the document getting the data of them in the process.

Using PHP and XPath

Now if we were to consider the following HTML:

<html>
   <head>
      <title>Test</title>
   </head>
   <body>
      <div id="mainDiv">
         <div id="leftDiv">
	        <p class="bodyText">This is left</p>
	        <img src="images/test.jpg" />
	     </div>
	     <div id="rightDiv">
	        <p class="bodyText">This is right</p>
	     </div>
      </div>
      <div id="footer">
         <p class="smallText">This is the footer</p>			
      </div>
   </body>
</html>

And now, lets say I wanted to get the text of the rightDiv. This is how we would go about it:

<?php

// $content is the content you scraped (via curl for example)

$dom = new DOMDocument();  
@$dom->loadHTML($content)

$xpath = new DOMXPath($dom);

$rightDivText = $xpath->query("//html/body/div[@id='mainDiv']/div[@id='rightDiv']/p/text()");

// Returns: This is right
echo $rightDivText->item(0)->nodeValue;
?>

Simply, it will load the $content (HTML) into a DOMDocument and then using XPath it looks for the for the div with the id of ‘mainDiv’ and then inside of ‘mainDiv’ it looks for the div with the id of ‘rightDiv’. Finally it then gets the text of the ‘p’ element.

Now that is one of the more straight forward scenarios and is made easier by the fact that most of the different elements have custom IDs like ‘mainDiv’ or ‘rightDiv’. If we were to look at the same HTML block again but this time without IDs, this is how it would look.

<html>
   <head>
      <title>Test</title>
   </head>
   <body>
      <div>
         <div>
	        <p class="bodyText">This is left</p>
	        <img src="images/test.jpg" />
	     </div>
	     <div>
	        <p class="bodyText">This is right</p>
	     </div>
      </div>
      <div id="footer">
         <p class="smallText">This is the footer</p>			
      </div>
   </body>
</html>

This time lets get the src of the image in the former leftDiv.

<?php

// $content is the content you scraped (via curl for example)

$dom = new DOMDocument();  
@$dom->loadHTML($content)

$xpath = new DOMXPath($dom);

$imgSrc = $xpath->query("//html/body/div[1]/div[1]/img/@src");

// Returns: images/test.jpg
echo $imgSrc->item(0)->nodeValue;
?>

As you can see, the difference this time is that instead of using the divs ID, we used the elements number. Inside the body, it looks for the first div, and then inside of that it again looks for the first child div before returning the src of the img element.

Again though, this is probably another pretty simple solution but definitely gives you an idea of how XPath works and some of the ways it can be used. The next scenario is basically the one I came face to face with, and that scenario is one in which we have multiple divs with the same name. Consider this html:

<html>
   <head>
      <title>Test</title>
   </head>
   <body>
      <div id="container">
         <div id="person">
	        <p>Bob</p>
            <p>25</p>
            <p>180lbs</p>
	        <img src="images/p1.jpg" />
	     </div>
         <div id="person">
	        <p>Stacy</p>
            <p>26</p>
            <p>187lbs</p>
	        <img src="images/p2.jpg" />
	     </div>
         <div id="person">
	        <p>John</p>
            <p>21</p>
            <p>255lbs</p>
	        <img src="images/p3.jpg" />
	     </div>
      </div> 
      <div id="footer"> 
         <p class="smallText">This is the footer</p> 
      </div> 
   </body> 
</html>

So here we have a webpage that displays a bunch of people with information such as their name, age, weight, and picture. Now as someone who is interested in getting the information of all of these people, I need to scrape the website and then using XPath I can loop through each person and get it.

To do this, we get everything inside the ‘container’ div and then loop through each individual ‘person’ div. Then using XPath on the ‘person’ div we can use the above examples to get the information we want. Finally we store all the results in an array.

<?php

$dom = new DOMDocument();  
@$dom->loadHTML($content);  
$tempDom = new DOMDocument();  

$xpath = new DOMXPath($dom); 
$container = $xpath->query("//div[@id='container']");
foreach ( $container as $item ) {  
    $tempDom->appendChild($tempDom->importNode($item,true));  
} 
$tempDom->saveHTML(); 
$peopleXpath = new DOMXPath($tempDom);

$peopleDiv = $peopleXpath->query("div[@id='person']"); 

$results = array(); 

foreach ($peopleDiv as $people) { 
	$newDom = new DOMDocument;  
    $newDom->appendChild($newDom->importNode($people,true));  
    $personXpath = new DOMXPath($newDom);  

	$name = trim($personXpath->query("p[1]/text()")->item(0)->nodeValue); 
    $age = trim($resultXpath->query("p[2]/text()")->item(0)->nodeValue);
    $weight = trim($resultXpath->query("p[3]/text()")->item(0)->nodeValue);
    $image = trim($resultXpath->query("img[1]/@src")->item(0)->nodeValue);

	$results[] = array(  
   		'name' => $name,  
   		'age' => $age,  
  		 'weight' => $weight,  
   		'image' => $image,            
    );			          	      	 
}

?>

There you have it. If you run a print_r on the results array you should have yourself a bunch values containing the information of Bob, Stacy, and John.

Now a totally awesome cheat for this solution is to use the Google Chrome XPath Helper extension. All you need to do is hold down the shift key as you hover over webpage elements. This in turn will return the XPath query which is a HUGE help!

As always feel free to comment and or improve on the above. Also, don’t forget to follow me @JAGracie.

Scraping data with PHP and cURL

I’m working on another idea which I hope to release soon which involves scraping websites using PHP and cURL.

I don’t want to give too much away before I release the website so I won’t go into too much detail. However, what I can tell you is that it required me to go out and  get a lot of data from external websites using variables passed through from a form on my end.

I originally started out using a piece of python software called Scrapy which worked very well, but the logistics of using that and either storing the data or displaying it on a webpage became too much of a hassle so I instead opted to go for PHP and cURL.

For the PHP side I’m using the framework Codeigniter which is a very easy and very speedy framework which is perfect for what I wanted to do.

The basic flow of how everything works is:

  1. The form is filled out and submitted
  2. Data from the form is sent to the external website in a cURL request
  3. The webpage content is then returned
  4. From there the data can be formatted and displayed accordingly

To do this with PHP and cURL is a fairly straight forward process and I’ll show you how to go about it. The only real issue you may come across is that when forms come into play you need to make sure each and every form element is included in the call.

$url = 'http://www.website.com/login.php';
$postdata = array('username' => "Jamie",'password' => "password");

$ch = curl_init();
if($ch){
   curl_setopt($ch, CURLOPT_URL, $url);
   curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   curl_setopt($ch, CURLOPT_POST, 1);
   curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
   curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt'); // set cookie file to given file
   curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt'); // set same file as cookie jar

   $content = curl_exec($ch);
   $headers = curl_getinfo($ch);				

   curl_close($ch);

   // Debug option
   // print_r($headers);

   if($headers['http_code'] == 200){ 
      echo $content;
   }
}

That’s the entire call and will return the html contents of website.com/login.php. I’ll go through the above code piece by piece and give a run down on each of the different parts.

$url = 'http://www.website.com/login.php';
$postdata = array('username' => "Jamie", 'password' => "password");

Firstly, the url variable should be self explanatory and the postdata is just a simple array which contains the form elements that are required to login with (in this case a username and password).

$ch = curl_init();
if($ch){

Create a new curl object and if all is well continue on.

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt'); // set cookie file to given file
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt'); // set same file as cookie jar

These are all curl options which I am going to use. You can view the rest of the different options over at the php website. The ones we are using and basically all to do with logging in. Storing the cookies and passing through the post data are the main ones to take note of.

$content = curl_exec($ch);
$headers = curl_getinfo($ch);				

curl_close($ch);

Last but not least, execute the curl request passing through the options we used, set the returned content to a variable and also grab the headers before finally closing the curl object.

As you will note in the original code I use the headers variable as a debug option. This is very handy, in particular the header_code which can be very useful. If you ever find that something isn’t working, double check that you are getting a 200 code and not a 400/501.

From there you can grab/scrape the content and data to your hearts content. A great thing is now that you have received and stored the cookies from logging in, you have access to ‘authenticated only’ sections of the website. So you can go away and run more curl requests to get those areas of the website.

I was about to end it there but one other important piece I have come across is that some forms that you fill out will actually re-direct you to different parts of the website after submit. It’s fairly easy to identify because you will get a header code of 302 and the great thing is that you also get a redirect_url in the headers. All you need to do is make another curl request using the redirect url you received.

// original curl request up here

if ($headers['http_code'] == 302){
   $ch = @curl_init();
   curl_setopt($ch, CURLOPT_URL, $headers['redirect_url']);
   curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt'); // set cookie file to given file
   curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt'); // set same file as cookie jar

   $content = curl_exec($ch);
}

Once you have gotten the content you require you then need to get access to the specific data or text you’re after. I’m going to show you how to do this using xpath in another post, so keep your eyes out for that.

Like always, if you have any comments or questions feel free to post and I’ll do my best to answer ‘em.

Follow me on twitter @JAGracie

Atom text editor by GitHub is missing the title/menu-bar

I’ve been using this text editor in replacement to Sublime Text 3 for a few days as a test and I must say it’s an excellent piece of software – but sadly, it’s not very fast! (it’s not a native application, I’ll leave it at that).

If you run into the bug where you can’t see the menu/title bar go to:
"Window > Zoom"

Atom Zoom
That’s all there is to it.

:-)

Raspberry Pi Temperature Sensing Pt 1

This tutorial is going to teach you how to set up a Raspberry Pi Temperature sensor using GPIO pins and Occidentalis.

So like many others before me I decided to pick up a Raspberry Pi to see what all the fuss is about. Now for those stuck under a rock or if you genuinely don’t know what a Raspberry Pi is, it is basically a small computer slightly bigger than a credit card with a cost of less than $50.

With it’s small size, fairly decent specs and the ability to play HD video the options with the Pi  are virtually endless. Add to that the GPIO pins that are attached to the board and it really does open up a whole new world. Already we have seen projects along the lines of home automationmedia centresin-car computers and arcade gaming.

I haven’t had a lot of time to play around or do much development with it but I’ve decided on making a mini weather application. The plan is that around every hour the application will take the current temperature and an image (using a webcam with Motion) before uploading the results to a website (running via a web server on the Raspberry Pi).

Part 1 is going to be all about setting up the Raspberry Pi temperature sensor and reading the data from it.

What you will need

Raspberry Pi Temperature Sensor

The first step is really setting up the Raspberry Pi itself. This has been done to death in multiple tutorials so I’m not going to go into the details. I’m currently using the Occidentalis v0.2 distro by Adafruit which by default comes with a lot of the packages you will need.

Once this is all setup and you’re happy then it’s time to move on to wiring up the DS18B20 Raspberry Pi temperature sensor. In the parts list I’ve put the Adafruit Pi Cobbler and breadboard as optional but I highly suggest you get them. It makes life a lot easier and can easily save you from doing damage to the Raspberry Pi itself.

It’s very important to get the wire input correct otherwise you run the risk of killing the sensor before you even get it working. The sensor that I’m using (link in the parts list) uses the following. Red = Power, Yellow = Data, Green = Ground. So applying this layout, on the Pi Cobbler/Raspberry Pi we place the Red wire on the 3.3v pin, the Yellow wire on the GPIO #4 pin and the Green wire on the GND pin. The 4.7k resistor goes between the PWR and Data wires (Red and Yellow).

Raspberry Pi Temperature Sensor

Raspberry Pi Temperature Sensor

NB: There are two things to note. Firstly, if by the end of this tutorial nothing is working then try placing the Red PWR wire on the 5.5v pin instead of 3.3v. The 3.3v didn’t work for me (and  hasn’t for many others) so give this a go. Secondly, if you turn the Pi on and the sensor gets extremely hot (enough to burn you when you touch it) then you have the pin layout wrong and need to double check the wire layout.

Now it’s time to fire up the Raspberry Pi and start reading some temperatures. Once it has booted up you need to firstly use the ‘modprobe’ command to load up the GPIO module in order to read the sensors data. So using ssh or desktop type..

sudo modprobe w1-gpio
sudo modprobe w1-therm

Next browse to the system devices folder to find the Raspberry Pi temperature sensor device.

cd /sys/bus/w1/devices
ls

When you issue the listing command under this directory you should see a folder beginning with 28-00000. This is your temperature sensor device. Go into this directory and read out the temperature by issuing the command:

cd 28-00000xxxx (change this to your folder name)
cat w1-slave

You will see an output similar to this:

Raspberry Pi Temperature Sensor Output

The output will display either YES or NO at the end of the top line. If it is YES, then the temperature is valid and will be at the end of the bottom line. It will show as the temp*1000 so if it looks like a large number just divide it by 1000 to get the correct reading. Eg: 21500/1000 = 21.5C. If it displays NO then re-issue the ‘cat w1-slave’ until you get a correct reading. Putting your fingers over the sensor and issuing the cat command again should show the temperature going up.

Now one annoying part is that each time the Raspberry Pi is restarted you need to re-issue the modprobe commands. A neat little hint I found online will solve this problem. So type this command into a shell terminal and the modprobe commands will be done on startup!

sudo sh -c "echo 'w1_gpio\nw1_therm\n' >> /etc/modules"

This is all there is to it. In part 3 of this series I’m going to write a python script which will grab the temperature automatically for you as well as some other neat stuff. Next up though will be getting a webcam and motion working to go side by side with the Raspberry Pi temperature sensor.

Until then feel free to leave a comment or any questions (I’ll do my best to answer) and don’t forget to follow me on twitter!

We’re back!

On a bigger, faster server with forever more thoughts, code, hacks and apps coming your way soon! :-D Trying out this new Google Analytics features too. If anyone has any cool stat apps I could use, let me knooooow!

Random Cave Generator using Pygame

Based on this blog post I’ve written a small game that lets you explore a dynamically generated cave.

Use the WASD keys to move around.

dynamic cave using pygame

Game screenshot

You’ll need to get pygame to run the following python script:

import pygame
from collections import defaultdict

levelmap = defaultdict(dict)

class Player(pygame.sprite.Sprite):
def __init__(self, level):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((10,10))
self.image.fill((40,50,170))
self.rect = self.image.get_rect()
self.x, self.y = 0,0

def update(self, world):
spd = 2
keys = world.keys
if keys[pygame.K_a]:self.x+=spd
if keys[pygame.K_d]:self.x-=spd
if keys[pygame.K_w]:self.y+=spd
if keys[pygame.K_s]:self.y-=spd
world.update_camera()
self.rect.x, self.rect.y = world.position_transform(self)

def renderlevel(noiseimage, levelmap, screen, camerax, cameray):
mapsize = 10
for w in range(-1, screen.get_width() / mapsize):
for h in range(-1, screen.get_height() / mapsize):
x = int(w - camerax/mapsize)
y = int(h - cameray/mapsize)
if x in levelmap:
if y in levelmap[x]:
if levelmap[x][y] == 0:
continue
realx = x* mapsize + camerax
realy = y* mapsize + cameray
noiseimage.fill((40,150,60),(realx,realy,mapsize,mapsize))

class World():
seed = 7
def __init__(self, screen):
self.player = Player(levelmap)
self.sprites = pygame.sprite.LayeredUpdates()
self.sprites.add(self.player)
self.camerax = 0
self.cameray = 0
self.keys = 0
self.screen = screen

# random noise
size = 100
for i in range(size):
for j in range(size):
levelmap[i][j] = 0;
if self.seededRandom(2, 0) > 1:
levelmap[i][j] = self.seededRandom(2, 0);
# generate caves
smoothness = 6
for i in range(smoothness):
global levelmap
new_map = defaultdict(dict)
for x in range(size):
for y in range(size):
x_range = {'low': max(0, x - 1), 'high': min(size - 1, x + 1)}
y_range = {'low': max(0, y - 1), 'high': min(size - 1, y + 1)}
wall_count = 0
for a in range(x_range['low'], x_range['high']+1):
for b in range(y_range['low'], y_range['high']+1):
if ((a == x) and (b == y)):
continue;
wall_count += 1 - levelmap[a][b]
if (((levelmap[x][y] == 0) and (wall_count >= 4)) or
((levelmap[x][y] == 1) and (wall_count >= 5)) or
((x == 0) or (y == 0) or (x == size - 1) or (y == size - 1))):
new_map[x][y] = 0
else:
new_map[x][y] = 1
levelmap = new_map;

def position_transform(self, obj):
return -(obj.x - self.camerax), -(obj.y - self.cameray)

def update_camera(self):
self.camerax = self.player.x + self.screen.get_width()/2
self.cameray = self.player.y + self.screen.get_height()/2

def seededRandom (self, maxa, mina):
maxa = maxa or 1
mina = mina or 0

World.seed = (World.seed * 9301 + 49297) % 233280
rnd = World.seed / 233280.0

return mina + rnd * (maxa - mina)

def main():
pygame.init()
screen = pygame.display.set_mode((600, 480))
clock = pygame.time.Clock()
world = World(screen)

while 1:
world.keys=pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
world.sprites.update(world)
screen.fill((0,0,0))
renderlevel(screen, levelmap, screen, world.camerax, world.cameray)
world.sprites.draw(screen)
clock.tick(60)
pygame.display.flip()
pygame.display.update()

if __name__ =='__main__': main()

Perlin like noise with python and pygame

The below code will generate a Perlin like noise for use in graphics applications.

It’s handy for say generating a dynamic cave, or a set of islands.

Perlin noise

Perlin noise

import pygame 
import math

def findnoise2(x,y):
	n = int(x) + int(y) * 57
	allf = 0xFFFFFFFF
	an = (n << 13) & allf
	n = (an ^ n) & allf
	nn = (n*(n*n*60493+19990303)+1376312589)&0x7fffffff
	return 1.0-(float(nn)/1073741824.0);

def interpolate( a, b, x):
	ft = float(x * 3.1415927)
	f = float((1.0-math.cos(ft))* 0.5)
	return a*(1.0-f)+b*f;

def noise(x,y):
    floorx = float(int(x))
    floory = float(int(y))
    s=findnoise2(floorx,floory) 
    t=findnoise2(floorx+1,floory)
    u=findnoise2(floorx,floory+1) 
    v=findnoise2(floorx+1,floory+1)
    int1=interpolate(s,t,x-floorx) 
    int2=interpolate(u,v,x-floorx)
    return interpolate(int1,int2,y-floory) 

def main():
	pygame.init()
	screen = pygame.display.set_mode((600, 480))
	clock = pygame.time.Clock()
	noiseimage = pygame.Surface(screen.get_size())
	noiseimage.fill((120,40,120))
	scale1 = 2.0
	scale2 = 4.0
	scale3 = 8.0
	for w in range(0, noiseimage.get_width()):
		for h in range(0, noiseimage.get_height()):
			i = int((noise(w/scale1,h/scale1)+1.0) * 42)
			i += int((noise(w/scale2,h/scale2)+1.0) * 42)
			i += int((noise(w/scale3,h/scale3)+1.0) * 42)
			if(i>255):
				i=255
			if(i<0):
				i=0
			noiseimage.set_at((w,h),(i,i,i))
	screen.blit(noiseimage, (0,0))
	pygame.display.flip()
	while 1:
		clock.tick(60)
	        for event in pygame.event.get():
	            if event.type == pygame.QUIT:
	                return
        screen.blit(noiseimage, (0,0))
        pygame.display.update()

if __name__ =='__main__': main()

Build a quadcopter (Part 3) – Preparing the quadcopter

Preparing the Quadcopter

Welcome back to this third installment on how to build a quadcopter. If you haven’t already check out part 1 (the parts) and part 2 (the build) to get up to speed and then read on to start preparing the quadcopter for it’s first flight.

KK2.0 Motor Layout

The first thing we want to do is tell the flight controller what our quadcopter layout looks like so that when it comes to receiving commands it knows exactly what to do and where to do it.

This is easy enough to do. Firstly Plug the battery harness into the battery and wait for the KK2.0 to fire up and follow these steps:

  1. Press button 4 (below the word ‘Menu’)
  2. Press button 3 (down) until you reach ‘Load motor layout’
  3. Press button 4 (enter)
  4. Press button 3 (down) until you reach Quadcopter – X
  5. Hit button 4 (change)

Just like that! You can then either go back (press button 1 over and over until you get back to the start) or press button 3 to scroll through each individual motor on the X layout. If you scroll through the motors you should take note that it shows you an arrow telling you which way the motor should spin (CW or CCW). This is important as this is what we’re going to cover next.

Preparing the quadcopter - Motor layout

Preparing the quadcopter – Motor layout

Motor Rotation

Now basically unless your motors spin the correct way (in line with the motor layout from above) you’re going to have a hard time flying. By hard time I mean the quadcopter will most likely flip before it gets off the ground and cause a bit of damage to itself. In other words this is also quite an important step.

If we follow what we saw in the previous step then motors 1&3 spin are going to spin CW and 2&4 will spin CCW. Check out the image below it you’re not sure:

Preparing the quadcopter - Motor rotation

Preparing the quadcopter – Motor rotation

The only way to find out if your motors are spinning in the correct direction is to fire it up and apply a little bit of throttle. So go ahead and turn on your radio, plug the battery into the harness and check each motor in turn.

By referencing the image above double check to make sure each motor is spinning in the right direction. If you find they aren’t, then all you need to do is switch 2 of the wires connecting from the motors to the ESCs (ie take the yellow and black and switch them). If you don’t know which wires I’m talking about, then these:

Preparing the quadcopter - Motor wiring

Preparing the quadcopter – Motor wiring

Again double check they’re spinning in the correct direction (rinse and repeat the above step for the other motors if needed) and then move onward!

Receiver Test

There are two reasons we need to do this. One, we need to zero out these numbers in order to make sure the quadcopter doesn’t decide to fly off on it’s own and two, we want to check to see if the radio inputs are going in the right direction (ie pushing forward actually makes the quad go forward). If you had trouble with the receiver in the previous post (ie trying to arm it by going to the bottom right didn’t work) then this is where we will hopefully fix those issues.

Firstly, switch on your radio and plug the battery into the harness to power it all up. On the KK2.0 do the following:

  1. Press the menu button (button 4)
  2. Press down and enter into ‘Receiver Test’
  3. You should come across the following:
Preparing the quadcopter - Receiver test

Preparing the quadcopter – Receiver test

This shows all the different channels (throttle, aileron, elevator, rudder, and aux) of your receiver. If you go ahead and move the sticks on your radio you will see the numbers next to the channels increase and decrease as you do so (this is a good sign).

We’re going to check all the inputs one-by-one now.

We’ll start off with the throttle first. So, on the radio move the throttle stick to idle. If you look at the KK2.0 board and the throttle input it showing both ‘0’ and ‘idle’ then this is correct. If you push the throttle up you’ll see the number increase. If this isn’t right then you need to reverse the input on your radio.

Next check the rudder. On the left stick (same stick as the throttle) move it from side to side. When you move it left it should give you a negative number and ‘left’ and vise verse for right. Again, if it isn’t then you’ll need to reverse it.

Rinse and repeat this for the aileron and elevator.

The next step is to zero out all the numbers. Firstly, set the throttle to idle and center and center the right stick both vertically and horizontally. Then, using the trim and subtrim options on your radio adjust the throttle, rudder, aileron, and elevator until they are all displaying 0 on the KK2.0 board.

Sensor Calibration

The next step is to calibrate the ACC sensors. The reason we do this is to make sure the quadcopter knows exactly what is level and what is not (fairly important when it comes to self-levelling).

Firstly making sure your quadcopter is sitting on a flat surface and is level (a table or counter-top is ideal) and then:

  1. Press menu on the KK2.0 board
  2. Press down and enter into ‘ACC Calibration’
  3. It will tell you to put the quad on a flat surface. Press button 4 to continue

It will now count down 5 seconds before calibrating. Once done you should see the all OK on the X,Y, and Z sensors:

Preparing the quadcopter - Sensor test

Preparing the quadcopter – Sensor test

ESC Calibration

One of the small tweaks you need to do is the ESC calibration. You may find that when you fire up the quadcopter and apply a little throttle the motors will start at different times. Basically we just need to calibrate them in order for all 4 to start at the same time. This can get a little bit fiddly so it may take a couple of times to complete

  1. Turn on your radio and apply full throttle
  2. Press and hold the 1st and 4th button on the KK2.0
  3. Plug in the battery while still holding the buttons
  4. Wait for 2 short beeps from all your ESCs
  5. Move the throttle to idle
  6. Then you should hear 1 short beep (you can take your fingers off the buttons now)

Now fire up the motors and you will find they all start at the same time.

Balancing and Attaching Props

Balancing the props isn’t extremely necessary, but having said that it is quite important. Having balanced props generally means a smoother flight with less vibrations. This will be very helpful for those of you who want to continue on to uses cameras and FPV on your quadcopters. It can also mean that screws are less likely to vibrate themselves loose, so after all that it probably is quite a good idea to do this.

If you got the cheap and easy balancer from part 1 then really all you need to do is screw the prop into it and then balance it between two objects the same height (I use tissue boxes). If the prop falls to one side then all you need to do is either add tape to the lighter side or using high grit sandpaper, sand the heavier side.

Once you’ve found the sweet spot (the prop will sit level in the balancer) then you’re done. Do the other props and you’re set to go.

Once the props are balanced it’s time to attach them. Now you need to be careful you attach the right props to the right motor. When you bought props you got a set of CW and CCW props. So make sure that you attach the CW props to the motors spinning CW and vise versa for CCW.

Preparing the quadcopter - Attached Props

Preparing the quadcopter – Attached Props

Test Flight

Now this is it. Time to fly this bad boy. More than likely it will be horribly out of tune so it will be fairly hard to fly. Feel free to skip this flight and move on to part 4 (tuning the KK2.) in order to ensure a more stable flight. However if you’re feeling up to it:

  1. Charge up the battery
  2. Take the quadcopter outside (in a large enough area to fly. I suggest a park or football field)
  3. Turn on the radio
  4. Plug the battery into the harness
  5. Step away a few meters and arm the quadcopter
  6. Apply enough throttle to get off the ground
  7. Practice flying and have fun!

Once you’ve tried it out I suggest reading part 4 in order to tune and upgrade the KK2.0

Feel free to comment or you can hit me up on twitter @JAGracie